提交 d0e68872 编写于 作者: 彭勇升 pengys 提交者: wu-sheng

SkyWalking's trace receiver implementation. (#1618)

* Buffer stream.

* Buffer file reader.

* Buffer library performance test and functional test successfully.

* Fixed the code merge mistake.

* SkyWalking's trace receiver implementation.

* SkyWalking's trace receiver implementation.

* Delete collector module.
上级 03d52ef3

要显示的变更太多。

To preserve performance only 1000 of 1000+ files are displayed.
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>agent-grpc</artifactId>
<groupId>org.apache.skywalking</groupId>
<version>6.0.0-alpha-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>agent-grpc-define</artifactId>
<packaging>jar</packaging>
</project>
\ No newline at end of file
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
org.apache.skywalking.apm.collector.agent.grpc.define.AgentGRPCModule
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>agent-grpc</artifactId>
<groupId>org.apache.skywalking</groupId>
<version>6.0.0-alpha-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>agent-grpc-provider</artifactId>
<properties>
<grpc.version>1.14.0</grpc.version>
<guava.version>20.0</guava.version>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>agent-grpc-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>collector-cluster-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>collector-naming-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>collector-grpc-manager-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>segment-parser-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>jvm-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>metric-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>register-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-testing</artifactId>
<version>${grpc.version}</version>
<scope>test</scope>
<exclusions>
<exclusion>
<artifactId>mockito-core</artifactId>
<groupId>org.mockito</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider;
import org.apache.skywalking.apm.collector.server.grpc.GRPCServerConfig;
/**
* @author peng-yongsheng
*/
class AgentModuleGRPCConfig extends GRPCServerConfig {
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider;
import java.io.File;
import org.apache.skywalking.apm.collector.agent.grpc.define.AgentGRPCModule;
import org.apache.skywalking.apm.collector.agent.grpc.provider.handler.ApplicationRegisterServiceHandler;
import org.apache.skywalking.apm.collector.agent.grpc.provider.handler.InstanceDiscoveryServiceHandler;
import org.apache.skywalking.apm.collector.agent.grpc.provider.handler.JVMMetricsServiceHandler;
import org.apache.skywalking.apm.collector.agent.grpc.provider.handler.NetworkAddressRegisterServiceHandler;
import org.apache.skywalking.apm.collector.agent.grpc.provider.handler.ServiceNameDiscoveryServiceHandler;
import org.apache.skywalking.apm.collector.agent.grpc.provider.handler.TraceSegmentServiceHandler;
import org.apache.skywalking.apm.collector.agent.grpc.provider.handler.naming.AgentGRPCNamingHandler;
import org.apache.skywalking.apm.collector.agent.grpc.provider.handler.naming.AgentGRPCNamingListener;
import org.apache.skywalking.apm.collector.analysis.metric.define.AnalysisMetricModule;
import org.apache.skywalking.apm.collector.analysis.segment.parser.define.AnalysisSegmentParserModule;
import org.apache.skywalking.apm.collector.cluster.ClusterModule;
import org.apache.skywalking.apm.collector.cluster.service.ModuleListenerService;
import org.apache.skywalking.apm.collector.cluster.service.ModuleRegisterService;
import org.apache.skywalking.apm.collector.core.module.ModuleDefine;
import org.apache.skywalking.apm.collector.core.module.ModuleConfig;
import org.apache.skywalking.apm.collector.core.module.ModuleProvider;
import org.apache.skywalking.apm.collector.core.module.ServiceNotProvidedException;
import org.apache.skywalking.apm.collector.core.util.Const;
import org.apache.skywalking.apm.collector.core.util.StringUtils;
import org.apache.skywalking.apm.collector.grpc.manager.GRPCManagerModule;
import org.apache.skywalking.apm.collector.grpc.manager.service.GRPCManagerService;
import org.apache.skywalking.apm.collector.naming.NamingModule;
import org.apache.skywalking.apm.collector.naming.service.NamingHandlerRegisterService;
import org.apache.skywalking.apm.collector.server.grpc.GRPCServer;
import org.eclipse.jetty.util.StringUtil;
/**
* @author peng-yongsheng
*/
public class AgentModuleGRPCProvider extends ModuleProvider {
public static final String NAME = "gRPC";
private final AgentModuleGRPCConfig config;
public AgentModuleGRPCProvider() {
super();
this.config = new AgentModuleGRPCConfig();
}
@Override
public String name() {
return NAME;
}
@Override
public Class<? extends ModuleDefine> module() {
return AgentGRPCModule.class;
}
@Override public ModuleConfig createConfigBeanIfAbsent() {
return config;
}
@Override
public void prepare() {
}
@Override
public void start() throws ServiceNotProvidedException {
String host = config.getHost();
Integer port = config.getPort();
String sslCertChainFilePath = config.getSslCertChainFilePath();
String sslPrivateKeyFilePath = config.getSslPrivateKeyFilePath();
String authentication = StringUtils.isNotEmpty(config.getAuthentication()) ? config.getAuthentication() : Const.EMPTY_STRING;
AuthenticationSimpleChecker.INSTANCE.setExpectedToken(authentication);
File sslCertChainFile = null;
File sslPrivateKeyFile = null;
if (StringUtil.isNotBlank(sslCertChainFilePath)) {
sslCertChainFile = new File(sslCertChainFilePath);
if (!(sslCertChainFile.exists() && sslCertChainFile.isFile())) {
sslCertChainFile = null;
}
}
if (StringUtil.isNotBlank(sslPrivateKeyFilePath)) {
sslPrivateKeyFile = new File(sslPrivateKeyFilePath);
if (!(sslPrivateKeyFile.exists() && sslPrivateKeyFile.isFile())) {
sslPrivateKeyFile = null;
}
}
ModuleRegisterService moduleRegisterService = getManager().find(ClusterModule.NAME).getService(ModuleRegisterService.class);
moduleRegisterService.register(AgentGRPCModule.NAME, this.name(), new AgentModuleGRPCRegistration(host, port));
AgentGRPCNamingListener namingListener = new AgentGRPCNamingListener();
ModuleListenerService moduleListenerService = getManager().find(ClusterModule.NAME).getService(ModuleListenerService.class);
moduleListenerService.addListener(namingListener);
NamingHandlerRegisterService namingHandlerRegisterService = getManager().find(NamingModule.NAME).getService(NamingHandlerRegisterService.class);
namingHandlerRegisterService.register(new AgentGRPCNamingHandler(namingListener));
GRPCManagerService managerService = getManager().find(GRPCManagerModule.NAME).getService(GRPCManagerService.class);
GRPCServer gRPCServer;
if (sslCertChainFile != null && sslPrivateKeyFile != null) {
gRPCServer = managerService.createIfAbsent(host, port, sslCertChainFile, sslPrivateKeyFile);
} else {
gRPCServer = managerService.createIfAbsent(host, port);
}
addHandlers(gRPCServer);
}
@Override
public void notifyAfterCompleted() {
}
@Override
public String[] requiredModules() {
return new String[] {ClusterModule.NAME, NamingModule.NAME, GRPCManagerModule.NAME, AnalysisSegmentParserModule.NAME, AnalysisMetricModule.NAME};
}
private void addHandlers(GRPCServer gRPCServer) {
AuthenticationSimpleChecker.INSTANCE.build(gRPCServer, new ApplicationRegisterServiceHandler(getManager()));
AuthenticationSimpleChecker.INSTANCE.build(gRPCServer, new InstanceDiscoveryServiceHandler(getManager()));
AuthenticationSimpleChecker.INSTANCE.build(gRPCServer, new ServiceNameDiscoveryServiceHandler(getManager()));
AuthenticationSimpleChecker.INSTANCE.build(gRPCServer, new JVMMetricsServiceHandler(getManager()));
AuthenticationSimpleChecker.INSTANCE.build(gRPCServer, new TraceSegmentServiceHandler(getManager()));
AuthenticationSimpleChecker.INSTANCE.build(gRPCServer, new NetworkAddressRegisterServiceHandler(getManager()));
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider;
import io.grpc.BindableService;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import io.grpc.ServerInterceptors;
import io.grpc.Status;
import org.apache.skywalking.apm.collector.core.util.StringUtils;
import org.apache.skywalking.apm.collector.server.grpc.GRPCServer;
/**
* Active the authentication token checker if expected token exists in application.yml
*
* @author wusheng
*/
public enum AuthenticationSimpleChecker {
INSTANCE;
private static final Metadata.Key<String> AUTH_HEAD_HEADER_NAME =
Metadata.Key.of("Authentication", Metadata.ASCII_STRING_MARSHALLER);
private String expectedToken = "";
public void build(GRPCServer gRPCServer, BindableService targetService) {
if (StringUtils.isNotEmpty(expectedToken)) {
gRPCServer.addHandler(ServerInterceptors.intercept(targetService, new ServerInterceptor() {
@Override
public <REQ, RESP> ServerCall.Listener<REQ> interceptCall(ServerCall<REQ, RESP> serverCall,
Metadata metadata,
ServerCallHandler<REQ, RESP> next) {
String token = metadata.get(AUTH_HEAD_HEADER_NAME);
if (expectedToken.equals(token)) {
return next.startCall(serverCall, metadata);
} else {
serverCall.close(Status.PERMISSION_DENIED, new Metadata());
return new ServerCall.Listener() {
};
}
}
}));
} else {
gRPCServer.addHandler(targetService);
}
}
public void setExpectedToken(String expectedToken) {
this.expectedToken = expectedToken;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.collector.analysis.register.define.AnalysisRegisterModule;
import org.apache.skywalking.apm.collector.analysis.register.define.service.IApplicationIDService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.grpc.GRPCHandler;
import org.apache.skywalking.apm.network.language.agent.Application;
import org.apache.skywalking.apm.network.language.agent.ApplicationMapping;
import org.apache.skywalking.apm.network.language.agent.ApplicationRegisterServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.KeyWithIntegerValue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class ApplicationRegisterServiceHandler extends ApplicationRegisterServiceGrpc.ApplicationRegisterServiceImplBase implements GRPCHandler {
private static final Logger logger = LoggerFactory.getLogger(ApplicationRegisterServiceHandler.class);
private final IApplicationIDService applicationIDService;
public ApplicationRegisterServiceHandler(ModuleManager moduleManager) {
applicationIDService = moduleManager.find(AnalysisRegisterModule.NAME).getService(IApplicationIDService.class);
}
@Override
public void applicationCodeRegister(Application request, StreamObserver<ApplicationMapping> responseObserver) {
if (logger.isDebugEnabled()) {
logger.debug("register application");
}
ApplicationMapping.Builder builder = ApplicationMapping.newBuilder();
String applicationCode = request.getApplicationCode();
int applicationId = applicationIDService.getOrCreateForApplicationCode(applicationCode);
if (applicationId != 0) {
KeyWithIntegerValue value = KeyWithIntegerValue.newBuilder().setKey(applicationCode).setValue(applicationId).build();
builder.setApplication(value);
}
responseObserver.onNext(builder.build());
responseObserver.onCompleted();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.collector.analysis.metric.define.AnalysisMetricModule;
import org.apache.skywalking.apm.collector.analysis.metric.define.service.IInstanceHeartBeatService;
import org.apache.skywalking.apm.collector.analysis.register.define.AnalysisRegisterModule;
import org.apache.skywalking.apm.collector.analysis.register.define.service.AgentOsInfo;
import org.apache.skywalking.apm.collector.analysis.register.define.service.IInstanceIDService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.grpc.GRPCHandler;
import org.apache.skywalking.apm.network.language.agent.ApplicationInstance;
import org.apache.skywalking.apm.network.language.agent.ApplicationInstanceHeartbeat;
import org.apache.skywalking.apm.network.language.agent.ApplicationInstanceMapping;
import org.apache.skywalking.apm.network.language.agent.Downstream;
import org.apache.skywalking.apm.network.language.agent.InstanceDiscoveryServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.OSInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class InstanceDiscoveryServiceHandler extends InstanceDiscoveryServiceGrpc.InstanceDiscoveryServiceImplBase implements GRPCHandler {
private static final Logger logger = LoggerFactory.getLogger(InstanceDiscoveryServiceHandler.class);
private final IInstanceIDService instanceIDService;
private final IInstanceHeartBeatService instanceHeartBeatService;
public InstanceDiscoveryServiceHandler(ModuleManager moduleManager) {
this.instanceIDService = moduleManager.find(AnalysisRegisterModule.NAME).getService(IInstanceIDService.class);
this.instanceHeartBeatService = moduleManager.find(AnalysisMetricModule.NAME).getService(IInstanceHeartBeatService.class);
}
@Override
public void registerInstance(ApplicationInstance request,
StreamObserver<ApplicationInstanceMapping> responseObserver) {
OSInfo osinfo = request.getOsinfo();
AgentOsInfo agentOsInfo = new AgentOsInfo();
agentOsInfo.setHostname(osinfo.getHostname());
agentOsInfo.setOsName(osinfo.getOsName());
agentOsInfo.setProcessNo(osinfo.getProcessNo());
agentOsInfo.setIpv4s(osinfo.getIpv4SList());
int instanceId = instanceIDService.getOrCreateByAgentUUID(request.getApplicationId(), request.getAgentUUID(), request.getRegisterTime(), agentOsInfo);
ApplicationInstanceMapping.Builder builder = ApplicationInstanceMapping.newBuilder();
builder.setApplicationId(request.getApplicationId());
builder.setApplicationInstanceId(instanceId);
responseObserver.onNext(builder.build());
responseObserver.onCompleted();
}
@Override public void heartbeat(ApplicationInstanceHeartbeat request, StreamObserver<Downstream> responseObserver) {
int instanceId = request.getApplicationInstanceId();
long heartBeatTime = request.getHeartbeatTime();
this.instanceHeartBeatService.heartBeat(instanceId, heartBeatTime);
responseObserver.onNext(Downstream.getDefaultInstance());
responseObserver.onCompleted();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import java.util.List;
import org.apache.skywalking.apm.collector.analysis.jvm.define.AnalysisJVMModule;
import org.apache.skywalking.apm.collector.analysis.jvm.define.service.*;
import org.apache.skywalking.apm.collector.analysis.metric.define.AnalysisMetricModule;
import org.apache.skywalking.apm.collector.analysis.metric.define.service.IInstanceHeartBeatService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.core.util.TimeBucketUtils;
import org.apache.skywalking.apm.collector.server.grpc.GRPCHandler;
import org.apache.skywalking.apm.network.language.agent.*;
import org.slf4j.*;
/**
* @author peng-yongsheng
*/
public class JVMMetricsServiceHandler extends JVMMetricsServiceGrpc.JVMMetricsServiceImplBase implements GRPCHandler {
private static final Logger logger = LoggerFactory.getLogger(JVMMetricsServiceHandler.class);
private final ICpuMetricService cpuMetricService;
private final IGCMetricService gcMetricService;
private final IMemoryMetricService memoryMetricService;
private final IMemoryPoolMetricService memoryPoolMetricService;
private final IInstanceHeartBeatService instanceHeartBeatService;
public JVMMetricsServiceHandler(ModuleManager moduleManager) {
this.cpuMetricService = moduleManager.find(AnalysisJVMModule.NAME).getService(ICpuMetricService.class);
this.gcMetricService = moduleManager.find(AnalysisJVMModule.NAME).getService(IGCMetricService.class);
this.memoryMetricService = moduleManager.find(AnalysisJVMModule.NAME).getService(IMemoryMetricService.class);
this.memoryPoolMetricService = moduleManager.find(AnalysisJVMModule.NAME).getService(IMemoryPoolMetricService.class);
this.instanceHeartBeatService = moduleManager.find(AnalysisMetricModule.NAME).getService(IInstanceHeartBeatService.class);
}
@Override public void collect(JVMMetrics request, StreamObserver<Downstream> responseObserver) {
int instanceId = request.getApplicationInstanceId();
if (logger.isDebugEnabled()) {
logger.debug("receive the jvm metric from application instance, id: {}", instanceId);
}
request.getMetricsList().forEach(metric -> {
long minuteTimeBucket = TimeBucketUtils.INSTANCE.getMinuteTimeBucket(metric.getTime());
sendToCpuMetricService(instanceId, minuteTimeBucket, metric.getCpu());
sendToMemoryMetricService(instanceId, minuteTimeBucket, metric.getMemoryList());
sendToMemoryPoolMetricService(instanceId, minuteTimeBucket, metric.getMemoryPoolList());
sendToGCMetricService(instanceId, minuteTimeBucket, metric.getGcList());
sendToInstanceHeartBeatService(instanceId, metric.getTime());
});
responseObserver.onNext(Downstream.newBuilder().build());
responseObserver.onCompleted();
}
private void sendToMemoryMetricService(int instanceId, long timeBucket, List<Memory> memories) {
memories.forEach(memory -> memoryMetricService.send(instanceId, timeBucket, memory.getIsHeap(), memory.getInit(), memory.getMax(), memory.getUsed(), memory.getCommitted()));
}
private void sendToMemoryPoolMetricService(int instanceId, long timeBucket,
List<MemoryPool> memoryPools) {
memoryPools.forEach(memoryPool -> memoryPoolMetricService.send(instanceId, timeBucket, memoryPool.getType().getNumber(), memoryPool.getInit(), memoryPool.getMax(), memoryPool.getUsed(), memoryPool.getCommited()));
}
private void sendToCpuMetricService(int instanceId, long timeBucket, CPU cpu) {
cpuMetricService.send(instanceId, timeBucket, cpu.getUsagePercent());
}
private void sendToGCMetricService(int instanceId, long timeBucket, List<GC> gcs) {
gcs.forEach(gc -> gcMetricService.send(instanceId, timeBucket, gc.getPhraseValue(), gc.getCount(), gc.getTime()));
}
private void sendToInstanceHeartBeatService(int instanceId, long heartBeatTime) {
instanceHeartBeatService.heartBeat(instanceId, heartBeatTime);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import com.google.protobuf.ProtocolStringList;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.collector.analysis.register.define.AnalysisRegisterModule;
import org.apache.skywalking.apm.collector.analysis.register.define.service.INetworkAddressIDService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.grpc.GRPCHandler;
import org.apache.skywalking.apm.network.language.agent.KeyWithIntegerValue;
import org.apache.skywalking.apm.network.language.agent.NetworkAddressMappings;
import org.apache.skywalking.apm.network.language.agent.NetworkAddressRegisterServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.NetworkAddresses;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class NetworkAddressRegisterServiceHandler extends NetworkAddressRegisterServiceGrpc.NetworkAddressRegisterServiceImplBase implements GRPCHandler {
private static final Logger logger = LoggerFactory.getLogger(NetworkAddressRegisterServiceHandler.class);
private final INetworkAddressIDService networkAddressIDService;
public NetworkAddressRegisterServiceHandler(ModuleManager moduleManager) {
this.networkAddressIDService = moduleManager.find(AnalysisRegisterModule.NAME).getService(INetworkAddressIDService.class);
}
@Override
public void batchRegister(NetworkAddresses request, StreamObserver<NetworkAddressMappings> responseObserver) {
if (logger.isDebugEnabled()) {
logger.debug("register application");
}
ProtocolStringList addressesList = request.getAddressesList();
NetworkAddressMappings.Builder builder = NetworkAddressMappings.newBuilder();
for (String networkAddress : addressesList) {
int addressId = networkAddressIDService.get(networkAddress);
if (addressId != 0) {
KeyWithIntegerValue value = KeyWithIntegerValue.newBuilder().setKey(networkAddress).setValue(addressId).build();
builder.addAddressIds(value);
}
}
responseObserver.onNext(builder.build());
responseObserver.onCompleted();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import java.util.List;
import org.apache.skywalking.apm.collector.analysis.register.define.AnalysisRegisterModule;
import org.apache.skywalking.apm.collector.analysis.register.define.service.IServiceNameService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.grpc.GRPCHandler;
import org.apache.skywalking.apm.network.language.agent.ServiceNameCollection;
import org.apache.skywalking.apm.network.language.agent.ServiceNameDiscoveryServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.ServiceNameElement;
import org.apache.skywalking.apm.network.language.agent.ServiceNameMappingCollection;
import org.apache.skywalking.apm.network.language.agent.ServiceNameMappingElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class ServiceNameDiscoveryServiceHandler extends ServiceNameDiscoveryServiceGrpc.ServiceNameDiscoveryServiceImplBase implements GRPCHandler {
private static final Logger logger = LoggerFactory.getLogger(ServiceNameDiscoveryServiceHandler.class);
private final IServiceNameService serviceNameService;
public ServiceNameDiscoveryServiceHandler(ModuleManager moduleManager) {
this.serviceNameService = moduleManager.find(AnalysisRegisterModule.NAME).getService(IServiceNameService.class);
}
@Override public void discovery(ServiceNameCollection request,
StreamObserver<ServiceNameMappingCollection> responseObserver) {
List<ServiceNameElement> serviceNameElementList = request.getElementsList();
ServiceNameMappingCollection.Builder builder = ServiceNameMappingCollection.newBuilder();
for (ServiceNameElement serviceNameElement : serviceNameElementList) {
int applicationId = serviceNameElement.getApplicationId();
String serviceName = serviceNameElement.getServiceName();
int srcSpanType = serviceNameElement.getSrcSpanTypeValue();
int serviceId = serviceNameService.get(applicationId, srcSpanType, serviceName);
if (serviceId != 0) {
ServiceNameMappingElement.Builder mappingElement = ServiceNameMappingElement.newBuilder();
mappingElement.setServiceId(serviceId);
mappingElement.setElement(serviceNameElement);
builder.addElements(mappingElement);
}
}
responseObserver.onNext(builder.build());
responseObserver.onCompleted();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.naming;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.skywalking.apm.collector.server.jetty.ArgumentsParseException;
import org.apache.skywalking.apm.collector.server.jetty.JettyJsonHandler;
/**
* @author peng-yongsheng
*/
public class AgentGRPCNamingHandler extends JettyJsonHandler {
private final AgentGRPCNamingListener namingListener;
public AgentGRPCNamingHandler(AgentGRPCNamingListener namingListener) {
this.namingListener = namingListener;
}
@Override public String pathSpec() {
return "/agent/gRPC";
}
@Override protected JsonElement doGet(HttpServletRequest req) throws ArgumentsParseException {
Set<String> servers = namingListener.getAddresses();
JsonArray serverArray = new JsonArray();
servers.forEach(serverArray::add);
return serverArray;
}
@Override protected JsonElement doPost(HttpServletRequest req) throws ArgumentsParseException {
throw new UnsupportedOperationException();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.naming;
import org.apache.skywalking.apm.collector.agent.grpc.define.AgentGRPCModule;
import org.apache.skywalking.apm.collector.agent.grpc.provider.AgentModuleGRPCProvider;
import org.apache.skywalking.apm.collector.cluster.ClusterModuleListener;
/**
* @author peng-yongsheng
*/
public class AgentGRPCNamingListener extends ClusterModuleListener {
public static final String PATH = "/" + AgentGRPCModule.NAME + "/" + AgentModuleGRPCProvider.NAME;
@Override public String path() {
return PATH;
}
@Override public void serverJoinNotify(String serverAddress) {
}
@Override public void serverQuitNotify(String serverAddress) {
}
}
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
org.apache.skywalking.apm.collector.agent.grpc.provider.AgentModuleGRPCProvider
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider;
import org.apache.skywalking.apm.collector.agent.grpc.define.AgentGRPCModule;
import org.apache.skywalking.apm.collector.core.module.MockModule;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.core.module.ServiceNotProvidedException;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class AgentModuleGRPCProviderTest {
private AgentModuleGRPCProvider agentModuleGRPCProvider;
@Mock
private AgentModuleGRPCConfig config;
@Mock
private ModuleManager moduleManager;
@Before
public void setUp() throws Exception {
agentModuleGRPCProvider = new AgentModuleGRPCProvider();
when(moduleManager.find(anyString())).then(invocation -> new MockModule());
Whitebox.setInternalState(agentModuleGRPCProvider, "config", config);
Whitebox.setInternalState(agentModuleGRPCProvider, "manager", moduleManager);
}
@Test
public void name() {
Assert.assertEquals(agentModuleGRPCProvider.name(), "gRPC");
}
@Test
public void module() {
Assert.assertEquals(agentModuleGRPCProvider.module(), AgentGRPCModule.class);
}
@Test
public void createConfigBeanIfAbsent() {
assertEquals(agentModuleGRPCProvider.createConfigBeanIfAbsent(), config);
}
@Test
public void prepare() {
agentModuleGRPCProvider.prepare();
}
@Test
public void start() throws ServiceNotProvidedException {
String host = "127.0.0.1";
Integer port = 12801;
Mockito.when(config.getHost()).thenReturn(host);
Mockito.when(config.getPort()).thenReturn(port);
Mockito.when(config.getAuthentication()).thenReturn("test_token");
agentModuleGRPCProvider.start();
}
@Test
public void notifyAfterCompleted() {
agentModuleGRPCProvider.notifyAfterCompleted();
}
@Test
public void requiredModules() {
String[] strings = agentModuleGRPCProvider.requiredModules();
assertTrue(strings.length > 0);
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider;
import org.apache.skywalking.apm.collector.cluster.ModuleRegistration;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class AgentModuleGRPCRegistrationTest {
private AgentModuleGRPCRegistration agentModuleGRPCRegistration;
@Before
public void setUp() throws Exception {
agentModuleGRPCRegistration = new AgentModuleGRPCRegistration("127.0.0.1", 10900);
}
@Test
public void buildValue() {
ModuleRegistration.Value value = agentModuleGRPCRegistration.buildValue();
Assert.assertEquals(value.getHostPort(),"127.0.0.1:10900");
Assert.assertEquals(value.getContextPath(),"");
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider;
import io.grpc.ServerServiceDefinition;
import io.grpc.StatusRuntimeException;
import io.grpc.testing.GrpcServerRule;
import org.apache.skywalking.apm.collector.agent.grpc.provider.handler.ApplicationRegisterServiceHandler;
import org.apache.skywalking.apm.collector.core.module.MockModule;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.ServerException;
import org.apache.skywalking.apm.collector.server.grpc.GRPCServer;
import org.apache.skywalking.apm.network.language.agent.Application;
import org.apache.skywalking.apm.network.language.agent.ApplicationMapping;
import org.apache.skywalking.apm.network.language.agent.ApplicationRegisterServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.KeyWithIntegerValue;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertEquals;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class AuthenticationSimpleCheckerTest {
@Rule
public final GrpcServerRule grpcServerRule = new GrpcServerRule().directExecutor();
@Mock
private ModuleManager moduleManager;
@Before
public void setUp() throws Exception {
when(moduleManager.find(anyString())).then(invocation -> new MockModule());
}
@Test(expected = StatusRuntimeException.class)
public void build() throws ServerException {
ApplicationRegisterServiceHandler applicationRegisterServiceHandler = new ApplicationRegisterServiceHandler(moduleManager);
MockGRPCServer mockGRPCServer = new MockGRPCServer(grpcServerRule);
mockGRPCServer.initialize();
AuthenticationSimpleChecker.INSTANCE.build(mockGRPCServer, applicationRegisterServiceHandler);
grpcServerRule.getServiceRegistry().addService(applicationRegisterServiceHandler);
ApplicationRegisterServiceGrpc.ApplicationRegisterServiceBlockingStub stub = ApplicationRegisterServiceGrpc.newBlockingStub(grpcServerRule.getChannel());
Application application = Application.newBuilder().setApplicationCode("test").build();
ApplicationMapping applicationMapping = stub.applicationCodeRegister(application);
assertEquals(applicationMapping.getApplication(), KeyWithIntegerValue.getDefaultInstance());
AuthenticationSimpleChecker.INSTANCE.setExpectedToken("test");
AuthenticationSimpleChecker.INSTANCE.build(mockGRPCServer, applicationRegisterServiceHandler);
stub.applicationCodeRegister(application);
}
@Test
public void setExpectedToken() {
}
class MockGRPCServer extends GRPCServer {
private GrpcServerRule grpcServerRule;
public MockGRPCServer(String host, int port) {
super(host, port);
}
public MockGRPCServer(GrpcServerRule grpcServerRule) {
super("127.0.0.1", 0);
this.grpcServerRule = grpcServerRule;
}
public void addHandler(ServerServiceDefinition definition) {
grpcServerRule.getServiceRegistry().addService(definition);
}
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.collector.analysis.register.define.service.IApplicationIDService;
import org.apache.skywalking.apm.collector.core.module.MockModule;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.network.language.agent.Application;
import org.apache.skywalking.apm.network.language.agent.ApplicationMapping;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class ApplicationRegisterServiceHandlerTest {
private ApplicationRegisterServiceHandler applicationRegisterServiceHandler;
@Mock
private IApplicationIDService applicationIDService;
@Before
public void setUp() {
// MockitoAnnotations.initMocks(this);
ModuleManager moduleManager = mock(ModuleManager.class);
when(moduleManager.find(anyString())).then(invocation -> new MockModule());
applicationRegisterServiceHandler = new ApplicationRegisterServiceHandler(moduleManager);
Whitebox.setInternalState(applicationRegisterServiceHandler, "applicationIDService", applicationIDService);
}
@Test
public void applicationCodeRegister() {
Application application = Application.newBuilder().setApplicationCode("test_code").build();
when(applicationIDService.getOrCreateForApplicationCode(anyString())).thenReturn(1000);
applicationRegisterServiceHandler.applicationCodeRegister(application, new StreamObserver<ApplicationMapping>() {
@Override
public void onNext(ApplicationMapping applicationMapping) {
Assert.assertTrue(applicationMapping.getApplication().getValue() == 1000);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
}
});
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import java.util.UUID;
import org.apache.skywalking.apm.collector.analysis.metric.define.service.IInstanceHeartBeatService;
import org.apache.skywalking.apm.collector.analysis.register.define.service.IInstanceIDService;
import org.apache.skywalking.apm.collector.core.module.MockModule;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.network.language.agent.ApplicationInstance;
import org.apache.skywalking.apm.network.language.agent.ApplicationInstanceHeartbeat;
import org.apache.skywalking.apm.network.language.agent.ApplicationInstanceMapping;
import org.apache.skywalking.apm.network.language.agent.Downstream;
import org.apache.skywalking.apm.network.language.agent.OSInfo;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class InstanceDiscoveryServiceHandlerTest {
private InstanceDiscoveryServiceHandler instanceDiscoveryServiceHandler;
@Mock
private IInstanceIDService instanceIDService;
@Mock
private IInstanceHeartBeatService instanceHeartBeatService;
@Before
public void setUp() throws Exception {
ModuleManager moduleManager = mock(ModuleManager.class);
when(moduleManager.find(anyString())).then(invocation -> new MockModule());
instanceDiscoveryServiceHandler = new InstanceDiscoveryServiceHandler(moduleManager);
Whitebox.setInternalState(instanceDiscoveryServiceHandler, "instanceIDService", instanceIDService);
Whitebox.setInternalState(instanceDiscoveryServiceHandler, "instanceHeartBeatService", instanceHeartBeatService);
}
@Test
public void registerInstance() {
ApplicationInstance applicationInstance = ApplicationInstance.newBuilder()
.setAgentUUID(UUID.randomUUID().toString())
.setApplicationId(10)
.setRegisterTime(System.currentTimeMillis())
.setOsinfo(
OSInfo.newBuilder()
.setOsName("MAC OS")
.setHostname("test")
.addIpv4S("127.0.0.1")
.setProcessNo(123456)
.build()
).build();
when(instanceIDService.getOrCreateByAgentUUID(anyInt(), anyString(), anyLong(), anyObject())).thenReturn(100);
instanceDiscoveryServiceHandler.registerInstance(applicationInstance, new StreamObserver<ApplicationInstanceMapping>() {
@Override
public void onNext(ApplicationInstanceMapping applicationInstanceMapping) {
Assert.assertEquals(100, applicationInstanceMapping.getApplicationInstanceId());
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
}
});
}
@Test
public void heartbeat() {
ApplicationInstanceHeartbeat heartbeat = ApplicationInstanceHeartbeat.newBuilder()
.setApplicationInstanceId(100)
.setHeartbeatTime(System.currentTimeMillis())
.build();
instanceDiscoveryServiceHandler.heartbeat(heartbeat, new StreamObserver<Downstream>() {
@Override
public void onNext(Downstream downstream) {
Assert.assertEquals(Downstream.getDefaultInstance(), downstream);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
}
});
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.collector.analysis.jvm.define.service.ICpuMetricService;
import org.apache.skywalking.apm.collector.analysis.jvm.define.service.IGCMetricService;
import org.apache.skywalking.apm.collector.analysis.jvm.define.service.IMemoryMetricService;
import org.apache.skywalking.apm.collector.analysis.jvm.define.service.IMemoryPoolMetricService;
import org.apache.skywalking.apm.collector.analysis.metric.define.service.IInstanceHeartBeatService;
import org.apache.skywalking.apm.collector.core.module.MockModule;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.network.language.agent.*;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import java.lang.management.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class JVMMetricsServiceHandlerTest {
@Mock
private ICpuMetricService cpuMetricService;
@Mock
private IGCMetricService gcMetricService;
@Mock
private IMemoryMetricService memoryMetricService;
@Mock
private IMemoryPoolMetricService memoryPoolMetricService;
@Mock
private IInstanceHeartBeatService instanceHeartBeatService;
private JVMMetricsServiceHandler jvmMetricsServiceHandler;
@Before
public void setUp() {
ModuleManager moduleManager = mock(ModuleManager.class);
when(moduleManager.find(anyString())).then(invocation -> new MockModule());
jvmMetricsServiceHandler = new JVMMetricsServiceHandler(moduleManager);
Whitebox.setInternalState(jvmMetricsServiceHandler, "cpuMetricService", cpuMetricService);
Whitebox.setInternalState(jvmMetricsServiceHandler, "gcMetricService", gcMetricService);
Whitebox.setInternalState(jvmMetricsServiceHandler, "memoryMetricService", memoryMetricService);
Whitebox.setInternalState(jvmMetricsServiceHandler, "memoryPoolMetricService", memoryPoolMetricService);
Whitebox.setInternalState(jvmMetricsServiceHandler, "instanceHeartBeatService", instanceHeartBeatService);
}
@Test
public void collect() {
List<GarbageCollectorMXBean> beans = ManagementFactory.getGarbageCollectorMXBeans();
List<GC> gcList = new ArrayList<>();
for (GarbageCollectorMXBean bean : beans) {
gcList.add(GC.newBuilder().setPhrase(GCPhrase.NEW)
.setCount(10)
.setTime(100)
.build());
}
CPU cpu = CPU.newBuilder()
.setUsagePercent(80.0d)
.build();
List<Memory> memoryList = new LinkedList<Memory>();
MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
Memory.Builder heapMemoryBuilder = Memory.newBuilder();
heapMemoryBuilder.setIsHeap(true);
heapMemoryBuilder.setInit(heapMemoryUsage.getInit());
heapMemoryBuilder.setUsed(heapMemoryUsage.getUsed());
heapMemoryBuilder.setCommitted(heapMemoryUsage.getCommitted());
heapMemoryBuilder.setMax(heapMemoryUsage.getMax());
memoryList.add(heapMemoryBuilder.build());
MemoryUsage nonHeapMemoryUsage = memoryMXBean.getNonHeapMemoryUsage();
Memory.Builder nonHeapMemoryBuilder = Memory.newBuilder();
nonHeapMemoryBuilder.setIsHeap(false);
nonHeapMemoryBuilder.setInit(nonHeapMemoryUsage.getInit());
nonHeapMemoryBuilder.setUsed(nonHeapMemoryUsage.getUsed());
nonHeapMemoryBuilder.setCommitted(nonHeapMemoryUsage.getCommitted());
nonHeapMemoryBuilder.setMax(nonHeapMemoryUsage.getMax());
memoryList.add(nonHeapMemoryBuilder.build());
List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
List<MemoryPool> poolList = new LinkedList<MemoryPool>();
for (MemoryPoolMXBean memoryPoolMXBean : memoryPoolMXBeans) {
MemoryUsage usage = memoryPoolMXBean.getUsage();
poolList.add(MemoryPool.newBuilder().setType(PoolType.CODE_CACHE_USAGE)
.setInit(usage.getInit())
.setMax(usage.getMax())
.setCommited(usage.getCommitted())
.setUsed(usage.getUsed())
.build());
}
JVMMetric jvmMetric = JVMMetric.newBuilder()
.addAllGc(gcList)
.setCpu(cpu)
.addAllMemory(memoryList)
.addAllMemoryPool(poolList)
.setTime(System.currentTimeMillis())
.build();
JVMMetrics request = JVMMetrics.newBuilder()
.addMetrics(jvmMetric)
.setApplicationInstanceId(120)
.build();
jvmMetricsServiceHandler.collect(request, new StreamObserver<Downstream>() {
@Override
public void onNext(Downstream downstream) {
Assert.assertEquals(downstream.isInitialized(), true);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
}
});
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.collector.analysis.register.define.service.INetworkAddressIDService;
import org.apache.skywalking.apm.collector.core.module.MockModule;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.network.language.agent.NetworkAddressMappings;
import org.apache.skywalking.apm.network.language.agent.NetworkAddresses;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class NetworkAddressRegisterServiceHandlerTest {
@Mock
private INetworkAddressIDService networkAddressIDService;
private NetworkAddressRegisterServiceHandler networkAddressRegisterServiceHandler;
@Before
public void setUp() throws Exception {
ModuleManager moduleManager = mock(ModuleManager.class);
when(moduleManager.find(anyString())).then(invocation -> new MockModule());
networkAddressRegisterServiceHandler = new NetworkAddressRegisterServiceHandler(moduleManager);
Whitebox.setInternalState(networkAddressRegisterServiceHandler, "networkAddressIDService", networkAddressIDService);
}
@Test
public void batchRegister() {
NetworkAddresses networkAddresses = NetworkAddresses.newBuilder()
.addAddresses("127.0.0.1:6379")
.build();
when(networkAddressIDService.get(anyString())).thenReturn(1);
networkAddressRegisterServiceHandler.batchRegister(networkAddresses, new StreamObserver<NetworkAddressMappings>() {
@Override
public void onNext(NetworkAddressMappings networkAddressMappings) {
Assert.assertEquals(networkAddressMappings.getAddressIdsList().get(0).getValue(), 1);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
}
});
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import org.junit.Assert;
import org.junit.Test;
import org.mockito.internal.util.reflection.Whitebox;
import java.util.concurrent.atomic.AtomicLong;
/**
* @author lican
*/
public class SegmentCounterTest {
@Test
public void incrementAndGet() {
//set default value in case in other test has increments
Whitebox.setInternalState(SegmentCounter.INSTANCE, "counter", new AtomicLong(0));
long l = SegmentCounter.INSTANCE.incrementAndGet();
Assert.assertEquals(1L, l);
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.collector.analysis.register.define.service.IServiceNameService;
import org.apache.skywalking.apm.collector.core.module.MockModule;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.network.language.agent.*;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class ServiceNameDiscoveryServiceHandlerTest {
@Mock
private IServiceNameService serviceNameService;
private ServiceNameDiscoveryServiceHandler serviceNameDiscoveryServiceHandler;
@Before
public void setUp() throws Exception {
ModuleManager moduleManager = mock(ModuleManager.class);
when(moduleManager.find(anyString())).then(invocation -> new MockModule());
serviceNameDiscoveryServiceHandler = new ServiceNameDiscoveryServiceHandler(moduleManager);
Whitebox.setInternalState(serviceNameDiscoveryServiceHandler, "serviceNameService", serviceNameService);
}
@Test
public void discovery() {
ServiceNameElement element = ServiceNameElement.newBuilder()
.setApplicationId(10)
.setServiceName("/hello/world")
.setSrcSpanType(SpanType.Entry)
.build();
ServiceNameCollection nameCollection = ServiceNameCollection.newBuilder()
.addElements(element)
.build();
when(serviceNameService.get(anyInt(), anyInt(), anyString())).thenReturn(1);
serviceNameDiscoveryServiceHandler.discovery(nameCollection, new StreamObserver<ServiceNameMappingCollection>() {
@Override
public void onNext(ServiceNameMappingCollection serviceNameMappingCollection) {
ServiceNameMappingElement mappingElement = serviceNameMappingCollection.getElementsList().get(0);
assertEquals(mappingElement.getElement(), element);
int serviceId = mappingElement.getServiceId();
assertEquals(serviceId, 1);
}
@Override
public void onError(Throwable throwable) {
}
@Override
public void onCompleted() {
}
});
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.collector.analysis.segment.parser.define.service.ISegmentParseService;
import org.apache.skywalking.apm.collector.core.module.MockModule;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.network.language.agent.Downstream;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class TraceSegmentServiceHandlerTest {
private TraceSegmentServiceHandler traceSegmentServiceHandler;
@Mock
private ISegmentParseService segmentParseService;
@Before
public void setUp() {
System.setProperty("debug", "true");
ModuleManager moduleManager = mock(ModuleManager.class);
when(moduleManager.find(anyString())).then(invocation -> new MockModule());
traceSegmentServiceHandler = new TraceSegmentServiceHandler(moduleManager);
Whitebox.setInternalState(traceSegmentServiceHandler, "segmentParseService", segmentParseService);
}
@Test
public void collect() {
StreamObserver<UpstreamSegment> upstreamSegmentStreamObserver = traceSegmentServiceHandler.collect(new StreamObserver<Downstream>() {
@Override
public void onNext(Downstream downstream) {
assertTrue(downstream.isInitialized());
}
@Override
public void onError(Throwable throwable) {
assertTrue(throwable instanceof IllegalArgumentException);
}
@Override
public void onCompleted() {
}
});
UpstreamSegment upstreamSegment = UpstreamSegment.newBuilder().build();
upstreamSegmentStreamObserver.onNext(upstreamSegment);
upstreamSegmentStreamObserver.onError(new IllegalArgumentException("exception"));
upstreamSegmentStreamObserver.onCompleted();
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.mock;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;
import java.util.LinkedList;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.Downstream;
import org.apache.skywalking.apm.network.language.agent.TraceSegmentServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class AgentDataMock {
private static final Logger logger = LoggerFactory.getLogger(TraceSegmentMock.class);
public static void main(String[] args) throws InterruptedException {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 11800).usePlaintext(true).build();
List<StreamObserver<UpstreamSegment>> upstreamSegments = new LinkedList<>();
upstreamSegments.add(createStreamObserver());
upstreamSegments.add(createStreamObserver());
upstreamSegments.add(createStreamObserver());
upstreamSegments.add(createStreamObserver());
RegisterMock registerMock = new RegisterMock();
registerMock.mock(channel);
TraceSegmentMock segmentMock = new TraceSegmentMock();
segmentMock.mock(upstreamSegments, new Long[] {System.currentTimeMillis()}, true);
Thread.sleep(30000);
Long[] times = TimeBuilder.INSTANCE.generateTimes();
logger.info("times size: {}", times.length);
segmentMock.mock(upstreamSegments, times, false);
JVMMetricMock jvmMetricMock = new JVMMetricMock();
jvmMetricMock.mock(channel, times);
Thread.sleep(60);
}
private static StreamObserver<UpstreamSegment> createStreamObserver() {
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 11800).usePlaintext(true).build();
TraceSegmentServiceGrpc.TraceSegmentServiceStub stub = TraceSegmentServiceGrpc.newStub(channel);
StreamObserver<UpstreamSegment> segmentStreamObserver = stub.collect(new StreamObserver<Downstream>() {
@Override public void onNext(Downstream downstream) {
}
@Override public void onError(Throwable throwable) {
}
@Override public void onCompleted() {
}
});
return segmentStreamObserver;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.mock;
import com.google.protobuf.ByteString;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.network.language.agent.*;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
/**
* @author peng-yongsheng
*/
class ConsumerMock {
void mock(StreamObserver<UpstreamSegment> segmentStreamObserver, UniqueId.Builder globalTraceId,
UniqueId.Builder segmentId, long startTimestamp, boolean isPrepare) {
UpstreamSegment.Builder upstreamSegment = UpstreamSegment.newBuilder();
upstreamSegment.addGlobalTraceIds(globalTraceId);
upstreamSegment.setSegment(createSegment(startTimestamp, segmentId, isPrepare));
segmentStreamObserver.onNext(upstreamSegment.build());
}
private ByteString createSegment(long startTimestamp, UniqueId.Builder segmentId, boolean isPrepare) {
TraceSegmentObject.Builder segment = TraceSegmentObject.newBuilder();
segment.setTraceSegmentId(segmentId);
segment.setApplicationId(-1);
segment.setApplicationInstanceId(2);
segment.addSpans(createEntrySpan(startTimestamp, isPrepare));
segment.addSpans(createLocalSpan(startTimestamp, isPrepare));
segment.addSpans(createMqEntrySpan(startTimestamp, isPrepare));
segment.addSpans(createExitSpan(startTimestamp, isPrepare));
segment.addSpans(createMqEntrySpan2(startTimestamp, isPrepare));
segment.addSpans(createExitSpan2(startTimestamp, isPrepare));
return segment.build().toByteString();
}
private SpanObject.Builder createEntrySpan(long startTimestamp, boolean isPrepare) {
SpanObject.Builder span = SpanObject.newBuilder();
span.setSpanId(0);
span.setSpanType(SpanType.Entry);
span.setSpanLayer(SpanLayer.Http);
span.setParentSpanId(-1);
span.setStartTime(startTimestamp);
span.setEndTime(startTimestamp + 2000);
span.setComponentId(ComponentsDefine.TOMCAT.getId());
if (isPrepare) {
span.setOperationName("/dubbox-case/case/dubbox-rest");
} else {
span.setOperationNameId(2);
}
span.setIsError(false);
return span;
}
private SpanObject.Builder createLocalSpan(long startTimestamp, boolean isPrepare) {
SpanObject.Builder span = SpanObject.newBuilder();
span.setSpanId(1);
span.setSpanType(SpanType.Local);
span.setParentSpanId(0);
span.setStartTime(startTimestamp + 100);
span.setEndTime(startTimestamp + 1900);
if (isPrepare) {
span.setOperationName("org.apache.skywalking.Local.do");
} else {
span.setOperationNameId(2);
}
span.setIsError(false);
return span;
}
private SpanObject.Builder createMqEntrySpan(long startTimestamp, boolean isPrepare) {
SpanObject.Builder span = SpanObject.newBuilder();
span.setSpanId(2);
span.setSpanType(SpanType.Entry);
span.setSpanLayer(SpanLayer.MQ);
span.setParentSpanId(1);
span.setStartTime(startTimestamp + 110);
span.setEndTime(startTimestamp + 1800);
span.setComponentId(ComponentsDefine.ROCKET_MQ_CONSUMER.getId());
if (isPrepare) {
span.setOperationName("org.apache.skywalking.RocketMQ");
} else {
span.setOperationNameId(2);
}
span.setIsError(false);
return span;
}
private SpanObject.Builder createExitSpan(long startTimestamp, boolean isPrepare) {
SpanObject.Builder span = SpanObject.newBuilder();
span.setSpanId(3);
span.setSpanType(SpanType.Exit);
span.setSpanLayer(SpanLayer.RPCFramework);
span.setParentSpanId(2);
span.setStartTime(startTimestamp + 120);
span.setEndTime(startTimestamp + 1780);
span.setComponentId(ComponentsDefine.DUBBO.getId());
if (isPrepare) {
span.setPeer("172.25.0.4:20880");
span.setOperationName("org.skywaking.apm.testcase.dubbo.services.GreetService.doBusiness()");
} else {
span.setOperationNameId(-1);
span.setPeerId(-1);
}
span.setIsError(false);
return span;
}
private SpanObject.Builder createMqEntrySpan2(long startTimestamp, boolean isPrepare) {
SpanObject.Builder span = SpanObject.newBuilder();
span.setSpanId(4);
span.setSpanType(SpanType.Entry);
span.setSpanLayer(SpanLayer.MQ);
span.setParentSpanId(1);
span.setStartTime(startTimestamp + 110);
span.setEndTime(startTimestamp + 1800);
span.setComponentId(ComponentsDefine.ROCKET_MQ_CONSUMER.getId());
if (isPrepare) {
span.setOperationName("org.apache.skywalking.RocketMQ");
} else {
span.setOperationNameId(2);
}
span.setIsError(false);
return span;
}
private SpanObject.Builder createExitSpan2(long startTimestamp, boolean isPrepare) {
SpanObject.Builder span = SpanObject.newBuilder();
span.setSpanId(5);
span.setSpanType(SpanType.Exit);
span.setSpanLayer(SpanLayer.RPCFramework);
span.setParentSpanId(4);
span.setStartTime(startTimestamp + 120);
span.setEndTime(startTimestamp + 1780);
span.setComponentId(ComponentsDefine.DUBBO.getId());
if (isPrepare) {
span.setPeer("172.25.0.4:20880");
span.setOperationName("org.skywaking.apm.testcase.dubbo.services.GreetService.doBusiness()");
} else {
span.setOperationNameId(-1);
span.setPeerId(-1);
}
span.setIsError(false);
return span;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.mock;
import io.grpc.ManagedChannel;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.skywalking.apm.network.language.agent.CPU;
import org.apache.skywalking.apm.network.language.agent.GC;
import org.apache.skywalking.apm.network.language.agent.GCPhrase;
import org.apache.skywalking.apm.network.language.agent.JVMMetric;
import org.apache.skywalking.apm.network.language.agent.JVMMetrics;
import org.apache.skywalking.apm.network.language.agent.JVMMetricsServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.Memory;
import org.apache.skywalking.apm.network.language.agent.MemoryPool;
import org.apache.skywalking.apm.network.language.agent.PoolType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
class JVMMetricMock {
private static final Logger logger = LoggerFactory.getLogger(JVMMetricMock.class);
void mock(ManagedChannel channel, Long[] times) {
JVMMetricsServiceGrpc.JVMMetricsServiceBlockingStub jvmMetricsServiceBlockingStub = JVMMetricsServiceGrpc.newBlockingStub(channel);
Set<Long> timeSet = new HashSet<>();
timeSet.addAll(Arrays.asList(times));
AtomicInteger increment = new AtomicInteger(0);
timeSet.forEach(timestamp -> {
JVMMetrics.Builder jvmMetrics = JVMMetrics.newBuilder();
jvmMetrics.setApplicationInstanceId(2);
JVMMetric.Builder jvmMetricBuilder = JVMMetric.newBuilder();
jvmMetricBuilder.setTime(timestamp);
buildCPUMetric(jvmMetricBuilder);
buildGCMetric(jvmMetricBuilder);
buildMemoryMetric(jvmMetricBuilder);
buildMemoryPoolMetric(jvmMetricBuilder);
jvmMetrics.addMetrics(jvmMetricBuilder.build());
jvmMetricsServiceBlockingStub.collect(jvmMetrics.build());
if (increment.incrementAndGet() % 100 == 0) {
logger.info("sending jvm metric number: {}", increment.get());
}
});
logger.info("sending jvm metric number: {}", increment.get());
}
private static void buildMemoryPoolMetric(JVMMetric.Builder metricBuilder) {
MemoryPool.Builder codeCache = MemoryPool.newBuilder();
codeCache.setInit(10);
codeCache.setMax(100);
codeCache.setCommited(10);
codeCache.setUsed(50);
codeCache.setType(PoolType.CODE_CACHE_USAGE);
metricBuilder.addMemoryPool(codeCache);
MemoryPool.Builder newGen = MemoryPool.newBuilder();
newGen.setInit(10);
newGen.setMax(100);
newGen.setCommited(10);
newGen.setUsed(50);
newGen.setType(PoolType.NEWGEN_USAGE);
metricBuilder.addMemoryPool(newGen);
MemoryPool.Builder oldGen = MemoryPool.newBuilder();
oldGen.setInit(10);
oldGen.setMax(100);
oldGen.setCommited(10);
oldGen.setUsed(50);
oldGen.setType(PoolType.OLDGEN_USAGE);
metricBuilder.addMemoryPool(oldGen);
MemoryPool.Builder survivor = MemoryPool.newBuilder();
survivor.setInit(10);
survivor.setMax(100);
survivor.setCommited(10);
survivor.setUsed(50);
survivor.setType(PoolType.SURVIVOR_USAGE);
metricBuilder.addMemoryPool(survivor);
MemoryPool.Builder permGen = MemoryPool.newBuilder();
permGen.setInit(10);
permGen.setMax(100);
permGen.setCommited(10);
permGen.setUsed(50);
permGen.setType(PoolType.PERMGEN_USAGE);
metricBuilder.addMemoryPool(permGen);
MemoryPool.Builder metaSpace = MemoryPool.newBuilder();
metaSpace.setInit(10);
metaSpace.setMax(100);
metaSpace.setCommited(10);
metaSpace.setUsed(50);
metaSpace.setType(PoolType.METASPACE_USAGE);
metricBuilder.addMemoryPool(metaSpace);
}
private static void buildMemoryMetric(JVMMetric.Builder metricBuilder) {
Memory.Builder isHeap = Memory.newBuilder();
isHeap.setInit(20);
isHeap.setMax(100);
isHeap.setCommitted(20);
isHeap.setUsed(60);
isHeap.setIsHeap(true);
metricBuilder.addMemory(isHeap);
Memory.Builder nonHeap = Memory.newBuilder();
nonHeap.setInit(20);
nonHeap.setMax(100);
nonHeap.setCommitted(20);
nonHeap.setUsed(60);
nonHeap.setIsHeap(false);
metricBuilder.addMemory(nonHeap);
}
private static void buildGCMetric(JVMMetric.Builder metricBuilder) {
GC.Builder newGC = GC.newBuilder();
newGC.setPhrase(GCPhrase.NEW);
newGC.setCount(2);
newGC.setTime(1000);
metricBuilder.addGc(newGC);
GC.Builder oldGC = GC.newBuilder();
oldGC.setPhrase(GCPhrase.OLD);
oldGC.setCount(4);
oldGC.setTime(49);
metricBuilder.addGc(oldGC);
}
private static void buildCPUMetric(JVMMetric.Builder metricBuilder) {
CPU.Builder cpu = CPU.newBuilder();
cpu.setUsagePercent(20);
metricBuilder.setCpu(cpu.build());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.mock;
import com.google.protobuf.ByteString;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.network.language.agent.RefType;
import org.apache.skywalking.apm.network.language.agent.SpanLayer;
import org.apache.skywalking.apm.network.language.agent.SpanObject;
import org.apache.skywalking.apm.network.language.agent.SpanType;
import org.apache.skywalking.apm.network.language.agent.TraceSegmentObject;
import org.apache.skywalking.apm.network.language.agent.TraceSegmentReference;
import org.apache.skywalking.apm.network.language.agent.UniqueId;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
/**
* @author peng-yongsheng
*/
class ProviderMock {
void mock(StreamObserver<UpstreamSegment> segmentStreamObserver, UniqueId.Builder globalTraceId,
UniqueId.Builder segmentId, UniqueId.Builder parentTraceSegmentId, long startTimestamp, boolean isPrepare) {
UpstreamSegment.Builder upstreamSegment = UpstreamSegment.newBuilder();
upstreamSegment.addGlobalTraceIds(globalTraceId);
upstreamSegment.setSegment(createSegment(startTimestamp, segmentId, parentTraceSegmentId, isPrepare));
segmentStreamObserver.onNext(upstreamSegment.build());
}
private ByteString createSegment(long startTimestamp, UniqueId.Builder segmentId,
UniqueId.Builder parentTraceSegmentId, boolean isPrepare) {
TraceSegmentObject.Builder segment = TraceSegmentObject.newBuilder();
segment.setTraceSegmentId(segmentId);
segment.setApplicationId(2);
segment.setApplicationInstanceId(3);
segment.addSpans(createExitSpan(startTimestamp, isPrepare));
segment.addSpans(createEntrySpan(startTimestamp, parentTraceSegmentId, isPrepare));
return segment.build().toByteString();
}
private TraceSegmentReference.Builder createReference(UniqueId.Builder parentTraceSegmentId, boolean isPrepare) {
TraceSegmentReference.Builder reference = TraceSegmentReference.newBuilder();
reference.setParentTraceSegmentId(parentTraceSegmentId);
reference.setParentApplicationInstanceId(2);
reference.setParentSpanId(1);
reference.setEntryApplicationInstanceId(2);
reference.setRefType(RefType.CrossProcess);
if (isPrepare) {
reference.setParentServiceName("/dubbox-case/case/dubbox-rest");
reference.setNetworkAddress("172.25.0.4:20880");
reference.setEntryServiceName("/dubbox-case/case/dubbox-rest");
} else {
reference.setParentServiceId(2);
reference.setNetworkAddressId(-1);
reference.setEntryServiceId(2);
}
return reference;
}
private SpanObject.Builder createExitSpan(long startTimestamp, boolean isPrepare) {
SpanObject.Builder span = SpanObject.newBuilder();
span.setSpanId(1);
span.setSpanType(SpanType.Exit);
span.setSpanLayer(SpanLayer.Database);
span.setParentSpanId(0);
span.setStartTime(startTimestamp + 510);
span.setEndTime(startTimestamp + 1490);
span.setComponentId(ComponentsDefine.MONGO_DRIVER.getId());
span.setIsError(true);
if (isPrepare) {
span.setOperationName("mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]");
span.setPeer("localhost:27017");
} else {
span.setOperationNameId(-2);
span.setPeerId(1);
}
return span;
}
private SpanObject.Builder createEntrySpan(long startTimestamp, UniqueId.Builder uniqueId, boolean isPrepare) {
SpanObject.Builder span = SpanObject.newBuilder();
span.setSpanId(0);
span.setSpanType(SpanType.Entry);
span.setSpanLayer(SpanLayer.RPCFramework);
span.setParentSpanId(-1);
span.setStartTime(startTimestamp + 500);
span.setEndTime(startTimestamp + 1500);
span.setComponentId(ComponentsDefine.DUBBO.getId());
span.setIsError(false);
span.addRefs(createReference(uniqueId, isPrepare));
if (isPrepare) {
span.setOperationName("org.skywaking.apm.testcase.dubbo.services.GreetService.doBusiness()");
} else {
span.setOperationNameId(3);
}
return span;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.mock;
import io.grpc.ManagedChannel;
import java.util.UUID;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.skywalking.apm.network.language.agent.Application;
import org.apache.skywalking.apm.network.language.agent.ApplicationInstance;
import org.apache.skywalking.apm.network.language.agent.ApplicationInstanceHeartbeat;
import org.apache.skywalking.apm.network.language.agent.ApplicationInstanceMapping;
import org.apache.skywalking.apm.network.language.agent.ApplicationMapping;
import org.apache.skywalking.apm.network.language.agent.ApplicationRegisterServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.InstanceDiscoveryServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.OSInfo;
import org.apache.skywalking.apm.network.language.agent.ServiceNameCollection;
import org.apache.skywalking.apm.network.language.agent.ServiceNameDiscoveryServiceGrpc;
import org.apache.skywalking.apm.network.language.agent.ServiceNameElement;
import org.apache.skywalking.apm.network.language.agent.ServiceNameMappingCollection;
import org.apache.skywalking.apm.network.language.agent.SpanType;
import org.apache.skywalking.apm.util.RunnableWithExceptionProtection;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
class RegisterMock {
private static final Logger logger = LoggerFactory.getLogger(RegisterMock.class);
private ApplicationRegisterServiceGrpc.ApplicationRegisterServiceBlockingStub applicationRegisterServiceBlockingStub;
private InstanceDiscoveryServiceGrpc.InstanceDiscoveryServiceBlockingStub instanceDiscoveryServiceBlockingStub;
private ServiceNameDiscoveryServiceGrpc.ServiceNameDiscoveryServiceBlockingStub serviceNameDiscoveryServiceBlockingStub;
void mock(ManagedChannel channel) throws InterruptedException {
applicationRegisterServiceBlockingStub = ApplicationRegisterServiceGrpc.newBlockingStub(channel);
instanceDiscoveryServiceBlockingStub = InstanceDiscoveryServiceGrpc.newBlockingStub(channel);
serviceNameDiscoveryServiceBlockingStub = ServiceNameDiscoveryServiceGrpc.newBlockingStub(channel);
registerConsumer();
registerProvider();
}
private void registerConsumer() throws InterruptedException {
Application.Builder application = Application.newBuilder();
application.setApplicationCode("dubbox-consumer");
ApplicationMapping applicationMapping;
do {
applicationMapping = applicationRegisterServiceBlockingStub.applicationCodeRegister(application.build());
logger.debug("application id: {}", applicationMapping.getApplication().getValue());
Thread.sleep(20);
}
while (applicationMapping.getApplication().getValue() == 0);
ApplicationInstance.Builder instance = ApplicationInstance.newBuilder();
instance.setApplicationId(applicationMapping.getApplication().getValue());
instance.setAgentUUID(UUID.randomUUID().toString());
instance.setRegisterTime(new DateTime("2017-01-01T00:01:01.001").getMillis());
OSInfo.Builder osInfo = OSInfo.newBuilder();
osInfo.setHostname("pengys");
osInfo.setOsName("MacOS XX");
osInfo.setProcessNo(1001);
osInfo.addIpv4S("10.0.0.3");
osInfo.addIpv4S("10.0.0.4");
instance.setOsinfo(osInfo);
ApplicationInstanceMapping instanceMapping;
do {
instanceMapping = instanceDiscoveryServiceBlockingStub.registerInstance(instance.build());
logger.debug("instance id: {}", instanceMapping.getApplicationInstanceId());
Thread.sleep(20);
}
while (instanceMapping.getApplicationInstanceId() == 0);
ServiceNameCollection.Builder serviceNameCollection = ServiceNameCollection.newBuilder();
ServiceNameElement.Builder serviceNameElement = ServiceNameElement.newBuilder();
serviceNameElement.setApplicationId(applicationMapping.getApplication().getValue());
serviceNameElement.setServiceName("org.skywaking.apm.testcase.dubbo.services.GreetService.doBusiness()");
serviceNameElement.setSrcSpanType(SpanType.Exit);
serviceNameCollection.addElements(serviceNameElement);
// registerServiceName(serviceNameCollection);
heartBeatScheduled(instanceMapping.getApplicationInstanceId());
}
private void registerProvider() throws InterruptedException {
Application.Builder application = Application.newBuilder();
application.setApplicationCode("dubbox-provider");
ApplicationMapping applicationMapping;
do {
applicationMapping = applicationRegisterServiceBlockingStub.applicationCodeRegister(application.build());
logger.debug("application id: {}", applicationMapping.getApplication().getValue());
Thread.sleep(20);
}
while (applicationMapping.getApplication().getValue() == 0);
ApplicationInstance.Builder instance = ApplicationInstance.newBuilder();
instance.setApplicationId(applicationMapping.getApplication().getValue());
instance.setAgentUUID(UUID.randomUUID().toString());
instance.setRegisterTime(new DateTime("2017-01-01T00:01:01.001").getMillis());
OSInfo.Builder osInfo = OSInfo.newBuilder();
osInfo.setHostname("peng-yongsheng");
osInfo.setOsName("MacOS X");
osInfo.setProcessNo(1000);
osInfo.addIpv4S("10.0.0.1");
osInfo.addIpv4S("10.0.0.2");
instance.setOsinfo(osInfo);
ApplicationInstanceMapping instanceMapping;
do {
instanceMapping = instanceDiscoveryServiceBlockingStub.registerInstance(instance.build());
logger.debug("instance id: {}", instanceMapping.getApplicationInstanceId());
Thread.sleep(20);
}
while (instanceMapping.getApplicationInstanceId() == 0);
ServiceNameCollection.Builder serviceNameCollection = ServiceNameCollection.newBuilder();
ServiceNameElement.Builder serviceNameElement = ServiceNameElement.newBuilder();
serviceNameElement.setApplicationId(applicationMapping.getApplication().getValue());
serviceNameElement.setServiceName("org.skywaking.apm.testcase.dubbo.services.GreetService.doBusiness()");
serviceNameElement.setSrcSpanType(SpanType.Entry);
serviceNameCollection.addElements(serviceNameElement);
// registerServiceName(serviceNameCollection);
heartBeatScheduled(instanceMapping.getApplicationInstanceId());
}
private void registerServiceName(ServiceNameCollection.Builder serviceNameCollection) throws InterruptedException {
ServiceNameMappingCollection serviceNameMappingCollection;
do {
logger.debug("register service name: {}", serviceNameCollection.getElements(0).getServiceName());
serviceNameMappingCollection = serviceNameDiscoveryServiceBlockingStub.discovery(serviceNameCollection.build());
logger.debug("service name mapping collection size: {}", serviceNameMappingCollection.getElementsCount());
if (serviceNameMappingCollection.getElementsCount() > 0) {
logger.debug("service id: {}", serviceNameMappingCollection.getElements(0).getServiceId());
}
Thread.sleep(20);
}
while (serviceNameMappingCollection.getElementsCount() == 0 || serviceNameMappingCollection.getElements(0).getServiceId() == 0);
}
private void heartBeatScheduled(int instanceId) {
Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(
new RunnableWithExceptionProtection(() -> heartBeat(instanceId),
t -> logger.error("instance heart beat scheduled error.", t)), 4, 1, TimeUnit.SECONDS);
}
private void heartBeat(int instanceId) {
long now = System.currentTimeMillis();
logger.debug("instance heart beat, instance id: {}, time: {}", instanceId, now);
ApplicationInstanceHeartbeat.Builder heartbeat = ApplicationInstanceHeartbeat.newBuilder();
heartbeat.setApplicationInstanceId(instanceId);
heartbeat.setHeartbeatTime(now);
instanceDiscoveryServiceBlockingStub.heartbeat(heartbeat.build());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.mock;
import java.util.LinkedList;
import java.util.List;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public enum TimeBuilder {
INSTANCE;
private static final Logger logger = LoggerFactory.getLogger(TimeBuilder.class);
private Duration[] durations = {
new Duration("2017-01-01T00:02:01.001", "2017-01-01T00:05:01.001", 20),
new Duration("2017-02-01T00:02:01.001", "2017-02-01T00:05:01.001", 20),
new Duration("2017-03-01T00:02:01.001", "2017-03-01T00:05:01.001", 20),
new Duration("2017-04-01T00:02:01.001", "2017-04-01T00:05:01.001", 20),
new Duration("2017-04-02T00:02:01.001", "2017-04-02T00:05:01.001", 20),
new Duration("2017-04-03T00:02:01.001", "2017-04-03T00:05:01.001", 20),
new Duration("2017-05-01T08:02:01.001", "2017-05-01T08:05:01.001", 20),
new Duration("2017-05-01T09:02:01.001", "2017-05-01T09:05:01.001", 20),
new Duration("2017-05-01T10:02:01.001", "2017-05-01T10:05:01.001", 20),
new Duration("2017-06-01T1:02:01.001", "2017-06-01T11:02:01.001", 100),
};
public Long[] generateTimes() {
List<Long> times = new LinkedList<>();
for (Duration duration : durations) {
DateTime start = new DateTime(duration.getStart());
DateTime end = new DateTime(duration.getEnd());
while (!start.isAfter(end)) {
for (int i = 0; i < duration.getTps(); i++) {
times.add(start.getMillis());
}
start = start.plusSeconds(1);
}
}
return times.toArray(new Long[0]);
}
class Duration {
private String start;
private String end;
private int tps;
Duration(String start, String end, int tps) {
this.start = start;
this.end = end;
this.tps = tps;
}
String getStart() {
return start;
}
String getEnd() {
return end;
}
int getTps() {
return tps;
}
}
public static void main(String[] args) {
Long[] times = TimeBuilder.INSTANCE.generateTimes();
for (Long time : times) {
DateTime dateTime = new DateTime(time);
logger.debug("{}-{}-{} {}:{}:{} {}", dateTime.year().getAsText(), dateTime.monthOfYear().getAsString(),
dateTime.dayOfMonth().getAsText(), dateTime.hourOfDay().getAsText(),
dateTime.minuteOfHour().getAsText(), dateTime.secondOfMinute().getAsText(),
dateTime.millisOfSecond().getAsText());
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.mock;
import io.grpc.stub.StreamObserver;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.UniqueId;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
class TraceSegmentMock {
private static final Logger logger = LoggerFactory.getLogger(TraceSegmentMock.class);
void mock(List<StreamObserver<UpstreamSegment>> upstreamSegments, Long[] times, boolean isPrepare) {
long startTime = System.currentTimeMillis();
long lastTime = System.currentTimeMillis();
for (int i = 0; i < times.length; i++) {
long startTimestamp = times[i];
UniqueId.Builder globalTraceId = UniqueIdBuilder.INSTANCE.create();
ConsumerMock consumerMock = new ConsumerMock();
UniqueId.Builder consumerSegmentId = UniqueIdBuilder.INSTANCE.create();
consumerMock.mock(upstreamSegments.get(i % 4), globalTraceId, consumerSegmentId, startTimestamp, isPrepare);
ProviderMock providerMock = new ProviderMock();
UniqueId.Builder providerSegmentId = UniqueIdBuilder.INSTANCE.create();
providerMock.mock(upstreamSegments.get(i % 4), globalTraceId, providerSegmentId, consumerSegmentId, startTimestamp, isPrepare);
if (i % 10000 == 0) {
logger.info("sending segment number: {}", i);
}
if (i % 10000 == 0) {
long endTime = System.currentTimeMillis();
if (endTime - startTime > 0) {
logger.info("tps: {}", ((long)i * 2 * 1000) / (endTime - startTime));
}
}
if (i % 5000 == 0) {
long endTime = System.currentTimeMillis();
long duration = endTime - lastTime;
if (duration > 0 && duration < 1000) {
try {
logger.info("begin sleeping...");
Thread.sleep(1000 - duration + 100);
logger.info("sleep: {}", 1000 - duration + 100);
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
} else {
try {
logger.info("begin sleeping...");
Thread.sleep(duration);
logger.info("sleep: {}", duration);
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
lastTime = System.currentTimeMillis();
}
}
logger.info("sending segment number: {}", times.length);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.mock;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.skywalking.apm.network.language.agent.UniqueId;
/**
* @author peng-yongsheng
*/
public enum UniqueIdBuilder {
INSTANCE;
private AtomicLong idPart = new AtomicLong(1);
UniqueId.Builder create() {
UniqueId.Builder uniqueId = UniqueId.newBuilder();
uniqueId.addIdParts(idPart.getAndIncrement());
uniqueId.addIdParts(idPart.getAndIncrement());
uniqueId.addIdParts(idPart.getAndIncrement());
return uniqueId;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.naming;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import org.apache.skywalking.apm.collector.server.jetty.ArgumentsParseException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import javax.servlet.http.HttpServletRequest;
import static org.junit.Assert.assertEquals;
/**
* @author lican
*/
public class AgentGRPCNamingHandlerTest {
private AgentGRPCNamingHandler handler;
@Mock
private HttpServletRequest request;
@Before
public void setUp() throws Exception {
AgentGRPCNamingListener listener = new AgentGRPCNamingListener();
listener.addAddress("127.0.0.1:10080");
handler = new AgentGRPCNamingHandler(listener);
}
@Test
public void pathSpec() {
assertEquals(handler.pathSpec(), "/agent/gRPC");
}
@Test
public void doGet() throws ArgumentsParseException {
JsonElement jsonElement = handler.doGet(request);
String s = ((JsonArray) jsonElement).get(0).getAsString();
assertEquals(s, "127.0.0.1:10080");
}
@Test(expected = UnsupportedOperationException.class)
public void doPost() throws ArgumentsParseException {
handler.doPost(request);
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.grpc.provider.handler.naming;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author lican
*/
public class AgentGRPCNamingListenerTest {
private AgentGRPCNamingListener listener;
@Before
public void setUp() throws Exception {
listener = new AgentGRPCNamingListener();
}
@Test
public void path() {
assertEquals(listener.path(), "/agent_gRPC/gRPC");
}
@Test
public void serverJoinNotify() {
listener.serverJoinNotify(null);
}
@Test
public void serverQuitNotify() {
listener.serverQuitNotify(null);
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.core.module;
import com.google.common.collect.Lists;
import org.apache.skywalking.apm.collector.grpc.manager.service.GRPCManagerService;
import org.apache.skywalking.apm.collector.server.grpc.GRPCServer;
import org.mockito.Mockito;
import org.mockito.internal.util.reflection.Whitebox;
import java.util.LinkedList;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.when;
/**
* @author lican
*/
public class MockModule extends ModuleDefine {
public MockModule() throws ServiceNotProvidedException {
ModuleProvider moduleProvider = Mockito.mock(ModuleProvider.class);
LinkedList<ModuleProvider> linkedList = Lists.newLinkedList();
linkedList.add(moduleProvider);
Whitebox.setInternalState(this, "loadedProviders", linkedList);
when(moduleProvider.getService(any())).then(invocation -> {
Class argumentAt = invocation.getArgumentAt(0, Class.class);
Object mock = Mockito.mock(argumentAt);
if (mock instanceof GRPCManagerService) {
when(((GRPCManagerService) mock).createIfAbsent(anyString(), anyInt())).then(invocation1 -> {
GRPCServer grpcServer = new GRPCServer("127.0.0.1", 18098);
grpcServer.initialize();
return grpcServer;
});
}
return mock;
});
}
@Override
public String name() {
return null;
}
@Override
public Class[] services() {
return new Class[0];
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~
-->
<Configuration status="debug">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout charset="UTF-8" pattern="%d - %c -%-4r [%t] %-5p %x - %m%n"/>
</Console>
</Appenders>
<Loggers>
<logger name="org.eclipse.jetty" level="INFO"/>
<logger name="org.apache.zookeeper" level="INFO"/>
<logger name="org.elasticsearch.common.network.IfConfig" level="INFO"/>
<logger name="org.apache.skywalking.apm.collector.agent.grpc.provider.handler.JVMMetricsServiceHandler" level="INFO"/>
<logger name="org.apache.skywalking.apm.collector.analysis.worker.timer.PersistenceTimer" level="INFO"/>
<logger name="io.grpc.netty" level="INFO"/>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>apm-collector-agent</artifactId>
<groupId>org.apache.skywalking</groupId>
<version>6.0.0-alpha-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>agent-grpc</artifactId>
<packaging>pom</packaging>
<modules>
<module>agent-grpc-define</module>
<module>agent-grpc-provider</module>
</modules>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>agent-jetty</artifactId>
<groupId>org.apache.skywalking</groupId>
<version>6.0.0-alpha-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>agent-jetty-define</artifactId>
</project>
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.define;
import org.apache.skywalking.apm.collector.core.module.ModuleDefine;
/**
* @author peng-yongsheng
*/
public class AgentJettyModule extends ModuleDefine {
public static final String NAME = "agent_jetty";
@Override public String name() {
return NAME;
}
@Override public Class[] services() {
return new Class[0];
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!--
~ Licensed to the Apache Software Foundation (ASF) under one or more
~ contributor license agreements. See the NOTICE file distributed with
~ this work for additional information regarding copyright ownership.
~ The ASF licenses this file to You under the Apache License, Version 2.0
~ (the "License"); you may not use this file except in compliance with
~ the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
~
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>agent-jetty</artifactId>
<groupId>org.apache.skywalking</groupId>
<version>6.0.0-alpha-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>agent-jetty-provider</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>agent-jetty-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>collector-cluster-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>collector-naming-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>collector-jetty-manager-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>register-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>segment-parser-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>jvm-define</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.apache.skywalking</groupId>
<artifactId>metric-define</artifactId>
<version>${project.version}</version>
</dependency>
</dependencies>
</project>
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import org.apache.skywalking.apm.collector.server.jetty.JettyServerConfig;
/**
* @author peng-yongsheng
*/
class AgentModuleJettyConfig extends JettyServerConfig {
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import org.apache.skywalking.apm.collector.agent.jetty.define.AgentJettyModule;
import org.apache.skywalking.apm.collector.agent.jetty.provider.handler.ApplicationRegisterServletHandler;
import org.apache.skywalking.apm.collector.agent.jetty.provider.handler.InstanceDiscoveryServletHandler;
import org.apache.skywalking.apm.collector.agent.jetty.provider.handler.InstanceHeartBeatServletHandler;
import org.apache.skywalking.apm.collector.agent.jetty.provider.handler.NetworkAddressRegisterServletHandler;
import org.apache.skywalking.apm.collector.agent.jetty.provider.handler.ServiceNameDiscoveryServiceHandler;
import org.apache.skywalking.apm.collector.agent.jetty.provider.handler.TraceSegmentServletHandler;
import org.apache.skywalking.apm.collector.agent.jetty.provider.handler.naming.AgentJettyNamingHandler;
import org.apache.skywalking.apm.collector.agent.jetty.provider.handler.naming.AgentJettyNamingListener;
import org.apache.skywalking.apm.collector.cluster.ClusterModule;
import org.apache.skywalking.apm.collector.cluster.service.ModuleListenerService;
import org.apache.skywalking.apm.collector.cluster.service.ModuleRegisterService;
import org.apache.skywalking.apm.collector.core.module.*;
import org.apache.skywalking.apm.collector.core.module.ModuleDefine;
import org.apache.skywalking.apm.collector.jetty.manager.JettyManagerModule;
import org.apache.skywalking.apm.collector.jetty.manager.service.JettyManagerService;
import org.apache.skywalking.apm.collector.naming.NamingModule;
import org.apache.skywalking.apm.collector.naming.service.NamingHandlerRegisterService;
import org.apache.skywalking.apm.collector.server.jetty.JettyServer;
/**
* @author peng-yongsheng
*/
public class AgentModuleJettyProvider extends ModuleProvider {
public static final String NAME = "jetty";
private final AgentModuleJettyConfig config;
public AgentModuleJettyProvider() {
super();
this.config = new AgentModuleJettyConfig();
}
@Override public String name() {
return NAME;
}
@Override public Class<? extends ModuleDefine> module() {
return AgentJettyModule.class;
}
@Override public ModuleConfig createConfigBeanIfAbsent() {
return config;
}
@Override public void prepare() {
}
@Override public void start() {
ModuleRegisterService moduleRegisterService = getManager().find(ClusterModule.NAME).getService(ModuleRegisterService.class);
moduleRegisterService.register(AgentJettyModule.NAME, this.name(), new AgentModuleJettyRegistration(config.getHost(), config.getPort(), config.getContextPath()));
AgentJettyNamingListener namingListener = new AgentJettyNamingListener();
ModuleListenerService moduleListenerService = getManager().find(ClusterModule.NAME).getService(ModuleListenerService.class);
moduleListenerService.addListener(namingListener);
NamingHandlerRegisterService namingHandlerRegisterService = getManager().find(NamingModule.NAME).getService(NamingHandlerRegisterService.class);
namingHandlerRegisterService.register(new AgentJettyNamingHandler(namingListener));
JettyManagerService managerService = getManager().find(JettyManagerModule.NAME).getService(JettyManagerService.class);
JettyServer jettyServer = managerService.createIfAbsent(config.getHost(), config.getPort(), config.getContextPath());
addHandlers(jettyServer);
}
@Override public void notifyAfterCompleted() {
}
@Override public String[] requiredModules() {
return new String[] {ClusterModule.NAME, NamingModule.NAME, JettyManagerModule.NAME};
}
private void addHandlers(JettyServer jettyServer) {
jettyServer.addHandler(new TraceSegmentServletHandler(getManager()));
jettyServer.addHandler(new ApplicationRegisterServletHandler(getManager()));
jettyServer.addHandler(new InstanceDiscoveryServletHandler(getManager()));
jettyServer.addHandler(new InstanceHeartBeatServletHandler(getManager()));
jettyServer.addHandler(new ServiceNameDiscoveryServiceHandler(getManager()));
jettyServer.addHandler(new NetworkAddressRegisterServletHandler(getManager()));
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import org.apache.skywalking.apm.collector.cluster.ModuleRegistration;
/**
* @author peng-yongsheng
*/
public class AgentModuleJettyRegistration extends ModuleRegistration {
private final String host;
private final int port;
private final String contextPath;
public AgentModuleJettyRegistration(String host, int port, String contextPath) {
this.host = host;
this.port = port;
this.contextPath = contextPath;
}
@Override public Value buildValue() {
return new Value(host, port, contextPath);
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.skywalking.apm.collector.analysis.register.define.AnalysisRegisterModule;
import org.apache.skywalking.apm.collector.analysis.register.define.service.IApplicationIDService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.jetty.ArgumentsParseException;
import org.apache.skywalking.apm.collector.server.jetty.JettyJsonHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class ApplicationRegisterServletHandler extends JettyJsonHandler {
private static final Logger logger = LoggerFactory.getLogger(ApplicationRegisterServletHandler.class);
private final IApplicationIDService applicationIDService;
private Gson gson = new Gson();
private static final String APPLICATION_CODE = "c";
private static final String APPLICATION_ID = "i";
public ApplicationRegisterServletHandler(ModuleManager moduleManager) {
this.applicationIDService = moduleManager.find(AnalysisRegisterModule.NAME).getService(IApplicationIDService.class);
}
@Override public String pathSpec() {
return "/application/register";
}
@Override protected JsonElement doGet(HttpServletRequest req) throws ArgumentsParseException {
throw new UnsupportedOperationException();
}
@Override protected JsonElement doPost(HttpServletRequest req) throws ArgumentsParseException {
JsonArray responseArray = new JsonArray();
try {
JsonArray applicationCodes = gson.fromJson(req.getReader(), JsonArray.class);
for (int i = 0; i < applicationCodes.size(); i++) {
String applicationCode = applicationCodes.get(i).getAsString();
int applicationId = applicationIDService.getOrCreateForApplicationCode(applicationCode);
JsonObject mapping = new JsonObject();
mapping.addProperty(APPLICATION_CODE, applicationCode);
mapping.addProperty(APPLICATION_ID, applicationId);
responseArray.add(mapping);
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return responseArray;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.skywalking.apm.collector.analysis.register.define.AnalysisRegisterModule;
import org.apache.skywalking.apm.collector.analysis.register.define.service.AgentOsInfo;
import org.apache.skywalking.apm.collector.analysis.register.define.service.IInstanceIDService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.jetty.ArgumentsParseException;
import org.apache.skywalking.apm.collector.server.jetty.JettyJsonHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class InstanceDiscoveryServletHandler extends JettyJsonHandler {
private static final Logger logger = LoggerFactory.getLogger(InstanceDiscoveryServletHandler.class);
private final IInstanceIDService instanceIDService;
private final Gson gson = new Gson();
private static final String APPLICATION_ID = "ai";
private static final String AGENT_UUID = "au";
private static final String REGISTER_TIME = "rt";
private static final String INSTANCE_ID = "ii";
private static final String OS_INFO = "oi";
public InstanceDiscoveryServletHandler(ModuleManager moduleManager) {
this.instanceIDService = moduleManager.find(AnalysisRegisterModule.NAME).getService(IInstanceIDService.class);
}
@Override public String pathSpec() {
return "/instance/register";
}
@Override protected JsonElement doGet(HttpServletRequest req) throws ArgumentsParseException {
throw new UnsupportedOperationException();
}
@Override protected JsonElement doPost(HttpServletRequest req) throws ArgumentsParseException {
JsonObject responseJson = new JsonObject();
try {
JsonObject instance = gson.fromJson(req.getReader(), JsonObject.class);
int applicationId = instance.get(APPLICATION_ID).getAsInt();
String agentUUID = instance.get(AGENT_UUID).getAsString();
long registerTime = instance.get(REGISTER_TIME).getAsLong();
JsonObject osInfoJson = instance.get(OS_INFO).getAsJsonObject();
AgentOsInfo osInfo = gson.fromJson(osInfoJson, AgentOsInfo.class);
int instanceId = instanceIDService.getOrCreateByAgentUUID(applicationId, agentUUID, registerTime, osInfo);
responseJson.addProperty(APPLICATION_ID, applicationId);
responseJson.addProperty(INSTANCE_ID, instanceId);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return responseJson;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.skywalking.apm.collector.analysis.metric.define.AnalysisMetricModule;
import org.apache.skywalking.apm.collector.analysis.metric.define.service.IInstanceHeartBeatService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.jetty.ArgumentsParseException;
import org.apache.skywalking.apm.collector.server.jetty.JettyJsonHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class InstanceHeartBeatServletHandler extends JettyJsonHandler {
private static final Logger logger = LoggerFactory.getLogger(InstanceHeartBeatServletHandler.class);
private final IInstanceHeartBeatService instanceHeartBeatService;
private final Gson gson = new Gson();
private static final String INSTANCE_ID = "ii";
private static final String HEARTBEAT_TIME = "ht";
public InstanceHeartBeatServletHandler(ModuleManager moduleManager) {
this.instanceHeartBeatService = moduleManager.find(AnalysisMetricModule.NAME).getService(IInstanceHeartBeatService.class);
}
@Override public String pathSpec() {
return "/instance/heartbeat";
}
@Override protected JsonElement doGet(HttpServletRequest req) throws ArgumentsParseException {
throw new UnsupportedOperationException();
}
@Override protected JsonElement doPost(HttpServletRequest req) throws ArgumentsParseException, IOException {
JsonObject responseJson = new JsonObject();
try {
JsonObject heartBeat = gson.fromJson(req.getReader(), JsonObject.class);
int instanceId = heartBeat.get(INSTANCE_ID).getAsInt();
long heartBeatTime = heartBeat.get(HEARTBEAT_TIME).getAsLong();
instanceHeartBeatService.heartBeat(instanceId, heartBeatTime);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return responseJson;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler;
import com.google.gson.*;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.skywalking.apm.collector.analysis.register.define.AnalysisRegisterModule;
import org.apache.skywalking.apm.collector.analysis.register.define.service.INetworkAddressIDService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.jetty.JettyJsonHandler;
import org.slf4j.*;
/**
* @author peng-yongsheng
*/
public class NetworkAddressRegisterServletHandler extends JettyJsonHandler {
private static final Logger logger = LoggerFactory.getLogger(NetworkAddressRegisterServletHandler.class);
private final INetworkAddressIDService networkAddressIDService;
private Gson gson = new Gson();
private static final String NETWORK_ADDRESS = "n";
private static final String ADDRESS_ID = "i";
public NetworkAddressRegisterServletHandler(ModuleManager moduleManager) {
this.networkAddressIDService = moduleManager.find(AnalysisRegisterModule.NAME).getService(INetworkAddressIDService.class);
}
@Override public String pathSpec() {
return "/networkAddress/register";
}
@Override protected JsonElement doGet(HttpServletRequest req) {
throw new UnsupportedOperationException();
}
@Override protected JsonElement doPost(HttpServletRequest req) {
JsonArray responseArray = new JsonArray();
try {
JsonArray networkAddresses = gson.fromJson(req.getReader(), JsonArray.class);
for (int i = 0; i < networkAddresses.size(); i++) {
String networkAddress = networkAddresses.get(i).getAsString();
if (logger.isDebugEnabled()) {
logger.debug("network address register, network address: {}", networkAddress);
}
int addressId = networkAddressIDService.get(networkAddress);
JsonObject mapping = new JsonObject();
mapping.addProperty(ADDRESS_ID, addressId);
mapping.addProperty(NETWORK_ADDRESS, networkAddress);
responseArray.add(mapping);
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return responseArray;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.skywalking.apm.collector.analysis.register.define.AnalysisRegisterModule;
import org.apache.skywalking.apm.collector.analysis.register.define.service.IServiceNameService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.jetty.ArgumentsParseException;
import org.apache.skywalking.apm.collector.server.jetty.JettyJsonHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class ServiceNameDiscoveryServiceHandler extends JettyJsonHandler {
private static final Logger logger = LoggerFactory.getLogger(ServiceNameDiscoveryServiceHandler.class);
private final IServiceNameService serviceNameService;
private final Gson gson = new Gson();
private static final String APPLICATION_ID = "ai";
private static final String SERVICE_NAME = "sn";
private static final String SRC_SPAN_TYPE = "st";
private static final String SERVICE_ID = "si";
private static final String ELEMENT = "el";
public ServiceNameDiscoveryServiceHandler(ModuleManager moduleManager) {
this.serviceNameService = moduleManager.find(AnalysisRegisterModule.NAME).getService(IServiceNameService.class);
}
@Override public String pathSpec() {
return "/servicename/discovery";
}
@Override protected JsonElement doGet(HttpServletRequest req) throws ArgumentsParseException {
throw new UnsupportedOperationException();
}
@Override protected JsonElement doPost(HttpServletRequest req) throws ArgumentsParseException {
JsonArray responseArray = new JsonArray();
try {
JsonArray services = gson.fromJson(req.getReader(), JsonArray.class);
for (JsonElement service : services) {
int applicationId = service.getAsJsonObject().get(APPLICATION_ID).getAsInt();
String serviceName = service.getAsJsonObject().get(SERVICE_NAME).getAsString();
int srcSpanType = service.getAsJsonObject().get(SRC_SPAN_TYPE).getAsInt();
int serviceId = serviceNameService.getOrCreate(applicationId, srcSpanType, serviceName);
if (serviceId != 0) {
JsonObject responseJson = new JsonObject();
responseJson.addProperty(SERVICE_ID, serviceId);
responseJson.add(ELEMENT, service);
responseArray.add(responseJson);
}
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return responseArray;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler;
import com.google.gson.JsonElement;
import com.google.gson.stream.JsonReader;
import java.io.*;
import javax.servlet.http.HttpServletRequest;
import org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader.*;
import org.apache.skywalking.apm.collector.analysis.segment.parser.define.AnalysisSegmentParserModule;
import org.apache.skywalking.apm.collector.analysis.segment.parser.define.service.ISegmentParseService;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.apache.skywalking.apm.collector.server.jetty.JettyJsonHandler;
import org.slf4j.*;
/**
* @author peng-yongsheng
*/
public class TraceSegmentServletHandler extends JettyJsonHandler {
private static final Logger logger = LoggerFactory.getLogger(TraceSegmentServletHandler.class);
private final ISegmentParseService segmentParseService;
public TraceSegmentServletHandler(ModuleManager moduleManager) {
this.segmentParseService = moduleManager.find(AnalysisSegmentParserModule.NAME).getService(ISegmentParseService.class);
}
@Override public String pathSpec() {
return "/segments";
}
@Override protected JsonElement doGet(HttpServletRequest req) {
throw new UnsupportedOperationException();
}
@Override protected JsonElement doPost(HttpServletRequest req) {
if (logger.isDebugEnabled()) {
logger.debug("receive stream segment");
}
try {
BufferedReader bufferedReader = req.getReader();
read(bufferedReader);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return null;
}
private TraceSegmentJsonReader jsonReader = new TraceSegmentJsonReader();
private void read(BufferedReader bufferedReader) throws IOException {
JsonReader reader = new JsonReader(bufferedReader);
reader.beginArray();
while (reader.hasNext()) {
TraceSegment traceSegment = jsonReader.read(reader);
segmentParseService.parse(traceSegment.getUpstreamSegment(), ISegmentParseService.Source.Agent);
}
reader.endArray();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.naming;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.skywalking.apm.collector.server.jetty.ArgumentsParseException;
import org.apache.skywalking.apm.collector.server.jetty.JettyJsonHandler;
/**
* @author peng-yongsheng
*/
public class AgentJettyNamingHandler extends JettyJsonHandler {
private final AgentJettyNamingListener namingListener;
public AgentJettyNamingHandler(AgentJettyNamingListener namingListener) {
this.namingListener = namingListener;
}
@Override public String pathSpec() {
return "/agent/jetty";
}
@Override protected JsonElement doGet(HttpServletRequest req) throws ArgumentsParseException {
Set<String> servers = namingListener.getAddresses();
JsonArray serverArray = new JsonArray();
servers.forEach(serverArray::add);
return serverArray;
}
@Override protected JsonElement doPost(HttpServletRequest req) throws ArgumentsParseException {
throw new UnsupportedOperationException();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.naming;
import org.apache.skywalking.apm.collector.agent.jetty.define.AgentJettyModule;
import org.apache.skywalking.apm.collector.agent.jetty.provider.AgentModuleJettyProvider;
import org.apache.skywalking.apm.collector.cluster.ClusterModuleListener;
/**
* @author peng-yongsheng
*/
public class AgentJettyNamingListener extends ClusterModuleListener {
public static final String PATH = "/" + AgentJettyModule.NAME + "/" + AgentModuleJettyProvider.NAME;
@Override public String path() {
return PATH;
}
@Override public void serverJoinNotify(String serverAddress) {
}
@Override public void serverQuitNotify(String serverAddress) {
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import org.apache.skywalking.apm.network.language.agent.KeyWithStringValue;
/**
* @author peng-yongsheng
*/
public class KeyWithStringValueJsonReader implements StreamJsonReader<KeyWithStringValue> {
private static final String KEY = "k";
private static final String VALUE = "v";
@Override public KeyWithStringValue read(JsonReader reader) throws IOException {
KeyWithStringValue.Builder builder = KeyWithStringValue.newBuilder();
reader.beginObject();
while (reader.hasNext()) {
switch (reader.nextName()) {
case KEY:
builder.setKey(reader.nextString());
break;
case VALUE:
builder.setValue(reader.nextString());
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return builder.build();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import org.apache.skywalking.apm.network.language.agent.LogMessage;
/**
* @author peng-yongsheng
*/
public class LogJsonReader implements StreamJsonReader<LogMessage> {
private KeyWithStringValueJsonReader keyWithStringValueJsonReader = new KeyWithStringValueJsonReader();
private static final String TIME = "ti";
private static final String LOG_DATA = "ld";
@Override public LogMessage read(JsonReader reader) throws IOException {
LogMessage.Builder builder = LogMessage.newBuilder();
reader.beginObject();
while (reader.hasNext()) {
switch (reader.nextName()) {
case TIME:
builder.setTime(reader.nextLong());
break;
case LOG_DATA:
reader.beginArray();
while (reader.hasNext()) {
builder.addData(keyWithStringValueJsonReader.read(reader));
}
reader.endArray();
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return builder.build();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import org.apache.skywalking.apm.network.language.agent.TraceSegmentReference;
/**
* @author peng-yongsheng
*/
public class ReferenceJsonReader implements StreamJsonReader<TraceSegmentReference> {
private UniqueIdJsonReader uniqueIdJsonReader = new UniqueIdJsonReader();
private static final String PARENT_TRACE_SEGMENT_ID = "pts";
private static final String PARENT_APPLICATION_INSTANCE_ID = "pii";
private static final String PARENT_SPAN_ID = "psp";
private static final String PARENT_SERVICE_ID = "psi";
private static final String PARENT_SERVICE_NAME = "psn";
private static final String NETWORK_ADDRESS_ID = "ni";
private static final String NETWORK_ADDRESS = "nn";
private static final String ENTRY_APPLICATION_INSTANCE_ID = "eii";
private static final String ENTRY_SERVICE_ID = "esi";
private static final String ENTRY_SERVICE_NAME = "esn";
private static final String REF_TYPE_VALUE = "rv";
@Override public TraceSegmentReference read(JsonReader reader) throws IOException {
TraceSegmentReference.Builder builder = TraceSegmentReference.newBuilder();
reader.beginObject();
while (reader.hasNext()) {
switch (reader.nextName()) {
case PARENT_TRACE_SEGMENT_ID:
builder.setParentTraceSegmentId(uniqueIdJsonReader.read(reader));
break;
case PARENT_APPLICATION_INSTANCE_ID:
builder.setParentApplicationInstanceId(reader.nextInt());
break;
case PARENT_SPAN_ID:
builder.setParentSpanId(reader.nextInt());
break;
case PARENT_SERVICE_ID:
builder.setParentServiceId(reader.nextInt());
break;
case PARENT_SERVICE_NAME:
builder.setParentServiceName(reader.nextString());
break;
case NETWORK_ADDRESS_ID:
builder.setNetworkAddressId(reader.nextInt());
break;
case NETWORK_ADDRESS:
builder.setNetworkAddress(reader.nextString());
break;
case ENTRY_APPLICATION_INSTANCE_ID:
builder.setEntryApplicationInstanceId(reader.nextInt());
break;
case ENTRY_SERVICE_ID:
builder.setEntryServiceId(reader.nextInt());
break;
case ENTRY_SERVICE_NAME:
builder.setEntryServiceName(reader.nextString());
break;
case REF_TYPE_VALUE:
builder.setRefTypeValue(reader.nextInt());
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return builder.build();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import org.apache.skywalking.apm.network.language.agent.TraceSegmentObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class SegmentJsonReader implements StreamJsonReader<TraceSegmentObject.Builder> {
private static final Logger logger = LoggerFactory.getLogger(SegmentJsonReader.class);
private UniqueIdJsonReader uniqueIdJsonReader = new UniqueIdJsonReader();
private SpanJsonReader spanJsonReader = new SpanJsonReader();
private static final String TRACE_SEGMENT_ID = "ts";
private static final String APPLICATION_ID = "ai";
private static final String APPLICATION_INSTANCE_ID = "ii";
private static final String SPANS = "ss";
@Override public TraceSegmentObject.Builder read(JsonReader reader) throws IOException {
TraceSegmentObject.Builder builder = TraceSegmentObject.newBuilder();
reader.beginObject();
while (reader.hasNext()) {
switch (reader.nextName()) {
case TRACE_SEGMENT_ID:
builder.setTraceSegmentId(uniqueIdJsonReader.read(reader));
if (logger.isDebugEnabled()) {
StringBuilder segmentId = new StringBuilder();
builder.getTraceSegmentId().getIdPartsList().forEach(idPart -> segmentId.append(idPart));
logger.debug("segment id: {}", segmentId);
}
break;
case APPLICATION_ID:
builder.setApplicationId(reader.nextInt());
break;
case APPLICATION_INSTANCE_ID:
builder.setApplicationInstanceId(reader.nextInt());
break;
case SPANS:
reader.beginArray();
while (reader.hasNext()) {
builder.addSpans(spanJsonReader.read(reader));
}
reader.endArray();
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return builder;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import org.apache.skywalking.apm.network.language.agent.SpanObject;
/**
* @author peng-yongsheng
*/
public class SpanJsonReader implements StreamJsonReader<SpanObject> {
private KeyWithStringValueJsonReader keyWithStringValueJsonReader = new KeyWithStringValueJsonReader();
private LogJsonReader logJsonReader = new LogJsonReader();
private ReferenceJsonReader referenceJsonReader = new ReferenceJsonReader();
private static final String SPAN_ID = "si";
private static final String SPAN_TYPE_VALUE = "tv";
private static final String SPAN_LAYER_VALUE = "lv";
private static final String PARENT_SPAN_ID = "ps";
private static final String START_TIME = "st";
private static final String END_TIME = "et";
private static final String COMPONENT_ID = "ci";
private static final String COMPONENT_NAME = "cn";
private static final String OPERATION_NAME_ID = "oi";
private static final String OPERATION_NAME = "on";
private static final String PEER_ID = "pi";
private static final String PEER = "pn";
private static final String IS_ERROR = "ie";
private static final String TRACE_SEGMENT_REFERENCE = "rs";
private static final String TAGS = "to";
private static final String LOGS = "lo";
@Override public SpanObject read(JsonReader reader) throws IOException {
SpanObject.Builder builder = SpanObject.newBuilder();
reader.beginObject();
while (reader.hasNext()) {
switch (reader.nextName()) {
case SPAN_ID:
builder.setSpanId(reader.nextInt());
break;
case SPAN_TYPE_VALUE:
builder.setSpanTypeValue(reader.nextInt());
break;
case SPAN_LAYER_VALUE:
builder.setSpanLayerValue(reader.nextInt());
break;
case PARENT_SPAN_ID:
builder.setParentSpanId(reader.nextInt());
break;
case START_TIME:
builder.setStartTime(reader.nextLong());
break;
case END_TIME:
builder.setEndTime(reader.nextLong());
break;
case COMPONENT_ID:
builder.setComponentId(reader.nextInt());
break;
case COMPONENT_NAME:
builder.setComponent(reader.nextString());
break;
case OPERATION_NAME_ID:
builder.setOperationNameId(reader.nextInt());
break;
case OPERATION_NAME:
builder.setOperationName(reader.nextString());
break;
case PEER_ID:
builder.setPeerId(reader.nextInt());
break;
case PEER:
builder.setPeer(reader.nextString());
break;
case IS_ERROR:
builder.setIsError(reader.nextBoolean());
break;
case TRACE_SEGMENT_REFERENCE:
reader.beginArray();
while (reader.hasNext()) {
builder.addRefs(referenceJsonReader.read(reader));
}
reader.endArray();
break;
case TAGS:
reader.beginArray();
while (reader.hasNext()) {
builder.addTags(keyWithStringValueJsonReader.read(reader));
}
reader.endArray();
break;
case LOGS:
reader.beginArray();
while (reader.hasNext()) {
builder.addLogs(logJsonReader.read(reader));
}
reader.endArray();
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return builder.build();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
/**
* @author peng-yongsheng
*/
public interface StreamJsonReader<T> {
T read(JsonReader reader) throws IOException;
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader;
import org.apache.skywalking.apm.network.language.agent.TraceSegmentObject;
import org.apache.skywalking.apm.network.language.agent.UniqueId;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
/**
* @author peng-yongsheng
*/
public class TraceSegment {
private UpstreamSegment.Builder builder;
public TraceSegment() {
builder = UpstreamSegment.newBuilder();
}
public void addGlobalTraceId(UniqueId.Builder globalTraceId) {
builder.addGlobalTraceIds(globalTraceId);
}
public void setTraceSegmentBuilder(TraceSegmentObject.Builder traceSegmentBuilder) {
builder.setSegment(traceSegmentBuilder.build().toByteString());
}
public UpstreamSegment getUpstreamSegment() {
return builder.build();
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public class TraceSegmentJsonReader implements StreamJsonReader<TraceSegment> {
private static final Logger logger = LoggerFactory.getLogger(TraceSegmentJsonReader.class);
private UniqueIdJsonReader uniqueIdJsonReader = new UniqueIdJsonReader();
private SegmentJsonReader segmentJsonReader = new SegmentJsonReader();
private static final String GLOBAL_TRACE_IDS = "gt";
private static final String SEGMENT = "sg";
@Override public TraceSegment read(JsonReader reader) throws IOException {
TraceSegment traceSegment = new TraceSegment();
reader.beginObject();
while (reader.hasNext()) {
switch (reader.nextName()) {
case GLOBAL_TRACE_IDS:
reader.beginArray();
while (reader.hasNext()) {
traceSegment.addGlobalTraceId(uniqueIdJsonReader.read(reader));
}
reader.endArray();
break;
case SEGMENT:
traceSegment.setTraceSegmentBuilder(segmentJsonReader.read(reader));
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return traceSegment;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider.handler.reader;
import com.google.gson.stream.JsonReader;
import java.io.IOException;
import org.apache.skywalking.apm.network.language.agent.UniqueId;
/**
* @author peng-yongsheng
*/
public class UniqueIdJsonReader implements StreamJsonReader<UniqueId.Builder> {
@Override public UniqueId.Builder read(JsonReader reader) throws IOException {
UniqueId.Builder builder = UniqueId.newBuilder();
reader.beginArray();
while (reader.hasNext()) {
builder.addIdParts(reader.nextLong());
}
reader.endArray();
return builder;
}
}
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
#
org.apache.skywalking.apm.collector.agent.jetty.provider.AgentModuleJettyProvider
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector;
import org.junit.Assert;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* @author lican
*/
public class DelegatingServletInputStream extends ServletInputStream {
private final InputStream sourceStream;
/**
* Create a DelegatingServletInputStream for the given source stream.
* @param sourceStream the source stream (never <code>null</code>)
*/
public DelegatingServletInputStream(InputStream sourceStream) {
Assert.assertNotNull("Source InputStream must not be null",sourceStream);
this.sourceStream = sourceStream;
}
/**
* Return the underlying source stream (never <code>null</code>).
*/
public final InputStream getSourceStream() {
return this.sourceStream;
}
public int read() throws IOException {
return this.sourceStream.read();
}
public void close() throws IOException {
super.close();
this.sourceStream.close();
}
@Override
public boolean isFinished() {
return false;
}
@Override
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import org.apache.skywalking.apm.collector.agent.jetty.define.AgentJettyModule;
import org.apache.skywalking.apm.collector.core.module.MockModule;
import org.apache.skywalking.apm.collector.core.module.ModuleManager;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
import static org.mockito.Matchers.anyString;
import static org.powermock.api.mockito.PowerMockito.when;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class AgentModuleJettyProviderTest {
@Mock
private ModuleManager moduleManager;
@Mock
private AgentModuleJettyConfig config;
private AgentModuleJettyProvider provider;
@Before
public void setUp() throws Exception {
when(moduleManager.find(anyString())).then(invocation -> new MockModule());
provider = new AgentModuleJettyProvider();
Whitebox.setInternalState(provider, "manager", moduleManager);
Whitebox.setInternalState(provider, "config", config);
}
@Test
public void name() {
assertEquals(provider.name(), "jetty");
}
@Test
public void module() {
assertEquals(provider.module(), AgentJettyModule.class);
}
@Test
public void createConfigBeanIfAbsent() {
assertEquals(provider.createConfigBeanIfAbsent(), config);
}
@Test
public void prepare() {
provider.prepare();
}
@Test
public void start() {
provider.start();
}
@Test
public void notifyAfterCompleted() {
provider.notifyAfterCompleted();
}
@Test
public void requiredModules() {
assertTrue(provider.requiredModules().length > 0);
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import org.apache.skywalking.apm.collector.cluster.ModuleRegistration;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.*;
/**
* @author lican
*/
@RunWith(MockitoJUnitRunner.class)
public class AgentModuleJettyRegistrationTest {
private AgentModuleJettyRegistration registration;
@Before
public void setUp() throws Exception {
registration = new AgentModuleJettyRegistration("127.0.0.1", 8080, "/");
}
@Test
public void buildValue() {
ModuleRegistration.Value value = registration.buildValue();
Assert.assertEquals(value.getHostPort(), "127.0.0.1:8080");
assertEquals(value.getContextPath(), "/");
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import com.google.gson.JsonElement;
import java.io.IOException;
/**
* @author peng-yongsheng
*/
public class ApplicationRegisterPost {
public void send(String jsonFile) throws IOException {
JsonElement application = JsonFileReader.INSTANCE.read(jsonFile);
HttpClientTools.INSTANCE.post("http://localhost:12800/application/register", application.toString());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public enum HttpClientTools {
INSTANCE;
private static final Logger logger = LoggerFactory.getLogger(HttpClientTools.class);
public String get(String url, List<NameValuePair> params) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet(url);
String paramStr = EntityUtils.toString(new UrlEncodedFormEntity(params));
httpget.setURI(new URI(httpget.getURI().toString() + "?" + paramStr));
logger.debug("executing get request {}", httpget.getURI());
try (CloseableHttpResponse response = httpClient.execute(httpget)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
httpClient.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
}
return null;
}
public String post(String url, String data) throws IOException {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost(url);
httppost.setEntity(new StringEntity(data, Consts.UTF_8));
logger.debug("executing post request {}", httppost.getURI());
try (CloseableHttpResponse response = httpClient.execute(httppost)) {
HttpEntity entity = response.getEntity();
if (entity != null) {
return EntityUtils.toString(entity);
}
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
httpClient.close();
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
return null;
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import com.google.gson.JsonElement;
import java.io.IOException;
/**
* @author peng-yongsheng
*/
public class InstanceRegisterPost {
public void send(String jsonFile) throws IOException {
JsonElement instance = JsonFileReader.INSTANCE.read(jsonFile);
HttpClientTools.INSTANCE.post("http://localhost:12800/instance/register", instance.toString());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import java.io.FileNotFoundException;
import java.io.FileReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author peng-yongsheng
*/
public enum JsonFileReader {
INSTANCE;
private final Logger logger = LoggerFactory.getLogger(JsonFileReader.class);
public JsonElement read(String fileName) throws FileNotFoundException {
String path = this.getClass().getClassLoader().getResource(fileName).getFile();
logger.debug("path: {}", path);
JsonParser jsonParser = new JsonParser();
return jsonParser.parse(new FileReader(path));
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import com.google.gson.JsonElement;
import java.io.IOException;
/**
* @author peng-yongsheng
*/
public class SegmentPost {
public static void main(String[] args) throws IOException {
ApplicationRegisterPost applicationRegisterPost = new ApplicationRegisterPost();
applicationRegisterPost.send("json/application-register-consumer.json");
applicationRegisterPost.send("json/application-register-provider.json");
InstanceRegisterPost instanceRegisterPost = new InstanceRegisterPost();
instanceRegisterPost.send("json/instance-register-consumer.json");
instanceRegisterPost.send("json/instance-register-provider.json");
ServiceNameRegisterPost serviceNameRegisterPost = new ServiceNameRegisterPost();
serviceNameRegisterPost.send("json/servicename-register-consumer.json");
serviceNameRegisterPost.send("json/servicename-register-provider.json");
JsonElement provider = JsonFileReader.INSTANCE.read("json/dubbox-provider.json");
JsonElement consumer = JsonFileReader.INSTANCE.read("json/dubbox-consumer.json");
for (int i = 0; i < 1; i++) {
HttpClientTools.INSTANCE.post("http://localhost:12800/segments", provider.toString());
HttpClientTools.INSTANCE.post("http://localhost:12800/segments", consumer.toString());
}
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.skywalking.apm.collector.agent.jetty.provider;
import com.google.gson.JsonElement;
import java.io.IOException;
/**
* @author peng-yongsheng
*/
public class ServiceNameRegisterPost {
public void send(String jsonFile) throws IOException {
JsonElement instance = JsonFileReader.INSTANCE.read(jsonFile);
HttpClientTools.INSTANCE.post("http://localhost:12800/servicename/discovery", instance.toString());
}
}
[
{
"ai": -1,
"sn": "org.skywaking.apm.testcase.dubbo.services.GreetService.doBusiness()"
}
]
\ No newline at end of file
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册