未验证 提交 6fe2041b 编写于 作者: wu-sheng's avatar wu-sheng 提交者: GitHub

Make 8.0.0 Core available. New protocol and register removed. (#4599)

Here are the list of changes we made in this pull request. Top 3 are the principle changes, others are following these principles.
1. New agent and mesh report protocol. 
2. New agent header protocol. 
3. Service register, instance register and network address register have been removed permanently.
4. Service traffic, instance traffic and network alias metrics are added to replace the service, instance and network address inventory.
5. Register process has been removed.
6. Metrics stream process supports insert only mode, especially for traffic entities.
7. Metrics stream process supports no-downsampling mode for traffic entities and network alias.
8. Remove all register mechanism and cache in the java agent.
9. Remove MONTH step in GraphQL query.
10. Update UI to remove MONTH step query, the max query range is 60 days now.
11. Simplify the TTL to metrics and record. And the unit has been formatted in Day unit. No specific TTL for ElasticSearch storage.
12. Buffer mechanism of trace receiver and mesh receiver has been removed due to no register.
13. New service id, instance id and endpoint id rules, including service relation, instance relation and endpoint relation id rules.
14. Java agent support `keep tracing` mode, meaning, agent generating tracing context even the backend is unconnected/unavailable.
15. Plugin test tool up to date, in order to support new protocol.
16. Plugin tests expected data files updated.
17. E2E tests updated.
18. Telemetry of Grafana config has been merged into one.
19. Documentation updates.
20. [TBD] InfluxDB storage implementation is not available, need @dmsolr to fix later, in order to reduce the master change block by this PR.
上级 50a54161
......@@ -35,7 +35,7 @@ jobs:
strategy:
matrix:
coordinator: ['zk']
storage: ['mysql', 'es6', 'es7', 'influxdb']
storage: ['mysql', 'es6', 'es7'] #TODO: 'influxdb'
env:
SW_COORDINATOR: ${{ matrix.coordinator }}
SW_STORAGE: ${{ matrix.storage }}
......
......@@ -44,8 +44,9 @@ jobs:
run: make docker
- name: Copy dist package
run: cp -R dist test/e2e/
- name: PHP
run: ./mvnw --batch-mode -f test/e2e/pom.xml -am -DfailIfNoTests=false verify -Dit.test=org.apache.skywalking.e2e.PHPE2E
# TODO, PHP hasn't followed the v3 protocol
# - name: PHP
# run: ./mvnw --batch-mode -f test/e2e/pom.xml -am -DfailIfNoTests=false verify -Dit.test=org.apache.skywalking.e2e.PHPE2E
- uses: actions/upload-artifact@v1
if: failure()
with:
......
......@@ -34,7 +34,7 @@ jobs:
timeout-minutes: 90
strategy:
matrix:
storage: ['h2', 'mysql', 'es6', 'es7', 'influxdb']
storage: ['h2', 'mysql', 'es6', 'es7'] #TODO: 'influxdb'
env:
SW_STORAGE: ${{ matrix.storage }}
steps:
......
......@@ -34,7 +34,7 @@ jobs:
timeout-minutes: 90
strategy:
matrix:
storage: ['mysql', 'es6', 'es7', 'influxdb']
storage: ['mysql', 'es6', 'es7'] #TODO: 'influxdb'
env:
SW_STORAGE: ${{ matrix.storage }}
steps:
......
......@@ -34,7 +34,7 @@ jobs:
timeout-minutes: 90
strategy:
matrix:
storage: ['es6', 'es7', 'influxdb']
storage: ['es6', 'es7'] #TODO: 'influxdb'
env:
SW_STORAGE: ${{ matrix.storage }}
steps:
......
......@@ -35,7 +35,7 @@ jobs:
timeout-minutes: 90
strategy:
matrix:
case: [auth, compatibility, ssl]
case: [auth, ssl]
env:
SW_SIMPLE_CASE: ${{ matrix.case }}
steps:
......@@ -58,7 +58,7 @@ jobs:
path: logs
FeatureGroup02:
name: Agent Reboot & Lua Nginx
name: Lua Nginx
runs-on: ubuntu-latest
timeout-minutes: 90
steps:
......@@ -72,10 +72,9 @@ jobs:
run: make docker
- name: Copy dist package
run: cp -R dist test/e2e/
- name: Nginx Lua
run: ./mvnw --batch-mode -f test/e2e/pom.xml -am -DfailIfNoTests=false verify -Dit.test=org.apache.skywalking.e2e.LuaE2E
- name: Agent Reboot
run: ./mvnw --batch-mode -f test/e2e/pom.xml -am -DfailIfNoTests=false verify -Dit.test=org.apache.skywalking.e2e.AgentRebootE2E
# TODO, LUA hasn't followed the v3 protocol
# - name: Nginx Lua
# run: ./mvnw --batch-mode -f test/e2e/pom.xml -am -DfailIfNoTests=false verify -Dit.test=org.apache.skywalking.e2e.LuaE2E
- uses: actions/upload-artifact@v1
if: failure()
with:
......@@ -103,4 +102,4 @@ jobs:
if: failure()
with:
name: logs
path: logs
\ No newline at end of file
path: logs
......@@ -40,22 +40,16 @@ including
1. Envoy gRPC Access Log Service (ALS) format in Istio controlled service mesh.
1. Istio telemetry format.
1. Envoy Metrics Service format.
1. Zipkin v1/v2 format.
1. Jaeger gRPC format.
1. Zipkin v1/v2 and Jaeger gRPC format with limited topology and metrics analysis.(Experimental)
# Document
- [8.x Documentation, dev version](docs/README.md).
- [7.0.0 Documentation](https://github.com/apache/skywalking/blob/v7.0.0/docs/README.md).
- [6.6 Documentation](https://github.com/apache/skywalking/blob/v6.6.0/docs/README.md).
- [6.5 Documentation](https://github.com/apache/skywalking/blob/v6.6.0/docs/README.md).
[8.x dev](docs/README.md) | [7.0](https://github.com/apache/skywalking/blob/v7.0.0/docs/README.md) | [6.6](https://github.com/apache/skywalking/blob/v6.6.0/docs/README.md), [6.5](https://github.com/apache/skywalking/blob/v6.5.0/docs/README.md).
The documentation links works after the official release.
NOTICE, SkyWalking 8.0+ uses [v3 protocols](docs/en/protocols/README.md). They are incompatible with previous released.
# Downloads
Please head to the [releases page](http://skywalking.apache.org/downloads/) to download a release of Apache SkyWalking.
# Code of conduct
This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code.
Please follow the [REPORTING GUIDELINES](CODE_OF_CONDUCT.md#reporting-guidelines) to report unacceptable behavior.
......
......@@ -36,7 +36,6 @@ public class SkywalkingSpanBuilder implements Tracer.SpanBuilder {
private boolean isExit = false;
private int port;
private String peer;
private String componentName;
private boolean isError = false;
private long startTime;
......@@ -73,9 +72,7 @@ public class SkywalkingSpanBuilder implements Tracer.SpanBuilder {
@Override
public Tracer.SpanBuilder withTag(String key, String value) {
if (Tags.COMPONENT.getKey().equals(key)) {
componentName = value;
} else if (Tags.SPAN_KIND.getKey().equals(key)) {
if (Tags.SPAN_KIND.getKey().equals(key)) {
if (Tags.SPAN_KIND_CLIENT.equals(value) || Tags.SPAN_KIND_PRODUCER.equals(value)) {
isEntry = false;
isExit = true;
......@@ -167,18 +164,10 @@ public class SkywalkingSpanBuilder implements Tracer.SpanBuilder {
return peer;
}
public String getComponentName() {
return componentName;
}
public boolean isError() {
return isError;
}
public long getStartTime() {
return startTime;
}
/**
* All the following methods are needed for activation.
*/
......
......@@ -42,7 +42,7 @@ public class ConfigInitializer {
}
private static void initNextLevel(Properties properties, Class<?> recentConfigType,
ConfigDesc parentDesc) throws IllegalArgumentException, IllegalAccessException {
ConfigDesc parentDesc) throws IllegalArgumentException, IllegalAccessException {
for (Field field : recentConfigType.getFields()) {
if (Modifier.isPublic(field.getModifiers()) && Modifier.isStatic(field.getModifiers())) {
String configKey = (parentDesc + "." + field.getName()).toLowerCase();
......@@ -73,6 +73,12 @@ public class ConfigInitializer {
*/
String value = properties.getProperty(configKey);
// Convert the value into real type
final Length lengthDefine = field.getAnnotation(Length.class);
if (lengthDefine != null) {
if (value != null && value.length() > lengthDefine.value()) {
value = value.substring(0, lengthDefine.value());
}
}
Object convertedValue = convertToTypicalType(type, value);
if (convertedValue != null) {
field.set(null, convertedValue);
......@@ -133,7 +139,7 @@ public class ConfigInitializer {
* @param valueType value type of the map
*/
private static void setForMapType(String configKey, Map<Object, Object> map, Properties properties,
final Type keyType, final Type valueType) {
final Type keyType, final Type valueType) {
Objects.requireNonNull(configKey);
Objects.requireNonNull(map);
......@@ -145,7 +151,8 @@ public class ConfigInitializer {
properties.forEach((propertyKey, propertyValue) -> {
String propertyStringKey = propertyKey.toString();
if (propertyStringKey.startsWith(prefix) && propertyStringKey.endsWith(suffix)) {
String itemKey = propertyStringKey.substring(prefix.length(), propertyStringKey.length() - suffix.length());
String itemKey = propertyStringKey.substring(
prefix.length(), propertyStringKey.length() - suffix.length());
Object keyObj;
Object valueObj;
......
......@@ -16,14 +16,19 @@
*
*/
package org.apache.skywalking.oap.server.receiver.trace.provider.parser.decorator;
package org.apache.skywalking.apm.util;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* The implementation supports immutable data format to mutable builder transformation.
* The length rule of the target field.
*/
public interface StandardBuilder {
/**
* Change the status to be mutable if it hasn't. Keep in the mutable status when this is called multiple times.
*/
void toBuilder();
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Length {
int value();
}
......@@ -18,8 +18,8 @@
package org.apache.skywalking.apm.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import org.apache.skywalking.apm.network.common.v3.Command;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
public abstract class BaseCommand {
......
......@@ -17,15 +17,13 @@
package org.apache.skywalking.apm.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.v3.Command;
public class CommandDeserializer {
public static BaseCommand deserialize(final Command command) {
final String commandName = command.getCommand();
if (ServiceResetCommand.NAME.equals(commandName)) {
return ServiceResetCommand.DESERIALIZER.deserialize(command);
} else if (ProfileTaskCommand.NAME.equals(commandName)) {
if (ProfileTaskCommand.NAME.equals(commandName)) {
return ProfileTaskCommand.DESERIALIZER.deserialize(command);
}
throw new UnsupportedCommandException(command);
......
......@@ -18,7 +18,7 @@
package org.apache.skywalking.apm.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.v3.Command;
public interface Deserializable<T extends BaseCommand> {
T deserialize(Command command);
......
/*
* 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.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
/**
* Remove the specified endpoint names from endpoint metadata cache, and re-register it. If not specified, clear whole
* endpoint metadata cache.
*/
public class EndpointResetCommand extends BaseCommand implements Serializable {
public EndpointResetCommand(String serialNumber) {
super("EndpointMetadataReset", serialNumber);
}
@Override
public Command.Builder serialize() {
return commandBuilder();
}
public void addSpecifiedEndpointName(String endpointName) {
KeyStringValuePair.Builder arguments = KeyStringValuePair.newBuilder();
arguments.setKey("EndpointName");
arguments.setValue(endpointName);
commandBuilder().addArgs(arguments);
}
}
/*
* 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.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
/**
* Remove the specified network addresses from network address metadata cache, and re-register it. If not specified,
* clear whole network address metadata cache.
*/
public class NetworkResetCommand extends BaseCommand implements Serializable {
public NetworkResetCommand(String serialNumber) {
super("NetworkAddressMetadataReset", serialNumber);
}
@Override
public Command.Builder serialize() {
return commandBuilder();
}
public void addSpecifiedNetworkAddress(String networkAddress) {
KeyStringValuePair.Builder arguments = KeyStringValuePair.newBuilder();
arguments.setKey("NetworkAddress");
arguments.setValue(networkAddress);
commandBuilder().addArgs(arguments);
}
}
......@@ -18,8 +18,8 @@
package org.apache.skywalking.apm.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import org.apache.skywalking.apm.network.common.v3.Command;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
import java.util.List;
......
......@@ -18,7 +18,7 @@
package org.apache.skywalking.apm.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.v3.Command;
public interface Serializable {
Command.Builder serialize();
......
/*
* 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.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import java.util.List;
/**
* Clear the service metadata cache and other metadata caches belong to it, and re-register them.
*/
public class ServiceResetCommand extends BaseCommand implements Serializable, Deserializable<ServiceResetCommand> {
public static final Deserializable<ServiceResetCommand> DESERIALIZER = new ServiceResetCommand("");
public static final String NAME = "ServiceMetadataReset";
public ServiceResetCommand(String serialNumber) {
super(NAME, serialNumber);
}
@Override
public Command.Builder serialize() {
return commandBuilder();
}
@Override
public ServiceResetCommand deserialize(Command command) {
final List<KeyStringValuePair> argsList = command.getArgsList();
String serialNumber = null;
for (final KeyStringValuePair pair : argsList) {
if ("SerialNumber".equals(pair.getKey())) {
serialNumber = pair.getValue();
break;
}
}
return new ServiceResetCommand(serialNumber);
}
}
......@@ -18,8 +18,8 @@
package org.apache.skywalking.apm.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import org.apache.skywalking.apm.network.common.v3.Command;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
/**
* Trace ignore sync, each configuration downstream is the full amount of data related to the received agent.
......
......@@ -17,7 +17,7 @@
package org.apache.skywalking.apm.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.v3.Command;
public class UnsupportedCommandException extends RuntimeException {
private final Command command;
......
Subproject commit eebd016e32b0808416923acf04dcd31d9eb86c09
Subproject commit 7e563891f3cfaf5c19ad086434af93aaab996719
/*
* 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.api.network.trace.component.command;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import org.apache.skywalking.apm.network.trace.component.command.ServiceResetCommand;
import org.junit.Assert;
import org.junit.Test;
public class ServiceResetCommandTest {
@Test
public void serialize_Serialize_SerialNumberIsaa() throws Exception {
ServiceResetCommand command = new ServiceResetCommand("aa");
Command.Builder builder = command.serialize();
Assert.assertEquals(ServiceResetCommand.NAME, builder.getCommand());
Assert.assertEquals("aa", builder.getArgs(0).getValue());
}
@Test
public void deserialize_NullPointerException_CommandKeyIsNotSerialNumber() throws Exception {
ServiceResetCommand command = new ServiceResetCommand("aa");
Command command1 = Command.newBuilder()
.addArgs(KeyStringValuePair.newBuilder().setKey("aa").setValue("aa").build())
.build();
boolean exception = false;
try {
command.deserialize(command1);
} catch (NullPointerException e) {
exception = true;
}
Assert.assertEquals(true, exception);
}
@Test
public void deserialize_SerialNumberCompare_CommandKeyIsSerialNumberValueIsaa() throws Exception {
ServiceResetCommand command = new ServiceResetCommand("aa");
Command command2 = Command.newBuilder()
.addArgs(KeyStringValuePair.newBuilder()
.setKey("SerialNumber")
.setValue("aa")
.build())
.build();
ServiceResetCommand deserialize2 = command.deserialize(command2);
Assert.assertEquals("aa", deserialize2.getSerialNumber());
}
@Test
public void deserialize_SerializeAndDeserialize_SerialNumberValueIsaa() throws Exception {
ServiceResetCommand command = new ServiceResetCommand("aa");
Command.Builder builder = command.serialize();
Command command3 = builder.build();
ServiceResetCommand deserialize3 = command.deserialize(command3);
Assert.assertEquals(command.getCommand(), deserialize3.getCommand());
Assert.assertEquals(command.getSerialNumber(), deserialize3.getSerialNumber());
}
}
......@@ -25,9 +25,9 @@ import io.grpc.StatusRuntimeException;
import io.grpc.internal.DnsNameResolverProvider;
import io.grpc.netty.NettyChannelBuilder;
import io.grpc.stub.StreamObserver;
import org.apache.skywalking.apm.network.common.Commands;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
import org.apache.skywalking.apm.network.language.agent.v2.TraceSegmentReportServiceGrpc;
import org.apache.skywalking.apm.network.common.v3.Commands;
import org.apache.skywalking.apm.network.language.agent.v3.SegmentObject;
import org.apache.skywalking.apm.network.language.agent.v3.TraceSegmentReportServiceGrpc;
import org.junit.Assert;
public class GRPCNoServerTest {
......@@ -39,7 +39,7 @@ public class GRPCNoServerTest {
ManagedChannel channel = channelBuilder.build();
TraceSegmentReportServiceGrpc.TraceSegmentReportServiceStub serviceStub = TraceSegmentReportServiceGrpc.newStub(channel);
final Status[] status = {null};
StreamObserver<UpstreamSegment> streamObserver = serviceStub.collect(new StreamObserver<Commands>() {
StreamObserver<SegmentObject> streamObserver = serviceStub.collect(new StreamObserver<Commands>() {
@Override
public void onNext(Commands value) {
......
......@@ -17,7 +17,7 @@
package org.apache.skywalking.apm.agent.core.commands;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.v3.Command;
/**
* Indicates that the execution of a command failed
......
......@@ -17,17 +17,14 @@
package org.apache.skywalking.apm.agent.core.commands;
import java.util.HashMap;
import java.util.Map;
import org.apache.skywalking.apm.agent.core.boot.BootService;
import org.apache.skywalking.apm.agent.core.boot.DefaultImplementor;
import org.apache.skywalking.apm.agent.core.commands.executor.NoopCommandExecutor;
import org.apache.skywalking.apm.agent.core.commands.executor.ProfileTaskCommandExecutor;
import org.apache.skywalking.apm.agent.core.commands.executor.ServiceResetCommandExecutor;
import org.apache.skywalking.apm.network.trace.component.command.BaseCommand;
import org.apache.skywalking.apm.network.trace.component.command.ProfileTaskCommand;
import org.apache.skywalking.apm.network.trace.component.command.ServiceResetCommand;
import java.util.HashMap;
import java.util.Map;
/**
* Command executor service, acts like a routing executor that controls all commands' execution, is responsible for
......@@ -44,9 +41,6 @@ public class CommandExecutorService implements BootService, CommandExecutor {
public void prepare() throws Throwable {
commandExecutorMap = new HashMap<String, CommandExecutor>();
// Register all the supported commands with their executors here
commandExecutorMap.put(ServiceResetCommand.NAME, new ServiceResetCommandExecutor());
// Profile task executor
commandExecutorMap.put(ProfileTaskCommand.NAME, new ProfileTaskCommandExecutor());
}
......
......@@ -27,8 +27,8 @@ import org.apache.skywalking.apm.agent.core.boot.DefaultNamedThreadFactory;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.network.common.Command;
import org.apache.skywalking.apm.network.common.Commands;
import org.apache.skywalking.apm.network.common.v3.Command;
import org.apache.skywalking.apm.network.common.v3.Commands;
import org.apache.skywalking.apm.network.trace.component.command.BaseCommand;
import org.apache.skywalking.apm.network.trace.component.command.CommandDeserializer;
import org.apache.skywalking.apm.network.trace.component.command.UnsupportedCommandException;
......
/*
* 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.agent.core.commands.executor;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.commands.CommandExecutionException;
import org.apache.skywalking.apm.agent.core.commands.CommandExecutor;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.agent.core.dictionary.NetworkAddressDictionary;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.remote.ServiceRegisterClient;
import org.apache.skywalking.apm.network.trace.component.command.BaseCommand;
import org.apache.skywalking.apm.network.trace.component.command.ServiceResetCommand;
/**
* Command executor that executes the {@link ServiceResetCommand} command
*/
public class ServiceResetCommandExecutor implements CommandExecutor {
private static final ILog LOGGER = LogManager.getLogger(ServiceResetCommandExecutor.class);
@Override
public void execute(final BaseCommand command) throws CommandExecutionException {
LOGGER.warn("Received ServiceResetCommand, a re-register task is scheduled.");
ServiceManager.INSTANCE.findService(ServiceRegisterClient.class).coolDown();
RemoteDownstreamConfig.Agent.SERVICE_ID = DictionaryUtil.nullValue();
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID = DictionaryUtil.nullValue();
RemoteDownstreamConfig.Agent.INSTANCE_REGISTERED_TIME = DictionaryUtil.nullValue();
NetworkAddressDictionary.INSTANCE.clear();
}
}
......@@ -24,6 +24,7 @@ import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.logging.core.LogLevel;
import org.apache.skywalking.apm.agent.core.logging.core.LogOutput;
import org.apache.skywalking.apm.agent.core.logging.core.WriterFactory;
import org.apache.skywalking.apm.util.Length;
/**
* This is the core config in sniffer agent.
......@@ -40,6 +41,7 @@ public class Config {
* Service name is showed in skywalking-ui. Suggestion: set a unique name for each service, service instance
* nodes share the same code
*/
@Length(50)
public static String SERVICE_NAME = "";
/**
......@@ -74,7 +76,8 @@ public class Config {
/**
* The identifier of the instance
*/
public static String INSTANCE_UUID = "";
@Length(50)
public volatile static String INSTANCE_NAME = "";
/*
* service instance properties
......@@ -88,12 +91,6 @@ public class Config {
*/
public static int CAUSE_EXCEPTION_DEPTH = 5;
/**
* How long should the agent wait (in minute) before re-registering to the OAP server after receiving reset
* command
*/
public static int COOL_DOWN_THRESHOLD = 10;
/**
* Force reconnection period of grpc, based on grpc_channel_check_interval. If count of check grpc channel
* status more than this number. The channel check will call channel.getState(true) to requestConnection.
......@@ -107,6 +104,11 @@ public class Config {
* In the current practice, we don't recommend the length over 190.
*/
public static int OPERATION_NAME_THRESHOLD = 150;
/**
* Keep tracing even the backend is not available.
*/
public static boolean KEEP_TRACING = false;
}
public static class Collector {
......@@ -173,13 +175,6 @@ public class Config {
public static int BUFFER_SIZE = 300;
}
public static class Dictionary {
/**
* The buffer size of the registered network addresses.
*/
public static int NETWORK_ADDRESS_BUFFER_SIZE = 10 * 10000;
}
public static class Logging {
/**
* Log file name.
......
/*
* 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.agent.core.conf;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
/**
* The <code>RemoteDownstreamConfig</code> includes configurations from collector side. All of them initialized null,
* Null-Value or empty collection.
*/
public class RemoteDownstreamConfig {
public static class Agent {
public volatile static int SERVICE_ID = DictionaryUtil.nullValue();
public volatile static int SERVICE_INSTANCE_ID = DictionaryUtil.nullValue();
public volatile static long INSTANCE_REGISTERED_TIME = DictionaryUtil.nullValue();
}
}
......@@ -60,7 +60,7 @@ public interface AbstractTracerContext {
*
* @return the string represents the id.
*/
String getReadableGlobalTraceId();
String getReadablePrimaryTraceId();
/**
* Create an entry span
......
......@@ -19,12 +19,10 @@
package org.apache.skywalking.apm.agent.core.context;
import java.io.Serializable;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.apache.skywalking.apm.agent.core.base64.Base64;
import org.apache.skywalking.apm.agent.core.context.ids.DistributedTraceId;
import org.apache.skywalking.apm.agent.core.context.ids.ID;
import org.apache.skywalking.apm.agent.core.context.ids.PropagatedTraceId;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.agent.core.conf.Constants;
import org.apache.skywalking.apm.util.StringUtil;
/**
......@@ -32,50 +30,23 @@ import org.apache.skywalking.apm.util.StringUtil;
* TracingContext}.
* <p>
*/
@Setter
@Getter
public class ContextCarrier implements Serializable {
private ID traceSegmentId;
/**
* id of parent span. It is unique in parent trace segment.
*/
private String traceId;
private String traceSegmentId;
private int spanId = -1;
/**
* id of parent application instance, it's the id assigned by collector.
*/
private int parentServiceInstanceId = DictionaryUtil.nullValue();
/**
* id of first application instance in this distributed trace, it's the id assigned by collector.
*/
private int entryServiceInstanceId = DictionaryUtil.nullValue();
/**
* peer(ipv4s/ipv6/hostname + port) of the server, from client side.
*/
private String peerHost;
/**
* Operation/Service name of the first one in this distributed trace. This name may be compressed to an integer.
*/
private String entryEndpointName;
/**
* Operation/Service name of the parent one in this distributed trace. This name may be compressed to an integer.
*/
private String parentEndpointName;
/**
* {@link DistributedTraceId}, also known as TraceId
*/
private DistributedTraceId primaryDistributedTraceId;
private String parentService = Constants.EMPTY_STRING;
private String parentServiceInstance = Constants.EMPTY_STRING;
private String parentEndpoint;
private String addressUsedAtClient;
private CorrelationContext correlationContext = new CorrelationContext();
public CarrierItem items() {
SW8CorrelationCarrierItem sw8CorrelationCarrierItem = new SW8CorrelationCarrierItem(correlationContext, null);
SW6CarrierItem sw6CarrierItem = new SW6CarrierItem(this, sw8CorrelationCarrierItem);
return new CarrierItemHead(sw6CarrierItem);
SW8CarrierItem sw8CarrierItem = new SW8CarrierItem(this, sw8CorrelationCarrierItem);
return new CarrierItemHead(sw8CarrierItem);
}
/**
......@@ -88,14 +59,13 @@ public class ContextCarrier implements Serializable {
return StringUtil.join(
'-',
"1",
Base64.encode(this.getPrimaryDistributedTraceId().encode()),
Base64.encode(this.getTraceSegmentId().encode()),
Base64.encode(this.getTraceId()),
Base64.encode(this.getTraceSegmentId()),
this.getSpanId() + "",
this.getParentServiceInstanceId() + "",
this.getEntryServiceInstanceId() + "",
Base64.encode(this.getPeerHost()),
Base64.encode(this.getEntryEndpointName()),
Base64.encode(this.getParentEndpointName())
Base64.encode(this.getParentService()),
Base64.encode(this.getParentServiceInstance()),
Base64.encode(this.getParentEndpoint()),
Base64.encode(this.getAddressUsedAtClient())
);
}
return "";
......@@ -110,24 +80,19 @@ public class ContextCarrier implements Serializable {
if (text == null) {
return this;
}
// if this carrier is initialized by v2, don't do deserialize again for performance.
if (this.isValid(HeaderVersion.v2)) {
return this;
}
if (HeaderVersion.v2 == version) {
String[] parts = text.split("-", 9);
if (parts.length == 9) {
if (HeaderVersion.v3.equals(version)) {
String[] parts = text.split("-", 8);
if (parts.length == 8) {
try {
// parts[0] is sample flag, always trace if header exists.
this.primaryDistributedTraceId = new PropagatedTraceId(Base64.decode2UTFString(parts[1]));
this.traceSegmentId = new ID(Base64.decode2UTFString(parts[2]));
this.traceId = Base64.decode2UTFString(parts[1]);
this.traceSegmentId = Base64.decode2UTFString(parts[2]);
this.spanId = Integer.parseInt(parts[3]);
this.parentServiceInstanceId = Integer.parseInt(parts[4]);
this.entryServiceInstanceId = Integer.parseInt(parts[5]);
this.peerHost = Base64.decode2UTFString(parts[6]);
this.entryEndpointName = Base64.decode2UTFString(parts[7]);
this.parentEndpointName = Base64.decode2UTFString(parts[8]);
} catch (NumberFormatException ignored) {
this.parentService = Base64.decode2UTFString(parts[4]);
this.parentServiceInstance = Base64.decode2UTFString(parts[5]);
this.parentEndpoint = Base64.decode2UTFString(parts[6]);
this.addressUsedAtClient = Base64.decode2UTFString(parts[7]);
} catch (IllegalArgumentException ignored) {
}
}
......@@ -136,7 +101,7 @@ public class ContextCarrier implements Serializable {
}
public boolean isValid() {
return isValid(HeaderVersion.v2);
return isValid(HeaderVersion.v3);
}
/**
......@@ -145,95 +110,23 @@ public class ContextCarrier implements Serializable {
* @return true for unbroken {@link ContextCarrier} or no-initialized. Otherwise, false;
*/
boolean isValid(HeaderVersion version) {
if (HeaderVersion.v2 == version) {
return traceSegmentId != null
&& traceSegmentId.isValid()
if (HeaderVersion.v3 == version) {
return StringUtil.isNotEmpty(traceId)
&& StringUtil.isNotEmpty(traceSegmentId)
&& getSpanId() > -1
&& parentServiceInstanceId != DictionaryUtil.nullValue()
&& entryServiceInstanceId != DictionaryUtil.nullValue()
&& !StringUtil.isEmpty(peerHost)
&& primaryDistributedTraceId != null;
&& StringUtil.isNotEmpty(parentService)
&& StringUtil.isNotEmpty(parentServiceInstance)
&& StringUtil.isNotEmpty(parentEndpoint)
&& StringUtil.isNotEmpty(addressUsedAtClient);
}
return false;
}
public String getEntryEndpointName() {
return entryEndpointName;
}
void setEntryEndpointName(String entryEndpointName) {
this.entryEndpointName = '#' + entryEndpointName;
}
void setParentEndpointName(String parentEndpointName) {
this.parentEndpointName = '#' + parentEndpointName;
}
public ID getTraceSegmentId() {
return traceSegmentId;
}
public int getSpanId() {
return spanId;
}
void setTraceSegmentId(ID traceSegmentId) {
this.traceSegmentId = traceSegmentId;
}
void setSpanId(int spanId) {
this.spanId = spanId;
}
public int getParentServiceInstanceId() {
return parentServiceInstanceId;
}
void setParentServiceInstanceId(int parentServiceInstanceId) {
this.parentServiceInstanceId = parentServiceInstanceId;
}
public String getPeerHost() {
return peerHost;
}
void setPeerHost(String peerHost) {
this.peerHost = '#' + peerHost;
}
void setPeerId(int peerId) {
this.peerHost = peerId + "";
}
public DistributedTraceId getDistributedTraceId() {
return primaryDistributedTraceId;
}
public void setDistributedTraceIds(List<DistributedTraceId> distributedTraceIds) {
this.primaryDistributedTraceId = distributedTraceIds.get(0);
}
private DistributedTraceId getPrimaryDistributedTraceId() {
return primaryDistributedTraceId;
}
public String getParentEndpointName() {
return parentEndpointName;
}
public int getEntryServiceInstanceId() {
return entryServiceInstanceId;
}
public void setEntryServiceInstanceId(int entryServiceInstanceId) {
this.entryServiceInstanceId = entryServiceInstanceId;
}
public CorrelationContext getCorrelationContext() {
return correlationContext;
}
public enum HeaderVersion {
v2
v3
}
}
......@@ -20,10 +20,8 @@ package org.apache.skywalking.apm.agent.core.context;
import org.apache.skywalking.apm.agent.core.boot.BootService;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.sampling.SamplingService;
......@@ -54,18 +52,11 @@ public class ContextManager implements BootService {
}
context = new IgnoredTracerContext();
} else {
if (RemoteDownstreamConfig.Agent.SERVICE_ID != DictionaryUtil.nullValue()
&& RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID != DictionaryUtil.nullValue()) {
if (EXTEND_SERVICE == null) {
EXTEND_SERVICE = ServiceManager.INSTANCE.findService(ContextManagerExtendService.class);
}
context = EXTEND_SERVICE.createTraceContext(operationName, forceSampling);
} else {
/*
* Can't register to collector, no need to trace anything.
*/
context = new IgnoredTracerContext();
if (EXTEND_SERVICE == null) {
EXTEND_SERVICE = ServiceManager.INSTANCE.findService(ContextManagerExtendService.class);
}
context = EXTEND_SERVICE.createTraceContext(operationName, forceSampling);
}
CONTEXT.set(context);
}
......@@ -84,7 +75,7 @@ public class ContextManager implements BootService {
if (segment == null) {
return "N/A";
} else {
return segment.getReadableGlobalTraceId();
return segment.getReadablePrimaryTraceId();
}
}
......@@ -149,7 +140,7 @@ public class ContextManager implements BootService {
if (snapshot == null) {
throw new IllegalArgumentException("ContextSnapshot can't be null.");
}
if (snapshot.isValid() && !snapshot.isFromCurrent()) {
if (!snapshot.isFromCurrent()) {
get().continued(snapshot);
}
}
......
......@@ -22,13 +22,18 @@ import org.apache.skywalking.apm.agent.core.boot.BootService;
import org.apache.skywalking.apm.agent.core.boot.DefaultImplementor;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.remote.GRPCChannelListener;
import org.apache.skywalking.apm.agent.core.remote.GRPCChannelManager;
import org.apache.skywalking.apm.agent.core.remote.GRPCChannelStatus;
import org.apache.skywalking.apm.agent.core.sampling.SamplingService;
@DefaultImplementor
public class ContextManagerExtendService implements BootService {
public class ContextManagerExtendService implements BootService, GRPCChannelListener {
private volatile GRPCChannelStatus status = GRPCChannelStatus.DISCONNECT;
@Override
public void prepare() {
ServiceManager.INSTANCE.findService(GRPCChannelManager.class).addChannelListener(this);
}
@Override
......@@ -48,6 +53,13 @@ public class ContextManagerExtendService implements BootService {
public AbstractTracerContext createTraceContext(String operationName, boolean forceSampling) {
AbstractTracerContext context;
/*
* Don't trace anything if the backend is not available.
*/
if (!Config.Agent.KEEP_TRACING && GRPCChannelStatus.DISCONNECT.equals(status)) {
return new IgnoredTracerContext();
}
int suffixIdx = operationName.lastIndexOf(".");
if (suffixIdx > -1 && Config.Agent.IGNORE_SUFFIX.contains(operationName.substring(suffixIdx))) {
context = new IgnoredTracerContext();
......@@ -62,4 +74,9 @@ public class ContextManagerExtendService implements BootService {
return context;
}
@Override
public void statusChanged(final GRPCChannelStatus status) {
this.status = status;
}
}
......@@ -18,96 +18,34 @@
package org.apache.skywalking.apm.agent.core.context;
import java.util.List;
import lombok.Getter;
import org.apache.skywalking.apm.agent.core.context.ids.DistributedTraceId;
import org.apache.skywalking.apm.agent.core.context.ids.ID;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
/**
* The <code>ContextSnapshot</code> is a snapshot for current context. The snapshot carries the info for building
* reference between two segments in two thread, but have a causal relationship.
*/
@Getter
public class ContextSnapshot {
/**
* trace segment id of the parent trace segment.
*/
private ID traceSegmentId;
/**
* span id of the parent span, in parent trace segment.
*/
private int spanId = -1;
private String entryOperationName;
private String parentOperationName;
/**
* {@link DistributedTraceId}
*/
private DistributedTraceId primaryDistributedTraceId;
private int entryApplicationInstanceId = DictionaryUtil.nullValue();
private DistributedTraceId traceId;
private String traceSegmentId;
private int spanId;
private String parentEndpoint;
private CorrelationContext correlationContext;
ContextSnapshot(ID traceSegmentId, int spanId, List<DistributedTraceId> distributedTraceIds, CorrelationContext correlationContext) {
ContextSnapshot(String traceSegmentId,
int spanId,
DistributedTraceId primaryTraceId,
String parentEndpoint,
CorrelationContext correlationContext) {
this.traceSegmentId = traceSegmentId;
this.spanId = spanId;
if (distributedTraceIds != null) {
this.primaryDistributedTraceId = distributedTraceIds.get(0);
}
this.traceId = primaryTraceId;
this.parentEndpoint = parentEndpoint;
this.correlationContext = correlationContext.clone();
}
public void setEntryOperationName(String entryOperationName) {
this.entryOperationName = "#" + entryOperationName;
}
public void setEntryOperationId(int entryOperationId) {
this.entryOperationName = entryOperationId + "";
}
public void setParentOperationName(String parentOperationName) {
this.parentOperationName = "#" + parentOperationName;
}
public void setParentOperationId(int parentOperationId) {
this.parentOperationName = parentOperationId + "";
}
public DistributedTraceId getDistributedTraceId() {
return primaryDistributedTraceId;
}
public ID getTraceSegmentId() {
return traceSegmentId;
}
public int getSpanId() {
return spanId;
}
public String getParentOperationName() {
return parentOperationName;
}
public boolean isValid() {
return traceSegmentId != null && spanId > -1 && entryApplicationInstanceId != DictionaryUtil.nullValue() && primaryDistributedTraceId != null;
}
public String getEntryOperationName() {
return entryOperationName;
}
public void setEntryApplicationInstanceId(int entryApplicationInstanceId) {
this.entryApplicationInstanceId = entryApplicationInstanceId;
}
public int getEntryApplicationInstanceId() {
return entryApplicationInstanceId;
}
public boolean isFromCurrent() {
return traceSegmentId.equals(ContextManager.capture().getTraceSegmentId());
}
......@@ -115,4 +53,8 @@ public class ContextSnapshot {
public CorrelationContext getCorrelationContext() {
return correlationContext;
}
public boolean isValid() {
return traceSegmentId != null && spanId > -1 && traceId != null;
}
}
......@@ -53,7 +53,7 @@ public class IgnoredTracerContext implements AbstractTracerContext {
@Override
public ContextSnapshot capture() {
return new ContextSnapshot(null, -1, null, correlationContext);
return new ContextSnapshot(null, -1, null, null, correlationContext);
}
@Override
......@@ -62,7 +62,7 @@ public class IgnoredTracerContext implements AbstractTracerContext {
}
@Override
public String getReadableGlobalTraceId() {
public String getReadablePrimaryTraceId() {
return "[Ignored Trace]";
}
......
......@@ -18,17 +18,17 @@
package org.apache.skywalking.apm.agent.core.context;
public class SW6CarrierItem extends CarrierItem {
public static final String HEADER_NAME = "sw6";
public class SW8CarrierItem extends CarrierItem {
public static final String HEADER_NAME = "sw8";
private ContextCarrier carrier;
public SW6CarrierItem(ContextCarrier carrier, CarrierItem next) {
super(HEADER_NAME, carrier.serialize(ContextCarrier.HeaderVersion.v2), next);
public SW8CarrierItem(ContextCarrier carrier, CarrierItem next) {
super(HEADER_NAME, carrier.serialize(ContextCarrier.HeaderVersion.v3), next);
this.carrier = carrier;
}
@Override
public void setHeadValue(String headValue) {
carrier.deserialize(headValue, ContextCarrier.HeaderVersion.v2);
carrier.deserialize(headValue, ContextCarrier.HeaderVersion.v3);
}
}
\ No newline at end of file
......@@ -24,7 +24,8 @@ import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.context.ids.DistributedTraceId;
import org.apache.skywalking.apm.agent.core.context.ids.PropagatedTraceId;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.EntrySpan;
......@@ -35,8 +36,6 @@ import org.apache.skywalking.apm.agent.core.context.trace.NoopExitSpan;
import org.apache.skywalking.apm.agent.core.context.trace.NoopSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegmentRef;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryManager;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.profile.ProfileStatusReference;
......@@ -165,43 +164,17 @@ public class TracingContext implements AbstractTracerContext {
ExitTypeSpan spanWithPeer = (ExitTypeSpan) exitSpan;
String peer = spanWithPeer.getPeer();
int peerId = spanWithPeer.getPeerId();
if (StringUtil.isEmpty(peer) && DictionaryUtil.isNull(peerId)) {
if (StringUtil.isEmpty(peer)) {
throw new IllegalStateException("Exit span doesn't include meaningful peer information.");
}
carrier.setTraceId(getReadablePrimaryTraceId());
carrier.setTraceSegmentId(this.segment.getTraceSegmentId());
carrier.setSpanId(exitSpan.getSpanId());
carrier.setParentServiceInstanceId(segment.getApplicationInstanceId());
if (DictionaryUtil.isNull(peerId)) {
carrier.setPeerHost(peer);
} else {
carrier.setPeerId(peerId);
}
AbstractSpan firstSpan = first();
String firstSpanOperationName = firstSpan.getOperationName();
List<TraceSegmentRef> refs = this.segment.getRefs();
String operationName = "";
int entryApplicationInstanceId;
if (refs != null && refs.size() > 0) {
TraceSegmentRef ref = refs.get(0);
operationName = ref.getEntryEndpointName();
entryApplicationInstanceId = ref.getEntryServiceInstanceId();
} else {
operationName = firstSpanOperationName;
entryApplicationInstanceId = this.segment.getApplicationInstanceId();
}
carrier.setEntryServiceInstanceId(entryApplicationInstanceId);
carrier.setEntryEndpointName(operationName);
carrier.setParentEndpointName(firstSpanOperationName);
carrier.setDistributedTraceIds(this.segment.getRelatedGlobalTraces());
carrier.setParentService(Config.Agent.SERVICE_NAME);
carrier.setParentServiceInstance(Config.Agent.INSTANCE_NAME);
carrier.setParentEndpoint(first().getOperationName());
carrier.setAddressUsedAtClient(peer);
this.correlationContext.inject(carrier);
}
......@@ -215,7 +188,7 @@ public class TracingContext implements AbstractTracerContext {
public void extract(ContextCarrier carrier) {
TraceSegmentRef ref = new TraceSegmentRef(carrier);
this.segment.ref(ref);
this.segment.relatedGlobalTraces(carrier.getDistributedTraceId());
this.segment.relatedGlobalTraces(new PropagatedTraceId(carrier.getTraceId()));
AbstractSpan span = this.activeSpan();
if (span instanceof EntrySpan) {
span.ref(ref);
......@@ -231,28 +204,13 @@ public class TracingContext implements AbstractTracerContext {
*/
@Override
public ContextSnapshot capture() {
List<TraceSegmentRef> refs = this.segment.getRefs();
ContextSnapshot snapshot = new ContextSnapshot(
segment.getTraceSegmentId(), activeSpan().getSpanId(), segment.getRelatedGlobalTraces(),
segment.getTraceSegmentId(),
activeSpan().getSpanId(),
getPrimaryTraceId(),
first().getOperationName(),
this.correlationContext
);
int entryOperationId;
String entryOperationName = "";
int entryApplicationInstanceId;
AbstractSpan firstSpan = first();
String firstSpanOperationName = firstSpan.getOperationName();
if (refs != null && refs.size() > 0) {
TraceSegmentRef ref = refs.get(0);
entryOperationName = ref.getEntryEndpointName();
entryApplicationInstanceId = ref.getEntryServiceInstanceId();
} else {
entryOperationName = firstSpanOperationName;
entryApplicationInstanceId = this.segment.getApplicationInstanceId();
}
snapshot.setEntryApplicationInstanceId(entryApplicationInstanceId);
snapshot.setEntryOperationName(entryOperationName);
snapshot.setParentOperationName(firstSpanOperationName);
return snapshot;
}
......@@ -264,19 +222,25 @@ public class TracingContext implements AbstractTracerContext {
*/
@Override
public void continued(ContextSnapshot snapshot) {
TraceSegmentRef segmentRef = new TraceSegmentRef(snapshot);
this.segment.ref(segmentRef);
this.activeSpan().ref(segmentRef);
this.segment.relatedGlobalTraces(snapshot.getDistributedTraceId());
this.correlationContext.continued(snapshot);
if (snapshot.isValid()) {
TraceSegmentRef segmentRef = new TraceSegmentRef(snapshot);
this.segment.ref(segmentRef);
this.activeSpan().ref(segmentRef);
this.segment.relatedGlobalTraces(snapshot.getTraceId());
this.correlationContext.continued(snapshot);
}
}
/**
* @return the first global trace id.
*/
@Override
public String getReadableGlobalTraceId() {
return segment.getRelatedGlobalTraces().get(0).toString();
public String getReadablePrimaryTraceId() {
return getPrimaryTraceId().getId();
}
private DistributedTraceId getPrimaryTraceId() {
return segment.getRelatedGlobalTraces().get(0);
}
/**
......@@ -296,7 +260,7 @@ public class TracingContext implements AbstractTracerContext {
final AbstractSpan parentSpan = peek();
final int parentSpanId = parentSpan == null ? -1 : parentSpan.getSpanId();
if (parentSpan != null && parentSpan.isEntry()) {
/**
/*
* Only add the profiling recheck on creating entry span,
* as the operation name could be overrided.
*/
......@@ -360,21 +324,7 @@ public class TracingContext implements AbstractTracerContext {
exitSpan = parentSpan;
} else {
final int parentSpanId = parentSpan == null ? -1 : parentSpan.getSpanId();
if (StringUtil.isEmpty(remotePeer)) {
exitSpan = new ExitSpan(spanIdGenerator++, parentSpanId, operationName, owner);
} else {
exitSpan = (AbstractSpan) DictionaryManager.findNetworkAddressSection()
.find(remotePeer)
.doInCondition(
peerId -> new ExitSpan(spanIdGenerator++, parentSpanId,
operationName, peerId, owner
), () -> {
return new ExitSpan(
spanIdGenerator++, parentSpanId, operationName,
remotePeer, owner
);
});
}
exitSpan = new ExitSpan(spanIdGenerator++, parentSpanId, operationName, remotePeer, owner);
push(exitSpan);
}
exitSpan.start();
......@@ -492,15 +442,6 @@ public class TracingContext implements AbstractTracerContext {
}
}
/*
* Check that the segment is created after the agent (re-)registered to backend,
* otherwise the segment may be created when the agent is still rebooting and should
* be ignored
*/
if (segment.createTime() < RemoteDownstreamConfig.Agent.INSTANCE_REGISTERED_TIME) {
finishedSegment.setIgnore(true);
}
TracingContext.ListenerManager.notifyFinish(finishedSegment);
running = false;
......
......@@ -18,8 +18,10 @@
package org.apache.skywalking.apm.agent.core.context.ids;
import java.util.Objects;
import org.apache.skywalking.apm.network.language.agent.UniqueId;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
/**
* The <code>DistributedTraceId</code> presents a distributed call chain.
......@@ -32,51 +34,10 @@ import org.apache.skywalking.apm.network.language.agent.UniqueId;
* The <code>DistributedTraceId</code> contains only one string, and can NOT be reset, creating a new instance is the
* only option.
*/
@RequiredArgsConstructor
@ToString
@EqualsAndHashCode
public abstract class DistributedTraceId {
private ID id;
public DistributedTraceId(ID id) {
this.id = id;
}
public DistributedTraceId(String id) {
this.id = new ID(id);
}
public String encode() {
return id.encode();
}
@Override
public String toString() {
return id.toString();
}
public UniqueId toUniqueId() {
return id.transform();
}
/**
* Compare the two <code>DistributedTraceId</code> by its {@link #id}, even these two
* <code>DistributedTraceId</code>s are not the same instances.
*
* @param o target <code>DistributedTraceId</code>
* @return return if they have the same {@link #id}
*/
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
DistributedTraceId id1 = (DistributedTraceId) o;
return Objects.equals(id, id1.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
@Getter
private final String id;
}
......@@ -19,10 +19,11 @@
package org.apache.skywalking.apm.agent.core.context.ids;
import java.util.Random;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import java.util.UUID;
import org.apache.skywalking.apm.util.StringUtil;
public final class GlobalIdGenerator {
private static final String PROCESS_ID = UUID.randomUUID().toString().replaceAll("-", "");
private static final ThreadLocal<IDContext> THREAD_ID_SEQUENCE = ThreadLocal.withInitial(
() -> new IDContext(System.currentTimeMillis(), (short) 0));
......@@ -30,32 +31,23 @@ public final class GlobalIdGenerator {
}
/**
* Generate a new id, combined by three long numbers.
* Generate a new id, combined by three parts.
* <p>
* The first one represents application instance id. (most likely just an integer value, would be helpful in
* protobuf)
* The first one represents application instance id.
* <p>
* The second one represents thread id. (most likely just an integer value, would be helpful in protobuf)
* The second one represents thread id.
* <p>
* The third one also has two parts, 1) a timestamp, measured in milliseconds 2) a seq, in current thread, between
* 0(included) and 9999(included)
* <p>
* Notice, a long costs 8 bytes, three longs cost 24 bytes. And at the same time, a char costs 2 bytes. So
* sky-walking's old global and segment id like this: "S.1490097253214.-866187727.57515.1.1" which costs at least 72
* bytes.
*
* @return an array contains three long numbers, which represents a unique id.
* @return unique id to represent a trace or segment
*/
public static ID generate() {
if (RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID == DictionaryUtil.nullValue()) {
throw new IllegalStateException();
}
IDContext context = THREAD_ID_SEQUENCE.get();
return new ID(
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID,
Thread.currentThread().getId(),
context.nextSeq()
public static String generate() {
return StringUtil.join(
'.',
PROCESS_ID,
String.valueOf(Thread.currentThread().getId()),
String.valueOf(THREAD_ID_SEQUENCE.get().nextSeq())
);
}
......
/*
* 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.agent.core.context.ids;
import org.apache.skywalking.apm.network.language.agent.UniqueId;
public class ID {
private long part1;
private long part2;
private long part3;
private String encoding;
private boolean isValid;
public ID(long part1, long part2, long part3) {
this.part1 = part1;
this.part2 = part2;
this.part3 = part3;
this.encoding = null;
this.isValid = true;
}
public ID(String encodingString) {
String[] idParts = encodingString.split("\\.", 3);
this.isValid = true;
for (int part = 0; part < 3; part++) {
try {
if (part == 0) {
part1 = Long.parseLong(idParts[part]);
} else if (part == 1) {
part2 = Long.parseLong(idParts[part]);
} else {
part3 = Long.parseLong(idParts[part]);
}
} catch (NumberFormatException e) {
this.isValid = false;
break;
}
}
}
public String encode() {
if (encoding == null) {
encoding = toString();
}
return encoding;
}
@Override
public String toString() {
return part1 + "." + part2 + '.' + part3;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
ID id = (ID) o;
if (part1 != id.part1)
return false;
if (part2 != id.part2)
return false;
return part3 == id.part3;
}
@Override
public int hashCode() {
int result = (int) (part1 ^ (part1 >>> 32));
result = 31 * result + (int) (part2 ^ (part2 >>> 32));
result = 31 * result + (int) (part3 ^ (part3 >>> 32));
return result;
}
public boolean isValid() {
return isValid;
}
public UniqueId transform() {
return UniqueId.newBuilder().addIdParts(part1).addIdParts(part2).addIdParts(part3).build();
}
}
......@@ -36,14 +36,6 @@ public interface AbstractSpan extends AsyncSpan {
*/
AbstractSpan setComponent(Component component);
/**
* Only use this method in explicit instrumentation, like opentracing-skywalking-bridge. It is highly recommended
* not to use this method for performance reasons.
*
* @return the span for chaining.
*/
AbstractSpan setComponent(String componentName);
AbstractSpan setLayer(SpanLayer layer);
/**
......
......@@ -30,8 +30,8 @@ import org.apache.skywalking.apm.agent.core.context.util.KeyValuePair;
import org.apache.skywalking.apm.agent.core.context.util.TagValuePair;
import org.apache.skywalking.apm.agent.core.context.util.ThrowableTransformer;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.network.language.agent.SpanType;
import org.apache.skywalking.apm.network.language.agent.v2.SpanObjectV2;
import org.apache.skywalking.apm.network.language.agent.v3.SpanObject;
import org.apache.skywalking.apm.network.language.agent.v3.SpanType;
import org.apache.skywalking.apm.network.trace.component.Component;
/**
......@@ -73,8 +73,6 @@ public abstract class AbstractTracingSpan implements AbstractSpan {
protected int componentId = 0;
protected String componentName;
/**
* Log is a concept from OpenTracing spec. https://github.com/opentracing/specification/blob/master/specification.md#log-structured-data
*/
......@@ -234,25 +232,14 @@ public abstract class AbstractTracingSpan implements AbstractSpan {
return this;
}
/**
* Set the component name. By using this, cost more memory and network.
*
* @return span instance, for chaining.
*/
@Override
public AbstractTracingSpan setComponent(String componentName) {
this.componentName = componentName;
return this;
}
@Override
public AbstractSpan start(long startTime) {
this.startTime = startTime;
return this;
}
public SpanObjectV2.Builder transform() {
SpanObjectV2.Builder spanBuilder = SpanObjectV2.newBuilder();
public SpanObject.Builder transform() {
SpanObject.Builder spanBuilder = SpanObject.newBuilder();
spanBuilder.setSpanId(this.spanId);
spanBuilder.setParentSpanId(parentSpanId);
......@@ -271,10 +258,6 @@ public abstract class AbstractTracingSpan implements AbstractSpan {
}
if (componentId != DictionaryUtil.nullValue()) {
spanBuilder.setComponentId(componentId);
} else {
if (componentName != null) {
spanBuilder.setComponent(componentName);
}
}
spanBuilder.setIsError(errorOccurred);
if (this.tags != null) {
......
......@@ -79,15 +79,6 @@ public class EntrySpan extends StackBasedTracingSpan {
}
}
@Override
public AbstractTracingSpan setComponent(String componentName) {
if (stackDepth == currentMaxDepth) {
return super.setComponent(componentName);
} else {
return this;
}
}
@Override
public AbstractTracingSpan setOperationName(String operationName) {
if (stackDepth == currentMaxDepth || isInAsyncMode) {
......@@ -115,7 +106,6 @@ public class EntrySpan extends StackBasedTracingSpan {
private void clearWhenRestart() {
this.componentId = DictionaryUtil.nullValue();
this.componentName = null;
this.layer = null;
this.logs = null;
this.tags = null;
......
......@@ -39,10 +39,6 @@ public class ExitSpan extends StackBasedTracingSpan implements ExitTypeSpan {
super(spanId, parentSpanId, operationName, peer, owner);
}
public ExitSpan(int spanId, int parentSpanId, String operationName, int peerId, TracingContext owner) {
super(spanId, parentSpanId, operationName, peerId, owner);
}
public ExitSpan(int spanId, int parentSpanId, String operationName, TracingContext owner) {
super(spanId, parentSpanId, operationName, owner);
}
......@@ -92,15 +88,6 @@ public class ExitSpan extends StackBasedTracingSpan implements ExitTypeSpan {
}
}
@Override
public AbstractTracingSpan setComponent(String componentName) {
if (stackDepth == 1) {
return super.setComponent(componentName);
} else {
return this;
}
}
@Override
public ExitSpan log(Throwable t) {
if (stackDepth == 1) {
......@@ -118,11 +105,6 @@ public class ExitSpan extends StackBasedTracingSpan implements ExitTypeSpan {
}
}
@Override
public int getPeerId() {
return peerId;
}
@Override
public String getPeer() {
return peer;
......
......@@ -24,8 +24,6 @@ import org.apache.skywalking.apm.agent.core.context.ContextCarrier;
* The exit span has some additional behaviours
*/
public interface ExitTypeSpan {
int getPeerId();
String getPeer();
ExitTypeSpan inject(ContextCarrier carrier);
......
......@@ -22,7 +22,7 @@ import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.util.KeyValuePair;
import org.apache.skywalking.apm.network.language.agent.v2.Log;
import org.apache.skywalking.apm.network.language.agent.v3.Log;
/**
* The <code>LogDataEntity</code> represents a collection of {@link KeyValuePair}, contains several fields of a logging
......
......@@ -21,23 +21,12 @@ package org.apache.skywalking.apm.agent.core.context.trace;
import org.apache.skywalking.apm.agent.core.context.ContextCarrier;
public class NoopExitSpan extends NoopSpan implements ExitTypeSpan {
private String peer;
private int peerId;
public NoopExitSpan(int peerId) {
this.peerId = peerId;
}
public NoopExitSpan(String peer) {
this.peer = peer;
}
@Override
public int getPeerId() {
return peerId;
}
@Override
public String getPeer() {
return peer;
......
......@@ -50,11 +50,6 @@ public class NoopSpan implements AbstractSpan {
return this;
}
@Override
public AbstractSpan setComponent(String componentName) {
return this;
}
@Override
public AbstractSpan setLayer(SpanLayer layer) {
return this;
......
......@@ -19,9 +19,8 @@
package org.apache.skywalking.apm.agent.core.context.trace;
import org.apache.skywalking.apm.agent.core.context.TracingContext;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryManager;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.network.language.agent.v2.SpanObjectV2;
import org.apache.skywalking.apm.network.language.agent.v3.SpanObject;
import org.apache.skywalking.apm.util.StringUtil;
/**
* The <code>StackBasedTracingSpan</code> represents a span with an inside stack construction.
......@@ -31,38 +30,24 @@ import org.apache.skywalking.apm.network.language.agent.v2.SpanObjectV2;
public abstract class StackBasedTracingSpan extends AbstractTracingSpan {
protected int stackDepth;
protected String peer;
protected int peerId;
protected StackBasedTracingSpan(int spanId, int parentSpanId, String operationName, TracingContext owner) {
super(spanId, parentSpanId, operationName, owner);
this.stackDepth = 0;
this.peer = null;
this.peerId = DictionaryUtil.nullValue();
}
protected StackBasedTracingSpan(int spanId, int parentSpanId, String operationName, String peer,
TracingContext owner) {
super(spanId, parentSpanId, operationName, owner);
this.peer = peer;
this.peerId = DictionaryUtil.nullValue();
}
protected StackBasedTracingSpan(int spanId, int parentSpanId, String operationName, int peerId,
TracingContext owner) {
super(spanId, parentSpanId, operationName, owner);
this.peer = null;
this.peerId = peerId;
}
@Override
public SpanObjectV2.Builder transform() {
SpanObjectV2.Builder spanBuilder = super.transform();
if (peerId != DictionaryUtil.nullValue()) {
spanBuilder.setPeerId(peerId);
} else {
if (peer != null) {
spanBuilder.setPeer(peer);
}
public SpanObject.Builder transform() {
SpanObject.Builder spanBuilder = super.transform();
if (StringUtil.isNotEmpty(peer)) {
spanBuilder.setPeer(peer);
}
return spanBuilder;
}
......@@ -78,11 +63,7 @@ public abstract class StackBasedTracingSpan extends AbstractTracingSpan {
@Override
public AbstractSpan setPeer(final String remotePeer) {
DictionaryManager.findNetworkAddressSection().find(remotePeer).doInCondition(
remotePeerId -> peerId = remotePeerId, () -> {
peer = remotePeer;
}
);
this.peer = remotePeer;
return this;
}
}
......@@ -20,14 +20,12 @@ package org.apache.skywalking.apm.agent.core.context.trace;
import java.util.LinkedList;
import java.util.List;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.ids.DistributedTraceId;
import org.apache.skywalking.apm.agent.core.context.ids.DistributedTraceIds;
import org.apache.skywalking.apm.agent.core.context.ids.GlobalIdGenerator;
import org.apache.skywalking.apm.agent.core.context.ids.ID;
import org.apache.skywalking.apm.agent.core.context.ids.NewDistributedTraceId;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
import org.apache.skywalking.apm.network.language.agent.v2.SegmentObject;
import org.apache.skywalking.apm.network.language.agent.v3.SegmentObject;
/**
* {@link TraceSegment} is a segment or fragment of the distributed trace. See https://github.com/opentracing/specification/blob/master/specification.md#the-opentracing-data-model
......@@ -38,7 +36,7 @@ public class TraceSegment {
/**
* The id of this trace segment. Every segment has its unique-global-id.
*/
private ID traceSegmentId;
private String traceSegmentId;
/**
* The refs of parent trace segments, except the primary one. For most RPC call, {@link #refs} contains only one
......@@ -119,14 +117,10 @@ public class TraceSegment {
return this;
}
public ID getTraceSegmentId() {
public String getTraceSegmentId() {
return traceSegmentId;
}
public int getServiceId() {
return RemoteDownstreamConfig.Agent.SERVICE_ID;
}
public boolean hasRef() {
return !(refs == null || refs.size() == 0);
}
......@@ -156,28 +150,24 @@ public class TraceSegment {
*
* @return the segment as GRPC service parameter
*/
public UpstreamSegment transform() {
UpstreamSegment.Builder upstreamBuilder = UpstreamSegment.newBuilder();
for (DistributedTraceId distributedTraceId : getRelatedGlobalTraces()) {
upstreamBuilder = upstreamBuilder.addGlobalTraceIds(distributedTraceId.toUniqueId());
}
public SegmentObject transform() {
SegmentObject.Builder traceSegmentBuilder = SegmentObject.newBuilder();
traceSegmentBuilder.setTraceId(getRelatedGlobalTraces().get(0).getId());
/*
* Trace Segment
*/
traceSegmentBuilder.setTraceSegmentId(this.traceSegmentId.transform());
traceSegmentBuilder.setTraceSegmentId(this.traceSegmentId);
// Don't serialize TraceSegmentReference
// SpanObject
for (AbstractTracingSpan span : this.spans) {
traceSegmentBuilder.addSpans(span.transform());
}
traceSegmentBuilder.setServiceId(RemoteDownstreamConfig.Agent.SERVICE_ID);
traceSegmentBuilder.setServiceInstanceId(RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID);
traceSegmentBuilder.setService(Config.Agent.SERVICE_NAME);
traceSegmentBuilder.setServiceInstance(Config.Agent.INSTANCE_NAME);
traceSegmentBuilder.setIsSizeLimited(this.isSizeLimited);
upstreamBuilder.setSegment(traceSegmentBuilder.build().toByteString());
return upstreamBuilder.build();
return traceSegmentBuilder.build();
}
@Override
......@@ -185,10 +175,6 @@ public class TraceSegment {
return "TraceSegment{" + "traceSegmentId='" + traceSegmentId + '\'' + ", refs=" + refs + ", spans=" + spans + ", relatedGlobalTraces=" + relatedGlobalTraces + '}';
}
public int getApplicationInstanceId() {
return RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID;
}
public long createTime() {
return this.createTime;
}
......
......@@ -18,39 +18,28 @@
package org.apache.skywalking.apm.agent.core.context.trace;
import org.apache.skywalking.apm.agent.core.conf.Constants;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import lombok.Getter;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.ContextCarrier;
import org.apache.skywalking.apm.agent.core.context.ContextSnapshot;
import org.apache.skywalking.apm.agent.core.context.ids.ID;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.network.language.agent.RefType;
import org.apache.skywalking.apm.network.language.agent.v2.SegmentReference;
import org.apache.skywalking.apm.util.StringUtil;
import org.apache.skywalking.apm.network.language.agent.v3.RefType;
import org.apache.skywalking.apm.network.language.agent.v3.SegmentReference;
/**
* {@link TraceSegmentRef} is like a pointer, which ref to another {@link TraceSegment}, use {@link #spanId} point to
* the exact span of the ref {@link TraceSegment}.
* <p>
*/
@Getter
public class TraceSegmentRef {
private SegmentRefType type;
private ID traceSegmentId;
private String traceId;
private String traceSegmentId;
private int spanId;
private int peerId = DictionaryUtil.nullValue();
private String peerHost;
private int entryServiceInstanceId;
private int parentServiceInstanceId;
private String entryEndpointName = Constants.EMPTY_STRING;
private String parentEndpointName = Constants.EMPTY_STRING;
private String parentService;
private String parentServiceInstance;
private String parentEndpoint;
private String addressUsedAtClient;
/**
* Transform a {@link ContextCarrier} to the <code>TraceSegmentRef</code>
......@@ -59,77 +48,41 @@ public class TraceSegmentRef {
*/
public TraceSegmentRef(ContextCarrier carrier) {
this.type = SegmentRefType.CROSS_PROCESS;
this.traceId = carrier.getTraceId();
this.traceSegmentId = carrier.getTraceSegmentId();
this.spanId = carrier.getSpanId();
this.parentServiceInstanceId = carrier.getParentServiceInstanceId();
this.entryServiceInstanceId = carrier.getEntryServiceInstanceId();
String host = carrier.getPeerHost();
if (host.charAt(0) == '#') {
this.peerHost = host.substring(1);
} else {
this.peerId = Integer.parseInt(host);
}
String entryOperationName = carrier.getEntryEndpointName();
if (!StringUtil.isEmpty(entryOperationName)) {
if (entryOperationName.charAt(0) == '#') {
this.entryEndpointName = entryOperationName.substring(1);
}
}
String parentOperationName = carrier.getParentEndpointName();
if (!StringUtil.isEmpty(parentOperationName)) {
if (parentOperationName.charAt(0) == '#') {
this.parentEndpointName = parentOperationName.substring(1);
}
}
this.parentService = carrier.getParentService();
this.parentServiceInstance = carrier.getParentServiceInstance();
this.parentEndpoint = carrier.getParentEndpoint();
this.addressUsedAtClient = carrier.getAddressUsedAtClient();
}
public TraceSegmentRef(ContextSnapshot snapshot) {
this.type = SegmentRefType.CROSS_THREAD;
this.traceId = snapshot.getTraceId().getId();
this.traceSegmentId = snapshot.getTraceSegmentId();
this.spanId = snapshot.getSpanId();
this.parentServiceInstanceId = RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID;
this.entryServiceInstanceId = snapshot.getEntryApplicationInstanceId();
String entryOperationName = snapshot.getEntryOperationName();
if (!StringUtil.isEmpty(entryOperationName)) {
if (entryOperationName.charAt(0) == '#') {
this.entryEndpointName = entryOperationName.substring(1);
}
}
String parentOperationName = snapshot.getParentOperationName();
if (!StringUtil.isEmpty(parentOperationName)) {
if (parentOperationName.charAt(0) == '#') {
this.parentEndpointName = parentOperationName.substring(1);
}
}
}
public String getEntryEndpointName() {
return entryEndpointName;
}
public int getEntryServiceInstanceId() {
return entryServiceInstanceId;
this.parentService = Config.Agent.SERVICE_NAME;
this.parentServiceInstance = Config.Agent.INSTANCE_NAME;
this.parentEndpoint = snapshot.getParentEndpoint();
}
public SegmentReference transform() {
SegmentReference.Builder refBuilder = SegmentReference.newBuilder();
if (SegmentRefType.CROSS_PROCESS.equals(type)) {
refBuilder.setRefType(RefType.CrossProcess);
if (peerId == DictionaryUtil.nullValue()) {
refBuilder.setNetworkAddress(peerHost);
} else {
refBuilder.setNetworkAddressId(peerId);
}
} else {
refBuilder.setRefType(RefType.CrossThread);
}
refBuilder.setParentServiceInstanceId(parentServiceInstanceId);
refBuilder.setEntryServiceInstanceId(entryServiceInstanceId);
refBuilder.setParentTraceSegmentId(traceSegmentId.transform());
refBuilder.setTraceId(traceId);
refBuilder.setParentTraceSegmentId(traceSegmentId);
refBuilder.setParentSpanId(spanId);
refBuilder.setEntryEndpoint(entryEndpointName);
refBuilder.setParentEndpoint(parentEndpointName);
refBuilder.setParentService(parentService);
refBuilder.setParentServiceInstance(parentServiceInstance);
refBuilder.setParentEndpoint(parentEndpoint);
if (addressUsedAtClient != null) {
refBuilder.setNetworkAddressUsedAtPeer(addressUsedAtClient);
}
return refBuilder.build();
}
......
......@@ -18,7 +18,7 @@
package org.apache.skywalking.apm.agent.core.context.util;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
/**
* The <code>KeyValuePair</code> represents a object which contains a string key and a string value.
......
......@@ -18,7 +18,7 @@
package org.apache.skywalking.apm.agent.core.context.util;
import org.apache.skywalking.apm.agent.core.context.tag.AbstractTag;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
public class TagValuePair {
private AbstractTag key;
......
/*
* 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.agent.core.dictionary;
public class DictionaryManager {
/**
* @return {@link NetworkAddressDictionary} to find application id for application code and network address.
*/
public static NetworkAddressDictionary findNetworkAddressSection() {
return NetworkAddressDictionary.INSTANCE;
}
}
/*
* 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.agent.core.dictionary;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.skywalking.apm.network.common.KeyIntValuePair;
import org.apache.skywalking.apm.network.register.v2.NetAddressMapping;
import org.apache.skywalking.apm.network.register.v2.NetAddresses;
import org.apache.skywalking.apm.network.register.v2.RegisterGrpc;
import static org.apache.skywalking.apm.agent.core.conf.Config.Dictionary.NETWORK_ADDRESS_BUFFER_SIZE;
/**
* Map of network address id to network literal address, which is from the collector side.
*/
public enum NetworkAddressDictionary {
INSTANCE;
private Map<String, Integer> serviceDictionary = new ConcurrentHashMap<>();
private Set<String> unRegisterServices = ConcurrentHashMap.newKeySet();
public PossibleFound find(String networkAddress) {
Integer applicationId = serviceDictionary.get(networkAddress);
if (applicationId != null) {
return new Found(applicationId);
} else {
if (serviceDictionary.size() + unRegisterServices.size() < NETWORK_ADDRESS_BUFFER_SIZE) {
unRegisterServices.add(networkAddress);
}
return new NotFound();
}
}
public void syncRemoteDictionary(RegisterGrpc.RegisterBlockingStub networkAddressRegisterServiceBlockingStub) {
if (unRegisterServices.size() > 0) {
NetAddressMapping networkAddressMappings = networkAddressRegisterServiceBlockingStub
.doNetworkAddressRegister(NetAddresses.newBuilder()
.addAllAddresses(unRegisterServices)
.build());
if (networkAddressMappings.getAddressIdsCount() > 0) {
for (KeyIntValuePair keyWithIntegerValue : networkAddressMappings.getAddressIdsList()) {
unRegisterServices.remove(keyWithIntegerValue.getKey());
serviceDictionary.put(keyWithIntegerValue.getKey(), keyWithIntegerValue.getValue());
}
}
}
}
public void clear() {
this.serviceDictionary.clear();
}
}
......@@ -30,8 +30,6 @@ import org.apache.skywalking.apm.agent.core.boot.DefaultNamedThreadFactory;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.commands.CommandService;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.agent.core.jvm.cpu.CPUProvider;
import org.apache.skywalking.apm.agent.core.jvm.gc.GCProvider;
import org.apache.skywalking.apm.agent.core.jvm.memory.MemoryProvider;
......@@ -41,10 +39,10 @@ import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.remote.GRPCChannelListener;
import org.apache.skywalking.apm.agent.core.remote.GRPCChannelManager;
import org.apache.skywalking.apm.agent.core.remote.GRPCChannelStatus;
import org.apache.skywalking.apm.network.common.Commands;
import org.apache.skywalking.apm.network.language.agent.JVMMetric;
import org.apache.skywalking.apm.network.language.agent.v2.JVMMetricCollection;
import org.apache.skywalking.apm.network.language.agent.v2.JVMMetricReportServiceGrpc;
import org.apache.skywalking.apm.network.common.v3.Commands;
import org.apache.skywalking.apm.network.language.agent.v3.JVMMetric;
import org.apache.skywalking.apm.network.language.agent.v3.JVMMetricCollection;
import org.apache.skywalking.apm.network.language.agent.v3.JVMMetricReportServiceGrpc;
import org.apache.skywalking.apm.util.RunnableWithExceptionProtection;
import static org.apache.skywalking.apm.agent.core.conf.Config.Collector.GRPC_UPSTREAM_TIMEOUT;
......@@ -70,20 +68,36 @@ public class JVMService implements BootService, Runnable {
@Override
public void boot() throws Throwable {
collectMetricFuture = Executors.newSingleThreadScheduledExecutor(new DefaultNamedThreadFactory("JVMService-produce"))
.scheduleAtFixedRate(new RunnableWithExceptionProtection(this, new RunnableWithExceptionProtection.CallbackWhenException() {
@Override
public void handle(Throwable t) {
logger.error("JVMService produces metrics failure.", t);
collectMetricFuture = Executors.newSingleThreadScheduledExecutor(
new DefaultNamedThreadFactory("JVMService-produce"))
.scheduleAtFixedRate(new RunnableWithExceptionProtection(
this,
new RunnableWithExceptionProtection.CallbackWhenException() {
@Override
public void handle(
Throwable t) {
logger.error(
"JVMService produces metrics failure.",
t
);
}
}
}), 0, 1, TimeUnit.SECONDS);
sendMetricFuture = Executors.newSingleThreadScheduledExecutor(new DefaultNamedThreadFactory("JVMService-consume"))
.scheduleAtFixedRate(new RunnableWithExceptionProtection(sender, new RunnableWithExceptionProtection.CallbackWhenException() {
@Override
public void handle(Throwable t) {
logger.error("JVMService consumes and upload failure.", t);
), 0, 1, TimeUnit.SECONDS);
sendMetricFuture = Executors.newSingleThreadScheduledExecutor(
new DefaultNamedThreadFactory("JVMService-consume"))
.scheduleAtFixedRate(new RunnableWithExceptionProtection(
sender,
new RunnableWithExceptionProtection.CallbackWhenException() {
@Override
public void handle(
Throwable t) {
logger.error(
"JVMService consumes and upload failure.",
t
);
}
}
}), 0, 1, TimeUnit.SECONDS);
), 0, 1, TimeUnit.SECONDS);
}
@Override
......@@ -99,26 +113,24 @@ public class JVMService implements BootService, Runnable {
@Override
public void run() {
if (RemoteDownstreamConfig.Agent.SERVICE_ID != DictionaryUtil.nullValue() && RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID != DictionaryUtil
.nullValue()) {
long currentTimeMillis = System.currentTimeMillis();
try {
JVMMetric.Builder jvmBuilder = JVMMetric.newBuilder();
jvmBuilder.setTime(currentTimeMillis);
jvmBuilder.setCpu(CPUProvider.INSTANCE.getCpuMetric());
jvmBuilder.addAllMemory(MemoryProvider.INSTANCE.getMemoryMetricList());
jvmBuilder.addAllMemoryPool(MemoryPoolProvider.INSTANCE.getMemoryPoolMetricsList());
jvmBuilder.addAllGc(GCProvider.INSTANCE.getGCList());
JVMMetric jvmMetric = jvmBuilder.build();
if (!queue.offer(jvmMetric)) {
queue.poll();
queue.offer(jvmMetric);
}
} catch (Exception e) {
logger.error(e, "Collect JVM info fail.");
long currentTimeMillis = System.currentTimeMillis();
try {
JVMMetric.Builder jvmBuilder = JVMMetric.newBuilder();
jvmBuilder.setTime(currentTimeMillis);
jvmBuilder.setCpu(CPUProvider.INSTANCE.getCpuMetric());
jvmBuilder.addAllMemory(MemoryProvider.INSTANCE.getMemoryMetricList());
jvmBuilder.addAllMemoryPool(MemoryPoolProvider.INSTANCE.getMemoryPoolMetricsList());
jvmBuilder.addAllGc(GCProvider.INSTANCE.getGCList());
JVMMetric jvmMetric = jvmBuilder.build();
if (!queue.offer(jvmMetric)) {
queue.poll();
queue.offer(jvmMetric);
}
} catch (Exception e) {
logger.error(e, "Collect JVM info fail.");
}
}
private class Sender implements Runnable, GRPCChannelListener {
......@@ -127,23 +139,22 @@ public class JVMService implements BootService, Runnable {
@Override
public void run() {
if (RemoteDownstreamConfig.Agent.SERVICE_ID != DictionaryUtil.nullValue() && RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID != DictionaryUtil
.nullValue()) {
if (status == GRPCChannelStatus.CONNECTED) {
try {
JVMMetricCollection.Builder builder = JVMMetricCollection.newBuilder();
LinkedList<JVMMetric> buffer = new LinkedList<JVMMetric>();
queue.drainTo(buffer);
if (buffer.size() > 0) {
builder.addAllMetrics(buffer);
builder.setServiceInstanceId(RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID);
Commands commands = stub.withDeadlineAfter(GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS)
.collect(builder.build());
ServiceManager.INSTANCE.findService(CommandService.class).receiveCommand(commands);
}
} catch (Throwable t) {
logger.error(t, "send JVM metrics to Collector fail.");
if (status == GRPCChannelStatus.CONNECTED) {
try {
JVMMetricCollection.Builder builder = JVMMetricCollection.newBuilder();
LinkedList<JVMMetric> buffer = new LinkedList<JVMMetric>();
queue.drainTo(buffer);
if (buffer.size() > 0) {
builder.addAllMetrics(buffer);
builder.setService(Config.Agent.SERVICE_NAME);
builder.setServiceInstance(Config.Agent.INSTANCE_NAME);
Commands commands = stub.withDeadlineAfter(GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS)
.collect(builder.build());
ServiceManager.INSTANCE.findService(CommandService.class).receiveCommand(commands);
}
} catch (Throwable t) {
logger.error(t, "send JVM metrics to Collector fail.");
}
}
}
......
......@@ -18,7 +18,7 @@
package org.apache.skywalking.apm.agent.core.jvm.cpu;
import org.apache.skywalking.apm.network.common.CPU;
import org.apache.skywalking.apm.network.common.v3.CPU;
/**
* The unit of CPU usage is 1/10000. The backend is using `avg` func directly, and query for percentage requires this
......
......@@ -21,7 +21,7 @@ package org.apache.skywalking.apm.agent.core.jvm.cpu;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.os.ProcessorUtil;
import org.apache.skywalking.apm.network.common.CPU;
import org.apache.skywalking.apm.network.common.v3.CPU;
public enum CPUProvider {
INSTANCE;
......
......@@ -19,7 +19,7 @@
package org.apache.skywalking.apm.agent.core.jvm.gc;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.GC;
import org.apache.skywalking.apm.network.language.agent.v3.GC;
public interface GCMetricAccessor {
List<GC> getGCList();
......
......@@ -21,8 +21,8 @@ package org.apache.skywalking.apm.agent.core.jvm.gc;
import java.lang.management.GarbageCollectorMXBean;
import java.util.LinkedList;
import java.util.List;
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.v3.GC;
import org.apache.skywalking.apm.network.language.agent.v3.GCPhrase;
public abstract class GCModule implements GCMetricAccessor {
private List<GarbageCollectorMXBean> beans;
......
......@@ -21,7 +21,7 @@ package org.apache.skywalking.apm.agent.core.jvm.gc;
import java.lang.management.GarbageCollectorMXBean;
import java.lang.management.ManagementFactory;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.GC;
import org.apache.skywalking.apm.network.language.agent.v3.GC;
public enum GCProvider {
INSTANCE;
......
......@@ -20,8 +20,8 @@ package org.apache.skywalking.apm.agent.core.jvm.gc;
import java.util.LinkedList;
import java.util.List;
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.v3.GC;
import org.apache.skywalking.apm.network.language.agent.v3.GCPhrase;
public class UnknowGC implements GCMetricAccessor {
@Override
......
......@@ -23,7 +23,7 @@ import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.util.LinkedList;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.Memory;
import org.apache.skywalking.apm.network.language.agent.v3.Memory;
public enum MemoryProvider {
INSTANCE;
......
......@@ -19,7 +19,7 @@
package org.apache.skywalking.apm.agent.core.jvm.memorypool;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.MemoryPool;
import org.apache.skywalking.apm.network.language.agent.v3.MemoryPool;
public interface MemoryPoolMetricsAccessor {
List<MemoryPool> getMemoryPoolMetricsList();
......
......@@ -22,8 +22,8 @@ import java.lang.management.MemoryPoolMXBean;
import java.lang.management.MemoryUsage;
import java.util.LinkedList;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.MemoryPool;
import org.apache.skywalking.apm.network.language.agent.PoolType;
import org.apache.skywalking.apm.network.language.agent.v3.MemoryPool;
import org.apache.skywalking.apm.network.language.agent.v3.PoolType;
public abstract class MemoryPoolModule implements MemoryPoolMetricsAccessor {
private List<MemoryPoolMXBean> beans;
......@@ -59,7 +59,7 @@ public abstract class MemoryPoolModule implements MemoryPoolMetricsAccessor {
.setType(type)
.setInit(usage.getInit())
.setMax(usage.getMax())
.setCommited(usage.getCommitted())
.setCommitted(usage.getCommitted())
.setUsed(usage.getUsed())
.build());
}
......
......@@ -21,7 +21,7 @@ package org.apache.skywalking.apm.agent.core.jvm.memorypool;
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryPoolMXBean;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.MemoryPool;
import org.apache.skywalking.apm.network.language.agent.v3.MemoryPool;
public enum MemoryPoolProvider {
INSTANCE;
......
......@@ -20,8 +20,8 @@ package org.apache.skywalking.apm.agent.core.jvm.memorypool;
import java.util.LinkedList;
import java.util.List;
import org.apache.skywalking.apm.network.language.agent.MemoryPool;
import org.apache.skywalking.apm.network.language.agent.PoolType;
import org.apache.skywalking.apm.network.language.agent.v3.MemoryPool;
import org.apache.skywalking.apm.network.language.agent.v3.PoolType;
public class UnknownMemoryPool implements MemoryPoolMetricsAccessor {
@Override
......
......@@ -28,7 +28,7 @@ import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedList;
import java.util.List;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
public class OSUtil {
private static volatile String OS_NAME;
......@@ -69,6 +69,8 @@ public class OSUtil {
String addressStr = address.getHostAddress();
if ("127.0.0.1".equals(addressStr)) {
continue;
} else if ("localhost".equals(addressStr)) {
continue;
}
IPV4_LIST.add(addressStr);
}
......@@ -81,6 +83,15 @@ public class OSUtil {
return IPV4_LIST;
}
public static String getIPV4() {
final List<String> allIPV4 = getAllIPV4();
if (allIPV4.size() > 0) {
return allIPV4.get(0);
} else {
return "no-hostname";
}
}
public static int getProcessNo() {
if (PROCESS_NO == 0) {
try {
......@@ -97,11 +108,11 @@ public class OSUtil {
String osName = getOsName();
if (osName != null) {
osInfo.add(KeyStringValuePair.newBuilder().setKey("os_name").setValue(osName).build());
osInfo.add(KeyStringValuePair.newBuilder().setKey("OS Name").setValue(osName).build());
}
String hostName = getHostName();
if (hostName != null) {
osInfo.add(KeyStringValuePair.newBuilder().setKey("host_name").setValue(hostName).build());
osInfo.add(KeyStringValuePair.newBuilder().setKey("hostname").setValue(hostName).build());
}
List<String> allIPV4 = getAllIPV4();
if (allIPV4.size() > 0) {
......@@ -109,7 +120,7 @@ public class OSUtil {
osInfo.add(KeyStringValuePair.newBuilder().setKey("ipv4").setValue(ipv4).build());
}
}
osInfo.add(KeyStringValuePair.newBuilder().setKey("process_no").setValue(getProcessNo() + "").build());
osInfo.add(KeyStringValuePair.newBuilder().setKey("Process No.").setValue(getProcessNo() + "").build());
osInfo.add(KeyStringValuePair.newBuilder().setKey("language").setValue("java").build());
return osInfo;
}
......
......@@ -34,19 +34,17 @@ import org.apache.skywalking.apm.agent.core.boot.DefaultNamedThreadFactory;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.commands.CommandService;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.remote.GRPCChannelListener;
import org.apache.skywalking.apm.agent.core.remote.GRPCChannelManager;
import org.apache.skywalking.apm.agent.core.remote.GRPCChannelStatus;
import org.apache.skywalking.apm.agent.core.remote.GRPCStreamServiceStatus;
import org.apache.skywalking.apm.network.common.Commands;
import org.apache.skywalking.apm.network.language.profile.ProfileTaskCommandQuery;
import org.apache.skywalking.apm.network.language.profile.ProfileTaskFinishReport;
import org.apache.skywalking.apm.network.language.profile.ProfileTaskGrpc;
import org.apache.skywalking.apm.network.language.profile.ThreadSnapshot;
import org.apache.skywalking.apm.network.common.v3.Commands;
import org.apache.skywalking.apm.network.language.profile.v3.ProfileTaskCommandQuery;
import org.apache.skywalking.apm.network.language.profile.v3.ProfileTaskFinishReport;
import org.apache.skywalking.apm.network.language.profile.v3.ProfileTaskGrpc;
import org.apache.skywalking.apm.network.language.profile.v3.ThreadSnapshot;
import org.apache.skywalking.apm.util.RunnableWithExceptionProtection;
import static org.apache.skywalking.apm.agent.core.conf.Config.Collector.GRPC_UPSTREAM_TIMEOUT;
......@@ -78,45 +76,41 @@ public class ProfileTaskChannelService implements BootService, Runnable, GRPCCha
@Override
public void run() {
if (RemoteDownstreamConfig.Agent.SERVICE_ID != DictionaryUtil.nullValue()
&& RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID != DictionaryUtil.nullValue()) {
if (status == GRPCChannelStatus.CONNECTED) {
try {
ProfileTaskCommandQuery.Builder builder = ProfileTaskCommandQuery.newBuilder();
if (status == GRPCChannelStatus.CONNECTED) {
try {
ProfileTaskCommandQuery.Builder builder = ProfileTaskCommandQuery.newBuilder();
// sniffer info
builder.setServiceId(RemoteDownstreamConfig.Agent.SERVICE_ID)
.setInstanceId(RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID);
// sniffer info
builder.setService(Config.Agent.SERVICE_NAME)
.setServiceInstance(Config.Agent.INSTANCE_NAME);
// last command create time
builder.setLastCommandTime(ServiceManager.INSTANCE.findService(ProfileTaskExecutionService.class)
.getLastCommandCreateTime());
// last command create time
builder.setLastCommandTime(ServiceManager.INSTANCE.findService(ProfileTaskExecutionService.class)
.getLastCommandCreateTime());
Commands commands = profileTaskBlockingStub.withDeadlineAfter(GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS)
.getProfileTaskCommands(builder.build());
Commands commands = profileTaskBlockingStub.withDeadlineAfter(GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS)
.getProfileTaskCommands(builder.build());
ServiceManager.INSTANCE.findService(CommandService.class).receiveCommand(commands);
} catch (Throwable t) {
if (!(t instanceof StatusRuntimeException)) {
logger.error(t, "Query profile task from backend fail.");
return;
ServiceManager.INSTANCE.findService(CommandService.class).receiveCommand(commands);
} catch (Throwable t) {
if (!(t instanceof StatusRuntimeException)) {
logger.error(t, "Query profile task from backend fail.");
return;
}
final StatusRuntimeException statusRuntimeException = (StatusRuntimeException) t;
if (statusRuntimeException.getStatus().getCode() == Status.Code.UNIMPLEMENTED) {
logger.warn("Backend doesn't support profiling, profiling will be disabled");
if (getTaskListFuture != null) {
getTaskListFuture.cancel(true);
}
final StatusRuntimeException statusRuntimeException = (StatusRuntimeException) t;
if (statusRuntimeException.getStatus().getCode() == Status.Code.UNIMPLEMENTED) {
logger.warn("Backend doesn't support profiling, profiling will be disabled");
if (getTaskListFuture != null) {
getTaskListFuture.cancel(true);
}
// stop snapshot sender
if (sendSnapshotFuture != null) {
sendSnapshotFuture.cancel(true);
}
// stop snapshot sender
if (sendSnapshotFuture != null) {
sendSnapshotFuture.cancel(true);
}
}
}
}
}
@Override
......@@ -190,8 +184,8 @@ public class ProfileTaskChannelService implements BootService, Runnable, GRPCCha
try {
final ProfileTaskFinishReport.Builder reportBuilder = ProfileTaskFinishReport.newBuilder();
// sniffer info
reportBuilder.setServiceId(RemoteDownstreamConfig.Agent.SERVICE_ID)
.setInstanceId(RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID);
reportBuilder.setService(Config.Agent.SERVICE_NAME)
.setServiceInstance(Config.Agent.INSTANCE_NAME);
// task info
reportBuilder.setTaskId(task.getTaskId());
......@@ -212,7 +206,8 @@ public class ProfileTaskChannelService implements BootService, Runnable, GRPCCha
public void run() {
if (status == GRPCChannelStatus.CONNECTED) {
try {
ArrayList<TracingThreadSnapshot> buffer = new ArrayList<>(Config.Profile.SNAPSHOT_TRANSPORT_BUFFER_SIZE);
ArrayList<TracingThreadSnapshot> buffer = new ArrayList<>(
Config.Profile.SNAPSHOT_TRANSPORT_BUFFER_SIZE);
snapshotQueue.drainTo(buffer);
if (buffer.size() > 0) {
final GRPCStreamServiceStatus status = new GRPCStreamServiceStatus(false);
......
......@@ -18,15 +18,13 @@
package org.apache.skywalking.apm.agent.core.profile;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.TracingContext;
import org.apache.skywalking.apm.agent.core.context.ids.ID;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReferenceArray;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.TracingContext;
/**
* profile task execution context, it will create on process this profile task
......@@ -74,7 +72,9 @@ public class ProfileTaskExecutionContext {
*
* @return is add profile success
*/
public ProfileStatusReference attemptProfiling(TracingContext tracingContext, ID traceSegmentId, String firstSpanOPName) {
public ProfileStatusReference attemptProfiling(TracingContext tracingContext,
String traceSegmentId,
String firstSpanOPName) {
// check has available slot
final int usingSlotCount = currentProfilingCount.get();
if (usingSlotCount >= Config.Profile.MAX_PARALLEL) {
......@@ -96,7 +96,8 @@ public class ProfileTaskExecutionContext {
return ProfileStatusReference.createWithNone();
}
final ThreadProfiler threadProfiler = new ThreadProfiler(tracingContext, traceSegmentId, Thread.currentThread(), this);
final ThreadProfiler threadProfiler = new ThreadProfiler(
tracingContext, traceSegmentId, Thread.currentThread(), this);
int slotLength = profilingSegmentSlots.length();
for (int slot = 0; slot < slotLength; slot++) {
if (profilingSegmentSlots.compareAndSet(slot, null, threadProfiler)) {
......@@ -109,14 +110,15 @@ public class ProfileTaskExecutionContext {
/**
* profiling recheck
*/
public void profilingRecheck(TracingContext tracingContext, ID traceSegmentId, String firstSpanOPName) {
public void profilingRecheck(TracingContext tracingContext, String traceSegmentId, String firstSpanOPName) {
// if started, keep profiling
if (tracingContext.profileStatus().isBeingWatched()) {
return;
}
// update profiling status
tracingContext.profileStatus().updateStatus(attemptProfiling(tracingContext, traceSegmentId, firstSpanOPName).get());
tracingContext.profileStatus()
.updateStatus(attemptProfiling(tracingContext, traceSegmentId, firstSpanOPName).get());
}
/**
......
......@@ -32,7 +32,6 @@ import org.apache.skywalking.apm.agent.core.boot.DefaultNamedThreadFactory;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.context.TracingContext;
import org.apache.skywalking.apm.agent.core.context.TracingThreadListener;
import org.apache.skywalking.apm.agent.core.context.ids.ID;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.network.constants.ProfileConstants;
......@@ -91,7 +90,9 @@ public class ProfileTaskExecutionService implements BootService, TracingThreadLi
/**
* check and add {@link TracingContext} profiling
*/
public ProfileStatusReference addProfiling(TracingContext tracingContext, ID traceSegmentId, String firstSpanOPName) {
public ProfileStatusReference addProfiling(TracingContext tracingContext,
String traceSegmentId,
String firstSpanOPName) {
// get current profiling task, check need profiling
final ProfileTaskExecutionContext executionContext = taskExecutionContext.get();
if (executionContext == null) {
......@@ -104,7 +105,7 @@ public class ProfileTaskExecutionService implements BootService, TracingThreadLi
/**
* Re-check current trace need profiling, in case that third-party plugins change the operation name.
*/
public void profilingRecheck(TracingContext tracingContext, ID traceSegmentId, String firstSpanOPName) {
public void profilingRecheck(TracingContext tracingContext, String traceSegmentId, String firstSpanOPName) {
// get current profiling task, check need profiling
final ProfileTaskExecutionContext executionContext = taskExecutionContext.get();
if (executionContext == null) {
......
......@@ -19,19 +19,17 @@
package org.apache.skywalking.apm.agent.core.profile;
import com.google.common.base.Objects;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.TracingContext;
import org.apache.skywalking.apm.agent.core.context.ids.ID;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.TracingContext;
public class ThreadProfiler {
// current tracing context
private final TracingContext tracingContext;
// current tracing segment id
private final ID traceSegmentId;
private final String traceSegmentId;
// need to profiling thread
private final Thread profilingThread;
// profiling execution context
......@@ -46,7 +44,7 @@ public class ThreadProfiler {
// thread dump sequence
private int dumpSequence = 0;
public ThreadProfiler(TracingContext tracingContext, ID traceSegmentId, Thread profilingThread,
public ThreadProfiler(TracingContext tracingContext, String traceSegmentId, Thread profilingThread,
ProfileTaskExecutionContext executionContext) {
this.tracingContext = tracingContext;
this.traceSegmentId = traceSegmentId;
......@@ -130,7 +128,7 @@ public class ThreadProfiler {
*/
public boolean matches(TracingContext context) {
// match trace id
return Objects.equal(context.getReadableGlobalTraceId(), tracingContext.getReadableGlobalTraceId());
return Objects.equal(context.getReadablePrimaryTraceId(), tracingContext.getReadablePrimaryTraceId());
}
/**
......
......@@ -18,24 +18,26 @@
package org.apache.skywalking.apm.agent.core.profile;
import org.apache.skywalking.apm.agent.core.context.ids.ID;
import org.apache.skywalking.apm.network.language.profile.ThreadSnapshot;
import org.apache.skywalking.apm.network.language.profile.ThreadStack;
import java.util.List;
import org.apache.skywalking.apm.network.language.profile.v3.ThreadSnapshot;
import org.apache.skywalking.apm.network.language.profile.v3.ThreadStack;
public class TracingThreadSnapshot {
// thread profiler
private final String taskId;
private final ID traceSegmentId;
private final String traceSegmentId;
// dump info
private final int sequence;
private final long time;
private final List<String> stackList;
public TracingThreadSnapshot(String taskId, ID traceSegmentId, int sequence, long time, List<String> stackList) {
public TracingThreadSnapshot(String taskId,
String traceSegmentId,
int sequence,
long time,
List<String> stackList) {
this.taskId = taskId;
this.traceSegmentId = traceSegmentId;
this.sequence = sequence;
......@@ -51,7 +53,7 @@ public class TracingThreadSnapshot {
// task id
builder.setTaskId(taskId);
// dumped segment id
builder.setTraceSegmentId(traceSegmentId.transform());
builder.setTraceSegmentId(traceSegmentId);
// dump time
builder.setTime(time);
// snapshot dump sequence
......
......@@ -31,51 +31,36 @@ import org.apache.skywalking.apm.agent.core.boot.DefaultNamedThreadFactory;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.commands.CommandService;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.agent.core.dictionary.NetworkAddressDictionary;
import org.apache.skywalking.apm.agent.core.logging.api.ILog;
import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.agent.core.os.OSUtil;
import org.apache.skywalking.apm.network.common.Commands;
import org.apache.skywalking.apm.network.common.KeyIntValuePair;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import org.apache.skywalking.apm.network.common.ServiceType;
import org.apache.skywalking.apm.network.register.v2.RegisterGrpc;
import org.apache.skywalking.apm.network.register.v2.Service;
import org.apache.skywalking.apm.network.register.v2.ServiceInstance;
import org.apache.skywalking.apm.network.register.v2.ServiceInstancePingGrpc;
import org.apache.skywalking.apm.network.register.v2.ServiceInstancePingPkg;
import org.apache.skywalking.apm.network.register.v2.ServiceInstanceRegisterMapping;
import org.apache.skywalking.apm.network.register.v2.ServiceInstances;
import org.apache.skywalking.apm.network.register.v2.ServiceRegisterMapping;
import org.apache.skywalking.apm.network.register.v2.Services;
import org.apache.skywalking.apm.network.common.v3.Commands;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
import org.apache.skywalking.apm.network.management.v3.InstancePingPkg;
import org.apache.skywalking.apm.network.management.v3.InstanceProperties;
import org.apache.skywalking.apm.network.management.v3.ManagementServiceGrpc;
import org.apache.skywalking.apm.util.RunnableWithExceptionProtection;
import org.apache.skywalking.apm.util.StringUtil;
import static org.apache.skywalking.apm.agent.core.conf.Config.Collector.GRPC_UPSTREAM_TIMEOUT;
@DefaultImplementor
public class ServiceRegisterClient implements BootService, Runnable, GRPCChannelListener {
private static final ILog logger = LogManager.getLogger(ServiceRegisterClient.class);
private static String INSTANCE_UUID;
public class ServiceManagementClient implements BootService, Runnable, GRPCChannelListener {
private static final ILog logger = LogManager.getLogger(ServiceManagementClient.class);
private static List<KeyStringValuePair> SERVICE_INSTANCE_PROPERTIES;
private volatile GRPCChannelStatus status = GRPCChannelStatus.DISCONNECT;
private volatile RegisterGrpc.RegisterBlockingStub registerBlockingStub;
private volatile ServiceInstancePingGrpc.ServiceInstancePingBlockingStub serviceInstancePingStub;
private volatile ManagementServiceGrpc.ManagementServiceBlockingStub managementServiceBlockingStub;
private volatile ScheduledFuture<?> serviceRegisterFuture;
private volatile long coolDownStartTime = -1;
private volatile boolean instancePropertiesSubmitted = false;
@Override
public void statusChanged(GRPCChannelStatus status) {
if (GRPCChannelStatus.CONNECTED.equals(status)) {
Channel channel = ServiceManager.INSTANCE.findService(GRPCChannelManager.class).getChannel();
registerBlockingStub = RegisterGrpc.newBlockingStub(channel);
serviceInstancePingStub = ServiceInstancePingGrpc.newBlockingStub(channel);
managementServiceBlockingStub = ManagementServiceGrpc.newBlockingStub(channel);
} else {
registerBlockingStub = null;
serviceInstancePingStub = null;
managementServiceBlockingStub = null;
}
this.status = status;
}
......@@ -84,10 +69,6 @@ public class ServiceRegisterClient implements BootService, Runnable, GRPCChannel
public void prepare() {
ServiceManager.INSTANCE.findService(GRPCChannelManager.class).addChannelListener(this);
INSTANCE_UUID = StringUtil.isEmpty(Config.Agent.INSTANCE_UUID)
? UUID.randomUUID().toString().replaceAll("-", "")
: Config.Agent.INSTANCE_UUID;
SERVICE_INSTANCE_PROPERTIES = new ArrayList<>();
for (String key : Config.Agent.INSTANCE_PROPERTIES.keySet()) {
......@@ -96,6 +77,10 @@ public class ServiceRegisterClient implements BootService, Runnable, GRPCChannel
.setValue(Config.Agent.INSTANCE_PROPERTIES.get(key))
.build());
}
Config.Agent.INSTANCE_NAME = StringUtil.isEmpty(Config.Agent.INSTANCE_NAME)
? UUID.randomUUID().toString().replaceAll("-", "") + "@" + OSUtil.getIPV4()
: Config.Agent.INSTANCE_NAME;
}
@Override
......@@ -122,96 +107,37 @@ public class ServiceRegisterClient implements BootService, Runnable, GRPCChannel
@Override
public void run() {
logger.debug("ServiceRegisterClient running, status:{}.", status);
if (coolDownStartTime > 0) {
final long coolDownDurationInMillis = TimeUnit.MINUTES.toMillis(Config.Agent.COOL_DOWN_THRESHOLD);
if (System.currentTimeMillis() - coolDownStartTime < coolDownDurationInMillis) {
logger.warn("The agent is cooling down, won't register itself");
return;
} else {
logger.warn("The agent is re-registering itself to backend");
}
}
coolDownStartTime = -1;
logger.debug("ServiceManagementClient running, status:{}.", status);
boolean shouldTry = true;
while (GRPCChannelStatus.CONNECTED.equals(status) && shouldTry) {
shouldTry = false;
while (GRPCChannelStatus.CONNECTED.equals(status)) {
try {
if (RemoteDownstreamConfig.Agent.SERVICE_ID == DictionaryUtil.nullValue()) {
if (registerBlockingStub != null) {
ServiceRegisterMapping serviceRegisterMapping = registerBlockingStub.withDeadlineAfter(
if (managementServiceBlockingStub != null) {
if (!instancePropertiesSubmitted) {
managementServiceBlockingStub
.withDeadlineAfter(GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS)
.reportInstanceProperties(InstanceProperties.newBuilder()
.setService(Config.Agent.SERVICE_NAME)
.setServiceInstance(Config.Agent.INSTANCE_NAME)
.addAllProperties(OSUtil.buildOSInfo())
.addAllProperties(SERVICE_INSTANCE_PROPERTIES)
.build());
instancePropertiesSubmitted = true;
} else {
final Commands commands = managementServiceBlockingStub.withDeadlineAfter(
GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS
).doServiceRegister(
Services.newBuilder()
.addServices(
Service
.newBuilder()
.setServiceName(Config.Agent.SERVICE_NAME)
.setType(ServiceType.normal))
.build()
);
if (serviceRegisterMapping != null) {
for (KeyIntValuePair registered : serviceRegisterMapping.getServicesList()) {
if (Config.Agent.SERVICE_NAME.equals(registered.getKey())) {
RemoteDownstreamConfig.Agent.SERVICE_ID = registered.getValue();
shouldTry = true;
}
}
}
}
} else {
if (registerBlockingStub != null) {
if (RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID == DictionaryUtil.nullValue()) {
ServiceInstanceRegisterMapping instanceMapping = registerBlockingStub.withDeadlineAfter(
GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS
).doServiceInstanceRegister(
ServiceInstances
.newBuilder()
.addInstances(
ServiceInstance
.newBuilder()
.setServiceId(RemoteDownstreamConfig.Agent.SERVICE_ID)
.setInstanceUUID(INSTANCE_UUID)
.setTime(System.currentTimeMillis())
.addAllProperties(OSUtil.buildOSInfo())
.addAllProperties(SERVICE_INSTANCE_PROPERTIES))
.build());
for (KeyIntValuePair serviceInstance : instanceMapping.getServiceInstancesList()) {
if (INSTANCE_UUID.equals(serviceInstance.getKey())) {
int serviceInstanceId = serviceInstance.getValue();
if (serviceInstanceId != DictionaryUtil.nullValue()) {
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID = serviceInstanceId;
RemoteDownstreamConfig.Agent.INSTANCE_REGISTERED_TIME = System.currentTimeMillis();
}
}
}
} else {
final Commands commands = serviceInstancePingStub.withDeadlineAfter(
GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS
).doPing(ServiceInstancePingPkg.newBuilder()
.setServiceInstanceId(
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID)
.setTime(System.currentTimeMillis())
.setServiceInstanceUUID(INSTANCE_UUID)
.build());
NetworkAddressDictionary.INSTANCE.syncRemoteDictionary(
registerBlockingStub.withDeadlineAfter(GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS));
ServiceManager.INSTANCE.findService(CommandService.class).receiveCommand(commands);
}
).keepAlive(InstancePingPkg.newBuilder()
.setService(Config.Agent.SERVICE_NAME)
.setServiceInstance(Config.Agent.INSTANCE_NAME)
.build());
ServiceManager.INSTANCE.findService(CommandService.class).receiveCommand(commands);
}
}
} catch (Throwable t) {
logger.error(t, "ServiceRegisterClient execute fail.");
logger.error(t, "ServiceManagementClient execute fail.");
ServiceManager.INSTANCE.findService(GRPCChannelManager.class).reportError(t);
}
}
}
public void coolDown() {
this.coolDownStartTime = System.currentTimeMillis();
}
}
......@@ -35,9 +35,9 @@ import org.apache.skywalking.apm.agent.core.logging.api.LogManager;
import org.apache.skywalking.apm.commons.datacarrier.DataCarrier;
import org.apache.skywalking.apm.commons.datacarrier.buffer.BufferStrategy;
import org.apache.skywalking.apm.commons.datacarrier.consumer.IConsumer;
import org.apache.skywalking.apm.network.common.Commands;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
import org.apache.skywalking.apm.network.language.agent.v2.TraceSegmentReportServiceGrpc;
import org.apache.skywalking.apm.network.common.v3.Commands;
import org.apache.skywalking.apm.network.language.agent.v3.SegmentObject;
import org.apache.skywalking.apm.network.language.agent.v3.TraceSegmentReportServiceGrpc;
import static org.apache.skywalking.apm.agent.core.conf.Config.Buffer.BUFFER_SIZE;
import static org.apache.skywalking.apm.agent.core.conf.Config.Buffer.CHANNEL_SIZE;
......@@ -89,7 +89,7 @@ public class TraceSegmentServiceClient implements BootService, IConsumer<TraceSe
public void consume(List<TraceSegment> data) {
if (CONNECTED.equals(status)) {
final GRPCStreamServiceStatus status = new GRPCStreamServiceStatus(false);
StreamObserver<UpstreamSegment> upstreamSegmentStreamObserver = serviceStub.withDeadlineAfter(
StreamObserver<SegmentObject> upstreamSegmentStreamObserver = serviceStub.withDeadlineAfter(
Config.Collector.GRPC_UPSTREAM_TIMEOUT, TimeUnit.SECONDS
).collect(new StreamObserver<Commands>() {
@Override
......@@ -121,7 +121,7 @@ public class TraceSegmentServiceClient implements BootService, IConsumer<TraceSe
try {
for (TraceSegment segment : data) {
UpstreamSegment upstreamSegment = segment.transform();
SegmentObject upstreamSegment = segment.transform();
upstreamSegmentStreamObserver.onNext(upstreamSegment);
}
} catch (Throwable t) {
......
......@@ -21,7 +21,7 @@ org.apache.skywalking.apm.agent.core.context.ContextManager
org.apache.skywalking.apm.agent.core.sampling.SamplingService
org.apache.skywalking.apm.agent.core.remote.GRPCChannelManager
org.apache.skywalking.apm.agent.core.jvm.JVMService
org.apache.skywalking.apm.agent.core.remote.ServiceRegisterClient
org.apache.skywalking.apm.agent.core.remote.ServiceManagementClient
org.apache.skywalking.apm.agent.core.context.ContextManagerExtendService
org.apache.skywalking.apm.agent.core.commands.CommandService
org.apache.skywalking.apm.agent.core.commands.CommandExecutorService
......
......@@ -105,7 +105,7 @@ public class ServiceManagerTest {
assertNotNull(service);
List<GRPCChannelListener> listeners = getFieldValue(service, "listeners");
assertEquals(listeners.size(), 4);
assertEquals(listeners.size(), 5);
}
private void assertSamplingService(SamplingService service) {
......
......@@ -21,21 +21,20 @@ package org.apache.skywalking.apm.agent.core.context;
import java.util.ArrayList;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.ids.DistributedTraceId;
import org.apache.skywalking.apm.agent.core.context.ids.ID;
import org.apache.skywalking.apm.agent.core.context.ids.PropagatedTraceId;
import org.junit.Assert;
import org.junit.Test;
public class ContextCarrierV2HeaderTest {
public class ContextCarrierV3HeaderTest {
@Test
public void testDeserializeV2Header() {
public void testDeserializeV3Header() {
ContextCarrier contextCarrier = new ContextCarrier();
CarrierItem next = contextCarrier.items();
while (next.hasNext()) {
next = next.next();
if (next.getHeadKey().equals(SW6CarrierItem.HEADER_NAME)) {
next.setHeadValue("1-My40LjU=-MS4yLjM=-4-1-1-IzEyNy4wLjAuMTo4MDgw--");
if (next.getHeadKey().equals(SW8CarrierItem.HEADER_NAME)) {
next.setHeadValue("1-My40LjU=-MS4yLjM=-4-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=");
} else if (next.getHeadKey().equals(SW8CorrelationCarrierItem.HEADER_NAME)) {
next.setHeadValue("dGVzdA==:dHJ1ZQ==");
} else {
......@@ -47,32 +46,26 @@ public class ContextCarrierV2HeaderTest {
}
@Test
public void testSerializeV2Header() {
public void testSerializeV3Header() {
List<DistributedTraceId> distributedTraceIds = new ArrayList<>();
distributedTraceIds.add(new PropagatedTraceId("3.4.5"));
ContextCarrier contextCarrier = new ContextCarrier();
contextCarrier.setTraceSegmentId(new ID(1, 2, 3));
contextCarrier.setDistributedTraceIds(distributedTraceIds);
contextCarrier.setTraceSegmentId("1.2.3");
contextCarrier.setTraceId("3.4.5");
contextCarrier.setSpanId(4);
contextCarrier.setEntryServiceInstanceId(1);
contextCarrier.setParentServiceInstanceId(1);
contextCarrier.setPeerHost("127.0.0.1:8080");
contextCarrier.setEntryEndpointName("/portal");
contextCarrier.setParentEndpointName("/app");
contextCarrier.setParentService("service");
contextCarrier.setParentServiceInstance("instance");
contextCarrier.setAddressUsedAtClient("127.0.0.1:8080");
contextCarrier.setParentEndpoint("/portal");
contextCarrier.setParentEndpoint("/app");
contextCarrier.getCorrelationContext().put("test", "true");
CarrierItem next = contextCarrier.items();
while (next.hasNext()) {
next = next.next();
/*
* sampleFlag-traceId-segmentId-spanId-parentAppInstId-entryAppInstId-peerHost-entryEndpoint-parentEndpoint
*
* "1-3.4.5-1.2.3-4-1-1-#127.0.0.1:8080-#/portal-123"
*/
if (next.getHeadKey().equals(SW6CarrierItem.HEADER_NAME)) {
Assert.assertEquals("1-My40LjU=-MS4yLjM=-4-1-1-IzEyNy4wLjAuMTo4MDgw-Iy9wb3J0YWw=-Iy9hcHA=", next.getHeadValue());
if (next.getHeadKey().equals(SW8CarrierItem.HEADER_NAME)) {
Assert.assertEquals("1-My40LjU=-MS4yLjM=-4-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=", next.getHeadValue());
} else if (next.getHeadKey().equals(SW8CorrelationCarrierItem.HEADER_NAME)) {
/**
* customKey:customValue
......@@ -88,8 +81,8 @@ public class ContextCarrierV2HeaderTest {
next = contextCarrier.items();
while (next.hasNext()) {
next = next.next();
if (next.getHeadKey().equals(SW6CarrierItem.HEADER_NAME)) {
Assert.assertEquals("1-My40LjU=-MS4yLjM=-4-1-1-IzEyNy4wLjAuMTo4MDgw-Iy9wb3J0YWw=-Iy9hcHA=", next.getHeadValue());
if (next.getHeadKey().equals(SW8CarrierItem.HEADER_NAME)) {
Assert.assertEquals("1-My40LjU=-MS4yLjM=-4-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=", next.getHeadValue());
} else if (next.getHeadKey().equals(SW8CorrelationCarrierItem.HEADER_NAME)) {
Assert.assertEquals("dGVzdA==:dHJ1ZQ==", next.getHeadValue());
} else {
......@@ -106,14 +99,14 @@ public class ContextCarrierV2HeaderTest {
distributedTraceIds.add(new PropagatedTraceId("3.4.5"));
ContextCarrier contextCarrier = new ContextCarrier();
contextCarrier.setTraceSegmentId(new ID(1, 2, 3));
contextCarrier.setDistributedTraceIds(distributedTraceIds);
contextCarrier.setTraceSegmentId("1.2.3");
contextCarrier.setTraceId("3.4.5");
contextCarrier.setSpanId(4);
contextCarrier.setEntryServiceInstanceId(1);
contextCarrier.setParentServiceInstanceId(1);
contextCarrier.setPeerHost("127.0.0.1:8080");
contextCarrier.setEntryEndpointName("/portal");
contextCarrier.setParentEndpointName("/app");
contextCarrier.setParentService("service");
contextCarrier.setParentServiceInstance("instance");
contextCarrier.setAddressUsedAtClient("127.0.0.1:8080");
contextCarrier.setParentEndpoint("/portal");
contextCarrier.setParentEndpoint("/app");
contextCarrier.getCorrelationContext().put("test", "true");
......@@ -122,7 +115,7 @@ public class ContextCarrierV2HeaderTest {
String correlationHeaderValue = null;
while (next.hasNext()) {
next = next.next();
if (next.getHeadKey().equals(SW6CarrierItem.HEADER_NAME)) {
if (next.getHeadKey().equals(SW8CarrierItem.HEADER_NAME)) {
sw6HeaderValue = next.getHeadValue();
} else if (next.getHeadKey().equals(SW8CorrelationCarrierItem.HEADER_NAME)) {
correlationHeaderValue = next.getHeadValue();
......@@ -135,7 +128,7 @@ public class ContextCarrierV2HeaderTest {
next = contextCarrier2.items();
while (next.hasNext()) {
next = next.next();
if (next.getHeadKey().equals(SW6CarrierItem.HEADER_NAME)) {
if (next.getHeadKey().equals(SW8CarrierItem.HEADER_NAME)) {
next.setHeadValue(sw6HeaderValue);
} else if (next.getHeadKey().equals(SW8CorrelationCarrierItem.HEADER_NAME)) {
next.setHeadValue(correlationHeaderValue);
......@@ -146,12 +139,12 @@ public class ContextCarrierV2HeaderTest {
Assert.assertTrue(contextCarrier2.isValid());
Assert.assertEquals(contextCarrier.getSpanId(), contextCarrier2.getSpanId());
Assert.assertEquals(contextCarrier.getPeerHost(), contextCarrier2.getPeerHost());
Assert.assertEquals(contextCarrier.getDistributedTraceId(), contextCarrier2.getDistributedTraceId());
Assert.assertEquals(contextCarrier.getAddressUsedAtClient(), contextCarrier2.getAddressUsedAtClient());
Assert.assertEquals(contextCarrier.getTraceId(), contextCarrier2.getTraceId());
Assert.assertEquals(contextCarrier.getTraceSegmentId(), contextCarrier2.getTraceSegmentId());
Assert.assertEquals(contextCarrier.getEntryEndpointName(), contextCarrier2.getEntryEndpointName());
Assert.assertEquals(contextCarrier.getEntryServiceInstanceId(), contextCarrier2.getEntryServiceInstanceId());
Assert.assertEquals(contextCarrier.getParentServiceInstanceId(), contextCarrier2.getParentServiceInstanceId());
Assert.assertEquals(contextCarrier.getParentService(), contextCarrier2.getParentService());
Assert.assertEquals(contextCarrier.getParentServiceInstance(), contextCarrier2.getParentServiceInstance());
Assert.assertEquals(contextCarrier.getParentEndpoint(), contextCarrier2.getParentEndpoint());
Assert.assertEquals(contextCarrier.getCorrelationContext(), contextCarrier2.getCorrelationContext());
}
}
......@@ -22,7 +22,7 @@ import com.google.protobuf.InvalidProtocolBufferException;
import java.util.List;
import java.util.Objects;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
......@@ -34,23 +34,20 @@ import org.apache.skywalking.apm.agent.core.context.util.AbstractTracingSpanHelp
import org.apache.skywalking.apm.agent.core.context.util.SegmentHelper;
import org.apache.skywalking.apm.agent.core.context.util.SpanHelper;
import org.apache.skywalking.apm.agent.core.context.util.TraceSegmentRefHelper;
import org.apache.skywalking.apm.agent.core.dictionary.DictionaryUtil;
import org.apache.skywalking.apm.agent.core.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.core.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.core.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.core.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.network.common.KeyStringValuePair;
import org.apache.skywalking.apm.network.language.agent.SpanType;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
import org.apache.skywalking.apm.network.language.agent.v2.Log;
import org.apache.skywalking.apm.network.language.agent.v2.SegmentObject;
import org.apache.skywalking.apm.network.language.agent.v2.SegmentReference;
import org.apache.skywalking.apm.network.language.agent.v2.SpanObjectV2;
import org.apache.skywalking.apm.network.common.v3.KeyStringValuePair;
import org.apache.skywalking.apm.network.language.agent.v3.Log;
import org.apache.skywalking.apm.network.language.agent.v3.SegmentObject;
import org.apache.skywalking.apm.network.language.agent.v3.SegmentReference;
import org.apache.skywalking.apm.network.language.agent.v3.SpanObject;
import org.apache.skywalking.apm.network.language.agent.v3.SpanType;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.hamcrest.MatcherAssert;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
......@@ -69,16 +66,15 @@ public class ContextManagerTest {
@Rule
public AgentServiceRule agentServiceRule = new AgentServiceRule();
@Before
public void setUp() throws Exception {
RemoteDownstreamConfig.Agent.SERVICE_ID = 1;
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID = 1;
@BeforeClass
public static void beforeClass() {
Config.Agent.KEEP_TRACING = true;
}
@AfterClass
public static void afterClass() {
Config.Agent.KEEP_TRACING = false;
ServiceManager.INSTANCE.shutdown();
}
@Test
......@@ -107,7 +103,10 @@ public class ContextManagerTest {
@Test
public void createMultipleEntrySpan() {
ContextCarrier contextCarrier = new ContextCarrier().deserialize("1-MS4yMzQzLjIzNDIzNDIzNA==-MS4yMzQzLjIzNDIzNDIzNA==-1-1-1-IzEyNy4wLjAuMTo4MDgw-Iy9wb3J0YWwv-Iy90ZXN0RW50cnlTcGFu", ContextCarrier.HeaderVersion.v2);
ContextCarrier contextCarrier = new ContextCarrier().deserialize(
"1-My40LjU=-MS4yLjM=-4-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=",
ContextCarrier.HeaderVersion.v3
);
assertTrue(contextCarrier.isValid());
AbstractSpan firstEntrySpan = ContextManager.createEntrySpan("/testFirstEntry", contextCarrier);
......@@ -140,7 +139,6 @@ public class ContextManagerTest {
TraceSegmentRef ref = actualSegment.getRefs().get(0);
MatcherAssert.assertThat(TraceSegmentRefHelper.getPeerHost(ref), is("127.0.0.1:8080"));
assertThat(ref.getEntryEndpointName(), is("/portal/"));
List<AbstractTracingSpan> spanList = SegmentHelper.getSpan(actualSegment);
assertThat(spanList.size(), is(2));
......@@ -162,8 +160,7 @@ public class ContextManagerTest {
assertThat(logs.get(0).getLogs().size(), is(4));
assertThat(injectContextCarrier.getSpanId(), is(1));
assertThat(injectContextCarrier.getEntryEndpointName(), is("#/portal/"));
assertThat(injectContextCarrier.getPeerHost(), is("#127.0.0.1:12800"));
assertThat(injectContextCarrier.getAddressUsedAtClient(), is("127.0.0.1:12800"));
}
@Test
......@@ -175,13 +172,15 @@ public class ContextManagerTest {
SpanLayer.asHttp(entrySpan);
ContextCarrier firstExitSpanContextCarrier = new ContextCarrier();
AbstractSpan firstExitSpan = ContextManager.createExitSpan("/testFirstExit", firstExitSpanContextCarrier, "127.0.0.1:8080");
AbstractSpan firstExitSpan = ContextManager.createExitSpan(
"/testFirstExit", firstExitSpanContextCarrier, "127.0.0.1:8080");
firstExitSpan.setComponent(ComponentsDefine.DUBBO);
Tags.URL.set(firstExitSpan, "dubbo://127.0.0.1:8080");
SpanLayer.asRPCFramework(firstExitSpan);
ContextCarrier secondExitSpanContextCarrier = new ContextCarrier();
AbstractSpan secondExitSpan = ContextManager.createExitSpan("/testSecondExit", secondExitSpanContextCarrier, "127.0.0.1:9080");
AbstractSpan secondExitSpan = ContextManager.createExitSpan(
"/testSecondExit", secondExitSpanContextCarrier, "127.0.0.1:9080");
secondExitSpan.setComponent(ComponentsDefine.TOMCAT);
Tags.HTTP.METHOD.set(secondExitSpan, "GET");
Tags.URL.set(secondExitSpan, "127.0.0.1:8080");
......@@ -211,25 +210,19 @@ public class ContextManagerTest {
assertThat(actualEntrySpan.getSpanId(), is(0));
assertThat(AbstractTracingSpanHelper.getParentSpanId(actualEntrySpan), is(-1));
assertThat(firstExitSpanContextCarrier.getPeerHost(), is("#127.0.0.1:8080"));
assertThat(firstExitSpanContextCarrier.getAddressUsedAtClient(), is("127.0.0.1:8080"));
assertThat(firstExitSpanContextCarrier.getSpanId(), is(1));
assertThat(firstExitSpanContextCarrier.getEntryEndpointName(), is("#/testEntrySpan"));
assertThat(secondExitSpanContextCarrier.getPeerHost(), is("#127.0.0.1:8080"));
assertThat(secondExitSpanContextCarrier.getSpanId(), is(1));
assertThat(secondExitSpanContextCarrier.getEntryEndpointName(), is("#/testEntrySpan"));
}
@After
public void tearDown() throws Exception {
RemoteDownstreamConfig.Agent.SERVICE_ID = DictionaryUtil.nullValue();
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID = DictionaryUtil.nullValue();
}
@Test
public void testTransform() throws InvalidProtocolBufferException {
ContextCarrier contextCarrier = new ContextCarrier().deserialize("1-MS4yMzQzLjIzNDIzNDIzNA==-MS4yMzQuMTk4MzgyOQ==-3-1-1-IzEyNy4wLjAuMTo4MDgw-Iy9wb3J0YWwv-Iy90ZXN0RW50cnlTcGFu", ContextCarrier.HeaderVersion.v2);
ContextCarrier contextCarrier = new ContextCarrier().deserialize(
"1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=",
ContextCarrier.HeaderVersion.v3
);
assertTrue(contextCarrier.isValid());
AbstractSpan firstEntrySpan = ContextManager.createEntrySpan("/testFirstEntry", contextCarrier);
......@@ -256,31 +249,26 @@ public class ContextManagerTest {
TraceSegment actualSegment = tracingData.getTraceSegments().get(0);
UpstreamSegment upstreamSegment = actualSegment.transform();
assertThat(upstreamSegment.getGlobalTraceIdsCount(), is(1));
SegmentObject traceSegmentObject = SegmentObject.parseFrom(upstreamSegment.getSegment());
SegmentObject traceSegmentObject = actualSegment.transform();
SegmentReference reference = traceSegmentObject.getSpans(1).getRefs(0);
assertThat(reference.getNetworkAddress(), is("127.0.0.1:8080"));
assertThat(reference.getNetworkAddressUsedAtPeer(), is("127.0.0.1:8080"));
assertThat(reference.getParentSpanId(), is(3));
assertThat(traceSegmentObject.getServiceId(), is(1));
assertThat(traceSegmentObject.getSpans(1).getRefsCount(), is(1));
assertThat(traceSegmentObject.getSpansCount(), is(2));
SpanObjectV2 actualSpan = traceSegmentObject.getSpans(1);
SpanObject actualSpan = traceSegmentObject.getSpans(1);
assertThat(actualSpan.getComponentId(), is(3));
assertThat(actualSpan.getComponent(), is(""));
assertThat(actualSpan.getOperationName(), is("/testSecondEntry"));
assertThat(actualSpan.getParentSpanId(), is(-1));
assertThat(actualSpan.getSpanId(), is(0));
assertThat(actualSpan.getSpanType(), is(SpanType.Entry));
SpanObjectV2 exitSpanObject = traceSegmentObject.getSpans(0);
SpanObject exitSpanObject = traceSegmentObject.getSpans(0);
assertThat(exitSpanObject.getComponentId(), is(2));
assertThat(exitSpanObject.getComponent(), is(""));
assertThat(exitSpanObject.getSpanType(), is(SpanType.Exit));
assertThat(exitSpanObject.getOperationName(), is("/textExitSpan"));
......
......@@ -21,16 +21,14 @@ package org.apache.skywalking.apm.agent.core.context;
import java.util.LinkedList;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.NoopSpan;
import org.apache.skywalking.apm.agent.core.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.core.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.core.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.core.test.tools.TracingSegmentRunner;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
......@@ -48,21 +46,17 @@ public class IgnoredTracerContextTest {
@Rule
public AgentServiceRule agentServiceRule = new AgentServiceRule();
@Before
public void setUp() throws Exception {
RemoteDownstreamConfig.Agent.SERVICE_ID = 1;
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID = 1;
@BeforeClass
public static void beforeClass() {
Config.Agent.KEEP_TRACING = true;
}
@AfterClass
public static void afterClass() {
Config.Agent.KEEP_TRACING = false;
ServiceManager.INSTANCE.shutdown();
}
@After
public void tearDown() throws Exception {
}
@Test
public void ignoredTraceContextWithSampling() {
Config.Agent.SAMPLE_N_PER_3_SECS = 1;
......@@ -101,9 +95,9 @@ public class IgnoredTracerContextTest {
ContextManager.stopSpan();
assertThat(abstractSpan.getClass().getName(), is(NoopSpan.class.getName()));
assertNull(contextCarrier.getEntryEndpointName());
assertNull(contextCarrier.getParentEndpoint());
assertThat(contextCarrier.getSpanId(), is(-1));
assertNull(contextCarrier.getPeerHost());
assertNull(contextCarrier.getAddressUsedAtClient());
LinkedList<IgnoredTracerContext> ignoredTracerContexts = storage.getIgnoredTracerContexts();
assertThat(ignoredTracerContexts.size(), is(1));
......
......@@ -18,8 +18,7 @@
package org.apache.skywalking.apm.agent.core.context;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.junit.AfterClass;
......@@ -29,15 +28,13 @@ import org.junit.Test;
public class TracingContextTest {
@BeforeClass
public static void setup() {
ServiceManager.INSTANCE.boot();
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID = 5;
public static void beforeClass() {
Config.Agent.KEEP_TRACING = true;
}
@AfterClass
public static void clear() {
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID = 0;
ServiceManager.INSTANCE.shutdown();
public static void afterClass() {
Config.Agent.KEEP_TRACING = false;
}
@Test
......
......@@ -23,7 +23,7 @@ import org.apache.skywalking.apm.agent.core.context.trace.TraceSegmentRef;
public class TraceSegmentRefHelper {
public static String getPeerHost(TraceSegmentRef ref) {
try {
return FieldGetter.getValue(ref, "peerHost");
return FieldGetter.getValue(ref, "addressUsedAtClient");
} catch (Exception e) {
}
......
/*
* 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.agent.core.remote;
import io.grpc.Server;
import io.grpc.netty.NettyServerBuilder;
import io.grpc.stub.StreamObserver;
import java.net.InetSocketAddress;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.network.register.v2.RegisterGrpc;
import org.apache.skywalking.apm.network.register.v2.Service;
import org.apache.skywalking.apm.network.register.v2.ServiceRegisterMapping;
import org.apache.skywalking.apm.network.register.v2.Services;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
public class GRPCChannelManagerTest {
@BeforeClass
public static void setup() {
Config.Collector.BACKEND_SERVICE = "127.0.0.1:8080";
}
@AfterClass
public static void clear() {
Config.Collector.BACKEND_SERVICE = "";
}
//@Test
public void testConnected() throws Throwable {
GRPCChannelManager manager = new GRPCChannelManager();
manager.addChannelListener(new GRPCChannelListener() {
@Override
public void statusChanged(GRPCChannelStatus status) {
}
});
manager.boot();
Thread.sleep(1000);
RegisterGrpc.RegisterBlockingStub stub = RegisterGrpc.newBlockingStub(manager.getChannel());
try {
stub.doServiceRegister(Services.newBuilder()
.addServices(Service.newBuilder().setServiceName("abc"))
.build());
} catch (Exception e) {
e.printStackTrace();
}
NettyServerBuilder nettyServerBuilder = NettyServerBuilder.forAddress(new InetSocketAddress("127.0.0.1", 8080));
nettyServerBuilder.addService(new RegisterGrpc.RegisterImplBase() {
@Override
public void doServiceRegister(Services request, StreamObserver<ServiceRegisterMapping> responseObserver) {
}
});
Server server = nettyServerBuilder.build();
server.start();
Thread.sleep(1000);
boolean registerSuccess = false;
try {
stub.doServiceRegister(Services.newBuilder()
.addServices(Service.newBuilder().setServiceName("abc"))
.build());
registerSuccess = true;
} catch (Exception e) {
e.printStackTrace();
}
Assert.assertTrue(registerSuccess);
server.shutdownNow();
}
}
......@@ -24,7 +24,7 @@ import io.grpc.testing.GrpcServerRule;
import java.util.ArrayList;
import java.util.List;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.RemoteDownstreamConfig;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.ContextManager;
import org.apache.skywalking.apm.agent.core.context.tag.Tags;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractSpan;
......@@ -33,12 +33,11 @@ import org.apache.skywalking.apm.agent.core.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.core.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.core.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.core.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.network.common.Commands;
import org.apache.skywalking.apm.network.language.agent.SpanType;
import org.apache.skywalking.apm.network.language.agent.UpstreamSegment;
import org.apache.skywalking.apm.network.language.agent.v2.SegmentObject;
import org.apache.skywalking.apm.network.language.agent.v2.SpanObjectV2;
import org.apache.skywalking.apm.network.language.agent.v2.TraceSegmentReportServiceGrpc;
import org.apache.skywalking.apm.network.common.v3.Commands;
import org.apache.skywalking.apm.network.language.agent.v3.SegmentObject;
import org.apache.skywalking.apm.network.language.agent.v3.SpanObject;
import org.apache.skywalking.apm.network.language.agent.v3.SpanType;
import org.apache.skywalking.apm.network.language.agent.v3.TraceSegmentReportServiceGrpc;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.junit.AfterClass;
import org.junit.Before;
......@@ -65,14 +64,14 @@ public class TraceSegmentServiceClientTest {
private SegmentStorage storage;
private TraceSegmentServiceClient serviceClient = new TraceSegmentServiceClient();
private List<UpstreamSegment> upstreamSegments;
private List<SegmentObject> upstreamSegments;
private TraceSegmentReportServiceGrpc.TraceSegmentReportServiceImplBase serviceImplBase = new TraceSegmentReportServiceGrpc.TraceSegmentReportServiceImplBase() {
@Override
public StreamObserver<UpstreamSegment> collect(final StreamObserver<Commands> responseObserver) {
return new StreamObserver<UpstreamSegment>() {
public StreamObserver<SegmentObject> collect(final StreamObserver<Commands> responseObserver) {
return new StreamObserver<SegmentObject>() {
@Override
public void onNext(UpstreamSegment value) {
public void onNext(SegmentObject value) {
upstreamSegments.add(value);
}
......@@ -90,13 +89,13 @@ public class TraceSegmentServiceClientTest {
};
@BeforeClass
public static void setUpBeforeClass() {
RemoteDownstreamConfig.Agent.SERVICE_ID = 1;
RemoteDownstreamConfig.Agent.SERVICE_INSTANCE_ID = 1;
public static void beforeClass() {
Config.Agent.KEEP_TRACING = true;
}
@AfterClass
public static void afterClass() {
Config.Agent.KEEP_TRACING = false;
ServiceManager.INSTANCE.shutdown();
}
......@@ -105,10 +104,11 @@ public class TraceSegmentServiceClientTest {
Whitebox.setInternalState(ServiceManager.INSTANCE.findService(GRPCChannelManager.class), "reconnect", false);
spy(serviceClient);
Whitebox.setInternalState(serviceClient, "serviceStub", TraceSegmentReportServiceGrpc.newStub(grpcServerRule.getChannel()));
Whitebox.setInternalState(
serviceClient, "serviceStub", TraceSegmentReportServiceGrpc.newStub(grpcServerRule.getChannel()));
Whitebox.setInternalState(serviceClient, "status", GRPCChannelStatus.CONNECTED);
upstreamSegments = new ArrayList<UpstreamSegment>();
upstreamSegments = new ArrayList<>();
}
@Test
......@@ -125,13 +125,11 @@ public class TraceSegmentServiceClientTest {
serviceClient.consume(storage.getTraceSegments());
assertThat(upstreamSegments.size(), is(1));
UpstreamSegment upstreamSegment = upstreamSegments.get(0);
assertThat(upstreamSegment.getGlobalTraceIdsCount(), is(1));
SegmentObject traceSegmentObject = SegmentObject.parseFrom(upstreamSegment.getSegment());
SegmentObject traceSegmentObject = upstreamSegments.get(0);
assertThat(traceSegmentObject.getSpans(0).getRefsCount(), is(0));
assertThat(traceSegmentObject.getSpansCount(), is(1));
SpanObjectV2 spanObject = traceSegmentObject.getSpans(0);
SpanObject spanObject = traceSegmentObject.getSpans(0);
assertThat(spanObject.getSpanType(), is(SpanType.Entry));
assertThat(spanObject.getSpanId(), is(0));
assertThat(spanObject.getParentSpanId(), is(-1));
......@@ -152,7 +150,8 @@ public class TraceSegmentServiceClientTest {
assertThat(upstreamSegments.size(), is(0));
boolean reconnect = Whitebox.getInternalState(ServiceManager.INSTANCE.findService(GRPCChannelManager.class), "reconnect");
boolean reconnect = Whitebox.getInternalState(
ServiceManager.INSTANCE.findService(GRPCChannelManager.class), "reconnect");
assertThat(reconnect, is(true));
}
......
......@@ -27,7 +27,7 @@ import java.util.List;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.ContextManagerExtendService;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.LogDataEntity;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
......@@ -166,7 +166,8 @@ public class DubboInterceptorTest {
@Test
public void testProviderWithAttachment() throws Throwable {
when(rpcContext.isConsumerSide()).thenReturn(false);
when(rpcContext.getAttachment(SW6CarrierItem.HEADER_NAME)).thenReturn("1-MC4wLjA=-MS4zMjMuNDQzMw==-3-1-1-IzE5Mi4xNjguMS44IDoxODAwMg==-Iy9wb3J0YWwv-Iy90ZXN0RW50cnlTcGFu");
when(rpcContext.getAttachment(
SW8CarrierItem.HEADER_NAME)).thenReturn("1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=");
dubboInterceptor.beforeMethod(enhancedInstance, null, allArguments, argumentTypes, methodInterceptResult);
dubboInterceptor.afterMethod(enhancedInstance, null, allArguments, argumentTypes, result);
......@@ -198,8 +199,8 @@ public class DubboInterceptorTest {
private void assertTraceSegmentRef(TraceSegmentRef actual) {
assertThat(SegmentRefHelper.getSpanId(actual), is(3));
assertThat(SegmentRefHelper.getEntryServiceInstanceId(actual), is(1));
assertThat(SegmentRefHelper.getTraceSegmentId(actual).toString(), is("1.323.4433"));
assertThat(SegmentRefHelper.getParentServiceInstance(actual), is("instance"));
assertThat(SegmentRefHelper.getTraceSegmentId(actual), is("3.4.5"));
}
private void assertProviderSpan(AbstractTracingSpan span) {
......
......@@ -27,7 +27,7 @@ import java.util.List;
import org.apache.skywalking.apm.agent.core.boot.ServiceManager;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.ContextManagerExtendService;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.LogDataEntity;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
......@@ -165,7 +165,8 @@ public class DubboInterceptorTest {
@Test
public void testProviderWithAttachment() throws Throwable {
when(rpcContext.isConsumerSide()).thenReturn(false);
when(rpcContext.getAttachment(SW6CarrierItem.HEADER_NAME)).thenReturn("1-MC4wLjA=-MS4zMjMuNDQzMw==-3-1-1-IzE5Mi4xNjguMS44IDoxODAwMg==-Iy9wb3J0YWwv-Iy90ZXN0RW50cnlTcGFu");
when(rpcContext.getAttachment(
SW8CarrierItem.HEADER_NAME)).thenReturn("1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=");
dubboInterceptor.beforeMethod(enhancedInstance, null, allArguments, argumentTypes, methodInterceptResult);
dubboInterceptor.afterMethod(enhancedInstance, null, allArguments, argumentTypes, result);
......@@ -197,8 +198,8 @@ public class DubboInterceptorTest {
private void assertTraceSegmentRef(TraceSegmentRef actual) {
assertThat(SegmentRefHelper.getSpanId(actual), is(3));
assertThat(SegmentRefHelper.getEntryServiceInstanceId(actual), is(1));
assertThat(SegmentRefHelper.getTraceSegmentId(actual).toString(), is("1.323.4433"));
assertThat(SegmentRefHelper.getParentServiceInstance(actual), is("instance"));
assertThat(SegmentRefHelper.getTraceSegmentId(actual).toString(), is("3.4.5"));
}
private void assertProviderSpan(AbstractTracingSpan span) {
......
......@@ -21,7 +21,7 @@ package org.apache.skywalking.apm.plugin.finagle;
import com.twitter.io.Bufs;
import org.apache.skywalking.apm.agent.core.context.CarrierItem;
import org.apache.skywalking.apm.agent.core.context.ContextCarrier;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.junit.Test;
import java.util.HashMap;
......@@ -54,7 +54,7 @@ public class CodecUtilsTest {
CarrierItem next = contextCarrier.items();
while (next.hasNext()) {
next = next.next();
if (next.getHeadKey().equals(SW6CarrierItem.HEADER_NAME)) {
if (next.getHeadKey().equals(SW8CarrierItem.HEADER_NAME)) {
next.setHeadValue(UUID.randomUUID().toString());
}
}
......
......@@ -21,7 +21,7 @@ package org.apache.skywalking.apm.plugin.finagle;
import com.twitter.finagle.context.Contexts;
import org.apache.skywalking.apm.agent.core.context.CarrierItem;
import org.apache.skywalking.apm.agent.core.context.ContextCarrier;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegmentRef;
......@@ -109,9 +109,8 @@ public class ServerTracingFilterInterceptorTest extends AbstractTracingFilterTes
CarrierItem next = contextCarrier.items();
while (next.hasNext()) {
next = next.next();
if (next.getHeadKey().equals(SW6CarrierItem.HEADER_NAME)) {
next.setHeadValue("1-MC4wLjA=-MS4zMjMuNDQzMw==-3-1-1-IzE5Mi4xNjguMS44IDoxODAwMg==-Iy9wb3J0Y" +
"Wwv-Iy90ZXN0RW50cnlTcGFu");
if (next.getHeadKey().equals(SW8CarrierItem.HEADER_NAME)) {
next.setHeadValue("1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=");
}
}
SWContextCarrier swContextCarrier = new SWContextCarrier();
......@@ -138,7 +137,7 @@ public class ServerTracingFilterInterceptorTest extends AbstractTracingFilterTes
TraceSegment traceSegment = segmentStorage.getTraceSegments().get(0);
TraceSegmentRef actual = traceSegment.getRefs().get(0);
assertThat(SegmentRefHelper.getSpanId(actual), is(3));
assertThat(SegmentRefHelper.getEntryServiceInstanceId(actual), is(1));
assertThat(SegmentRefHelper.getTraceSegmentId(actual).toString(), is("1.323.4433"));
assertThat(SegmentRefHelper.getParentServiceInstance(actual), is("instance"));
assertThat(SegmentRefHelper.getTraceSegmentId(actual).toString(), is("3.4.5"));
}
}
......@@ -19,7 +19,7 @@
package org.apache.skywalking.apm.plugin.jetty.v9.server;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.LogDataEntity;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
......@@ -108,7 +108,8 @@ public class HandleInterceptorTest {
@Test
public void testWithSerializedContextData() throws Throwable {
when(request.getHeader(SW6CarrierItem.HEADER_NAME)).thenReturn("1-MC4wLjA=-MS4yMzQuMTEx-3-1-1-IzE5Mi4xNjguMS44OjE4MDAy-Iy9wb3J0YWwv-Iy90ZXN0RW50cnlTcGFu");
when(request.getHeader(
SW8CarrierItem.HEADER_NAME)).thenReturn("1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=");
jettyInvokeInterceptor.beforeMethod(service, null, arguments, argumentType, methodInterceptResult);
jettyInvokeInterceptor.afterMethod(service, null, arguments, argumentType, null);
......@@ -138,9 +139,9 @@ public class HandleInterceptorTest {
}
private void assertTraceSegmentRef(TraceSegmentRef ref) {
assertThat(SegmentRefHelper.getEntryServiceInstanceId(ref), is(1));
assertThat(SegmentRefHelper.getParentServiceInstance(ref), is("instance"));
assertThat(SegmentRefHelper.getSpanId(ref), is(3));
assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("1.234.111"));
assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("3.4.5"));
}
private void assertHttpSpan(AbstractTracingSpan span) {
......
......@@ -145,7 +145,6 @@ public class CallbackInterceptorTest {
TraceSegmentRef segmentRef = refs.get(0);
SegmentRefAssert.assertSpanId(segmentRef, 1);
assertThat(segmentRef.getEntryEndpointName(), is("/for-test-entryOperationName"));
}
private void assertCallbackSpan(AbstractTracingSpan span) {
......
......@@ -24,7 +24,7 @@ import java.util.List;
import java.util.Map;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.TopicPartition;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
......@@ -97,8 +97,11 @@ public class KafkaConsumerInterceptorTest {
List<ConsumerRecord> records = new ArrayList<ConsumerRecord>();
ConsumerRecord consumerRecord = new ConsumerRecord("test", 1, 0, "1", "1");
consumerRecord.headers()
.add(SW6CarrierItem.HEADER_NAME, "1-MC4wLjA=-MS4yMzQuMTEx-3-1-1-IzE5Mi4xNjguMS44OjE4MDAy-Iy9wb3J0YWwv-I3Rlc3RFbnRyeVNwYW4="
.getBytes());
.add(
SW8CarrierItem.HEADER_NAME,
"1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA="
.getBytes()
);
records.add(consumerRecord);
messages.put(topicPartition, records);
}
......@@ -106,7 +109,8 @@ public class KafkaConsumerInterceptorTest {
@Test
public void testConsumerWithoutMessage() throws Throwable {
consumerInterceptor.beforeMethod(consumerInstance, null, new Object[0], new Class[0], null);
consumerInterceptor.afterMethod(consumerInstance, null, new Object[0], new Class[0], new HashMap<TopicPartition, List<ConsumerRecord>>());
consumerInterceptor.afterMethod(
consumerInstance, null, new Object[0], new Class[0], new HashMap<TopicPartition, List<ConsumerRecord>>());
List<TraceSegment> traceSegments = segmentStorage.getTraceSegments();
assertThat(traceSegments.size(), is(0));
......@@ -139,8 +143,8 @@ public class KafkaConsumerInterceptorTest {
}
private void assertTraceSegmentRef(TraceSegmentRef ref) {
MatcherAssert.assertThat(SegmentRefHelper.getEntryServiceInstanceId(ref), is(1));
MatcherAssert.assertThat(SegmentRefHelper.getParentServiceInstance(ref), is("instance"));
MatcherAssert.assertThat(SegmentRefHelper.getSpanId(ref), is(3));
MatcherAssert.assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("1.234.111"));
MatcherAssert.assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("3.4.5"));
}
}
\ No newline at end of file
......@@ -23,17 +23,21 @@ import com.weibo.api.motan.rpc.Response;
import com.weibo.api.motan.rpc.URL;
import java.util.HashMap;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.LogDataEntity;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegmentRef;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.test.helper.SegmentHelper;
import org.apache.skywalking.apm.agent.test.helper.SegmentRefHelper;
import org.apache.skywalking.apm.agent.test.helper.SpanHelper;
import org.apache.skywalking.apm.agent.test.tools.AgentServiceRule;
import org.apache.skywalking.apm.agent.test.tools.SegmentStorage;
import org.apache.skywalking.apm.agent.test.tools.SegmentStoragePoint;
import org.apache.skywalking.apm.agent.test.tools.SpanAssert;
import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import org.apache.skywalking.apm.network.trace.component.ComponentsDefine;
import org.hamcrest.MatcherAssert;
import org.junit.Before;
......@@ -43,16 +47,12 @@ import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.apache.skywalking.apm.agent.core.context.trace.LogDataEntity;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegmentRef;
import org.apache.skywalking.apm.agent.test.helper.SegmentRefHelper;
import org.apache.skywalking.apm.agent.test.tools.TracingSegmentRunner;
import static org.apache.skywalking.apm.agent.test.tools.SpanAssert.assertComponent;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.when;
import static org.apache.skywalking.apm.agent.test.tools.SpanAssert.assertComponent;
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(TracingSegmentRunner.class)
......@@ -107,7 +107,10 @@ public class MotanProviderInterceptorTest {
@Test
public void testInvokerWithRefSegment() throws Throwable {
HashMap attachments = new HashMap();
attachments.put(SW6CarrierItem.HEADER_NAME, "1-MC4wLjA=-MS4xMjMuNDU2-3-1-1-IzE5Mi4xNjguMS44OjE4MDAy-Iy9wb3J0YWwv-Iy90ZXN0RW50cnlTcGFu");
attachments.put(
SW8CarrierItem.HEADER_NAME,
"1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA="
);
when(request.getAttachments()).thenReturn(attachments);
invokeInterceptor.beforeMethod(enhancedInstance, null, arguments, argumentType, null);
......@@ -134,7 +137,8 @@ public class MotanProviderInterceptorTest {
public void testOccurException() throws Throwable {
invokeInterceptor.beforeMethod(enhancedInstance, null, arguments, argumentType, null);
invokeInterceptor.handleMethodException(enhancedInstance, null, arguments, argumentType, new RuntimeException());
invokeInterceptor.handleMethodException(
enhancedInstance, null, arguments, argumentType, new RuntimeException());
invokeInterceptor.afterMethod(enhancedInstance, null, arguments, argumentType, response);
assertTraceSegmentWhenOccurException();
......@@ -151,14 +155,17 @@ public class MotanProviderInterceptorTest {
}
private void assertRefSegment(TraceSegmentRef primaryRef) {
assertThat(SegmentRefHelper.getTraceSegmentId(primaryRef).toString(), is("1.123.456"));
assertThat(SegmentRefHelper.getTraceSegmentId(primaryRef).toString(), is("3.4.5"));
assertThat(SegmentRefHelper.getSpanId(primaryRef), is(3));
assertThat(SegmentRefHelper.getEntryServiceInstanceId(primaryRef), is(1));
assertThat(SegmentRefHelper.getPeerHost(primaryRef), is("192.168.1.8:18002"));
MatcherAssert.assertThat(SegmentRefHelper.getParentServiceInstance(primaryRef), is("instance"));
assertThat(SegmentRefHelper.getPeerHost(primaryRef), is("127.0.0.1:8080"));
}
private void assertMotanProviderSpan(AbstractTracingSpan span) {
assertThat(span.getOperationName(), is("org.apache.skywalking.apm.test.TestService.test(java.lang.String, java.lang.Object)"));
assertThat(
span.getOperationName(),
is("org.apache.skywalking.apm.test.TestService.test(java.lang.String, java.lang.Object)")
);
assertComponent(span, ComponentsDefine.MOTAN);
assertThat(span.isEntry(), is(true));
SpanAssert.assertLayer(span, SpanLayer.RPC_FRAMEWORK);
......
......@@ -19,7 +19,7 @@
package org.apache.skywalking.apm.plugin.pulsar;
import org.apache.pulsar.common.api.proto.PulsarApi;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
......@@ -85,8 +85,8 @@ public class PulsarConsumerInterceptorTest {
msg = new MockMessage();
msg.getMessageBuilder()
.addProperties(PulsarApi.KeyValue.newBuilder()
.setKey(SW6CarrierItem.HEADER_NAME)
.setValue("1-MC4wLjA=-MS4yMzQuMTEx-3-1-1-IzE5Mi4xNjguMS44OjE4MDAy-Iy9wb3J0YWwv-I3Rlc3RFbnRyeVNwYW4="));
.setKey(SW8CarrierItem.HEADER_NAME)
.setValue("1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA="));
}
@Test
......@@ -125,8 +125,8 @@ public class PulsarConsumerInterceptorTest {
}
private void assertTraceSegmentRef(TraceSegmentRef ref) {
MatcherAssert.assertThat(SegmentRefHelper.getEntryServiceInstanceId(ref), is(1));
MatcherAssert.assertThat(SegmentRefHelper.getParentServiceInstance(ref), is("instance"));
MatcherAssert.assertThat(SegmentRefHelper.getSpanId(ref), is(3));
MatcherAssert.assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("1.234.111"));
MatcherAssert.assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("3.4.5"));
}
}
......@@ -18,6 +18,7 @@
package org.apache.skywalking.apm.plugin.pulsar;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.MockContextSnapshot;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
......@@ -38,8 +39,6 @@ import org.junit.runner.RunWith;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
......@@ -137,7 +136,6 @@ public class SendCallbackInterceptorTest {
TraceSegmentRef segmentRef = refs.get(0);
SegmentRefAssert.assertSpanId(segmentRef, 1);
assertThat(segmentRef.getEntryEndpointName(), is("/for-test-entryOperationName"));
}
private void assertCallbackSpan(AbstractTracingSpan span) {
......
......@@ -20,7 +20,7 @@ package org.apache.skywalking.apm.plugin.rabbitmq;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Envelope;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
import org.apache.skywalking.apm.agent.core.plugin.interceptor.enhance.EnhancedInstance;
import org.apache.skywalking.apm.agent.test.tools.AgentServiceRule;
......@@ -73,7 +73,7 @@ public class RabbitMQConsumerInterceptorTest {
public void TestRabbitMQConsumerInterceptor() throws Throwable {
Envelope envelope = new Envelope(1111, false, "", "rabbitmq-test");
Map<String, Object> headers = new HashMap<String, Object>();
headers.put(SW6CarrierItem.HEADER_NAME, "1-MS4xLjE1NDM5NzU1OTEwMTQwMDAx-MS4xLjE1NDM5NzU1OTA5OTcwMDAw-0-1-1-IzEyNy4wLjAuMTo1Mjcy-I1JhYmJpdE1RL1RvcGljL1F1ZXVlL3JhYmJpdG1xLXRlc3QvUHJvZHVjZXI=-I1JhYmJpdE1RL1RvcGljL1F1ZXVlL3JhYmJpdG1xLXRlc3QvUHJvZHVjZXI=");
headers.put(SW8CarrierItem.HEADER_NAME, "1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=");
AMQP.BasicProperties.Builder propsBuilder = new AMQP.BasicProperties.Builder();
Object[] arguments = new Object[] {
0,
......
......@@ -32,9 +32,9 @@ import static org.hamcrest.MatcherAssert.assertThat;
class AssertTools {
static void assertTraceSegmentRef(TraceSegmentRef ref) {
assertThat(SegmentRefHelper.getEntryServiceInstanceId(ref), is(1));
assertThat(SegmentRefHelper.getParentServiceInstance(ref), is("instance"));
assertThat(SegmentRefHelper.getSpanId(ref), is(3));
assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("1.234.111"));
assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("3.4.5"));
}
static void assertHttpSpan(AbstractTracingSpan span) {
......
......@@ -21,7 +21,7 @@ package org.apache.skywalking.apm.plugin.resteasy.v3.server;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.LogDataEntity;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
......@@ -136,7 +136,7 @@ public class SynchronousDispatcherInterceptorTest {
@Test
public void testWithSW6SerializedContextData() throws Throwable {
MultivaluedMapImpl<String, String> multivaluedMap = new MultivaluedMapImpl<String, String>();
multivaluedMap.putSingle(SW6CarrierItem.HEADER_NAME, "1-I0FRQSojQVFBKkV0MFdlMHRRTlFBKg==-MS4yMzQuMTEx-3-1-1-IzE5Mi4xNjguMS44OjE4MDAy-Iy9wb3J0YWwv-Iy90ZXN0RW50cnlTcGFu");
multivaluedMap.putSingle(SW8CarrierItem.HEADER_NAME, "1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=");
when(request.getHttpHeaders()).thenReturn(new ResteasyHttpHeaders(multivaluedMap));
synchronousDispatcherInterceptor.beforeMethod(enhancedInstance, null, arguments, argumentType, methodInterceptResult);
......
......@@ -25,7 +25,7 @@ import com.alipay.sofa.rpc.core.response.SofaResponse;
import com.alipay.sofa.rpc.filter.ProviderInvoker;
import java.util.List;
import org.apache.skywalking.apm.agent.core.conf.Config;
import org.apache.skywalking.apm.agent.core.context.SW6CarrierItem;
import org.apache.skywalking.apm.agent.core.context.SW8CarrierItem;
import org.apache.skywalking.apm.agent.core.context.trace.AbstractTracingSpan;
import org.apache.skywalking.apm.agent.core.context.trace.SpanLayer;
import org.apache.skywalking.apm.agent.core.context.trace.TraceSegment;
......@@ -117,9 +117,11 @@ public class SofaRpcProviderInterceptorTest {
@Test
public void testProviderWithAttachment() throws Throwable {
when(rpcContext.isConsumerSide()).thenReturn(false);
when(sofaRequest.getRequestProp(SKYWALKING_PREFIX + SW6CarrierItem.HEADER_NAME)).thenReturn("1-MC4wLjA=-MS4zMjMuNDQzMw==-3-1-1-IzE5Mi4xNjguMS44IDoxODAwMg==-Iy9wb3J0YWwv-Iy90ZXN0RW50cnlTcGFu");
when(sofaRequest.getRequestProp(SKYWALKING_PREFIX + SW8CarrierItem.HEADER_NAME)).thenReturn(
"1-My40LjU=-MS4yLjM=-3-c2VydmljZQ==-aW5zdGFuY2U=-L2FwcA==-MTI3LjAuMC4xOjgwODA=");
sofaRpcProviderInterceptor.beforeMethod(enhancedInstance, null, allArguments, argumentTypes, methodInterceptResult);
sofaRpcProviderInterceptor.beforeMethod(
enhancedInstance, null, allArguments, argumentTypes, methodInterceptResult);
sofaRpcProviderInterceptor.afterMethod(enhancedInstance, null, allArguments, argumentTypes, sofaResponse);
assertProvider();
}
......@@ -133,8 +135,8 @@ public class SofaRpcProviderInterceptorTest {
private void assertTraceSegmentRef(TraceSegmentRef actual) {
assertThat(SegmentRefHelper.getSpanId(actual), is(3));
assertThat(SegmentRefHelper.getEntryServiceInstanceId(actual), is(1));
assertThat(SegmentRefHelper.getTraceSegmentId(actual).toString(), is("1.323.4433"));
assertThat(SegmentRefHelper.getParentServiceInstance(actual), is("instance"));
assertThat(SegmentRefHelper.getTraceSegmentId(actual).toString(), is("3.4.5"));
}
private void assertProviderSpan(AbstractTracingSpan span) {
......
......@@ -162,7 +162,7 @@ public class RequestMappingMethodInterceptorTest {
}
private void assertTraceSegmentRef(TraceSegmentRef ref) {
assertThat(SegmentRefHelper.getEntryServiceInstanceId(ref), is(1));
assertThat(SegmentRefHelper.getParentServiceInstance(ref), is("instance"));
assertThat(SegmentRefHelper.getSpanId(ref), is(3));
assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("1.444.555"));
}
......
......@@ -201,7 +201,8 @@ public class RestMappingMethodInterceptorTest {
RestMappingClass1 mappingClass1 = new RestMappingClass1();
Method m = mappingClass1.getClass().getMethod("deleteRequestURL");
when(request.getRequestURI()).thenReturn("/test/testRequestURL");
when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/test/deleteRequestURL"));
when(request.getRequestURL()).thenReturn(
new StringBuffer("http://localhost:8080/test/deleteRequestURL"));
ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(request, response);
RequestContextHolder.setRequestAttributes(servletRequestAttributes);
......@@ -227,7 +228,8 @@ public class RestMappingMethodInterceptorTest {
RestMappingClass1 mappingClass1 = new RestMappingClass1();
Method m = mappingClass1.getClass().getMethod("patchRequestURL");
when(request.getRequestURI()).thenReturn("/test/testRequestURL");
when(request.getRequestURL()).thenReturn(new StringBuffer("http://localhost:8080/test/patchRequestURL"));
when(request.getRequestURL()).thenReturn(
new StringBuffer("http://localhost:8080/test/patchRequestURL"));
ServletRequestAttributes servletRequestAttributes = new ServletRequestAttributes(request, response);
RequestContextHolder.setRequestAttributes(servletRequestAttributes);
......@@ -299,7 +301,7 @@ public class RestMappingMethodInterceptorTest {
}
private void assertTraceSegmentRef(TraceSegmentRef ref) {
MatcherAssert.assertThat(SegmentRefHelper.getEntryServiceInstanceId(ref), is(1));
MatcherAssert.assertThat(SegmentRefHelper.getParentServiceInstance(ref), is("instance"));
assertThat(SegmentRefHelper.getSpanId(ref), is(3));
MatcherAssert.assertThat(SegmentRefHelper.getTraceSegmentId(ref).toString(), is("1.444.555"));
}
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册