Unverified Commit ccad0cf3 authored by Lemon's avatar Lemon Committed by GitHub

Add language-agent-protocol-v2 support (#136)

* update protocol

* rm azure-pipeline.yml

* move build.ps1 to scripts

* Fix $Script path

* Fix $Script path

* fix version.props path

* Add protocol submodule

* cleanup protocol define

* move build.cake to rootpath

* Add submodule init

* Remove protos submodule

* pre release Protocol

* Agent anomalies do not affect the application

* Update version to 0.7.1

* Add service register v6

* Add ping service

* Fix licenses

* Clean up unused code

* Refactor segment reporter

* Modified version number
parent b8629db1
...@@ -264,3 +264,5 @@ tools/ ...@@ -264,3 +264,5 @@ tools/
*.proto *.proto
generated/
[submodule "protos"] [submodule "src/SkyWalking.Transport.Grpc.Protocol/protocol"]
path = protos path = src/SkyWalking.Transport.Grpc.Protocol/protocol
url = https://github.com/apache/incubator-skywalking-data-collect-protocol.git url = https://github.com/apache/incubator-skywalking-data-collect-protocol.git
...@@ -10,9 +10,11 @@ environment: ...@@ -10,9 +10,11 @@ environment:
skip_commits: skip_commits:
files: files:
- LICENSE - LICENSE
install:
- git submodule update --init
- dotnet build -c Release src/SkyWalking.Transport.Grpc.Protocol
build_script: build_script:
- ps: ./build.ps1 - ps: ./scripts/build.ps1
test: off
artifacts: artifacts:
- path: artifacts/packages/*.nupkg - path: artifacts/packages/*.nupkg
deploy: deploy:
......
# ASP.NET Core
# Build and test ASP.NET Core web applications targeting .NET Core.
# Add steps that run tests, create a NuGet package, deploy, and more:
# https://docs.microsoft.com/vsts/pipelines/languages/dotnet-core
pool:
vmImage: 'Ubuntu 16.04'
variables:
buildConfiguration: 'Release'
steps:
- script: dotnet build --configuration $(buildConfiguration)
displayName: 'dotnet build $(buildConfiguration)'
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<VersionMajor>0</VersionMajor> <VersionMajor>0</VersionMajor>
<VersionMinor>7</VersionMinor> <VersionMinor>8</VersionMinor>
<VersionPatch>0</VersionPatch> <VersionPatch>0</VersionPatch>
<VersionQuality></VersionQuality> <VersionQuality></VersionQuality>
<VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix> <VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix>
......
Subproject commit 04e6ecad27f19ee09068e1fdf9a42012dece0f30
...@@ -22,4 +22,7 @@ ...@@ -22,4 +22,7 @@
<CopyToOutputDirectory>Always</CopyToOutputDirectory> <CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content> </Content>
</ItemGroup> </ItemGroup>
<ItemGroup>
<Folder Include="logs" />
</ItemGroup>
</Project> </Project>
\ No newline at end of file
...@@ -13,6 +13,6 @@ ...@@ -13,6 +13,6 @@
} }
}, },
"SkyWalking": { "SkyWalking": {
"ApplicationCode": "asp-net-core-backend" "ServiceName": "asp-net-core-backend"
} }
} }
...@@ -85,6 +85,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.DotNet.CLI", "cl ...@@ -85,6 +85,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.DotNet.CLI", "cl
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Diagnostics.MySqlData", "src\SkyWalking.Diagnostics.MySqlData\SkyWalking.Diagnostics.MySqlData.csproj", "{A66B2179-9F35-4B52-9457-F60ED257BA60}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Diagnostics.MySqlData", "src\SkyWalking.Diagnostics.MySqlData\SkyWalking.Diagnostics.MySqlData.csproj", "{A66B2179-9F35-4B52-9457-F60ED257BA60}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Transport.Grpc.Protocol", "src\SkyWalking.Transport.Grpc.Protocol\SkyWalking.Transport.Grpc.Protocol.csproj", "{BAF5C1ED-09C4-4B32-8190-47D16265F01E}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
...@@ -179,6 +181,10 @@ Global ...@@ -179,6 +181,10 @@ Global
{A66B2179-9F35-4B52-9457-F60ED257BA60}.Debug|Any CPU.Build.0 = Debug|Any CPU {A66B2179-9F35-4B52-9457-F60ED257BA60}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A66B2179-9F35-4B52-9457-F60ED257BA60}.Release|Any CPU.ActiveCfg = Release|Any CPU {A66B2179-9F35-4B52-9457-F60ED257BA60}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A66B2179-9F35-4B52-9457-F60ED257BA60}.Release|Any CPU.Build.0 = Release|Any CPU {A66B2179-9F35-4B52-9457-F60ED257BA60}.Release|Any CPU.Build.0 = Release|Any CPU
{BAF5C1ED-09C4-4B32-8190-47D16265F01E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BAF5C1ED-09C4-4B32-8190-47D16265F01E}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BAF5C1ED-09C4-4B32-8190-47D16265F01E}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BAF5C1ED-09C4-4B32-8190-47D16265F01E}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
...@@ -213,6 +219,7 @@ Global ...@@ -213,6 +219,7 @@ Global
{5CB2889E-33DD-4326-9403-4977849E065D} = {EF6194B2-9ACB-49B9-8049-DD6AFAEB0399} {5CB2889E-33DD-4326-9403-4977849E065D} = {EF6194B2-9ACB-49B9-8049-DD6AFAEB0399}
{412E5D7D-9448-4C65-8EC7-26F6D5C49865} = {A238D227-433B-461E-8C57-73B147E0F672} {412E5D7D-9448-4C65-8EC7-26F6D5C49865} = {A238D227-433B-461E-8C57-73B147E0F672}
{A66B2179-9F35-4B52-9457-F60ED257BA60} = {79ED86A5-E9B9-49B2-9354-C911C079D03E} {A66B2179-9F35-4B52-9457-F60ED257BA60} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{BAF5C1ED-09C4-4B32-8190-47D16265F01E} = {CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {94C0DA2C-CCCB-4314-93A2-9809B5DD0583} SolutionGuid = {94C0DA2C-CCCB-4314-93A2-9809B5DD0583}
......
...@@ -25,6 +25,8 @@ namespace SkyWalking.Config ...@@ -25,6 +25,8 @@ namespace SkyWalking.Config
public string ApplicationCode { get; set; } public string ApplicationCode { get; set; }
public string ServiceName { get; set; }
public int SpanLimitPerSegment { get; set; } = 300; public int SpanLimitPerSegment { get; set; } = 300;
} }
} }
\ No newline at end of file
...@@ -30,11 +30,9 @@ namespace SkyWalking ...@@ -30,11 +30,9 @@ namespace SkyWalking
protected readonly ILogger Logger; protected readonly ILogger Logger;
protected readonly IRuntimeEnvironment RuntimeEnvironment; protected readonly IRuntimeEnvironment RuntimeEnvironment;
protected readonly ISkyWalkingClient SkyWalking;
protected ExecutionService(ISkyWalkingClient skyWalking, IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory) protected ExecutionService(IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
{ {
SkyWalking = skyWalking;
RuntimeEnvironment = runtimeEnvironment; RuntimeEnvironment = runtimeEnvironment;
Logger = loggerFactory.CreateLogger(GetType()); Logger = loggerFactory.CreateLogger(GetType());
} }
......
...@@ -17,19 +17,18 @@ ...@@ -17,19 +17,18 @@
*/ */
using System; using System;
using SkyWalking.Config;
namespace SkyWalking namespace SkyWalking
{ {
public interface IRuntimeEnvironment public interface IRuntimeEnvironment
{ {
NullableValue ApplicationId { get; } NullableValue ServiceId { get; }
NullableValue ApplicationInstanceId { get; } NullableValue ServiceInstanceId { get; }
bool Initialized { get; } bool Initialized { get; }
Guid AgentUUID { get; } Guid InstanceId { get; }
IEnvironmentProvider Environment { get; } IEnvironmentProvider Environment { get; }
} }
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The OpenSkywalking 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
......
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking 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.
*
*/
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
......
...@@ -24,6 +24,7 @@ using SkyWalking.Transport; ...@@ -24,6 +24,7 @@ using SkyWalking.Transport;
namespace SkyWalking namespace SkyWalking
{ {
[Obsolete]
public interface ISkyWalkingClient public interface ISkyWalkingClient
{ {
Task<NullableValue> RegisterApplicationAsync(string applicationCode, CancellationToken cancellationToken = default(CancellationToken)); Task<NullableValue> RegisterApplicationAsync(string applicationCode, CancellationToken cancellationToken = default(CancellationToken));
......
...@@ -16,6 +16,8 @@ ...@@ -16,6 +16,8 @@
* *
*/ */
using System;
namespace SkyWalking.Transport namespace SkyWalking.Transport
{ {
public class AgentOsInfoRequest public class AgentOsInfoRequest
...@@ -27,5 +29,7 @@ namespace SkyWalking.Transport ...@@ -27,5 +29,7 @@ namespace SkyWalking.Transport
public int ProcessNo { get; set; } public int ProcessNo { get; set; }
public string[] IpAddress { get; set; } public string[] IpAddress { get; set; }
public string Language { get; set; }
} }
} }
\ No newline at end of file
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The OpenSkywalking 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
...@@ -16,31 +16,14 @@ ...@@ -16,31 +16,14 @@
* *
*/ */
//using Grpc.Core; using System.Threading;
//using SkyWalking.Utils; using System.Threading.Tasks;
// using SkyWalking.Transport;
//namespace SkyWalking.Remote.Authentication
//{ namespace SkyWalking.Transport
// internal static class AuthenticationInterceptors {
// { public interface IPingCaller
// private const string header = "authentication"; {
// Task PingAsync(PingRequest request, CancellationToken cancellationToken = default(CancellationToken));
// public static AsyncAuthInterceptor CreateAuthInterceptor(string token) }
// { }
// return (context, metadata) => \ No newline at end of file
// {
// var entry = CreateTokenHeader(token);
// if (entry != null)
// {
// metadata.Add(entry);
// }
// return TaskUtils.CompletedTask;
// };
// }
//
// private static Metadata.Entry CreateTokenHeader(string token)
// {
// return string.IsNullOrEmpty(token) ? null : new Metadata.Entry(header, token);
// }
// }
//}
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking 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.
*
*/
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Transport;
namespace SkyWalking.Transport
{
public interface IServiceRegister
{
Task<NullableValue> RegisterServiceAsync(ServiceRequest serviceRequest,
CancellationToken cancellationToken = default(CancellationToken));
Task<NullableValue> RegisterServiceInstanceAsync(ServiceInstanceRequest serviceInstanceRequest,
CancellationToken cancellationToken = default(CancellationToken));
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking.Transport
{
public interface ITraceReporter
{
Task ReportAsync(IReadOnlyCollection<TraceSegmentRequest> segmentRequests,
CancellationToken cancellationToken = default(CancellationToken));
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking 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.
*
*/
namespace SkyWalking.Transport
{
public class PingRequest
{
public int ServiceInstanceId { get; set; }
public string InstanceId { get; set; }
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking 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.
*
*/
namespace SkyWalking.Transport
{
public class ServiceInstanceRequest
{
public int ServiceId { get; set; }
public string InstanceUUID { get; set; }
public AgentOsInfoRequest Properties { get; set; }
}
}
\ No newline at end of file
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The OpenSkywalking 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
...@@ -16,21 +16,16 @@ ...@@ -16,21 +16,16 @@
* *
*/ */
namespace SkyWalking.Transport.Grpc using System.Collections.Generic;
namespace SkyWalking.Transport
{ {
public struct ServerMetadata public class ServiceRequest
{ {
public string Address { get; } public string ServiceName { get; set; }
public string Token { get; }
public string CertificatePath { get; } public Dictionary<string, string> Tags { get; set; }
public ServerMetadata(string address, string certificate, string token) public Dictionary<string,string> Properties { get; set; }
{
Address = address;
CertificatePath = certificate;
Token = token;
}
} }
} }
\ No newline at end of file
...@@ -33,6 +33,7 @@ using SkyWalking.Logging; ...@@ -33,6 +33,7 @@ using SkyWalking.Logging;
using SkyWalking.Service; using SkyWalking.Service;
using SkyWalking.Transport; using SkyWalking.Transport;
using SkyWalking.Transport.Grpc; using SkyWalking.Transport.Grpc;
using SkyWalking.Transport.Grpc.V6;
namespace SkyWalking.Agent.AspNetCore namespace SkyWalking.Agent.AspNetCore
{ {
...@@ -48,25 +49,29 @@ namespace SkyWalking.Agent.AspNetCore ...@@ -48,25 +49,29 @@ namespace SkyWalking.Agent.AspNetCore
services.AddSingleton<IContextCarrierFactory, ContextCarrierFactory>(); services.AddSingleton<IContextCarrierFactory, ContextCarrierFactory>();
services.AddSingleton<ITraceDispatcher, AsyncQueueTraceDispatcher>(); services.AddSingleton<ITraceDispatcher, AsyncQueueTraceDispatcher>();
services.AddSingleton<IExecutionService, TraceSegmentTransportService>(); services.AddSingleton<IExecutionService, TraceSegmentTransportService>();
services.AddSingleton<IExecutionService, ServiceDiscoveryService>(); services.AddSingleton<IExecutionService, RegisterService>();
services.AddSingleton<IExecutionService, PingService>();
services.AddSingleton<IExecutionService, SamplingRefreshService>(); services.AddSingleton<IExecutionService, SamplingRefreshService>();
services.AddSingleton<ISkyWalkingAgentStartup, SkyWalkingAgentStartup>(); services.AddSingleton<ISkyWalkingAgentStartup, SkyWalkingAgentStartup>();
services.AddSingleton<ISampler>(DefaultSampler.Instance); services.AddSingleton<ISampler>(DefaultSampler.Instance);
services.AddSingleton(RuntimeEnvironment.Instance); services.AddSingleton<IRuntimeEnvironment>(RuntimeEnvironment.Instance);
services.AddSingleton<TracingDiagnosticProcessorObserver>(); services.AddSingleton<TracingDiagnosticProcessorObserver>();
services.AddSingleton<IConfigAccessor, ConfigAccessor>(); services.AddSingleton<IConfigAccessor, ConfigAccessor>();
services.AddSingleton<IHostedService, InstrumentationHostedService>(); services.AddSingleton<IHostedService, InstrumentationHostedService>();
services.AddSingleton<IEnvironmentProvider, HostingEnvironmentProvider>(); services.AddSingleton<IEnvironmentProvider, HostingEnvironmentProvider>();
services.AddGrpcTransport().AddLogging(); services.AddGrpcTransport().AddLogging();
services.AddSkyWalkingExtensions().AddAspNetCoreHosting().AddHttpClient().AddSqlClient().AddEntityFrameworkCore(c => c.AddPomeloMysql().AddNpgsql().AddSqlite()); services.AddSkyWalkingExtensions().AddAspNetCoreHosting().AddHttpClient().AddSqlClient()
.AddEntityFrameworkCore(c => c.AddPomeloMysql().AddNpgsql().AddSqlite());
return services; return services;
} }
private static IServiceCollection AddGrpcTransport(this IServiceCollection services) private static IServiceCollection AddGrpcTransport(this IServiceCollection services)
{ {
services.AddSingleton<ISkyWalkingClient, GrpcClient>(); services.AddSingleton<ITraceReporter, TraceReporter>();
services.AddSingleton<ConnectionManager>(); services.AddSingleton<ConnectionManager>();
services.AddSingleton<IExecutionService, GrpcStateCheckService>(); services.AddSingleton<IPingCaller, PingCaller>();
services.AddSingleton<IServiceRegister, ServiceRegister>();
services.AddSingleton<IExecutionService, ConnectService>();
return services; return services;
} }
......
...@@ -24,6 +24,7 @@ using SkyWalking.Logging; ...@@ -24,6 +24,7 @@ using SkyWalking.Logging;
using SkyWalking.Service; using SkyWalking.Service;
using SkyWalking.Transport; using SkyWalking.Transport;
using SkyWalking.Transport.Grpc; using SkyWalking.Transport.Grpc;
using SkyWalking.Transport.Grpc.V6;
using SkyWalking.Utilities.Configuration; using SkyWalking.Utilities.Configuration;
using SkyWalking.Utilities.Logging; using SkyWalking.Utilities.Logging;
...@@ -33,22 +34,24 @@ namespace SkyWalking.AspNet.Extensions ...@@ -33,22 +34,24 @@ namespace SkyWalking.AspNet.Extensions
{ {
public static IServiceCollection AddSkyWalkingCore(this IServiceCollection services) public static IServiceCollection AddSkyWalkingCore(this IServiceCollection services)
{ {
services.AddSingleton<SkyWalkingApplicationRequestCallback>();
services.AddSingleton<IContextCarrierFactory, ContextCarrierFactory>(); services.AddSingleton<IContextCarrierFactory, ContextCarrierFactory>();
services.AddSingleton<ITraceDispatcher, AsyncQueueTraceDispatcher>(); services.AddSingleton<ITraceDispatcher, AsyncQueueTraceDispatcher>();
services.AddSingleton<IExecutionService, TraceSegmentTransportService>(); services.AddSingleton<IExecutionService, TraceSegmentTransportService>();
services.AddSingleton<IExecutionService, ServiceDiscoveryService>(); services.AddSingleton<IExecutionService, RegisterService>();
services.AddSingleton<IExecutionService, PingService>();
services.AddSingleton<IExecutionService, SamplingRefreshService>(); services.AddSingleton<IExecutionService, SamplingRefreshService>();
services.AddSingleton<ISkyWalkingAgentStartup, SkyWalkingAgentStartup>(); services.AddSingleton<ISkyWalkingAgentStartup, SkyWalkingAgentStartup>();
services.AddSingleton<ISampler>(DefaultSampler.Instance);
services.AddSingleton<IRuntimeEnvironment>(RuntimeEnvironment.Instance);
services.AddSingleton<TracingDiagnosticProcessorObserver>(); services.AddSingleton<TracingDiagnosticProcessorObserver>();
services.AddSingleton<IConfigAccessor, ConfigAccessor>(); services.AddSingleton<IConfigAccessor, ConfigAccessor>();
services.AddSingleton<IEnvironmentProvider, HostingEnvironmentProvider>(); services.AddSingleton<IEnvironmentProvider, HostingEnvironmentProvider>();
services.AddSingleton<ILoggerFactory, DefaultLoggerFactory>(); services.AddSingleton<ITraceReporter, TraceReporter>();
services.AddSingleton<ISkyWalkingClient, GrpcClient>();
services.AddSingleton<ConnectionManager>(); services.AddSingleton<ConnectionManager>();
services.AddSingleton<IExecutionService, GrpcStateCheckService>(); services.AddSingleton<IPingCaller, PingCaller>();
services.AddSingleton<ISampler>(DefaultSampler.Instance); services.AddSingleton<IServiceRegister, ServiceRegister>();
services.AddSingleton(RuntimeEnvironment.Instance); services.AddSingleton<IExecutionService, ConnectService>();
services.AddSingleton<ILoggerFactory, DefaultLoggerFactory>();
return services; return services;
} }
} }
......
...@@ -27,7 +27,7 @@ namespace SkyWalking.Context.Ids ...@@ -27,7 +27,7 @@ namespace SkyWalking.Context.Ids
public static ID Generate() public static ID Generate()
{ {
if (!RuntimeEnvironment.Instance.ApplicationInstanceId.HasValue) if (!RuntimeEnvironment.Instance.ServiceInstanceId.HasValue)
{ {
throw new InvalidOperationException(); throw new InvalidOperationException();
} }
...@@ -35,7 +35,7 @@ namespace SkyWalking.Context.Ids ...@@ -35,7 +35,7 @@ namespace SkyWalking.Context.Ids
IDContext context = threadIdSequence.Value; IDContext context = threadIdSequence.Value;
return new ID( return new ID(
RuntimeEnvironment.Instance.ApplicationInstanceId.Value, RuntimeEnvironment.Instance.ServiceInstanceId.Value,
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId,
context.NextSeq() context.NextSeq()
); );
......
...@@ -30,9 +30,9 @@ namespace SkyWalking.Context.Trace ...@@ -30,9 +30,9 @@ namespace SkyWalking.Context.Trace
private readonly DistributedTraceIdCollection _relatedGlobalTraces; private readonly DistributedTraceIdCollection _relatedGlobalTraces;
private bool _isSizeLimited; private bool _isSizeLimited;
public int ApplicationId => RuntimeEnvironment.Instance.ApplicationId.Value; public int ApplicationId => RuntimeEnvironment.Instance.ServiceId.Value;
public int ApplicationInstanceId => RuntimeEnvironment.Instance.ApplicationInstanceId.Value; public int ApplicationInstanceId => RuntimeEnvironment.Instance.ServiceInstanceId.Value;
public IEnumerable<ITraceSegmentRef> Refs => _refs; public IEnumerable<ITraceSegmentRef> Refs => _refs;
......
...@@ -80,7 +80,7 @@ namespace SkyWalking.Context.Trace ...@@ -80,7 +80,7 @@ namespace SkyWalking.Context.Trace
_type = SegmentRefType.CrossThread; _type = SegmentRefType.CrossThread;
_traceSegmentId = contextSnapshot.TraceSegmentId; _traceSegmentId = contextSnapshot.TraceSegmentId;
_spanId = contextSnapshot.SpanId; _spanId = contextSnapshot.SpanId;
_parentApplicationInstanceId = RuntimeEnvironment.Instance.ApplicationInstanceId.Value; _parentApplicationInstanceId = RuntimeEnvironment.Instance.ServiceInstanceId.Value;
_entryApplicationInstanceId = contextSnapshot.EntryApplicationInstanceId; _entryApplicationInstanceId = contextSnapshot.EntryApplicationInstanceId;
string entryOperationName = contextSnapshot.EntryOperationName; string entryOperationName = contextSnapshot.EntryOperationName;
if (entryOperationName.First() == '#') if (entryOperationName.First() == '#')
......
...@@ -18,16 +18,20 @@ ...@@ -18,16 +18,20 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using SkyWalking.Logging;
namespace SkyWalking.Diagnostics namespace SkyWalking.Diagnostics
{ {
internal class TracingDiagnosticObserver : IObserver<KeyValuePair<string, object>> internal class TracingDiagnosticObserver : IObserver<KeyValuePair<string, object>>
{ {
private readonly TracingDiagnosticMethodCollection _methodCollection; private readonly TracingDiagnosticMethodCollection _methodCollection;
private readonly ILogger _logger;
public TracingDiagnosticObserver(ITracingDiagnosticProcessor tracingDiagnosticProcessor) public TracingDiagnosticObserver(ITracingDiagnosticProcessor tracingDiagnosticProcessor,
ILoggerFactory loggerFactory)
{ {
_methodCollection = new TracingDiagnosticMethodCollection(tracingDiagnosticProcessor); _methodCollection = new TracingDiagnosticMethodCollection(tracingDiagnosticProcessor);
_logger = loggerFactory.CreateLogger(typeof(TracingDiagnosticObserver));
} }
public void OnCompleted() public void OnCompleted()
...@@ -41,9 +45,16 @@ namespace SkyWalking.Diagnostics ...@@ -41,9 +45,16 @@ namespace SkyWalking.Diagnostics
public void OnNext(KeyValuePair<string, object> value) public void OnNext(KeyValuePair<string, object> value)
{ {
foreach (var method in _methodCollection) foreach (var method in _methodCollection)
{
try
{ {
method.Invoke(value.Key, value.Value); method.Invoke(value.Key, value.Value);
} }
catch (Exception exception)
{
_logger.Error("Invoke diagnostic method exception.", exception);
}
}
} }
} }
} }
\ No newline at end of file
...@@ -27,11 +27,14 @@ namespace SkyWalking.Diagnostics ...@@ -27,11 +27,14 @@ namespace SkyWalking.Diagnostics
public class TracingDiagnosticProcessorObserver : IObserver<DiagnosticListener> public class TracingDiagnosticProcessorObserver : IObserver<DiagnosticListener>
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly ILoggerFactory _loggerFactory;
private readonly IEnumerable<ITracingDiagnosticProcessor> _tracingDiagnosticProcessors; private readonly IEnumerable<ITracingDiagnosticProcessor> _tracingDiagnosticProcessors;
public TracingDiagnosticProcessorObserver(IEnumerable<ITracingDiagnosticProcessor> tracingDiagnosticProcessors, ILoggerFactory loggerFactory) public TracingDiagnosticProcessorObserver(IEnumerable<ITracingDiagnosticProcessor> tracingDiagnosticProcessors,
ILoggerFactory loggerFactory)
{ {
_logger = loggerFactory.CreateLogger(typeof(TracingDiagnosticProcessorObserver)); _logger = loggerFactory.CreateLogger(typeof(TracingDiagnosticProcessorObserver));
_loggerFactory = loggerFactory;
_tracingDiagnosticProcessors = tracingDiagnosticProcessors ?? _tracingDiagnosticProcessors = tracingDiagnosticProcessors ??
throw new ArgumentNullException(nameof(tracingDiagnosticProcessors)); throw new ArgumentNullException(nameof(tracingDiagnosticProcessors));
} }
...@@ -60,7 +63,7 @@ namespace SkyWalking.Diagnostics ...@@ -60,7 +63,7 @@ namespace SkyWalking.Diagnostics
protected virtual void Subscribe(DiagnosticListener listener, protected virtual void Subscribe(DiagnosticListener listener,
ITracingDiagnosticProcessor tracingDiagnosticProcessor) ITracingDiagnosticProcessor tracingDiagnosticProcessor)
{ {
listener.Subscribe(new TracingDiagnosticObserver(tracingDiagnosticProcessor)); listener.Subscribe(new TracingDiagnosticObserver(tracingDiagnosticProcessor, _loggerFactory));
} }
} }
} }
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking 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.
// *
// */
//
//using System;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.Linq;
//using System.Net;
//using System.Net.Sockets;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//using SkyWalking.Config;
//using SkyWalking.Context;
//using SkyWalking.Dictionarys;
//using SkyWalking.Logging;
//using SkyWalking.NetworkProtocol;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcApplicationService : TimerService
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcApplicationService>();
// public override int Order { get; } = -1;
//
// protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15);
//
// protected override async Task Execute(CancellationToken token)
// {
// if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) &&
// !DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
// {
// return;
// }
//
// if (string.IsNullOrEmpty(AgentConfig.ApplicationCode))
// {
// return;
// }
//
// if (!GrpcConnectionManager.Instance.Available)
// {
// return;
// }
//
// var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
//
// if (availableConnection == null)
// {
// return;
// }
//
// try
// {
// await RegisterApplication(availableConnection, token);
// await RegisterApplicationInstance(availableConnection, token);
// }
// catch (Exception exception)
// {
// Logger.Warning($"Register application fail. {exception.Message}");
// availableConnection.Failure();
// }
// }
//
// private async Task RegisterApplication(GrpcConnection availableConnection, CancellationToken token)
// {
// if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId))
// {
// var application = new Application {ApplicationCode = AgentConfig.ApplicationCode};
// var applicationRegisterService =
// new ApplicationRegisterService.ApplicationRegisterServiceClient(availableConnection.GrpcChannel);
//
// var retry = 0;
// var applicationId = 0;
// while (retry++ < 3 && DictionaryUtil.IsNull(applicationId))
// {
// var applicationMapping = await applicationRegisterService.applicationCodeRegisterAsync(application);
// applicationId = applicationMapping?.Application?.Value ?? 0;
// if (!DictionaryUtil.IsNull(applicationId))
// {
// break;
// }
// await Task.Delay(500, token);
// }
//
// if (DictionaryUtil.IsNull(applicationId))
// {
// Logger.Warning(
// "Register application fail. Server response null.");
// return;
// }
//
// Logger.Information(
// $"Register application success. [applicationCode] = {application.ApplicationCode}. [applicationId] = {applicationId}");
// RemoteDownstreamConfig.Agent.ApplicationId = applicationId;
// }
// }
//
// private async Task RegisterApplicationInstance(GrpcConnection availableConnection, CancellationToken token)
// {
// if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
// {
// var instanceDiscoveryService =
// new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel);
//
// var agentUUID = Guid.NewGuid().ToString("N");
// var registerTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//
// var hostName = Dns.GetHostName();
//
// var osInfo = new OSInfo
// {
// Hostname = hostName,
// OsName = PlatformInformation.GetOSName(),
// ProcessNo = Process.GetCurrentProcess().Id
// };
//
// osInfo.Ipv4S.AddRange(GetIpV4S(hostName));
//
// var applicationInstance = new ApplicationInstance
// {
// ApplicationId = RemoteDownstreamConfig.Agent.ApplicationId,
// AgentUUID = agentUUID,
// RegisterTime = registerTime,
// Osinfo = osInfo
// };
//
// var retry = 0;
// var applicationInstanceId = 0;
// while (retry++ < 5 && DictionaryUtil.IsNull(applicationInstanceId))
// {
// var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance);
// applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId;
// if (!DictionaryUtil.IsNull(applicationInstanceId))
// {
// break;
// }
//
// await Task.Delay(500, token);
// }
//
// if (!DictionaryUtil.IsNull(applicationInstanceId))
// {
// RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId;
// Logger.Information(
// $"Register application instance success. [applicationInstanceId] = {applicationInstanceId}");
// }
// else
// {
// Logger.Warning(
// "Register application instance fail. Server response null.");
// }
// }
// }
//
// private IEnumerable<string> GetIpV4S(string hostName)
// {
// try
// {
//
// var ipAddresses = Dns.GetHostAddresses(hostName);
// var ipV4S = new List<string>();
// foreach (var ipAddress in ipAddresses.Where(x => x.AddressFamily == AddressFamily.InterNetwork))
// ipV4S.Add(ipAddress.ToString());
// return ipV4S;
// }
// catch (Exception e)
// {
// Logger.Warning($"Get host addresses fail. {e.Message}");
// return new string[0];
// }
// }
// }
//}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking 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.
// *
// */
//
//using Grpc.Core;
//using SkyWalking.Remote.Authentication;
//
//namespace SkyWalking.Remote
//{
// internal class GrpcChannelBuilder
// {
// private string _token;
//
// private string _server;
//
// private string _rootCertificatePath;
//
// public GrpcChannelBuilder WithAuthenticationToken(string token)
// {
// _token = token;
// return this;
// }
//
// public GrpcChannelBuilder WithServer(string server)
// {
// _server = server;
// return this;
// }
//
// public GrpcChannelBuilder WithCredential(string rootCertificatePath)
// {
// _rootCertificatePath = rootCertificatePath;
// return this;
// }
//
// public Channel Build()
// {
// return new Channel(_server, GetCredentials());
// }
//
// private ChannelCredentials GetCredentials()
// {
// if (_rootCertificatePath != null)
// {
// var authInterceptor = AuthenticationInterceptors.CreateAuthInterceptor(_token);
// return ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor(authInterceptor));
// }
//
// return ChannelCredentials.Insecure;
// }
// }
//}
///*
// * Licensed to the OpenSkywalking 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.
// *
// */
//
//using System;
//using System.Threading.Tasks;
//using Grpc.Core;
//using SkyWalking.Logging;
//
//namespace SkyWalking.Remote
//{
// public class GrpcConnection
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcConnection>();
//
// public Channel GrpcChannel { get; }
//
// public GrpcConnectionState State { get; private set; } = GrpcConnectionState.Idle;
//
// public string Server { get; }
//
// public GrpcConnection(string server, string rootCertificatePath = null, string token = null)
// {
// Server = server;
// GrpcChannel = new GrpcChannelBuilder()
// .WithServer(server)
// .WithCredential(rootCertificatePath)
// .WithAuthenticationToken(token)
// .Build();
// }
//
// public async Task<bool> ConnectAsync(TimeSpan timeout)
// {
// if (State == GrpcConnectionState.Ready)
// {
// return true;
// }
// State = GrpcConnectionState.Connecting;
// try
// {
// var deadLine = DateTime.UtcNow.AddSeconds(timeout.TotalSeconds);
// await GrpcChannel.ConnectAsync(deadLine);
// State = GrpcConnectionState.Ready;
// Logger.Information($"Grpc channel connect success. [Server] = {GrpcChannel.Target}");
// }
// catch (TaskCanceledException ex)
// {
// State = GrpcConnectionState.Failure;
// Logger.Warning($"Grpc channel connect timeout. {ex.Message}");
// }
// catch (Exception ex)
// {
// State = GrpcConnectionState.Failure;
// Logger.Warning($"Grpc channel connect fail. {ex.Message}");
// }
//
// return State == GrpcConnectionState.Ready;
// }
//
// public async Task ShutdowmAsync()
// {
// try
// {
// await GrpcChannel.ShutdownAsync();
// }
// catch (Exception e)
// {
// Logger.Debug($"Grpc channel shutdown fail. {e.Message}");
// }
// finally
// {
// State = GrpcConnectionState.Shutdown;
// }
// }
//
// public bool CheckState()
// {
// return State == GrpcConnectionState.Ready && GrpcChannel.State == ChannelState.Ready;
// }
//
// public void Failure()
// {
// var currentState = State;
//
// if (GrpcConnectionState.Ready == currentState)
// {
// Logger.Debug($"Grpc channel state changed. {State} -> {GrpcChannel.State}");
// }
//
// State = GrpcConnectionState.Failure;
// }
// }
//}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking 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.
// *
// */
//
//using System;
//using System.Linq;
//using System.Threading.Tasks;
//using SkyWalking.Config;
//using SkyWalking.Logging;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcConnectionManager
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcConnectionManager>();
//
// public const string NotFoundErrorMessage = "Not found available connection.";
//
// public static GrpcConnectionManager Instance { get; } = new GrpcConnectionManager();
//
// private readonly Random _random = new Random();
// private readonly AsyncLock _lock = new AsyncLock();
// private GrpcConnection _connection;
//
// public bool Available => _connection != null && _connection.CheckState();
//
// private GrpcConnectionManager()
// {
// }
//
// public async Task ConnectAsync(TimeSpan timeout)
// {
// // using async lock
// using (await _lock.LockAsync())
// {
// if (_connection != null && _connection.CheckState())
// {
// return;
// }
//
// if (_connection != null && !_connection.CheckState())
// {
// await _connection.ShutdowmAsync();
// }
//
// var metadata = GetServerMetadata(_connection?.Server);
// _connection = new GrpcConnection(metadata.Address, metadata.CertificatePath, metadata.Token);
// await _connection.ConnectAsync(timeout);
// }
// }
//
// public async Task ShutdownAsync()
// {
// await _connection?.ShutdowmAsync();
// }
//
// public GrpcConnection GetAvailableConnection()
// {
// var connection = _connection;
// if (connection == null || connection.State != GrpcConnectionState.Ready)
// {
// Logger.Debug(NotFoundErrorMessage);
// return null;
// }
//
// return connection;
// }
//
// private ServerMetadata GetServerMetadata(string currentServer)
// {
// return new ServerMetadata(GetServerAddress(currentServer),
// CollectorConfig.CertificatePath, CollectorConfig.Authentication);
// }
//
// private string GetServerAddress(string currentServer)
// {
// var servers = RemoteDownstreamConfig.Collector.gRPCServers.Distinct().ToArray();
// if (servers.Length == 1)
// {
// return servers[0];
// }
//
// if (currentServer != null)
// {
// servers = servers.Where(x => x != currentServer).ToArray();
// }
//
// var index = _random.Next() % servers.Length;
// return servers[index];
// }
//
// public struct ServerMetadata
// {
// public string Address { get; }
//
// public string Token { get; }
//
// public string CertificatePath { get; }
//
// public ServerMetadata(string address, string certificate, string token)
// {
// Address = address;
// CertificatePath = certificate;
// Token = token;
// }
// }
// }
//}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking 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.
// *
// */
//
//using System;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//
//namespace SkyWalking.Remote
//{
// public class GrpcConnectionService : TimerService
// {
// protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15);
//
// protected override async Task Execute(CancellationToken token)
// {
// if (!GrpcConnectionManager.Instance.Available)
// {
// // default timeout = 5s
// await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(5));
// }
// }
// }
//}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking 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.
// *
// */
//
//namespace SkyWalking.Remote
//{
// public enum GrpcConnectionState
// {
// Idle,
// Connecting,
// Ready,
// Failure,
// Shutdown
// }
//}
///*
// * Licensed to the OpenSkywalking 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.
// *
// */
//
//using System;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//using SkyWalking.Config;
//using SkyWalking.Dictionarys;
//using SkyWalking.Logging;
//using SkyWalking.NetworkProtocol;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcHeartbeatService : TimerService
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcHeartbeatService>();
// protected override TimeSpan Interval { get; } = TimeSpan.FromMinutes(1);
//
// protected override async Task Starting(CancellationToken token)
// {
// await Task.Delay(TimeSpan.FromMinutes(1), token);
// }
//
// protected override async Task Execute(CancellationToken token)
// {
// if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
// {
// Logger.Debug($"{DateTime.Now} Heartbeat fail. Application instance is not registered.");
// return;
// }
//
// var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
//
// if (availableConnection == null)
// {
// Logger.Debug($"{DateTime.Now} Heartbeat fail. {GrpcConnectionManager.NotFoundErrorMessage}");
// return;
// }
//
// try
// {
// var instanceDiscoveryService =
// new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel);
//
// var heartbeat = new ApplicationInstanceHeartbeat
// {
// ApplicationInstanceId = RemoteDownstreamConfig.Agent.ApplicationInstanceId,
// HeartbeatTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
// };
//
// await instanceDiscoveryService.heartbeatAsync(heartbeat);
//
// Logger.Debug($"{DateTime.Now} Heartbeat.");
// }
// catch (Exception e)
// {
// Logger.Debug($"{DateTime.Now} Heartbeat fail. {e.Message}");
// availableConnection.Failure();
// }
// }
// }
//}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking 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.
// *
// */
//
//using System;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcRuntimeService : TimerService
// {
// protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(120);
//
// protected override Task Execute(CancellationToken token)
// {
// // todo
// return TaskUtils.CompletedTask;
// }
// }
//}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking 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.
// *
// */
//
//using System;
//using System.Collections.Concurrent;
//using System.Collections.Generic;
//using System.Linq;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//using SkyWalking.Config;
//using SkyWalking.Context;
//using SkyWalking.Context.Trace;
//using SkyWalking.Logging;
//using SkyWalking.NetworkProtocol;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcTraceSegmentService : TimerService, ITracingContextListener
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcTraceSegmentService>();
// private static readonly ConcurrentQueue<ITraceSegment> _traceSegments
// = new ConcurrentQueue<ITraceSegment>();
//
// public override void Dispose()
// {
// TracingContext.ListenerManager.Remove(this);
// if (_traceSegments.Count > 0)
// {
// BatchSendTraceSegments().ConfigureAwait(false).GetAwaiter().GetResult();
// }
// base.Dispose();
// }
//
// public override int Order { get; } = 1;
//
// protected override TimeSpan Interval => TimeSpan.FromSeconds(1);
//
// protected override Task Initializing(CancellationToken token)
// {
// TracingContext.ListenerManager.Add(this);
// return base.Initializing(token);
// }
//
// public void AfterFinished(ITraceSegment traceSegment)
// {
// if (traceSegment.IsIgnore)
// {
// return;
// }
//
// if (_traceSegments.Count >= AgentConfig.PendingSegmentLimit && AgentConfig.PendingSegmentLimit > 0)
// {
// _traceSegments.TryDequeue(out var v);
// }
// _traceSegments.Enqueue(traceSegment);
// }
//
// protected override async Task Execute(CancellationToken token)
// {
// await BatchSendTraceSegments();
// }
//
// private async Task BatchSendTraceSegments()
// {
// if (_traceSegments.Count == 0)
// return;
//
// var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
// if (availableConnection == null)
// {
// Logger.Warning(
// $"Transform and send UpstreamSegment to collector fail. {GrpcConnectionManager.NotFoundErrorMessage}");
// return;
// }
//
// try
// {
// var traceSegmentService =
// new TraceSegmentService.TraceSegmentServiceClient(availableConnection.GrpcChannel);
// using (var asyncClientStreamingCall = traceSegmentService.collect())
// {
// while (_traceSegments.TryDequeue(out var segment))
// {
// await asyncClientStreamingCall.RequestStream.WriteAsync(segment.Transform());
// Logger.Debug(
// $"Transform and send UpstreamSegment to collector. [TraceSegmentId] = {segment.TraceSegmentId} [GlobalTraceId] = {segment.RelatedGlobalTraces.FirstOrDefault()}");
// }
// await asyncClientStreamingCall.RequestStream.CompleteAsync();
// await asyncClientStreamingCall.ResponseAsync;
// }
// }
// catch (Exception e)
// {
// Logger.Warning($"Transform and send UpstreamSegment to collector fail. {e.Message}");
// availableConnection?.Failure();
// return;
// }
// }
// }
//}
\ No newline at end of file
...@@ -24,13 +24,13 @@ namespace SkyWalking ...@@ -24,13 +24,13 @@ namespace SkyWalking
{ {
public static IRuntimeEnvironment Instance { get; } = new RuntimeEnvironment(); public static IRuntimeEnvironment Instance { get; } = new RuntimeEnvironment();
public NullableValue ApplicationId { get; internal set; } public NullableValue ServiceId { get; internal set; }
public NullableValue ApplicationInstanceId { get; internal set; } public NullableValue ServiceInstanceId { get; internal set; }
public bool Initialized => ApplicationId.HasValue && ApplicationInstanceId.HasValue; public bool Initialized => ServiceId.HasValue && ServiceInstanceId.HasValue;
public Guid AgentUUID { get; } = Guid.NewGuid(); public Guid InstanceId { get; } = Guid.NewGuid();
public IEnvironmentProvider Environment { get; set; } public IEnvironmentProvider Environment { get; set; }
} }
......
/*
* Licensed to the OpenSkywalking 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.
*
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Logging;
using SkyWalking.Transport;
namespace SkyWalking.Service
{
public class PingService : ExecutionService
{
private readonly IPingCaller _pingCaller;
public PingService(IPingCaller pingCaller, IRuntimeEnvironment runtimeEnvironment,
ILoggerFactory loggerFactory) : base(
runtimeEnvironment, loggerFactory)
{
_pingCaller = pingCaller;
}
protected override TimeSpan DueTime { get; } = TimeSpan.FromSeconds(30);
protected override TimeSpan Period { get; } = TimeSpan.FromSeconds(60);
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
try
{
await _pingCaller.PingAsync(
new PingRequest
{
ServiceInstanceId = RuntimeEnvironment.ServiceInstanceId.Value,
InstanceId = RuntimeEnvironment.InstanceId.ToString("N")
}, cancellationToken);
Logger.Information($"Ping server @{DateTimeOffset.UtcNow}");
}
catch (Exception exception)
{
Logger.Error($"Ping server fail @{DateTimeOffset.UtcNow}", exception);
}
}
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking 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.
*
*/
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using System.Threading; using System.Threading;
...@@ -27,66 +9,81 @@ using SkyWalking.Utils; ...@@ -27,66 +9,81 @@ using SkyWalking.Utils;
namespace SkyWalking.Service namespace SkyWalking.Service
{ {
public class ServiceDiscoveryService : ExecutionService public class RegisterService : ExecutionService
{ {
private readonly InstrumentationConfig _config; private readonly InstrumentationConfig _config;
private readonly IServiceRegister _serviceRegister;
public RegisterService(IConfigAccessor configAccessor, IServiceRegister serviceRegister,
IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory) : base(runtimeEnvironment,
loggerFactory)
{
_serviceRegister = serviceRegister;
_config = configAccessor.Get<InstrumentationConfig>();
}
protected override TimeSpan DueTime { get; } = TimeSpan.Zero; protected override TimeSpan DueTime { get; } = TimeSpan.Zero;
protected override TimeSpan Period { get; } = TimeSpan.FromSeconds(30); protected override TimeSpan Period { get; } = TimeSpan.FromSeconds(30);
public ServiceDiscoveryService(IConfigAccessor configAccessor, ISkyWalkingClient client, protected override bool CanExecute() => true;
IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
: base(client, runtimeEnvironment, loggerFactory)
{
_config = configAccessor.Get<InstrumentationConfig>();
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken) protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{ {
await RegisterApplication(cancellationToken); await RegisterServiceAsync(cancellationToken);
await RegisterApplicationInstance(cancellationToken); await RegisterServiceInstanceAsync(cancellationToken);
await Heartbeat(cancellationToken);
} }
protected override bool CanExecute() => true; private async Task RegisterServiceAsync(CancellationToken cancellationToken)
{
private async Task RegisterApplication(CancellationToken cancellationToken) if (!RuntimeEnvironment.ServiceId.HasValue)
{ {
if (!RuntimeEnvironment.ApplicationId.HasValue) var request = new ServiceRequest
{ {
var value = await Polling(3, () => SkyWalking.RegisterApplicationAsync(_config.ApplicationCode, cancellationToken), cancellationToken); ServiceName = _config.ServiceName ?? _config.ApplicationCode
};
var value = await Polling(3,
() => _serviceRegister.RegisterServiceAsync(request, cancellationToken),
cancellationToken);
if (value.HasValue && RuntimeEnvironment is RuntimeEnvironment environment) if (value.HasValue && RuntimeEnvironment is RuntimeEnvironment environment)
{ {
environment.ApplicationId = value; environment.ServiceId = value;
Logger.Information($"Registered Application[Id={environment.ApplicationId.Value}]."); Logger.Information($"Registered Service[Id={environment.ServiceId.Value}].");
} }
} }
} }
private async Task RegisterApplicationInstance(CancellationToken cancellationToken) private async Task RegisterServiceInstanceAsync(CancellationToken cancellationToken)
{ {
if (RuntimeEnvironment.ApplicationId.HasValue && !RuntimeEnvironment.ApplicationInstanceId.HasValue) if (RuntimeEnvironment.ServiceId.HasValue && !RuntimeEnvironment.ServiceInstanceId.HasValue)
{ {
var osInfoRequest = new AgentOsInfoRequest var properties = new AgentOsInfoRequest
{ {
HostName = DnsHelpers.GetHostName(), HostName = DnsHelpers.GetHostName(),
IpAddress = DnsHelpers.GetIpV4s(), IpAddress = DnsHelpers.GetIpV4s(),
OsName = PlatformInformation.GetOSName(), OsName = PlatformInformation.GetOSName(),
ProcessNo = Process.GetCurrentProcess().Id ProcessNo = Process.GetCurrentProcess().Id,
Language = "dotnet"
};
var request = new ServiceInstanceRequest
{
ServiceId = RuntimeEnvironment.ServiceId.Value,
InstanceUUID = RuntimeEnvironment.InstanceId.ToString("N"),
Properties = properties
}; };
var value = await Polling(3, var value = await Polling(3,
() => SkyWalking.RegisterApplicationInstanceAsync(RuntimeEnvironment.ApplicationId.Value, RuntimeEnvironment.AgentUUID, () => _serviceRegister.RegisterServiceInstanceAsync(request, cancellationToken),
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), osInfoRequest, cancellationToken), cancellationToken); cancellationToken);
if (value.HasValue && RuntimeEnvironment is RuntimeEnvironment environment) if (value.HasValue && RuntimeEnvironment is RuntimeEnvironment environment)
{ {
environment.ApplicationInstanceId = value; environment.ServiceInstanceId = value;
Logger.Information($"Registered Application Instance[Id={environment.ApplicationInstanceId.Value}]."); Logger.Information($"Registered ServiceInstance[Id={environment.ServiceInstanceId.Value}].");
} }
} }
} }
private static async Task<NullableValue> Polling(int retry, Func<Task<NullableValue>> execute, CancellationToken cancellationToken) private static async Task<NullableValue> Polling(int retry, Func<Task<NullableValue>> execute,
CancellationToken cancellationToken)
{ {
var index = 0; var index = 0;
while (index++ < retry) while (index++ < retry)
...@@ -102,21 +99,5 @@ namespace SkyWalking.Service ...@@ -102,21 +99,5 @@ namespace SkyWalking.Service
return NullableValue.Null; return NullableValue.Null;
} }
private async Task Heartbeat(CancellationToken cancellationToken)
{
if (RuntimeEnvironment.Initialized)
{
try
{
await SkyWalking.HeartbeatAsync(RuntimeEnvironment.ApplicationInstanceId.Value, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), cancellationToken);
Logger.Debug($"Heartbeat at {DateTimeOffset.UtcNow}.");
}
catch (Exception e)
{
Logger.Error("Heartbeat error.", e);
}
}
}
} }
} }
\ No newline at end of file
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The OpenSkywalking 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
...@@ -28,9 +28,9 @@ namespace SkyWalking.Service ...@@ -28,9 +28,9 @@ namespace SkyWalking.Service
{ {
private readonly SamplingConfig _config; private readonly SamplingConfig _config;
public SamplingRefreshService(IConfigAccessor configAccessor, ISkyWalkingClient skyWalking, public SamplingRefreshService(IConfigAccessor configAccessor,
IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory) IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
: base(skyWalking, runtimeEnvironment, loggerFactory) : base(runtimeEnvironment, loggerFactory)
{ {
_config = configAccessor.Get<SamplingConfig>(); _config = configAccessor.Get<SamplingConfig>();
DefaultSampler.Instance.SetSamplePer3Secs(_config.SamplePer3Secs); DefaultSampler.Instance.SetSamplePer3Secs(_config.SamplePer3Secs);
......
...@@ -33,8 +33,8 @@ namespace SkyWalking.Service ...@@ -33,8 +33,8 @@ namespace SkyWalking.Service
private readonly ITraceDispatcher _dispatcher; private readonly ITraceDispatcher _dispatcher;
public TraceSegmentTransportService(IConfigAccessor configAccessor, ITraceDispatcher dispatcher, public TraceSegmentTransportService(IConfigAccessor configAccessor, ITraceDispatcher dispatcher,
ISkyWalkingClient skyWalking, IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory) IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
: base(skyWalking, runtimeEnvironment, loggerFactory) : base(runtimeEnvironment, loggerFactory)
{ {
_dispatcher = dispatcher; _dispatcher = dispatcher;
_config = configAccessor.Get<TransportConfig>(); _config = configAccessor.Get<TransportConfig>();
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The OpenSkywalking 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 not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
...@@ -29,13 +29,14 @@ namespace SkyWalking.Transport ...@@ -29,13 +29,14 @@ namespace SkyWalking.Transport
{ {
private readonly ILogger _logger; private readonly ILogger _logger;
private readonly TransportConfig _config; private readonly TransportConfig _config;
private readonly ISkyWalkingClient _skyWalkingClient; private readonly ITraceReporter _traceReporter;
private readonly ConcurrentQueue<TraceSegmentRequest> _segmentQueue; private readonly ConcurrentQueue<TraceSegmentRequest> _segmentQueue;
private readonly CancellationTokenSource _cancellation; private readonly CancellationTokenSource _cancellation;
public AsyncQueueTraceDispatcher(IConfigAccessor configAccessor, ISkyWalkingClient client, ILoggerFactory loggerFactory) public AsyncQueueTraceDispatcher(IConfigAccessor configAccessor, ITraceReporter traceReporter,
ILoggerFactory loggerFactory)
{ {
_skyWalkingClient = client; _traceReporter = traceReporter;
_logger = loggerFactory.CreateLogger(typeof(AsyncQueueTraceDispatcher)); _logger = loggerFactory.CreateLogger(typeof(AsyncQueueTraceDispatcher));
_config = configAccessor.Get<TransportConfig>(); _config = configAccessor.Get<TransportConfig>();
_segmentQueue = new ConcurrentQueue<TraceSegmentRequest>(); _segmentQueue = new ConcurrentQueue<TraceSegmentRequest>();
...@@ -71,7 +72,7 @@ namespace SkyWalking.Transport ...@@ -71,7 +72,7 @@ namespace SkyWalking.Transport
// send async // send async
if (segments.Count > 0) if (segments.Count > 0)
_skyWalkingClient.CollectAsync(segments, token); _traceReporter.ReportAsync(segments, token);
return Task.CompletedTask; return Task.CompletedTask;
} }
......
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<Description>SkyWalking gRPC data transmitter.</Description>
<AssemblyTitle>SkyWalking.Transport.Grpc.Protocol</AssemblyTitle>
<AssemblyName>SkyWalking.Transport.Grpc.Protocol</AssemblyName>
<PackageId>SkyWalking.Transport.Grpc.Protocol</PackageId>
<PackageTags>SkyWalking;Grpc</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.6.1" />
<PackageReference Include="Grpc" Version="1.17.0" />
<PackageReference Include="Grpc.Tools" Version="1.17.0" PrivateAssets="All" />
</ItemGroup>
<ItemGroup>
<Protobuf Include="protocol/**/*.proto" ProtoRoot="protocol" OutputDir="%(RelativePath)generated" CompileOutputs="false" />
</ItemGroup>
<PropertyGroup>
<Protobuf_NoWarnMissingExpected>true</Protobuf_NoWarnMissingExpected>
<Protobuf_TouchMissingExpected>true</Protobuf_TouchMissingExpected>
</PropertyGroup>
</Project>
Subproject commit b66fa070fd647662f06497e4ed3657eb258cb6e9
...@@ -65,20 +65,19 @@ namespace SkyWalking.Transport.Grpc ...@@ -65,20 +65,19 @@ namespace SkyWalking.Transport.Grpc
try try
{ {
var deadLine = DateTime.UtcNow.AddMilliseconds(_config.ConnectTimeout); await _channel.ConnectAsync(_config.GetConnectTimeout());
await _channel.ConnectAsync(deadLine);
_state = ConnectionState.Connected; _state = ConnectionState.Connected;
_logger.Information($"Connected collector server[{_channel.Target}]."); _logger.Information($"Connected server[{_channel.Target}].");
} }
catch (TaskCanceledException ex) catch (TaskCanceledException ex)
{ {
_state = ConnectionState.Failure; _state = ConnectionState.Failure;
_logger.Error($"Connect collector timeout.", ex); _logger.Error($"Connect server timeout.", ex);
} }
catch (Exception ex) catch (Exception ex)
{ {
_state = ConnectionState.Failure; _state = ConnectionState.Failure;
_logger.Error($"Connect collector fail.", ex); _logger.Error($"Connect server fail.", ex);
} }
} }
} }
......
/*
* Licensed to the OpenSkywalking 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.
*
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Config;
using SkyWalking.Logging;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Transport.Grpc
{
public class GrpcClient : ISkyWalkingClient
{
private readonly ConnectionManager _connectionManager;
private readonly ILogger _logger;
private readonly GrpcConfig _config;
public GrpcClient(ConnectionManager connectionManager, IConfigAccessor configAccessor, ILoggerFactory loggerFactory)
{
_connectionManager = connectionManager;
_config = configAccessor.Get<GrpcConfig>();
_logger = loggerFactory.CreateLogger(typeof(GrpcClient));
}
public async Task<NullableValue> RegisterApplicationAsync(string applicationCode, CancellationToken cancellationToken = default(CancellationToken))
{
if (!_connectionManager.Ready)
{
return NullableValue.Null;
}
var connection = _connectionManager.GetConnection();
var client = new ApplicationRegisterService.ApplicationRegisterServiceClient(connection);
return await ExecuteWithCatch(async () =>
{
var applicationMapping = await client.applicationCodeRegisterAsync(new Application {ApplicationCode = applicationCode},
null, _config.GetTimeout(), cancellationToken);
return new NullableValue(applicationMapping?.Application?.Value ?? 0);
},
() => NullableValue.Null,
() => ExceptionHelpers.RegisterApplicationError);
}
public async Task<NullableValue> RegisterApplicationInstanceAsync(int applicationId, Guid agentUUID, long registerTime, AgentOsInfoRequest osInfoRequest,
CancellationToken cancellationToken = default(CancellationToken))
{
if (!_connectionManager.Ready)
{
return NullableValue.Null;
}
var connection = _connectionManager.GetConnection();
var client = new InstanceDiscoveryService.InstanceDiscoveryServiceClient(connection);
var applicationInstance = new ApplicationInstance
{
ApplicationId = applicationId,
AgentUUID = agentUUID.ToString("N"),
RegisterTime = registerTime,
Osinfo = new OSInfo
{
OsName = osInfoRequest.OsName,
Hostname = osInfoRequest.HostName,
ProcessNo = osInfoRequest.ProcessNo
}
};
applicationInstance.Osinfo.Ipv4S.AddRange(osInfoRequest.IpAddress);
return await ExecuteWithCatch(async () =>
{
var applicationInstanceMapping = await client.registerInstanceAsync(applicationInstance, null, _config.GetTimeout(), cancellationToken);
return new NullableValue(applicationInstanceMapping?.ApplicationInstanceId ?? 0);
},
() => NullableValue.Null,
() => ExceptionHelpers.RegisterApplicationInstanceError);
}
public async Task HeartbeatAsync(int applicationInstance, long heartbeatTime, CancellationToken cancellationToken = default(CancellationToken))
{
if (!_connectionManager.Ready)
{
return;
}
var connection = _connectionManager.GetConnection();
var client = new InstanceDiscoveryService.InstanceDiscoveryServiceClient(connection);
var heartbeat = new ApplicationInstanceHeartbeat
{
ApplicationInstanceId = applicationInstance,
HeartbeatTime = heartbeatTime
};
await ExecuteWithCatch(async () => await client.heartbeatAsync(heartbeat, null, _config.GetTimeout(), cancellationToken), () => ExceptionHelpers.HeartbeatError);
}
public async Task CollectAsync(IEnumerable<TraceSegmentRequest> request, CancellationToken cancellationToken = default(CancellationToken))
{
if (!_connectionManager.Ready)
{
return;
}
var connection = _connectionManager.GetConnection();
var client = new TraceSegmentService.TraceSegmentServiceClient(connection);
try
{
using (var asyncClientStreamingCall = client.collect(null, null, cancellationToken))
{
foreach (var segment in request)
await asyncClientStreamingCall.RequestStream.WriteAsync(TraceSegmentHelpers.Map(segment));
await asyncClientStreamingCall.RequestStream.CompleteAsync();
await asyncClientStreamingCall.ResponseAsync;
}
}
catch (Exception ex)
{
_logger.Error("Heartbeat error.", ex);
_connectionManager.Failure(ex);
}
}
private async Task ExecuteWithCatch(Func<Task> task, Func<string> errMessage)
{
try
{
await task();
}
catch (Exception ex)
{
_logger.Error(errMessage(), ex);
_connectionManager.Failure(ex);
}
}
private async Task<T> ExecuteWithCatch<T>(Func<Task<T>> task, Func<T> errCallback, Func<string> errMessage)
{
try
{
return await task();
}
catch (Exception ex)
{
_logger.Error(errMessage(), ex);
_connectionManager.Failure(ex);
return errCallback();
}
}
}
}
\ No newline at end of file
...@@ -21,7 +21,7 @@ using SkyWalking.Config; ...@@ -21,7 +21,7 @@ using SkyWalking.Config;
namespace SkyWalking.Transport.Grpc namespace SkyWalking.Transport.Grpc
{ {
[Config("SkyWalking", "Transport","gRPC")] [Config("SkyWalking", "Transport", "gRPC")]
public class GrpcConfig public class GrpcConfig
{ {
public string Servers { get; set; } public string Servers { get; set; }
...@@ -29,6 +29,8 @@ namespace SkyWalking.Transport.Grpc ...@@ -29,6 +29,8 @@ namespace SkyWalking.Transport.Grpc
public int ConnectTimeout { get; set; } public int ConnectTimeout { get; set; }
public int Timeout { get; set; } public int Timeout { get; set; }
public int ReportTimeout { get; set; }
} }
public static class GrpcConfigExtensions public static class GrpcConfigExtensions
...@@ -37,5 +39,15 @@ namespace SkyWalking.Transport.Grpc ...@@ -37,5 +39,15 @@ namespace SkyWalking.Transport.Grpc
{ {
return DateTime.UtcNow.AddMilliseconds(config.Timeout); return DateTime.UtcNow.AddMilliseconds(config.Timeout);
} }
public static DateTime GetConnectTimeout(this GrpcConfig config)
{
return DateTime.UtcNow.AddMilliseconds(config.ConnectTimeout);
}
public static DateTime GetReportTimeout(this GrpcConfig config)
{
return DateTime.UtcNow.AddMilliseconds(config.ReportTimeout);
}
} }
} }
\ No newline at end of file
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: ApplicationRegisterService.proto
// </auto-generated>
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace SkyWalking.NetworkProtocol {
/// <summary>
///register service for ApplicationCode, this service is called when service starts.
/// </summary>
public static partial class ApplicationRegisterService
{
static readonly string __ServiceName = "ApplicationRegisterService";
static readonly grpc::Marshaller<global::SkyWalking.NetworkProtocol.Application> __Marshaller_Application = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::SkyWalking.NetworkProtocol.Application.Parser.ParseFrom);
static readonly grpc::Marshaller<global::SkyWalking.NetworkProtocol.ApplicationMapping> __Marshaller_ApplicationMapping = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::SkyWalking.NetworkProtocol.ApplicationMapping.Parser.ParseFrom);
static readonly grpc::Method<global::SkyWalking.NetworkProtocol.Application, global::SkyWalking.NetworkProtocol.ApplicationMapping> __Method_applicationCodeRegister = new grpc::Method<global::SkyWalking.NetworkProtocol.Application, global::SkyWalking.NetworkProtocol.ApplicationMapping>(
grpc::MethodType.Unary,
__ServiceName,
"applicationCodeRegister",
__Marshaller_Application,
__Marshaller_ApplicationMapping);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::SkyWalking.NetworkProtocol.ApplicationRegisterServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of ApplicationRegisterService</summary>
public abstract partial class ApplicationRegisterServiceBase
{
public virtual global::System.Threading.Tasks.Task<global::SkyWalking.NetworkProtocol.ApplicationMapping> applicationCodeRegister(global::SkyWalking.NetworkProtocol.Application request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for ApplicationRegisterService</summary>
public partial class ApplicationRegisterServiceClient : grpc::ClientBase<ApplicationRegisterServiceClient>
{
/// <summary>Creates a new client for ApplicationRegisterService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public ApplicationRegisterServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for ApplicationRegisterService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public ApplicationRegisterServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected ApplicationRegisterServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected ApplicationRegisterServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::SkyWalking.NetworkProtocol.ApplicationMapping applicationCodeRegister(global::SkyWalking.NetworkProtocol.Application request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return applicationCodeRegister(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::SkyWalking.NetworkProtocol.ApplicationMapping applicationCodeRegister(global::SkyWalking.NetworkProtocol.Application request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_applicationCodeRegister, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::SkyWalking.NetworkProtocol.ApplicationMapping> applicationCodeRegisterAsync(global::SkyWalking.NetworkProtocol.Application request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return applicationCodeRegisterAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::SkyWalking.NetworkProtocol.ApplicationMapping> applicationCodeRegisterAsync(global::SkyWalking.NetworkProtocol.Application request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_applicationCodeRegister, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override ApplicationRegisterServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new ApplicationRegisterServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(ApplicationRegisterServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_applicationCodeRegister, serviceImpl.applicationCodeRegister).Build();
}
}
}
#endregion
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Common.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace SkyWalking.NetworkProtocol {
/// <summary>Holder for reflection information generated from Common.proto</summary>
public static partial class CommonReflection {
#region Descriptor
/// <summary>File descriptor for Common.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static CommonReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CgxDb21tb24ucHJvdG8qKgoIU3BhblR5cGUSCQoFRW50cnkQABIICgRFeGl0",
"EAESCQoFTG9jYWwQAkJICidvcmcuYXBhY2hlLnNreXdhbGtpbmcuYXBtLm5l",
"dHdvcmsucHJvdG9QAaoCGlNreVdhbGtpbmcuTmV0d29ya1Byb3RvY29sYgZw",
"cm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(new[] {typeof(global::SkyWalking.NetworkProtocol.SpanType), }, null));
}
#endregion
}
#region Enums
public enum SpanType {
[pbr::OriginalName("Entry")] Entry = 0,
[pbr::OriginalName("Exit")] Exit = 1,
[pbr::OriginalName("Local")] Local = 2,
}
#endregion
}
#endregion Designer generated code
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: Downstream.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace SkyWalking.NetworkProtocol {
/// <summary>Holder for reflection information generated from Downstream.proto</summary>
public static partial class DownstreamReflection {
#region Descriptor
/// <summary>File descriptor for Downstream.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static DownstreamReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChBEb3duc3RyZWFtLnByb3RvIgwKCkRvd25zdHJlYW1CSAonb3JnLmFwYWNo",
"ZS5za3l3YWxraW5nLmFwbS5uZXR3b3JrLnByb3RvUAGqAhpTa3lXYWxraW5n",
"Lk5ldHdvcmtQcm90b2NvbGIGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::SkyWalking.NetworkProtocol.Downstream), global::SkyWalking.NetworkProtocol.Downstream.Parser, null, null, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// nothing down stream from collector yet.
/// </summary>
public sealed partial class Downstream : pb::IMessage<Downstream> {
private static readonly pb::MessageParser<Downstream> _parser = new pb::MessageParser<Downstream>(() => new Downstream());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<Downstream> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::SkyWalking.NetworkProtocol.DownstreamReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Downstream() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Downstream(Downstream other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public Downstream Clone() {
return new Downstream(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as Downstream);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(Downstream other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(Downstream other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
}
}
#endregion
}
#endregion Designer generated code
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: JVMMetricsService.proto
// </auto-generated>
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace SkyWalking.NetworkProtocol {
public static partial class JVMMetricsService
{
static readonly string __ServiceName = "JVMMetricsService";
static readonly grpc::Marshaller<global::SkyWalking.NetworkProtocol.JVMMetrics> __Marshaller_JVMMetrics = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::SkyWalking.NetworkProtocol.JVMMetrics.Parser.ParseFrom);
static readonly grpc::Marshaller<global::SkyWalking.NetworkProtocol.Downstream> __Marshaller_Downstream = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::SkyWalking.NetworkProtocol.Downstream.Parser.ParseFrom);
static readonly grpc::Method<global::SkyWalking.NetworkProtocol.JVMMetrics, global::SkyWalking.NetworkProtocol.Downstream> __Method_collect = new grpc::Method<global::SkyWalking.NetworkProtocol.JVMMetrics, global::SkyWalking.NetworkProtocol.Downstream>(
grpc::MethodType.Unary,
__ServiceName,
"collect",
__Marshaller_JVMMetrics,
__Marshaller_Downstream);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::SkyWalking.NetworkProtocol.JVMMetricsServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of JVMMetricsService</summary>
public abstract partial class JVMMetricsServiceBase
{
public virtual global::System.Threading.Tasks.Task<global::SkyWalking.NetworkProtocol.Downstream> collect(global::SkyWalking.NetworkProtocol.JVMMetrics request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for JVMMetricsService</summary>
public partial class JVMMetricsServiceClient : grpc::ClientBase<JVMMetricsServiceClient>
{
/// <summary>Creates a new client for JVMMetricsService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public JVMMetricsServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for JVMMetricsService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public JVMMetricsServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected JVMMetricsServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected JVMMetricsServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::SkyWalking.NetworkProtocol.Downstream collect(global::SkyWalking.NetworkProtocol.JVMMetrics request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return collect(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::SkyWalking.NetworkProtocol.Downstream collect(global::SkyWalking.NetworkProtocol.JVMMetrics request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_collect, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::SkyWalking.NetworkProtocol.Downstream> collectAsync(global::SkyWalking.NetworkProtocol.JVMMetrics request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return collectAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::SkyWalking.NetworkProtocol.Downstream> collectAsync(global::SkyWalking.NetworkProtocol.JVMMetrics request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_collect, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override JVMMetricsServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new JVMMetricsServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(JVMMetricsServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_collect, serviceImpl.collect).Build();
}
}
}
#endregion
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: KeyWithIntegerValue.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace SkyWalking.NetworkProtocol {
/// <summary>Holder for reflection information generated from KeyWithIntegerValue.proto</summary>
public static partial class KeyWithIntegerValueReflection {
#region Descriptor
/// <summary>File descriptor for KeyWithIntegerValue.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static KeyWithIntegerValueReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChlLZXlXaXRoSW50ZWdlclZhbHVlLnByb3RvIjEKE0tleVdpdGhJbnRlZ2Vy",
"VmFsdWUSCwoDa2V5GAEgASgJEg0KBXZhbHVlGAIgASgFQkgKJ29yZy5hcGFj",
"aGUuc2t5d2Fsa2luZy5hcG0ubmV0d29yay5wcm90b1ABqgIaU2t5V2Fsa2lu",
"Zy5OZXR3b3JrUHJvdG9jb2xiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::SkyWalking.NetworkProtocol.KeyWithIntegerValue), global::SkyWalking.NetworkProtocol.KeyWithIntegerValue.Parser, new[]{ "Key", "Value" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class KeyWithIntegerValue : pb::IMessage<KeyWithIntegerValue> {
private static readonly pb::MessageParser<KeyWithIntegerValue> _parser = new pb::MessageParser<KeyWithIntegerValue>(() => new KeyWithIntegerValue());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<KeyWithIntegerValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::SkyWalking.NetworkProtocol.KeyWithIntegerValueReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KeyWithIntegerValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KeyWithIntegerValue(KeyWithIntegerValue other) : this() {
key_ = other.key_;
value_ = other.value_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KeyWithIntegerValue Clone() {
return new KeyWithIntegerValue(this);
}
/// <summary>Field number for the "key" field.</summary>
public const int KeyFieldNumber = 1;
private string key_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Key {
get { return key_; }
set {
key_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "value" field.</summary>
public const int ValueFieldNumber = 2;
private int value_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int Value {
get { return value_; }
set {
value_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as KeyWithIntegerValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(KeyWithIntegerValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Key != other.Key) return false;
if (Value != other.Value) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Key.Length != 0) hash ^= Key.GetHashCode();
if (Value != 0) hash ^= Value.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Key.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Key);
}
if (Value != 0) {
output.WriteRawTag(16);
output.WriteInt32(Value);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Key.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Key);
}
if (Value != 0) {
size += 1 + pb::CodedOutputStream.ComputeInt32Size(Value);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(KeyWithIntegerValue other) {
if (other == null) {
return;
}
if (other.Key.Length != 0) {
Key = other.Key;
}
if (other.Value != 0) {
Value = other.Value;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Key = input.ReadString();
break;
}
case 16: {
Value = input.ReadInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: KeyWithStringValue.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace SkyWalking.NetworkProtocol {
/// <summary>Holder for reflection information generated from KeyWithStringValue.proto</summary>
public static partial class KeyWithStringValueReflection {
#region Descriptor
/// <summary>File descriptor for KeyWithStringValue.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static KeyWithStringValueReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"ChhLZXlXaXRoU3RyaW5nVmFsdWUucHJvdG8iMAoSS2V5V2l0aFN0cmluZ1Zh",
"bHVlEgsKA2tleRgBIAEoCRINCgV2YWx1ZRgCIAEoCUJICidvcmcuYXBhY2hl",
"LnNreXdhbGtpbmcuYXBtLm5ldHdvcmsucHJvdG9QAaoCGlNreVdhbGtpbmcu",
"TmV0d29ya1Byb3RvY29sYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::SkyWalking.NetworkProtocol.KeyWithStringValue), global::SkyWalking.NetworkProtocol.KeyWithStringValue.Parser, new[]{ "Key", "Value" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class KeyWithStringValue : pb::IMessage<KeyWithStringValue> {
private static readonly pb::MessageParser<KeyWithStringValue> _parser = new pb::MessageParser<KeyWithStringValue>(() => new KeyWithStringValue());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<KeyWithStringValue> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::SkyWalking.NetworkProtocol.KeyWithStringValueReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KeyWithStringValue() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KeyWithStringValue(KeyWithStringValue other) : this() {
key_ = other.key_;
value_ = other.value_;
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public KeyWithStringValue Clone() {
return new KeyWithStringValue(this);
}
/// <summary>Field number for the "key" field.</summary>
public const int KeyFieldNumber = 1;
private string key_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Key {
get { return key_; }
set {
key_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "value" field.</summary>
public const int ValueFieldNumber = 2;
private string value_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string Value {
get { return value_; }
set {
value_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as KeyWithStringValue);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(KeyWithStringValue other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (Key != other.Key) return false;
if (Value != other.Value) return false;
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (Key.Length != 0) hash ^= Key.GetHashCode();
if (Value.Length != 0) hash ^= Value.GetHashCode();
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (Key.Length != 0) {
output.WriteRawTag(10);
output.WriteString(Key);
}
if (Value.Length != 0) {
output.WriteRawTag(18);
output.WriteString(Value);
}
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (Key.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Key);
}
if (Value.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(Value);
}
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(KeyWithStringValue other) {
if (other == null) {
return;
}
if (other.Key.Length != 0) {
Key = other.Key;
}
if (other.Value.Length != 0) {
Value = other.Value;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
case 10: {
Key = input.ReadString();
break;
}
case 18: {
Value = input.ReadString();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: NetworkAddressRegisterService.proto
// </auto-generated>
#pragma warning disable 0414, 1591
#region Designer generated code
using grpc = global::Grpc.Core;
namespace SkyWalking.NetworkProtocol {
public static partial class NetworkAddressRegisterService
{
static readonly string __ServiceName = "NetworkAddressRegisterService";
static readonly grpc::Marshaller<global::SkyWalking.NetworkProtocol.NetworkAddresses> __Marshaller_NetworkAddresses = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::SkyWalking.NetworkProtocol.NetworkAddresses.Parser.ParseFrom);
static readonly grpc::Marshaller<global::SkyWalking.NetworkProtocol.NetworkAddressMappings> __Marshaller_NetworkAddressMappings = grpc::Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::SkyWalking.NetworkProtocol.NetworkAddressMappings.Parser.ParseFrom);
static readonly grpc::Method<global::SkyWalking.NetworkProtocol.NetworkAddresses, global::SkyWalking.NetworkProtocol.NetworkAddressMappings> __Method_batchRegister = new grpc::Method<global::SkyWalking.NetworkProtocol.NetworkAddresses, global::SkyWalking.NetworkProtocol.NetworkAddressMappings>(
grpc::MethodType.Unary,
__ServiceName,
"batchRegister",
__Marshaller_NetworkAddresses,
__Marshaller_NetworkAddressMappings);
/// <summary>Service descriptor</summary>
public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor
{
get { return global::SkyWalking.NetworkProtocol.NetworkAddressRegisterServiceReflection.Descriptor.Services[0]; }
}
/// <summary>Base class for server-side implementations of NetworkAddressRegisterService</summary>
public abstract partial class NetworkAddressRegisterServiceBase
{
public virtual global::System.Threading.Tasks.Task<global::SkyWalking.NetworkProtocol.NetworkAddressMappings> batchRegister(global::SkyWalking.NetworkProtocol.NetworkAddresses request, grpc::ServerCallContext context)
{
throw new grpc::RpcException(new grpc::Status(grpc::StatusCode.Unimplemented, ""));
}
}
/// <summary>Client for NetworkAddressRegisterService</summary>
public partial class NetworkAddressRegisterServiceClient : grpc::ClientBase<NetworkAddressRegisterServiceClient>
{
/// <summary>Creates a new client for NetworkAddressRegisterService</summary>
/// <param name="channel">The channel to use to make remote calls.</param>
public NetworkAddressRegisterServiceClient(grpc::Channel channel) : base(channel)
{
}
/// <summary>Creates a new client for NetworkAddressRegisterService that uses a custom <c>CallInvoker</c>.</summary>
/// <param name="callInvoker">The callInvoker to use to make remote calls.</param>
public NetworkAddressRegisterServiceClient(grpc::CallInvoker callInvoker) : base(callInvoker)
{
}
/// <summary>Protected parameterless constructor to allow creation of test doubles.</summary>
protected NetworkAddressRegisterServiceClient() : base()
{
}
/// <summary>Protected constructor to allow creation of configured clients.</summary>
/// <param name="configuration">The client configuration.</param>
protected NetworkAddressRegisterServiceClient(ClientBaseConfiguration configuration) : base(configuration)
{
}
public virtual global::SkyWalking.NetworkProtocol.NetworkAddressMappings batchRegister(global::SkyWalking.NetworkProtocol.NetworkAddresses request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return batchRegister(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual global::SkyWalking.NetworkProtocol.NetworkAddressMappings batchRegister(global::SkyWalking.NetworkProtocol.NetworkAddresses request, grpc::CallOptions options)
{
return CallInvoker.BlockingUnaryCall(__Method_batchRegister, null, options, request);
}
public virtual grpc::AsyncUnaryCall<global::SkyWalking.NetworkProtocol.NetworkAddressMappings> batchRegisterAsync(global::SkyWalking.NetworkProtocol.NetworkAddresses request, grpc::Metadata headers = null, global::System.DateTime? deadline = null, global::System.Threading.CancellationToken cancellationToken = default(global::System.Threading.CancellationToken))
{
return batchRegisterAsync(request, new grpc::CallOptions(headers, deadline, cancellationToken));
}
public virtual grpc::AsyncUnaryCall<global::SkyWalking.NetworkProtocol.NetworkAddressMappings> batchRegisterAsync(global::SkyWalking.NetworkProtocol.NetworkAddresses request, grpc::CallOptions options)
{
return CallInvoker.AsyncUnaryCall(__Method_batchRegister, null, options, request);
}
/// <summary>Creates a new instance of client from given <c>ClientBaseConfiguration</c>.</summary>
protected override NetworkAddressRegisterServiceClient NewInstance(ClientBaseConfiguration configuration)
{
return new NetworkAddressRegisterServiceClient(configuration);
}
}
/// <summary>Creates service definition that can be registered with a server</summary>
/// <param name="serviceImpl">An object implementing the server-side handling logic.</param>
public static grpc::ServerServiceDefinition BindService(NetworkAddressRegisterServiceBase serviceImpl)
{
return grpc::ServerServiceDefinition.CreateBuilder()
.AddMethod(__Method_batchRegister, serviceImpl.batchRegister).Build();
}
}
}
#endregion
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" /> <Import Project="..\..\build\common.props" />
<PropertyGroup> <PropertyGroup>
...@@ -14,20 +14,7 @@ ...@@ -14,20 +14,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
</ItemGroup> <ProjectReference Include="..\SkyWalking.Transport.Grpc.Protocol\SkyWalking.Transport.Grpc.Protocol.csproj" />
<ItemGroup>
<Folder Include="NetworkProtocol" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.6.1" />
<PackageReference Include="Google.Protobuf.Tools" Version="3.6.1" />
<PackageReference Include="Grpc" Version="1.17.0" />
<PackageReference Include="Grpc.Tools" Version="1.17.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup> </ItemGroup>
</Project> </Project>
This diff is collapsed.
...@@ -6,5 +6,9 @@ namespace SkyWalking.Transport.Grpc ...@@ -6,5 +6,9 @@ namespace SkyWalking.Transport.Grpc
public static readonly string RegisterApplicationInstanceError = "Register application instance fail."; public static readonly string RegisterApplicationInstanceError = "Register application instance fail.";
public static readonly string HeartbeatError = "Heartbeat fail."; public static readonly string HeartbeatError = "Heartbeat fail.";
public static readonly string CollectError = "Send trace segment fail."; public static readonly string CollectError = "Send trace segment fail.";
public static readonly string RegisterServiceError = "Register service fail.";
public static readonly string RegisterServiceInstanceError = "Register service instance fail.";
public static readonly string PingError = "Ping server fail.";
} }
} }
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
...@@ -30,7 +30,7 @@ namespace SkyWalking.Utilities.Configuration ...@@ -30,7 +30,7 @@ namespace SkyWalking.Utilities.Configuration
var defaultConfig = new Dictionary<string, string> var defaultConfig = new Dictionary<string, string>
{ {
{"SkyWalking:Namespace", string.Empty}, {"SkyWalking:Namespace", string.Empty},
{"SkyWalking:ApplicationCode", "My_Application"}, {"SkyWalking:ApplicationCode", "My_Service"},
{"SkyWalking:SpanLimitPerSegment", "300"}, {"SkyWalking:SpanLimitPerSegment", "300"},
{"SkyWalking:Sampling:SamplePer3Secs", "-1"}, {"SkyWalking:Sampling:SamplePer3Secs", "-1"},
{"SkyWalking:Logging:Level", "Information"}, {"SkyWalking:Logging:Level", "Information"},
...@@ -40,6 +40,7 @@ namespace SkyWalking.Utilities.Configuration ...@@ -40,6 +40,7 @@ namespace SkyWalking.Utilities.Configuration
{"SkyWalking:Transport:PendingSegmentTimeout", "1000"}, {"SkyWalking:Transport:PendingSegmentTimeout", "1000"},
{"SkyWalking:Transport:gRPC:Servers", "localhost:11800"}, {"SkyWalking:Transport:gRPC:Servers", "localhost:11800"},
{"SkyWalking:Transport:gRPC:Timeout", "2000"}, {"SkyWalking:Transport:gRPC:Timeout", "2000"},
{"SkyWalking:Transport:gRPC:ReportTimeout", "300000"},
{"SkyWalking:Transport:gRPC:ConnectTimeout", "10000"} {"SkyWalking:Transport:gRPC:ConnectTimeout", "10000"}
}; };
return builder.AddInMemoryCollection(defaultConfig); return builder.AddInMemoryCollection(defaultConfig);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment