Commit b231a09a authored by Lemon's avatar Lemon Committed by 吴晟 Wu Sheng

Provide automatic-agent (#85)

* Feature/hostingstartup (#80)

* Update TargetFrameworkVersion

* Update appveyor.yml

* Feature/hostingstartup (#81)

* Update TargetFrameworkVersion

* Update appveyor.yml

* Update appveyor.yml

* Update version.props

* Add ISkyWalkingClient interface

* Refactor

* Fix ProjectReference

* Fix PackageReference

* Fix  System.Threading.ThreadPool

* Refactor IComponents

* Update appveyor.yml

* Update version.cake

* Fix namespace

* Remove SkyWalking.Dictionarys

* Refactor

* Refactor ServiceDiscoveryService

* Refactor

* Refactor

* Add TraceSegmentTransportService

* Blocking dispatcher strategy

* Add gRPC Transport

* Add InstrumentationHostedService

* Refactor skywalking logger

* Agent function test.

* Add debug log

* Fix trace segment queue

* Refactor AsyncQueueTraceDispatcher

* re-naming

* Rename gRPCClient

* Refactor SkyWalking.Utilities

* Trace data sent to collector

* Add SkyWalkingHostingStartup

* Fix peer transform

* Refactor ContextCarrier

* Refactor SkyWalking.AspNet

* Update appveyor.yml

* Fix CI

* Cleanup tests that are no longer applicable
parent d8fab96a
...@@ -23,3 +23,11 @@ deploy: ...@@ -23,3 +23,11 @@ deploy:
artifact: /artifacts\/packages\/.+\.nupkg/ artifact: /artifacts\/packages\/.+\.nupkg/
on: on:
branch: master branch: master
- provider: NuGet
server: https://api.nuget.org/v3/index.json
api_key:
secure: 6N8pLjIHa7SK3l+Lj7b1qKk7CvKdZdQyj9ZNTaUjfPSd+/SL8PuSHq+ysNKaMHAF
skip_symbols: true
artifact: /artifacts\/packages\/.+\.nupkg/
on:
appveyor_repo_tag: true
...@@ -77,7 +77,15 @@ public class BuildParameters ...@@ -77,7 +77,15 @@ public class BuildParameters
var suffix = versionQuality; var suffix = versionQuality;
if (!IsTagged) if (!IsTagged)
{ {
suffix += (IsCI ? "preview-" : "dev-") + Util.CreateStamp(); var buildSystem = Context.BuildSystem();
if (buildSystem.IsRunningOnAppVeyor && buildSystem.AppVeyor.Environment.Repository.Branch == "master")
{
suffix += "prerelease-" + Util.CreateStamp();
}
else
{
suffix += (IsCI ? "preview-" : "dev-") + Util.CreateStamp();
}
} }
suffix = string.IsNullOrWhiteSpace(suffix) ? null : suffix; suffix = string.IsNullOrWhiteSpace(suffix) ? null : suffix;
......
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<VersionMajor>0</VersionMajor> <VersionMajor>0</VersionMajor>
<VersionMinor>3</VersionMinor> <VersionMinor>6</VersionMinor>
<VersionPatch>0</VersionPatch> <VersionPatch>0</VersionPatch>
<VersionQuality></VersionQuality> <VersionQuality></VersionQuality>
<VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix> <VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix>
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SkyWalking.Sample.AspNet</RootNamespace> <RootNamespace>SkyWalking.Sample.AspNet</RootNamespace>
<AssemblyName>SkyWalking.Sample.AspNet</AssemblyName> <AssemblyName>SkyWalking.Sample.AspNet</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
......
...@@ -12,4 +12,17 @@ ...@@ -12,4 +12,17 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="appsettings.Development.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Folder Include="logs" />
</ItemGroup>
</Project> </Project>
\ No newline at end of file
...@@ -24,14 +24,7 @@ namespace SkyWalking.Sample.Backend ...@@ -24,14 +24,7 @@ namespace SkyWalking.Sample.Backend
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddMvc(); services.AddMvc();
services.AddSkyWalking(option =>
{
option.DirectServers = "localhost:11800";
option.ApplicationCode = "asp-net-core-backend";
}).
AddEntityFrameworkCore(c => { c.AddSqlite(); });
var sqliteConnection = new SqliteConnection("DataSource=:memory:"); var sqliteConnection = new SqliteConnection("DataSource=:memory:");
sqliteConnection.Open(); sqliteConnection.Open();
......
...@@ -11,5 +11,8 @@ ...@@ -11,5 +11,8 @@
"Default": "Warning" "Default": "Warning"
} }
} }
},
"SkyWalking": {
"ApplicationCode": "asp-net-core-backend"
} }
} }
...@@ -9,7 +9,7 @@ namespace SkyWalking.Sample.Frontend.Controllers ...@@ -9,7 +9,7 @@ namespace SkyWalking.Sample.Frontend.Controllers
public class ValuesController : Controller public class ValuesController : Controller
{ {
// GET api/values // GET api/values
[HttpGet] [HttpGet("/values")]
public async Task<IEnumerable<string>> Get() public async Task<IEnumerable<string>> Get()
{ {
await new HttpClient().GetAsync("http://localhost:5002/api/values"); await new HttpClient().GetAsync("http://localhost:5002/api/values");
......
...@@ -11,4 +11,10 @@ ...@@ -11,4 +11,10 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project> </Project>
\ No newline at end of file
...@@ -19,12 +19,6 @@ namespace SkyWalking.Sample.Frontend ...@@ -19,12 +19,6 @@ namespace SkyWalking.Sample.Frontend
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddMvc(); services.AddMvc();
services.AddSkyWalking(option =>
{
option.DirectServers = "localhost:11800";
option.ApplicationCode = "asp-net-core-frontend";
});
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
......
...@@ -11,6 +11,9 @@ ...@@ -11,6 +11,9 @@
"Default": "Warning" "Default": "Warning"
} }
} }
},
"SkyWalking": {
"ApplicationCode": "asp-net-core-frontend"
} }
} }
...@@ -22,8 +22,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{613F0980-9 ...@@ -22,8 +22,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{613F0980-9
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Core.Tests", "test\SkyWalking.Core.Tests\SkyWalking.Core.Tests.csproj", "{3915A2C2-7174-4651-A4F1-D45CD109916A}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Core.Tests", "test\SkyWalking.Core.Tests\SkyWalking.Core.Tests.csproj", "{3915A2C2-7174-4651-A4F1-D45CD109916A}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.NetworkProtocol.Trace", "src\SkyWalking.NetworkProtocol.Trace\SkyWalking.NetworkProtocol.Trace.csproj", "{50BE8184-EC7A-4257-AF54-764C0E61276F}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Components", "Components", "{79ED86A5-E9B9-49B2-9354-C911C079D03E}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Components", "Components", "{79ED86A5-E9B9-49B2-9354-C911C079D03E}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Core", "Core", "{CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810}"
...@@ -38,16 +36,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Sample.Frontend" ...@@ -38,16 +36,10 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Sample.Frontend"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Diagnostics.HttpClient", "src\SkyWalking.Diagnostics.HttpClient\SkyWalking.Diagnostics.HttpClient.csproj", "{49DEFCA8-4289-4875-B6A5-35D84B3D2290}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Diagnostics.HttpClient", "src\SkyWalking.Diagnostics.HttpClient\SkyWalking.Diagnostics.HttpClient.csproj", "{49DEFCA8-4289-4875-B6A5-35D84B3D2290}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Extensions.DependencyInjection", "src\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj", "{BF5579ED-113C-4EE6-AE03-9A9CA590C924}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Diagnostics.CAP", "src\SkyWalking.Diagnostics.CAP\SkyWalking.Diagnostics.CAP.csproj", "{55621423-19C3-4928-8B45-666FA87BF6A2}" Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Diagnostics.CAP", "src\SkyWalking.Diagnostics.CAP\SkyWalking.Diagnostics.CAP.csproj", "{55621423-19C3-4928-8B45-666FA87BF6A2}"
EndProject EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Diagnostics.HttpClient.Tests", "test\SkyWalking.Diagnostics.HttpClient.Tests\SkyWalking.Diagnostics.HttpClient.Tests.csproj", "{05E533B1-473F-48C0-95F7-B87061BE9834}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Diagnostics.EntityFrameworkCore", "src\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj", "{CD334460-8E61-41EB-9762-62C6A342CACB}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Diagnostics.EntityFrameworkCore", "src\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj", "{CD334460-8E61-41EB-9762-62C6A342CACB}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Diagnostics.EntityFrameworkCore.Tests", "test\SkyWalking.Diagnostics.EntityFrameworkCore.Tests\SkyWalking.Diagnostics.EntityFrameworkCore.Tests.csproj", "{4CF91A8C-25C8-4BD8-A93D-3183AF0FE2E2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Diagnostics.SqlClient", "src\SkyWalking.Diagnostics.SqlClient\SkyWalking.Diagnostics.SqlClient.csproj", "{44DFFDF7-5935-475A-825F-2C0298464117}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Diagnostics.SqlClient", "src\SkyWalking.Diagnostics.SqlClient\SkyWalking.Diagnostics.SqlClient.csproj", "{44DFFDF7-5935-475A-825F-2C0298464117}"
EndProject EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "EntityFrameworkCore", "EntityFrameworkCore", "{A4E67E09-3156-4D30-B451-F24F706E96C4}" Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "EntityFrameworkCore", "EntityFrameworkCore", "{A4E67E09-3156-4D30-B451-F24F706E96C4}"
...@@ -62,6 +54,20 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.AspNet", "src\Sk ...@@ -62,6 +54,20 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.AspNet", "src\Sk
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Sample.AspNet", "sample\SkyWalking.Sample.AspNet\SkyWalking.Sample.AspNet.csproj", "{C3649845-E458-448D-B97D-C7E231E1D040}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Sample.AspNet", "sample\SkyWalking.Sample.AspNet\SkyWalking.Sample.AspNet.csproj", "{C3649845-E458-448D-B97D-C7E231E1D040}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Transport.Grpc", "src\SkyWalking.Transport.Grpc\SkyWalking.Transport.Grpc.csproj", "{FF2FC3FB-D112-45C1-AF34-1FE37D55F682}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Diagnostics.AspNetCore", "src\SkyWalking.Diagnostics.AspNetCore\SkyWalking.Diagnostics.AspNetCore.csproj", "{CFBB522D-495F-40F9-B68F-DA25E48D9F6A}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Extensions", "Extensions", "{88AEFE60-F743-4AF3-8F55-B4B7B8079D95}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Utilities", "Utilities", "{4BD917BC-D579-4C75-9939-41BF012A4EE2}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Utilities.Configuration", "src\SkyWalking.Utilities.Configuration\SkyWalking.Utilities.Configuration.csproj", "{0B87C4B8-3F4F-456A-B588-28D8E9E3395A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Utilities.DependencyInjection", "src\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj", "{1812A19C-729C-410B-A90D-D5AF1404DD60}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Utilities.Logging", "src\SkyWalking.Utilities.Logging\SkyWalking.Utilities.Logging.csproj", "{AEB61F19-3DBB-411E-A67E-93007B96E160}"
EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
...@@ -84,10 +90,6 @@ Global ...@@ -84,10 +90,6 @@ Global
{3915A2C2-7174-4651-A4F1-D45CD109916A}.Debug|Any CPU.Build.0 = Debug|Any CPU {3915A2C2-7174-4651-A4F1-D45CD109916A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3915A2C2-7174-4651-A4F1-D45CD109916A}.Release|Any CPU.ActiveCfg = Release|Any CPU {3915A2C2-7174-4651-A4F1-D45CD109916A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3915A2C2-7174-4651-A4F1-D45CD109916A}.Release|Any CPU.Build.0 = Release|Any CPU {3915A2C2-7174-4651-A4F1-D45CD109916A}.Release|Any CPU.Build.0 = Release|Any CPU
{50BE8184-EC7A-4257-AF54-764C0E61276F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{50BE8184-EC7A-4257-AF54-764C0E61276F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{50BE8184-EC7A-4257-AF54-764C0E61276F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{50BE8184-EC7A-4257-AF54-764C0E61276F}.Release|Any CPU.Build.0 = Release|Any CPU
{D75B68C5-6788-4871-A63F-F6EB48FB0DC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {D75B68C5-6788-4871-A63F-F6EB48FB0DC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D75B68C5-6788-4871-A63F-F6EB48FB0DC5}.Debug|Any CPU.Build.0 = Debug|Any CPU {D75B68C5-6788-4871-A63F-F6EB48FB0DC5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D75B68C5-6788-4871-A63F-F6EB48FB0DC5}.Release|Any CPU.ActiveCfg = Release|Any CPU {D75B68C5-6788-4871-A63F-F6EB48FB0DC5}.Release|Any CPU.ActiveCfg = Release|Any CPU
...@@ -104,26 +106,14 @@ Global ...@@ -104,26 +106,14 @@ Global
{49DEFCA8-4289-4875-B6A5-35D84B3D2290}.Debug|Any CPU.Build.0 = Debug|Any CPU {49DEFCA8-4289-4875-B6A5-35D84B3D2290}.Debug|Any CPU.Build.0 = Debug|Any CPU
{49DEFCA8-4289-4875-B6A5-35D84B3D2290}.Release|Any CPU.ActiveCfg = Release|Any CPU {49DEFCA8-4289-4875-B6A5-35D84B3D2290}.Release|Any CPU.ActiveCfg = Release|Any CPU
{49DEFCA8-4289-4875-B6A5-35D84B3D2290}.Release|Any CPU.Build.0 = Release|Any CPU {49DEFCA8-4289-4875-B6A5-35D84B3D2290}.Release|Any CPU.Build.0 = Release|Any CPU
{BF5579ED-113C-4EE6-AE03-9A9CA590C924}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{BF5579ED-113C-4EE6-AE03-9A9CA590C924}.Debug|Any CPU.Build.0 = Debug|Any CPU
{BF5579ED-113C-4EE6-AE03-9A9CA590C924}.Release|Any CPU.ActiveCfg = Release|Any CPU
{BF5579ED-113C-4EE6-AE03-9A9CA590C924}.Release|Any CPU.Build.0 = Release|Any CPU
{55621423-19C3-4928-8B45-666FA87BF6A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {55621423-19C3-4928-8B45-666FA87BF6A2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{55621423-19C3-4928-8B45-666FA87BF6A2}.Debug|Any CPU.Build.0 = Debug|Any CPU {55621423-19C3-4928-8B45-666FA87BF6A2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{55621423-19C3-4928-8B45-666FA87BF6A2}.Release|Any CPU.ActiveCfg = Release|Any CPU {55621423-19C3-4928-8B45-666FA87BF6A2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{55621423-19C3-4928-8B45-666FA87BF6A2}.Release|Any CPU.Build.0 = Release|Any CPU {55621423-19C3-4928-8B45-666FA87BF6A2}.Release|Any CPU.Build.0 = Release|Any CPU
{05E533B1-473F-48C0-95F7-B87061BE9834}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{05E533B1-473F-48C0-95F7-B87061BE9834}.Debug|Any CPU.Build.0 = Debug|Any CPU
{05E533B1-473F-48C0-95F7-B87061BE9834}.Release|Any CPU.ActiveCfg = Release|Any CPU
{05E533B1-473F-48C0-95F7-B87061BE9834}.Release|Any CPU.Build.0 = Release|Any CPU
{CD334460-8E61-41EB-9762-62C6A342CACB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {CD334460-8E61-41EB-9762-62C6A342CACB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CD334460-8E61-41EB-9762-62C6A342CACB}.Debug|Any CPU.Build.0 = Debug|Any CPU {CD334460-8E61-41EB-9762-62C6A342CACB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CD334460-8E61-41EB-9762-62C6A342CACB}.Release|Any CPU.ActiveCfg = Release|Any CPU {CD334460-8E61-41EB-9762-62C6A342CACB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CD334460-8E61-41EB-9762-62C6A342CACB}.Release|Any CPU.Build.0 = Release|Any CPU {CD334460-8E61-41EB-9762-62C6A342CACB}.Release|Any CPU.Build.0 = Release|Any CPU
{4CF91A8C-25C8-4BD8-A93D-3183AF0FE2E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4CF91A8C-25C8-4BD8-A93D-3183AF0FE2E2}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4CF91A8C-25C8-4BD8-A93D-3183AF0FE2E2}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4CF91A8C-25C8-4BD8-A93D-3183AF0FE2E2}.Release|Any CPU.Build.0 = Release|Any CPU
{44DFFDF7-5935-475A-825F-2C0298464117}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {44DFFDF7-5935-475A-825F-2C0298464117}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{44DFFDF7-5935-475A-825F-2C0298464117}.Debug|Any CPU.Build.0 = Debug|Any CPU {44DFFDF7-5935-475A-825F-2C0298464117}.Debug|Any CPU.Build.0 = Debug|Any CPU
{44DFFDF7-5935-475A-825F-2C0298464117}.Release|Any CPU.ActiveCfg = Release|Any CPU {44DFFDF7-5935-475A-825F-2C0298464117}.Release|Any CPU.ActiveCfg = Release|Any CPU
...@@ -148,6 +138,26 @@ Global ...@@ -148,6 +138,26 @@ Global
{C3649845-E458-448D-B97D-C7E231E1D040}.Debug|Any CPU.Build.0 = Debug|Any CPU {C3649845-E458-448D-B97D-C7E231E1D040}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3649845-E458-448D-B97D-C7E231E1D040}.Release|Any CPU.ActiveCfg = Release|Any CPU {C3649845-E458-448D-B97D-C7E231E1D040}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3649845-E458-448D-B97D-C7E231E1D040}.Release|Any CPU.Build.0 = Release|Any CPU {C3649845-E458-448D-B97D-C7E231E1D040}.Release|Any CPU.Build.0 = Release|Any CPU
{FF2FC3FB-D112-45C1-AF34-1FE37D55F682}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FF2FC3FB-D112-45C1-AF34-1FE37D55F682}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FF2FC3FB-D112-45C1-AF34-1FE37D55F682}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FF2FC3FB-D112-45C1-AF34-1FE37D55F682}.Release|Any CPU.Build.0 = Release|Any CPU
{CFBB522D-495F-40F9-B68F-DA25E48D9F6A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CFBB522D-495F-40F9-B68F-DA25E48D9F6A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CFBB522D-495F-40F9-B68F-DA25E48D9F6A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CFBB522D-495F-40F9-B68F-DA25E48D9F6A}.Release|Any CPU.Build.0 = Release|Any CPU
{0B87C4B8-3F4F-456A-B588-28D8E9E3395A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0B87C4B8-3F4F-456A-B588-28D8E9E3395A}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0B87C4B8-3F4F-456A-B588-28D8E9E3395A}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0B87C4B8-3F4F-456A-B588-28D8E9E3395A}.Release|Any CPU.Build.0 = Release|Any CPU
{1812A19C-729C-410B-A90D-D5AF1404DD60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1812A19C-729C-410B-A90D-D5AF1404DD60}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1812A19C-729C-410B-A90D-D5AF1404DD60}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1812A19C-729C-410B-A90D-D5AF1404DD60}.Release|Any CPU.Build.0 = Release|Any CPU
{AEB61F19-3DBB-411E-A67E-93007B96E160}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AEB61F19-3DBB-411E-A67E-93007B96E160}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AEB61F19-3DBB-411E-A67E-93007B96E160}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AEB61F19-3DBB-411E-A67E-93007B96E160}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE HideSolutionNode = FALSE
...@@ -157,17 +167,13 @@ Global ...@@ -157,17 +167,13 @@ Global
{C3860B5F-21D0-429F-8A00-B0C0F4573DF7} = {CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810} {C3860B5F-21D0-429F-8A00-B0C0F4573DF7} = {CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810}
{FD84A10C-C962-4AEA-BA06-86F08EB048E6} = {CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810} {FD84A10C-C962-4AEA-BA06-86F08EB048E6} = {CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810}
{3915A2C2-7174-4651-A4F1-D45CD109916A} = {613F0980-91ED-4064-8E8C-168582EF4AD7} {3915A2C2-7174-4651-A4F1-D45CD109916A} = {613F0980-91ED-4064-8E8C-168582EF4AD7}
{50BE8184-EC7A-4257-AF54-764C0E61276F} = {CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810}
{79ED86A5-E9B9-49B2-9354-C911C079D03E} = {05BF0D4E-C824-4EC8-8330-36C1FC49910E} {79ED86A5-E9B9-49B2-9354-C911C079D03E} = {05BF0D4E-C824-4EC8-8330-36C1FC49910E}
{CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810} = {05BF0D4E-C824-4EC8-8330-36C1FC49910E} {CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810} = {05BF0D4E-C824-4EC8-8330-36C1FC49910E}
{D75B68C5-6788-4871-A63F-F6EB48FB0DC5} = {79ED86A5-E9B9-49B2-9354-C911C079D03E} {D75B68C5-6788-4871-A63F-F6EB48FB0DC5} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{80A67B09-83F2-477F-907F-95FFF5B8FEAF} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB} {80A67B09-83F2-477F-907F-95FFF5B8FEAF} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB}
{2B4E350E-A1E5-4B4A-A642-BCA6D3887E5A} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB} {2B4E350E-A1E5-4B4A-A642-BCA6D3887E5A} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB}
{49DEFCA8-4289-4875-B6A5-35D84B3D2290} = {79ED86A5-E9B9-49B2-9354-C911C079D03E} {49DEFCA8-4289-4875-B6A5-35D84B3D2290} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{BF5579ED-113C-4EE6-AE03-9A9CA590C924} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{55621423-19C3-4928-8B45-666FA87BF6A2} = {79ED86A5-E9B9-49B2-9354-C911C079D03E} {55621423-19C3-4928-8B45-666FA87BF6A2} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{05E533B1-473F-48C0-95F7-B87061BE9834} = {613F0980-91ED-4064-8E8C-168582EF4AD7}
{4CF91A8C-25C8-4BD8-A93D-3183AF0FE2E2} = {613F0980-91ED-4064-8E8C-168582EF4AD7}
{44DFFDF7-5935-475A-825F-2C0298464117} = {79ED86A5-E9B9-49B2-9354-C911C079D03E} {44DFFDF7-5935-475A-825F-2C0298464117} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{A4E67E09-3156-4D30-B451-F24F706E96C4} = {79ED86A5-E9B9-49B2-9354-C911C079D03E} {A4E67E09-3156-4D30-B451-F24F706E96C4} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{CD334460-8E61-41EB-9762-62C6A342CACB} = {A4E67E09-3156-4D30-B451-F24F706E96C4} {CD334460-8E61-41EB-9762-62C6A342CACB} = {A4E67E09-3156-4D30-B451-F24F706E96C4}
...@@ -176,6 +182,13 @@ Global ...@@ -176,6 +182,13 @@ Global
{F8D96C30-369C-4FCB-B5B2-02EAA74199C9} = {A4E67E09-3156-4D30-B451-F24F706E96C4} {F8D96C30-369C-4FCB-B5B2-02EAA74199C9} = {A4E67E09-3156-4D30-B451-F24F706E96C4}
{3A454A8A-A1B7-4C6D-BE08-52D956F95CC1} = {79ED86A5-E9B9-49B2-9354-C911C079D03E} {3A454A8A-A1B7-4C6D-BE08-52D956F95CC1} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{C3649845-E458-448D-B97D-C7E231E1D040} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB} {C3649845-E458-448D-B97D-C7E231E1D040} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB}
{FF2FC3FB-D112-45C1-AF34-1FE37D55F682} = {CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810}
{CFBB522D-495F-40F9-B68F-DA25E48D9F6A} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{88AEFE60-F743-4AF3-8F55-B4B7B8079D95} = {05BF0D4E-C824-4EC8-8330-36C1FC49910E}
{4BD917BC-D579-4C75-9939-41BF012A4EE2} = {05BF0D4E-C824-4EC8-8330-36C1FC49910E}
{0B87C4B8-3F4F-456A-B588-28D8E9E3395A} = {4BD917BC-D579-4C75-9939-41BF012A4EE2}
{1812A19C-729C-410B-A90D-D5AF1404DD60} = {4BD917BC-D579-4C75-9939-41BF012A4EE2}
{AEB61F19-3DBB-411E-A67E-93007B96E160} = {4BD917BC-D579-4C75-9939-41BF012A4EE2}
EndGlobalSection EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {94C0DA2C-CCCB-4314-93A2-9809B5DD0583} SolutionGuid = {94C0DA2C-CCCB-4314-93A2-9809B5DD0583}
......
/*
* 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.Collections.Generic;
namespace SkyWalking.Components
{
public class ComponentsDefine
{
public static readonly IComponent HttpClient = new OfficialComponent(2, "HttpClient");
public static readonly IComponent AspNetCore = new OfficialComponent(3001, "AspNetCore");
public static readonly IComponent EntityFrameworkCore = new OfficialComponent(3002, "EntityFrameworkCore");
public static readonly IComponent SqlClient = new OfficialComponent(3003, "SqlClient");
public static readonly IComponent CAP = new OfficialComponent(3004, "CAP");
public static readonly IComponent StackExchange_Redis = new OfficialComponent(3005, "StackExchange.Redis");
public static readonly IComponent SqlServer = new OfficialComponent(3006, "SqlServer");
public static readonly IComponent Npgsql = new OfficialComponent(3007, "Npgsql");
public static readonly IComponent MySqlConnector = new OfficialComponent(3008, "MySqlConnector");
public static readonly IComponent EntityFrameworkCore_InMemory = new OfficialComponent(3009, "EntityFrameworkCore.InMemory");
public static readonly IComponent EntityFrameworkCore_SqlServer = new OfficialComponent(3010, "EntityFrameworkCore.SqlServer");
public static readonly IComponent EntityFrameworkCore_Sqlite = new OfficialComponent(3011, "EntityFrameworkCore.Sqlite");
public static readonly IComponent Pomelo_EntityFrameworkCore_MySql = new OfficialComponent(3012, "Pomelo.EntityFrameworkCore.MySql");
public static readonly IComponent Npgsql_EntityFrameworkCore_PostgreSQL = new OfficialComponent(3013, "Npgsql.EntityFrameworkCore.PostgreSQL");
public static readonly IComponent InMemoryDatabase = new OfficialComponent(3014, "InMemoryDatabase");
public static readonly IComponent AspNet = new OfficialComponent(3015, "AspNet");
}
}
/* /*
* 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
namespace SkyWalking.NetworkProtocol.Trace namespace SkyWalking.Components
{ {
/// <summary> /// <summary>
/// The <code>Component</code> represents component library , which has been supported by skywalking /// The <code>Component</code> represents component library , which has been supported by skywalking
/// </summary> /// </summary>
public interface IComponent public interface IComponent
{ {
int Id { get; } int Id { get; }
string Name { get; }
} string Name { get; }
} }
}
\ 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
namespace SkyWalking.NetworkProtocol.Trace namespace SkyWalking.Components
{ {
public class OfficialComponent : IComponent public class OfficialComponent : IComponent
{ {
public OfficialComponent(int id, string name) public OfficialComponent(int id, string name)
{ {
Id = id; Id = id;
Name = name; Name = name;
} }
public int Id { get; } public int Id { get; }
public string Name { get; } public string Name { get; }
} }
} }
\ 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.Config
{
public static class AgentConfig
{
/// <summary>
/// Namespace isolates headers in cross propagation. The HEADER name will be 'HeaderName:Namespace'.
/// </summary>
public static string Namespace { get; set; }
/// <summary>
/// Application code is showed in sky-walking-ui
/// </summary>
public static string ApplicationCode { get; set; }
/// <summary>
/// The number of sampled traces per 3 seconds
/// Negative number means sample traces as many as possible, most likely 100% , by default
///
/// </summary>
public static int SamplePer3Secs = -1;
/// <summary>
/// If the operation name of the first span is included in this set, this segment should be ignored.
/// </summary>
public static string IgnoreSuffix = ".jpg,.jpeg,.js,.css,.png,.bmp,.gif,.ico,.mp3,.mp4,.html,.svg";
/// <summary>
/// The max number of spans in a single segment. Through this config item, skywalking keep your application memory cost estimated.
/// </summary>
public static int SpanLimitPerSegment = 300;
/// <summary>
/// The max number of segments in the memory queue waiting to be sent to collector.
/// It means that when the number of queued segments reachs this limit,
/// any more segments enqueued into the sending queue, will leads the same number of oldest queued segments dequeued and droped.
/// Zero or minus value means no limit.
/// </summary>
public static int PendingSegmentsLimit = 300000;
}
}
\ 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.Config
{
public class CollectorConfig
{
/// <summary>
/// service registry check interval
/// </summary>
public static long ServiceRegisterCheckInterval { get; set; } = 3;
/// <summary>
/// Collector agent_gRPC/grpc service addresses.
/// By using this, no discovery mechanism provided. The agent only uses these addresses to uplink data.
/// Recommend to use this only when collector cluster IPs are unreachable from agent side. Such as:
/// 1. Agent and collector cluster are in different VPC in Cloud.
/// 2. Agent uplinks data to collector cluster through Internet.
/// Single collector:DirectServers="127.0.0.1:11800"
/// Collector cluster:DirectServers="10.2.45.126:11800,10.2.45.127:11800"
/// </summary>
public static string DirectServers { get; set; }
public static string Authentication { get; set; }
public static string CertificatePath { 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,17 +16,17 @@ ...@@ -16,17 +16,17 @@
* *
*/ */
using SkyWalking.Dictionarys; using System;
namespace SkyWalking.Dictionarys namespace SkyWalking.Config
{ {
public class NotFound : PossibleFound public class ConfigAttribute : Attribute
{ {
public NotFound() public string[] Sections { get; }
: base()
public ConfigAttribute(params string[] sections)
{ {
Sections = sections;
} }
public static readonly PossibleFound Instance = new NotFound();
} }
} }
\ 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
namespace SkyWalking.Config namespace SkyWalking.Config
{ {
public static class DictionaryConfig public interface IConfigAccessor
{ {
public static int ApplicationCodeBufferSize { get; set; } = 10 * 10000; T Get<T>() where T : class, new();
public static int OperationNameBufferSize { get; set; } = 1000 * 10000; T Value<T>(string key, params string[] sections);
} }
} }
\ 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.Config
{
[Config("SkyWalking")]
public class InstrumentationConfig
{
public string Namespace { get; set; }
public string ApplicationCode { get; set; }
public int SpanLimitPerSegment { get; set; } = 300;
}
}
\ 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.Config
{
public class RuntimeConfig
{
public NullableValue ApplicationId { get; set; }
public NullableValue ApplicationInstance { 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using SkyWalking.Dictionarys; namespace SkyWalking.Config
{
namespace SkyWalking.Dictionarys [Config("SkyWalking", "Sampling")]
{ public class SamplingConfig
public class Found : PossibleFound {
{ public int SamplePer3Secs { get; set; } = -1;
public Found(int value) }
: base(value)
{
}
}
} }
\ 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.Config
{
[Config("SkyWalking", "Transport")]
public class TransportConfig
{
public int PendingSegmentLimit { get; set; } = 30000;
/// <summary>
/// Flush Interval Millisecond
/// </summary>
public int Interval { get; set; } = 3000;
/// <summary>
/// Data queued beyond this time will be discarded.
/// </summary>
public int PendingSegmentTimeout { get; set; } = 1000;
}
}
\ No newline at end of file
...@@ -16,56 +16,33 @@ ...@@ -16,56 +16,33 @@
* *
*/ */
using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using SkyWalking.Config;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
public class CarrierItem : IEnumerable<CarrierItem> public class CarrierItem : IEnumerable<CarrierItem>
{ {
private string _headKey; private readonly string _headKey;
private string _headValue; private string _headValue;
private CarrierItem _next; private readonly CarrierItem _next;
public virtual string HeadKey public virtual string HeadKey => _headKey;
{
get
{
return _headKey;
}
}
public virtual string HeadValue public virtual string HeadValue
{ {
get get => _headValue;
{ set => _headValue = value;
return _headValue;
}
set
{
_headValue = value;
}
} }
public CarrierItem(String headKey, String headValue) protected CarrierItem(string headKey, string headValue, string @namespace)
: this(headKey, headValue, null, @namespace)
{ {
_headKey = headKey;
_headValue = headValue;
_next = null;
} }
public CarrierItem(String headKey, String headValue, CarrierItem next) protected CarrierItem(string headKey, string headValue, CarrierItem next, string @namespace)
{ {
if (string.IsNullOrEmpty(AgentConfig.Namespace)) _headKey = string.IsNullOrEmpty(@namespace) ? headKey : $"{@namespace}-{headKey}";
{
_headKey = headKey;
}
else
{
_headKey = $"{AgentConfig.Namespace}-{headKey}";
}
_headValue = headValue; _headValue = headValue;
_next = next; _next = next;
} }
...@@ -82,17 +59,16 @@ namespace SkyWalking.Context ...@@ -82,17 +59,16 @@ namespace SkyWalking.Context
private class Enumerator : IEnumerator<CarrierItem> private class Enumerator : IEnumerator<CarrierItem>
{ {
private CarrierItem _head; private readonly CarrierItem _head;
private CarrierItem _current;
public CarrierItem Current => _current; public CarrierItem Current { get; private set; }
object IEnumerator.Current => _current; object IEnumerator.Current => Current;
public Enumerator(CarrierItem head) public Enumerator(CarrierItem head)
{ {
_head = head; _head = head;
_current = head; Current = head;
} }
public void Dispose() public void Dispose()
...@@ -101,19 +77,20 @@ namespace SkyWalking.Context ...@@ -101,19 +77,20 @@ namespace SkyWalking.Context
public bool MoveNext() public bool MoveNext()
{ {
var next = _current._next; var next = Current._next;
if (next == null) if (next == null)
{ {
return false; return false;
} }
_current = next;
Current = next;
return true; return true;
} }
public void Reset() public void Reset()
{ {
_current = _head; Current = _head;
} }
} }
} }
} }
\ 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System.Threading.Tasks; namespace SkyWalking.Context
{
namespace SkyWalking.Utils public interface IContextCarrierFactory
{ {
internal static class TaskUtils IContextCarrier Create();
{ }
public static readonly Task CompletedTask = Task.FromResult(0);
}
} }
\ No newline at end of file
...@@ -18,11 +18,12 @@ ...@@ -18,11 +18,12 @@
using System; using System;
using SkyWalking.NetworkProtocol; using SkyWalking.Transport;
namespace SkyWalking.Context.Ids namespace SkyWalking.Context.Ids
{ {
/// <inheritdoc />
/// <summary> /// <summary>
/// The <code>DistributedTraceId</code> presents a distributed call chain. /// The <code>DistributedTraceId</code> presents a distributed call chain.
/// This call chain has an unique (service) entrance, /// This call chain has an unique (service) entrance,
...@@ -34,50 +35,35 @@ namespace SkyWalking.Context.Ids ...@@ -34,50 +35,35 @@ namespace SkyWalking.Context.Ids
{ {
private readonly ID _id; private readonly ID _id;
public DistributedTraceId(ID id) protected DistributedTraceId(ID id)
{ {
_id = id; _id = id;
} }
public DistributedTraceId(string id) protected DistributedTraceId(string id)
{ {
_id = new ID(id); _id = new ID(id);
} }
public string Encode public string Encode => _id?.Encode;
{
get
{
return _id?.Encode;
}
}
public UniqueId ToUniqueId() public UniqueIdRequest ToUniqueId() => _id?.Transform();
{
return _id?.Transform();
}
public bool Equals(DistributedTraceId other) public bool Equals(DistributedTraceId other)
{ {
if (other == null) if (other == null)
return false; return false;
return _id != null ? _id.Equals(other._id) : other._id == null; return _id?.Equals(other._id) ?? other._id == null;
} }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
DistributedTraceId id = obj as DistributedTraceId; var id = obj as DistributedTraceId;
return Equals(id); return Equals(id);
} }
public override int GetHashCode() public override int GetHashCode() => _id != null ? _id.GetHashCode() : 0;
{
return _id != null ? _id.GetHashCode() : 0;
}
public override string ToString() public override string ToString() => _id?.ToString();
{
return _id?.ToString();
}
} }
} }
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
*/ */
using System; using System;
using SkyWalking.NetworkProtocol; using SkyWalking.Transport;
namespace SkyWalking.Context.Ids namespace SkyWalking.Context.Ids
{ {
...@@ -26,35 +26,18 @@ namespace SkyWalking.Context.Ids ...@@ -26,35 +26,18 @@ namespace SkyWalking.Context.Ids
private readonly long _part1; private readonly long _part1;
private readonly long _part2; private readonly long _part2;
private readonly long _part3; private readonly long _part3;
private readonly bool _isValid;
private string _encoding; private string _encoding;
public bool IsValid public bool IsValid { get; }
{
get
{
return _isValid;
}
}
public string Encode public string Encode => _encoding ?? (_encoding = ToString());
{
get
{
if (_encoding == null)
{
_encoding = ToString();
}
return _encoding;
}
}
public ID(long part1, long part2, long part3) public ID(long part1, long part2, long part3)
{ {
_part1 = part1; _part1 = part1;
_part2 = part2; _part2 = part2;
_part3 = part3; _part3 = part3;
_isValid = true; IsValid = true;
} }
public ID(string encodingString) public ID(string encodingString)
...@@ -68,17 +51,17 @@ namespace SkyWalking.Context.Ids ...@@ -68,17 +51,17 @@ namespace SkyWalking.Context.Ids
{ {
if (part == 0) if (part == 0)
{ {
_isValid = long.TryParse(idParts[part], out _part1); IsValid = long.TryParse(idParts[part], out _part1);
} }
else if (part == 1) else if (part == 1)
{ {
_isValid = long.TryParse(idParts[part], out _part2); IsValid = long.TryParse(idParts[part], out _part2);
} }
else else
{ {
_isValid = long.TryParse(idParts[part], out _part3); IsValid = long.TryParse(idParts[part], out _part3);
} }
if (!_isValid) if (!IsValid)
{ {
break; break;
} }
...@@ -92,7 +75,7 @@ namespace SkyWalking.Context.Ids ...@@ -92,7 +75,7 @@ namespace SkyWalking.Context.Ids
public override int GetHashCode() public override int GetHashCode()
{ {
int result = (int)(_part1 ^ (_part1 >> 32)); var result = (int)(_part1 ^ (_part1 >> 32));
result = 31 * result + (int)(_part2 ^ (_part2 >> 32)); result = 31 * result + (int)(_part2 ^ (_part2 >> 32));
result = 31 * result + (int)(_part3 ^ (_part3 >> 32)); result = 31 * result + (int)(_part3 ^ (_part3 >> 32));
return result; return result;
...@@ -100,7 +83,7 @@ namespace SkyWalking.Context.Ids ...@@ -100,7 +83,7 @@ namespace SkyWalking.Context.Ids
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
ID id = obj as ID; var id = obj as ID;
return Equals(id); return Equals(id);
} }
...@@ -117,12 +100,9 @@ namespace SkyWalking.Context.Ids ...@@ -117,12 +100,9 @@ namespace SkyWalking.Context.Ids
return _part3 == other._part3; return _part3 == other._part3;
} }
public UniqueId Transform() public UniqueIdRequest Transform()
{ {
UniqueId uniqueId = new UniqueId(); var uniqueId = new UniqueIdRequest {Part1 = _part1, Part2 = _part2, Part3 = _part3};
uniqueId.IdParts.Add(_part1);
uniqueId.IdParts.Add(_part2);
uniqueId.IdParts.Add(_part3);
return uniqueId; return uniqueId;
} }
} }
......
...@@ -18,11 +18,8 @@ ...@@ -18,11 +18,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using SkyWalking.Dictionarys; using SkyWalking.Transport;
using SkyWalking.NetworkProtocol; using SkyWalking.Components;
using SkyWalking.NetworkProtocol.Trace;
using System.Linq;
using SkyWalking.Utils;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -31,8 +28,8 @@ namespace SkyWalking.Context.Trace ...@@ -31,8 +28,8 @@ namespace SkyWalking.Context.Trace
/// </summary> /// </summary>
public abstract class AbstractTracingSpan : ISpan public abstract class AbstractTracingSpan : ISpan
{ {
protected int _spanId; protected readonly int _spanId;
protected int _parnetSpanId; protected readonly int _parnetSpanId;
protected Dictionary<string, string> _tags; protected Dictionary<string, string> _tags;
protected string _operationName; protected string _operationName;
protected int _operationId; protected int _operationId;
...@@ -69,7 +66,6 @@ namespace SkyWalking.Context.Trace ...@@ -69,7 +66,6 @@ namespace SkyWalking.Context.Trace
protected AbstractTracingSpan(int spanId, int parentSpanId, string operationName) protected AbstractTracingSpan(int spanId, int parentSpanId, string operationName)
{ {
_operationName = operationName; _operationName = operationName;
_operationId = DictionaryUtil.NullValue;
_spanId = spanId; _spanId = spanId;
_parnetSpanId = parentSpanId; _parnetSpanId = parentSpanId;
} }
...@@ -90,23 +86,17 @@ namespace SkyWalking.Context.Trace ...@@ -90,23 +86,17 @@ namespace SkyWalking.Context.Trace
public virtual string OperationName public virtual string OperationName
{ {
get get => _operationName;
{
return _operationName;
}
set set
{ {
_operationName = value; _operationName = value;
_operationId = DictionaryUtil.NullValue; _operationId = 0;
} }
} }
public virtual int OperationId public virtual int OperationId
{ {
get get => _operationId;
{
return _operationId;
}
set set
{ {
_operationId = value; _operationId = value;
...@@ -132,6 +122,7 @@ namespace SkyWalking.Context.Trace ...@@ -132,6 +122,7 @@ namespace SkyWalking.Context.Trace
{ {
_tags = new Dictionary<string, string>(); _tags = new Dictionary<string, string>();
} }
_tags.Add(key, value); _tags.Add(key, value);
return this; return this;
} }
...@@ -166,11 +157,12 @@ namespace SkyWalking.Context.Trace ...@@ -166,11 +157,12 @@ namespace SkyWalking.Context.Trace
public virtual ISpan Log(long timestamp, IDictionary<string, object> events) public virtual ISpan Log(long timestamp, IDictionary<string, object> events)
{ {
EnsureLogs(); EnsureLogs();
LogDataEntity.Builder builder = new LogDataEntity.Builder(); var builder = new LogDataEntity.Builder();
foreach (var @event in events) foreach (var @event in events)
{ {
builder.Add(@event.Key, @event.Value.ToString()); builder.Add(@event.Key, @event.Value.ToString());
} }
_logs.Add(builder.Build(timestamp)); _logs.Add(builder.Build(timestamp));
return this; return this;
} }
...@@ -193,6 +185,7 @@ namespace SkyWalking.Context.Trace ...@@ -193,6 +185,7 @@ namespace SkyWalking.Context.Trace
{ {
_refs = new List<ITraceSegmentRef>(); _refs = new List<ITraceSegmentRef>();
} }
if (!_refs.Contains(traceSegmentRef)) if (!_refs.Contains(traceSegmentRef))
{ {
_refs.Add(traceSegmentRef); _refs.Add(traceSegmentRef);
...@@ -211,69 +204,58 @@ namespace SkyWalking.Context.Trace ...@@ -211,69 +204,58 @@ namespace SkyWalking.Context.Trace
return true; return true;
} }
public virtual SpanObject Transform() public virtual SpanRequest Transform()
{ {
SpanObject spanObject = new SpanObject(); var spanRequest = new SpanRequest
spanObject.SpanId = _spanId;
spanObject.ParentSpanId = _parnetSpanId;
spanObject.StartTime = _startTime;
spanObject.EndTime = _endTime;
if (_operationId != DictionaryUtil.NullValue)
{ {
spanObject.OperationNameId = _operationId; SpanId = _spanId,
} ParentSpanId = _parnetSpanId,
else StartTime = _startTime,
{ EndTime = _endTime,
spanObject.OperationName = _operationName; OperationName = new StringOrIntValue(_operationId, _operationName),
} Component = new StringOrIntValue(_componentId, _componentName),
IsError = _errorOccurred
};
if (IsEntry) if (IsEntry)
{ {
spanObject.SpanType = SpanType.Entry; spanRequest.SpanType = 0;
} }
else if (IsExit) else if (IsExit)
{ {
spanObject.SpanType = SpanType.Exit; spanRequest.SpanType = 1;
} }
else else
{ {
spanObject.SpanType = SpanType.Local; spanRequest.SpanType = 2;
} }
if (_layer.HasValue) if (_layer.HasValue)
{ {
spanObject.SpanLayer = (NetworkProtocol.SpanLayer)((int)_layer.Value); spanRequest.SpanLayer = (int) _layer.Value;
}
if (_componentId != DictionaryUtil.NullValue)
{
spanObject.ComponentId = _componentId;
}
else
{
spanObject.Component = _componentName;
} }
spanObject.IsError = _errorOccurred;
if (_tags != null) foreach (var tag in _tags)
{ {
spanObject.Tags.Add(_tags.Select(x => new KeyWithStringValue { Key = x.Key, Value = x.Value })); spanRequest.Tags.Add(new KeyValuePair<string, string>(tag.Key, tag.Value));
} }
if (_logs != null) if (_logs != null)
{ {
spanObject.Logs.Add(_logs.Select(x => x.Transform())); foreach (var logDataEntity in _logs)
{
spanRequest.Logs.Add(logDataEntity.Transform());
}
} }
if (_refs != null) if (_refs == null) return spanRequest;
foreach (var traceSegmentRef in _refs)
{ {
spanObject.Refs.Add(_refs.Select(x => x.Transform())); spanRequest.References.Add(traceSegmentRef.Transform());
} }
return spanObject; return spanRequest;
} }
private void EnsureLogs() private void EnsureLogs()
...@@ -284,4 +266,4 @@ namespace SkyWalking.Context.Trace ...@@ -284,4 +266,4 @@ namespace SkyWalking.Context.Trace
} }
} }
} }
} }
\ No newline at end of file
...@@ -18,8 +18,7 @@ ...@@ -18,8 +18,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using SkyWalking.Components;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -36,7 +35,7 @@ namespace SkyWalking.Context.Trace ...@@ -36,7 +35,7 @@ namespace SkyWalking.Context.Trace
ISpan SetComponent(IComponent component); ISpan SetComponent(IComponent component);
/// <summary> /// <summary>
/// Only use this method in explicit instrumentation, like opentracing-skywalking-bridge. It it higher recommend /// Only use this method in explicit skyWalking, like opentracing-skywalking-bridge. It it higher recommend
/// don't use this for performance consideration. /// don't use this for performance consideration.
/// </summary> /// </summary>
/// <param name="componentName"></param> /// <param name="componentName"></param>
......
...@@ -17,8 +17,8 @@ ...@@ -17,8 +17,8 @@
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using SkyWalking.Transport;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -48,6 +48,6 @@ namespace SkyWalking.Context.Trace ...@@ -48,6 +48,6 @@ namespace SkyWalking.Context.Trace
void RelatedGlobalTrace(DistributedTraceId distributedTraceId); void RelatedGlobalTrace(DistributedTraceId distributedTraceId);
UpstreamSegment Transform(); TraceSegmentRequest Transform();
} }
} }
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
*/ */
using System; using System;
using SkyWalking.NetworkProtocol; using SkyWalking.Transport;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -29,6 +29,6 @@ namespace SkyWalking.Context.Trace ...@@ -29,6 +29,6 @@ namespace SkyWalking.Context.Trace
int EntryApplicationInstanceId { get; } int EntryApplicationInstanceId { get; }
TraceSegmentReference Transform(); TraceSegmentReferenceRequest Transform();
} }
} }
\ No newline at end of file
...@@ -18,14 +18,14 @@ ...@@ -18,14 +18,14 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using SkyWalking.NetworkProtocol; using SkyWalking.Transport;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
public class LogDataEntity public class LogDataEntity
{ {
private long _timestamp = 0; private readonly long _timestamp;
private Dictionary<string, string> _logs; private readonly Dictionary<string, string> _logs;
private LogDataEntity(long timestamp, Dictionary<string, string> logs) private LogDataEntity(long timestamp, Dictionary<string, string> logs)
{ {
...@@ -33,14 +33,11 @@ namespace SkyWalking.Context.Trace ...@@ -33,14 +33,11 @@ namespace SkyWalking.Context.Trace
_logs = logs; _logs = logs;
} }
public IReadOnlyDictionary<string, string> Logs public IReadOnlyDictionary<string, string> Logs => new ReadOnlyDictionary<string, string>(_logs);
{
get { return new ReadOnlyDictionary<string, string>(_logs); }
}
public class Builder public class Builder
{ {
private Dictionary<string, string> _logs; private readonly Dictionary<string, string> _logs;
public Builder() public Builder()
{ {
...@@ -66,16 +63,16 @@ namespace SkyWalking.Context.Trace ...@@ -66,16 +63,16 @@ namespace SkyWalking.Context.Trace
} }
} }
public LogMessage Transform() public LogDataRequest Transform()
{ {
LogMessage logMessage = new LogMessage(); var logMessage = new LogDataRequest();
logMessage.Time = _timestamp; logMessage.Timestamp = _timestamp;
foreach (var log in _logs) foreach (var log in _logs)
{ {
logMessage.Data.Add(new KeyWithStringValue {Key = log.Key, Value = log.Value}); logMessage.Data.Add(new KeyValuePair<string, string>(log.Key, log.Value));
} }
return logMessage; return logMessage;
} }
} }
} }
\ No newline at end of file
...@@ -20,7 +20,7 @@ namespace SkyWalking.Context.Trace ...@@ -20,7 +20,7 @@ namespace SkyWalking.Context.Trace
{ {
public enum SegmentRefType public enum SegmentRefType
{ {
CrossProcess, CrossProcess = 0,
CrossThread CrossThread = 1
} }
} }
\ 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.
...@@ -17,66 +17,65 @@ ...@@ -17,66 +17,65 @@
*/ */
using System; using System;
using System.Reflection; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Web.Configuration;
using SkyWalking.AspNet.Logging;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Logging; using SkyWalking.Logging;
using SkyWalking.Remote;
namespace SkyWalking.AspNet namespace SkyWalking
{ {
public class SkyWalkingStartup : IDisposable public abstract class ExecutionService : IExecutionService, IDisposable
{ {
public void Start() private Timer _timer;
private CancellationTokenSource _cancellationTokenSource;
protected readonly ILogger Logger;
protected readonly IRuntimeEnvironment RuntimeEnvironment;
protected readonly ISkyWalkingClient SkyWalking;
protected ExecutionService(ISkyWalkingClient skyWalking, IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
{ {
LoadConfigurationSetting(); SkyWalking = skyWalking;
LogManager.SetLoggerFactory(new DebugLoggerFactoryAdapter()); RuntimeEnvironment = runtimeEnvironment;
AsyncContext.Run(async () => await StartAsync()); Logger = loggerFactory.CreateLogger(GetType());
} }
private async Task StartAsync() public Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
{ {
await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(3)); _cancellationTokenSource = new CancellationTokenSource();
await ServiceManager.Instance.Initialize(); var source = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, cancellationToken);
_timer = new Timer(Callback, source, DueTime, Period);
Logger.Information($"Loaded instrument service [{GetType().FullName}].");
return Task.CompletedTask;
}
public async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken))
{
_cancellationTokenSource?.Cancel();
await Stopping(cancellationToken);
Logger.Information($"Stopped instrument service {GetType().Name}.");
} }
private void LoadConfigurationSetting() public void Dispose()
{ {
CollectorConfig.DirectServers = GetAppSetting(nameof(CollectorConfig.DirectServers), true); _timer?.Dispose();
AgentConfig.ApplicationCode = GetAppSetting(nameof(AgentConfig.ApplicationCode), true);
AgentConfig.Namespace = GetAppSetting(nameof(AgentConfig.Namespace), false);
CollectorConfig.CertificatePath = GetAppSetting(nameof(CollectorConfig.CertificatePath), false);
CollectorConfig.Authentication = GetAppSetting(nameof(CollectorConfig.Authentication), false);
var samplePer3Secs = GetAppSetting(nameof(AgentConfig.SamplePer3Secs), false);
if (int.TryParse(samplePer3Secs, out var v))
{
AgentConfig.SamplePer3Secs = v;
}
var pendingSegmentsLimit = GetAppSetting(nameof(AgentConfig.PendingSegmentsLimit), false);
if(int.TryParse(pendingSegmentsLimit, out v))
{
AgentConfig.PendingSegmentsLimit = v;
}
} }
private string GetAppSetting(string key, bool @throw) private async void Callback(object state)
{ {
var value = WebConfigurationManager.AppSettings[key]; if (state is CancellationTokenSource token && !token.IsCancellationRequested && CanExecute())
if (@throw && string.IsNullOrEmpty(value))
{ {
throw new InvalidOperationException($"Cannot read valid '{key}' in AppSettings."); await ExecuteAsync(token.Token);
} }
return value;
} }
public void Dispose() protected virtual bool CanExecute() => RuntimeEnvironment.Initialized;
{
AsyncContext.Run(async () => await GrpcConnectionManager.Instance.ShutdownAsync()); protected virtual Task Stopping(CancellationToken cancellationToke) => Task.CompletedTask;
ServiceManager.Instance.Dispose();
} protected abstract TimeSpan DueTime { get; }
protected abstract TimeSpan Period { get; }
protected abstract Task ExecuteAsync(CancellationToken cancellationToken);
} }
} }
\ No newline at end of file
namespace SkyWalking
{
public interface IEnvironmentProvider
{
string EnvironmentName { get; }
}
}
\ 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.
*
*/
using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking
{
public interface IExecutionService
{
Task StartAsync(CancellationToken cancellationToken = default(CancellationToken));
Task StopAsync(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.
*
*/
using System;
using SkyWalking.Config;
namespace SkyWalking
{
public interface IRuntimeEnvironment
{
NullableValue ApplicationId { get; }
NullableValue ApplicationInstanceId { get; }
bool Initialized { get; }
Guid AgentUUID { get; }
IEnvironmentProvider Environment { get; }
}
}
\ No newline at end of file
...@@ -16,13 +16,11 @@ ...@@ -16,13 +16,11 @@
* *
*/ */
using SkyWalking.Boot; namespace SkyWalking
namespace SkyWalking.Sampling
{ {
public interface ISampler : IBootService public interface ISampler
{ {
bool TrySampling(); bool Sampled();
void ForceSampled(); void ForceSampled();
} }
......
using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking
{
public interface ISkyWalkingAgentStartup
{
Task StartAsync(CancellationToken cancellationToken = default(CancellationToken));
Task StopAsync(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.
*
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Transport;
namespace SkyWalking
{
public interface ISkyWalkingClient
{
Task<NullableValue> RegisterApplicationAsync(string applicationCode, CancellationToken cancellationToken = default(CancellationToken));
Task<NullableValue> RegisterApplicationInstanceAsync(int applicationId, Guid agentUUID, long registerTime, AgentOsInfoRequest osInfoRequest,
CancellationToken cancellationToken = default(CancellationToken));
Task HeartbeatAsync(int applicationInstance, long heartbeatTime, CancellationToken cancellationToken = default(CancellationToken));
Task CollectAsync(IEnumerable<TraceSegmentRequest> request, CancellationToken cancellationToken = default(CancellationToken));
}
}
\ No newline at end of file
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
* *
*/ */
namespace SkyWalking.Diagnostics namespace SkyWalking
{ {
public interface ITracingDiagnosticProcessor public interface ITracingDiagnosticProcessor
{ {
......
...@@ -24,7 +24,7 @@ namespace SkyWalking.Logging ...@@ -24,7 +24,7 @@ namespace SkyWalking.Logging
{ {
void Debug(string message); void Debug(string message);
void Info(string message); void Information(string message);
void Warning(string message); void Warning(string message);
......
/*
* 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
{
public struct NullableValue
{
public static readonly NullableValue Null = new NullableValue(0);
private const int NULL_VALUE = 0;
public int Value { get; }
public NullableValue(int value)
{
Value = value;
}
public bool HasValue => Value != NULL_VALUE;
}
}
\ No newline at end of file
...@@ -3,16 +3,12 @@ ...@@ -3,16 +3,12 @@
<PropertyGroup> <PropertyGroup>
<Description>SkyWalking Core abstractions and interfaces for apm agent.</Description> <Description>SkyWalking Core abstractions and interfaces for apm agent.</Description>
<AssemblyTitle>SkyWalking.Abstractions</AssemblyTitle> <AssemblyTitle>SkyWalking.Abstractions</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net45;net451</TargetFrameworks>
<AssemblyName>SkyWalking.Abstractions</AssemblyName> <AssemblyName>SkyWalking.Abstractions</AssemblyName>
<PackageId>SkyWalking.Abstractions</PackageId> <PackageId>SkyWalking.Abstractions</PackageId>
<PackageTags>SkyWalking;APM</PackageTags> <PackageTags>SkyWalking;APM</PackageTags>
<PackageReleaseNotes> <PackageReleaseNotes>
</PackageReleaseNotes> </PackageReleaseNotes>
<RootNamespace>SkyWalking</RootNamespace> <RootNamespace>SkyWalking</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.NetworkProtocol.Trace\SkyWalking.NetworkProtocol.Trace.csproj" />
<ProjectReference Include="..\SkyWalking.NetworkProtocol\SkyWalking.NetworkProtocol.csproj" />
</ItemGroup>
</Project> </Project>
\ 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
{
public struct StringOrIntValue
{
private readonly int _intValue;
private readonly string _stringValue;
public StringOrIntValue(int value)
{
_intValue = value;
_stringValue = null;
}
public bool HasIntValue => _intValue != 0;
public bool HasStringValue => _stringValue != null;
public StringOrIntValue(string value)
{
_intValue = 0;
_stringValue = value;
}
public StringOrIntValue(int intValue, string stringValue)
{
_intValue = intValue;
_stringValue = stringValue;
}
public int GetIntValue() => _intValue;
public string GetStringValue() => _stringValue;
public (string, int) GetValue()
{
return (_stringValue, _intValue);
}
}
}
\ 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 AgentOsInfoRequest
{
public string OsName { get; set; }
public string HostName { get; set; }
public int ProcessNo { get; set; }
public string[] IpAddress { 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.
*
*/
using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking.Transport
{
public interface ITraceDispatcher
{
bool Dispatch(TraceSegmentRequest segment);
Task Flush(CancellationToken token = default(CancellationToken));
void Close();
}
}
/*
* 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;
namespace SkyWalking.Transport
{
public class TraceSegmentRequest
{
public IEnumerable<UniqueIdRequest> UniqueIds { get; set; }
public TraceSegmentObjectRequest Segment { get; set; }
}
public class UniqueIdRequest
{
public long Part1 { get; set; }
public long Part2 { get; set; }
public long Part3 { get; set; }
public override string ToString()
{
return $"{Part1}.{Part2}.{Part3}";
}
}
public class TraceSegmentObjectRequest
{
public UniqueIdRequest SegmentId { get; set; }
public int ApplicationId { get; set; }
public int ApplicationInstanceId { get; set; }
public IList<SpanRequest> Spans { get; set; } = new List<SpanRequest>();
}
public class SpanRequest
{
public int SpanId { get; set; }
public int SpanType { get; set; }
public int SpanLayer { get; set; }
public int ParentSpanId { get; set; }
public long StartTime { get; set; }
public long EndTime { get; set; }
public StringOrIntValue Component { get; set; }
public StringOrIntValue OperationName { get; set; }
public StringOrIntValue Peer { get; set; }
public bool IsError { get; set; }
public IList<TraceSegmentReferenceRequest> References { get; } = new List<TraceSegmentReferenceRequest>();
public IList<KeyValuePair<string, string>> Tags { get; } = new List<KeyValuePair<string, string>>();
public IList<LogDataRequest> Logs { get; } = new List<LogDataRequest>();
}
public class TraceSegmentReferenceRequest
{
public UniqueIdRequest ParentTraceSegmentId { get; set; }
public int ParentApplicationInstanceId { get; set; }
public int ParentSpanId { get; set; }
public int EntryApplicationInstanceId { get; set; }
public int RefType { get; set; }
public StringOrIntValue ParentServiceName { get; set; }
public StringOrIntValue EntryServiceName { get; set; }
public StringOrIntValue NetworkAddress { get; set; }
}
public class LogDataRequest
{
public long Timestamp { get; set; }
public IList<KeyValuePair<string, string>> Data { get; } = new List<KeyValuePair<string, string>>();
}
}
\ No newline at end of file
...@@ -22,7 +22,7 @@ using System.Threading.Tasks; ...@@ -22,7 +22,7 @@ using System.Threading.Tasks;
namespace SkyWalking.AspNet namespace SkyWalking.AspNet
{ {
internal class AsyncContext internal static class AsyncContext
{ {
public static void Run(Func<Task> task) public static void Run(Func<Task> task)
{ {
......
/*
* 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 Microsoft.Extensions.DependencyInjection;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Diagnostics;
using SkyWalking.Logging;
using SkyWalking.Service;
using SkyWalking.Transport;
using SkyWalking.Transport.Grpc;
using SkyWalking.Utilities.Configuration;
using SkyWalking.Utilities.Logging;
namespace SkyWalking.AspNet.Extensions
{
internal static class ServiceCollectionExtensions
{
public static IServiceCollection AddSkyWalkingCore(this IServiceCollection services)
{
services.AddSingleton<SkyWalkingApplicationRequestCallback>();
services.AddSingleton<IContextCarrierFactory, ContextCarrierFactory>();
services.AddSingleton<ITraceDispatcher, AsyncQueueTraceDispatcher>();
services.AddSingleton<IExecutionService, TraceSegmentTransportService>();
services.AddSingleton<IExecutionService, ServiceDiscoveryService>();
services.AddSingleton<IExecutionService, SamplingRefreshService>();
services.AddSingleton<ISkyWalkingAgentStartup, SkyWalkingAgentStartup>();
services.AddSingleton<TracingDiagnosticProcessorObserver>();
services.AddSingleton<IConfigAccessor, ConfigAccessor>();
services.AddSingleton<IEnvironmentProvider, HostingEnvironmentProvider>();
services.AddSingleton<ILoggerFactory, DefaultLoggerFactory>();
services.AddSingleton<ISkyWalkingClient, GrpcClient>();
services.AddSingleton<ConnectionManager>();
services.AddSingleton<IExecutionService, GrpcStateCheckService>();
services.AddSingleton<ISampler>(DefaultSampler.Instance);
services.AddSingleton(RuntimeEnvironment.Instance);
return services;
}
}
}
\ 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System; using System;
namespace SkyWalking.Utils namespace SkyWalking.AspNet
{ {
#if NET45 || NET451 internal class HostingEnvironmentProvider : IEnvironmentProvider
public static class DateTimeOffsetExtensions {
{ private const string ENVIRONMENT_KEY = "ASPNET__ENVIRONMENT";
public static long ToUnixTimeMilliseconds(this DateTimeOffset dateTimeOffset)
{ public string EnvironmentName { get; }
return dateTimeOffset.UtcDateTime.Ticks / 10000L - 62135596800000L;
} public HostingEnvironmentProvider()
} {
#endif EnvironmentName = Environment.GetEnvironmentVariable(ENVIRONMENT_KEY) ?? "Production";
} }
}
}
\ No newline at end of file
...@@ -20,30 +20,38 @@ using System; ...@@ -20,30 +20,38 @@ using System;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using SkyWalking.Components;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Context.Tag; using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.AspNet namespace SkyWalking.AspNet
{ {
public class HttpTracingHandler : DelegatingHandler public class HttpTracingHandler : DelegatingHandler
{ {
private readonly IContextCarrierFactory _contextCarrierFactory;
public HttpTracingHandler() public HttpTracingHandler()
: this(new HttpClientHandler()) : this(new HttpClientHandler())
{ {
} }
public HttpTracingHandler(HttpMessageHandler innerHandler) public HttpTracingHandler(HttpMessageHandler innerHandler)
: this(innerHandler, CommonServiceLocator.ServiceLocator.Current.GetInstance<IContextCarrierFactory>())
{
}
private HttpTracingHandler(HttpMessageHandler innerHandler, IContextCarrierFactory contextCarrierFactory)
{ {
InnerHandler = innerHandler; InnerHandler = innerHandler;
_contextCarrierFactory = contextCarrierFactory;
} }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
var peer = $"{request.RequestUri.Host}:{request.RequestUri.Port}"; var peer = $"{request.RequestUri.Host}:{request.RequestUri.Port}";
var contextCarrier = new ContextCarrier(); var contextCarrier = _contextCarrierFactory.Create();
var span = ContextManager.CreateExitSpan(request.RequestUri.ToString(), contextCarrier, peer); var span = ContextManager.CreateExitSpan(request.RequestUri.ToString(), contextCarrier, peer);
try try
{ {
...@@ -68,4 +76,4 @@ namespace SkyWalking.AspNet ...@@ -68,4 +76,4 @@ namespace SkyWalking.AspNet
} }
} }
} }
} }
\ 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.
...@@ -16,30 +16,34 @@ ...@@ -16,30 +16,34 @@
* *
*/ */
using CommonServiceLocator;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SkyWalking.AspNetCore.Diagnostics; namespace SkyWalking.AspNet
using SkyWalking.AspNetCore.Logging;
using SkyWalking.Diagnostics;
using SkyWalking.Extensions.DependencyInjection;
using SkyWalking.Logging;
namespace SkyWalking.AspNetCore
{ {
internal static class SkyWalkingBuilderExtensions internal class ServiceProviderLocator : IServiceLocator
{ {
public static SkyWalkingBuilder AddHosting(this SkyWalkingBuilder builder) private readonly IServiceProvider _serviceProvider;
{
builder.Services.AddSingleton<IHostedService, SkyWalkingHostedService>();
builder.Services.AddSingleton<ITracingDiagnosticProcessor, HostingDiagnosticProcessor>();
builder.Services.AddSingleton<ILoggerFactory, LoggerFactoryAdapter>();
return builder;
}
public static SkyWalkingBuilder AddDiagnostics(this SkyWalkingBuilder builder) public ServiceProviderLocator(IServiceProvider serviceProvider)
{ {
builder.Services.AddSingleton<TracingDiagnosticProcessorObserver>(); _serviceProvider = serviceProvider;
return builder;
} }
public object GetService(Type serviceType) => _serviceProvider.GetService(serviceType);
public object GetInstance(Type serviceType) => _serviceProvider.GetService(serviceType);
public object GetInstance(Type serviceType, string key) => GetInstance(serviceType);
public IEnumerable<object> GetAllInstances(Type serviceType) => _serviceProvider.GetServices(serviceType);
public TService GetInstance<TService>() => (TService) GetInstance(typeof(TService));
public TService GetInstance<TService>(string key) => (TService) GetInstance(typeof(TService));
public IEnumerable<TService> GetAllInstances<TService>() => _serviceProvider.GetServices<TService>();
} }
} }
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" /> <Import Project="..\..\build\common.props" />
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net45;net451;net452;net46;net461;net462;net47;net471</TargetFrameworks> <TargetFrameworks>net461;net462;net47;net471</TargetFrameworks>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<AssemblyName>SkyWalking.AspNet</AssemblyName> <AssemblyName>SkyWalking.AspNet</AssemblyName>
...@@ -13,13 +13,20 @@ ...@@ -13,13 +13,20 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Transport.Grpc\SkyWalking.Transport.Grpc.csproj" />
<ProjectReference Include="..\SkyWalking.Utilities.Configuration\SkyWalking.Utilities.Configuration.csproj" />
<ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
<ProjectReference Include="..\SkyWalking.Utilities.Logging\SkyWalking.Utilities.Logging.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System.Configuration" /> <Reference Include="System.Configuration" />
<Reference Include="System.Web" /> <Reference Include="System.Web" />
<Reference Include="System.Net.Http"/> <Reference Include="System.Net.Http" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CommonServiceLocator" Version="2.0.4" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />
<PackageReference Include="Microsoft.Web.Infrastructure" Version="1.0.0" /> <PackageReference Include="Microsoft.Web.Infrastructure" Version="1.0.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
\ 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.Web;
using SkyWalking.Components;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
namespace SkyWalking.AspNet
{
internal class SkyWalkingApplicationRequestCallback
{
private readonly IContextCarrierFactory _contextCarrierFactory;
private readonly InstrumentationConfig _config;
public SkyWalkingApplicationRequestCallback(IConfigAccessor configAccessor, IContextCarrierFactory carrierFactory)
{
_config = configAccessor.Get<InstrumentationConfig>();
_contextCarrierFactory = carrierFactory;
}
public void ApplicationOnBeginRequest(object sender, EventArgs e)
{
var httpApplication = sender as HttpApplication;
var httpContext = httpApplication.Context;
var carrier = _contextCarrierFactory.Create();
foreach (var item in carrier.Items)
item.HeadValue = httpContext.Request.Headers[item.HeadKey];
var httpRequestSpan = ContextManager.CreateEntrySpan($"{_config.ApplicationCode} {httpContext.Request.Path}", carrier);
httpRequestSpan.AsHttp();
httpRequestSpan.SetComponent(ComponentsDefine.AspNet);
Tags.Url.Set(httpRequestSpan, httpContext.Request.Path);
Tags.HTTP.Method.Set(httpRequestSpan, httpContext.Request.HttpMethod);
httpRequestSpan.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
new Dictionary<string, object>
{
{"event", "AspNet BeginRequest"},
{"message", $"Request starting {httpContext.Request.Url.Scheme} {httpContext.Request.HttpMethod} {httpContext.Request.Url.OriginalString}"}
});
}
public void ApplicationOnEndRequest(object sender, EventArgs e)
{
var httpRequestSpan = ContextManager.ActiveSpan;
if (httpRequestSpan == null)
{
return;
}
var httpApplication = sender as HttpApplication;
var httpContext = httpApplication.Context;
var statusCode = httpContext.Response.StatusCode;
if (statusCode >= 400)
{
httpRequestSpan.ErrorOccurred();
}
Tags.StatusCode.Set(httpRequestSpan, statusCode.ToString());
var exception = httpContext.Error;
if (exception != null)
{
httpRequestSpan.ErrorOccurred().Log(exception);
}
httpRequestSpan.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
new Dictionary<string, object>
{
{"event", "AspNet EndRequest"},
{"message", $"Request finished {httpContext.Response.StatusCode} {httpContext.Response.ContentType}"}
});
ContextManager.StopSpan(httpRequestSpan);
}
}
}
\ No newline at end of file
...@@ -16,87 +16,33 @@ ...@@ -16,87 +16,33 @@
* *
*/ */
using System; using CommonServiceLocator;
using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection;
using System.Web; using System.Web;
using SkyWalking.Boot; using SkyWalking.AspNet.Extensions;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Remote;
using SkyWalking.Utils;
namespace SkyWalking.AspNet namespace SkyWalking.AspNet
{ {
public class SkyWalkingModule : IHttpModule public class SkyWalkingModule : IHttpModule
{ {
private readonly SkyWalkingStartup _skyWalkingStartup = new SkyWalkingStartup(); public SkyWalkingModule()
public void Dispose()
{ {
_skyWalkingStartup.Dispose(); var serviceProvider = new ServiceCollection().AddSkyWalkingCore().BuildServiceProvider();
var serviceLocatorProvider = new ServiceProviderLocator(serviceProvider);
ServiceLocator.SetLocatorProvider(() => serviceLocatorProvider);
} }
public void Init(HttpApplication application) public void Init(HttpApplication application)
{ {
_skyWalkingStartup.Start(); var startup = ServiceLocator.Current.GetInstance<ISkyWalkingAgentStartup>();
application.BeginRequest += ApplicationOnBeginRequest; AsyncContext.Run(() => startup.StartAsync());
application.EndRequest += ApplicationOnEndRequest; var requestCallback = ServiceLocator.Current.GetInstance<SkyWalkingApplicationRequestCallback>();
application.BeginRequest += requestCallback.ApplicationOnBeginRequest;
application.EndRequest += requestCallback.ApplicationOnEndRequest;
} }
private void ApplicationOnBeginRequest(object sender, EventArgs e) public void Dispose()
{
var httpApplication = sender as HttpApplication;
var httpContext = httpApplication.Context;
var carrier = new ContextCarrier();
foreach (var item in carrier.Items)
item.HeadValue = httpContext.Request.Headers[item.HeadKey];
var httpRequestSpan = ContextManager.CreateEntrySpan($"{Config.AgentConfig.ApplicationCode} {httpContext.Request.Path}", carrier);
httpRequestSpan.AsHttp();
httpRequestSpan.SetComponent(ComponentsDefine.AspNet);
Tags.Url.Set(httpRequestSpan, httpContext.Request.Path);
Tags.HTTP.Method.Set(httpRequestSpan, httpContext.Request.HttpMethod);
httpRequestSpan.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
new Dictionary<string, object>
{
{"event", "AspNet BeginRequest"},
{"message", $"Request starting {httpContext.Request.Url.Scheme} {httpContext.Request.HttpMethod} {httpContext.Request.Url.OriginalString}"}
});
}
private void ApplicationOnEndRequest(object sender, EventArgs e)
{ {
var httpRequestSpan = ContextManager.ActiveSpan;
if (httpRequestSpan == null)
{
return;
}
var httpApplication = sender as HttpApplication;
var httpContext = httpApplication.Context;
var statusCode = httpContext.Response.StatusCode;
if (statusCode >= 400)
{
httpRequestSpan.ErrorOccurred();
}
Tags.StatusCode.Set(httpRequestSpan, statusCode.ToString());
var exception = httpContext.Error;
if (exception != null)
{
httpRequestSpan.ErrorOccurred().Log(exception);
}
httpRequestSpan.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
new Dictionary<string, object>
{
{"event", "AspNetCore Hosting EndRequest"},
{"message", $"Request finished {httpContext.Response.StatusCode} {httpContext.Response.ContentType}"}
});
ContextManager.StopSpan(httpRequestSpan);
} }
} }
} }
\ 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.AspNet
{
public class SkyWalkingOptions
{
/// <summary>
/// Application code is showed in sky-walking-ui
/// </summary>
public string ApplicationCode { get; set; }
/// <summary>
/// Collector agent_gRPC/grpc service addresses.
/// By using this, no discovery mechanism provided. The agent only uses these addresses to uplink data.
/// Recommend to use this only when collector cluster IPs are unreachable from agent side. Such as:
/// 1. Agent and collector cluster are in different VPC in Cloud.
/// 2. Agent uplinks data to collector cluster through Internet.
/// Single collector:DirectServers="127.0.0.1:11800"
/// Collector cluster:DirectServers="10.2.45.126:11800,10.2.45.127:11800"
/// </summary>
public string DirectServers { get; set; }
/// <summary>
/// The number of sampled traces per 3 seconds
/// Negative number means sample traces as many as possible, most likely 100% , by default
///
/// </summary>
public int SamplePer3Secs { get; set; } = -1;
/// <summary>
/// Namespace isolates headers in cross propagation. The HEADER name will be 'HeaderName:Namespace'.
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// The max number of segments in the memory queue waiting to be sent to collector.
/// It means that when the number of queued segments reachs this limit,
/// any more segments enqueued into the sending queue, will leads the same number of oldest queued segments dequeued and droped.
/// Zero or minus value means no limit.
/// </summary>
public int PendingSegmentsLimit { get; set; } = 300000;
/// <summary>
/// Set your own token to active auth
/// </summary>
public string Authentication
{
get;
set;
}
/// <summary>
/// Set certificate path to open ssl/tls
/// </summary>
public string CertificatePath
{
get;
set;
}
}
}
\ No newline at end of file
...@@ -17,45 +17,63 @@ ...@@ -17,45 +17,63 @@
*/ */
using System; using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SkyWalking.AspNetCore.Diagnostics;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Diagnostics;
using SkyWalking.Diagnostics.EntityFrameworkCore;
using SkyWalking.Diagnostics.HttpClient; using SkyWalking.Diagnostics.HttpClient;
using SkyWalking.Diagnostics.SqlClient; using SkyWalking.Diagnostics.SqlClient;
using SkyWalking.Extensions.DependencyInjection; using SkyWalking.Utilities.Configuration;
using SkyWalking.Utilities.DependencyInjection;
using SkyWalking.Utilities.Logging;
using SkyWalking.Logging;
using SkyWalking.Service;
using SkyWalking.Transport;
using SkyWalking.Transport.Grpc;
namespace SkyWalking.AspNetCore namespace SkyWalking.AspNetCore
{ {
public static class ServiceCollectionExtensions internal static class ServiceCollectionExtensions
{ {
public static SkyWalkingBuilder AddSkyWalking(this IServiceCollection services, public static IServiceCollection AddSkyWalkingCore(this IServiceCollection services)
Action<SkyWalkingOptions> options)
{ {
if (options == null) if (services == null)
{ {
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(services));
} }
return services.Configure(options).AddSkyWalkingCore(); services.AddSingleton<IContextCarrierFactory, ContextCarrierFactory>();
services.AddSingleton<ITraceDispatcher, AsyncQueueTraceDispatcher>();
services.AddSingleton<IExecutionService, TraceSegmentTransportService>();
services.AddSingleton<IExecutionService, ServiceDiscoveryService>();
services.AddSingleton<IExecutionService, SamplingRefreshService>();
services.AddSingleton<ISkyWalkingAgentStartup, SkyWalkingAgentStartup>();
services.AddSingleton<ISampler>(DefaultSampler.Instance);
services.AddSingleton(RuntimeEnvironment.Instance);
services.AddSingleton<TracingDiagnosticProcessorObserver>();
services.AddSingleton<IConfigAccessor, ConfigAccessor>();
services.AddSingleton<IHostedService, InstrumentationHostedService>();
services.AddSingleton<IEnvironmentProvider, HostingEnvironmentProvider>();
services.AddGrpcTransport().AddLogging();
services.AddSkyWalkingExtensions().AddAspNetCoreHosting().AddHttpClient().AddSqlClient().AddEntityFrameworkCore(c => c.AddSqlite().AddPomeloMysql().AddNpgsql());
return services;
} }
public static SkyWalkingBuilder AddSkyWalking(this IServiceCollection services, private static IServiceCollection AddGrpcTransport(this IServiceCollection services)
IConfiguration configuration)
{ {
return services.Configure<SkyWalkingOptions>(configuration).AddSkyWalkingCore(); services.AddSingleton<ISkyWalkingClient, GrpcClient>();
services.AddSingleton<ConnectionManager>();
services.AddSingleton<IExecutionService, GrpcStateCheckService>();
return services;
} }
private static SkyWalkingBuilder AddSkyWalkingCore(this IServiceCollection services) private static IServiceCollection AddLogging(this IServiceCollection services)
{ {
if (services == null) services.AddSingleton<ILoggerFactory, DefaultLoggerFactory>();
{ return services;
throw new ArgumentNullException(nameof(services));
}
var builder = new SkyWalkingBuilder(services);
builder.AddHosting().AddDiagnostics().AddHttpClient().AddSqlClient();
return builder;
} }
} }
} }
\ No newline at end of file
using Microsoft.AspNetCore.Hosting;
namespace SkyWalking.AspNetCore
{
internal class HostingEnvironmentProvider : IEnvironmentProvider
{
public string EnvironmentName { get; }
public HostingEnvironmentProvider(IHostingEnvironment hostingEnvironment)
{
EnvironmentName = hostingEnvironment.EnvironmentName;
}
}
}
\ 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System; using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking.Logging using Microsoft.Extensions.Hosting;
{
public static class LogManager namespace SkyWalking.AspNetCore
{ {
private static readonly ILoggerFactory defaultLoggerFactory = new NullLoggerFactory(); public class InstrumentationHostedService : IHostedService
private static ILoggerFactory _loggerFactory; {
private readonly ISkyWalkingAgentStartup _startup;
public static ILogger GetLogger(Type type)
{ public InstrumentationHostedService(ISkyWalkingAgentStartup startup)
var loggerFactory = _loggerFactory ?? defaultLoggerFactory; {
return loggerFactory.CreateLogger(type); _startup = startup;
} }
public static ILogger GetLogger<T>() public Task StartAsync(CancellationToken cancellationToken)
{ {
return GetLogger(typeof(T)); return _startup.StartAsync(cancellationToken);
} }
public static void SetLoggerFactory(ILoggerFactory loggerFactory) public Task StopAsync(CancellationToken cancellationToken)
{ {
_loggerFactory = loggerFactory; return _startup.StopAsync(cancellationToken);
} }
} }
} }
\ No newline at end of file
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<Description>SkyWalking ASP.NET Core Agent.</Description> <Description>SkyWalking ASP.NET Core Agent.</Description>
<AssemblyTitle>SkyWalking.AspNetCore</AssemblyTitle> <AssemblyTitle>SkyWalking.AspNetCore</AssemblyTitle>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>SkyWalking.AspNetCore</AssemblyName> <AssemblyName>SkyWalking_AspNetCore</AssemblyName>
<PackageId>SkyWalking.AspNetCore</PackageId> <PackageId>SkyWalking.AspNetCore</PackageId>
<PackageTags>SkyWalking;APM</PackageTags> <PackageTags>SkyWalking;APM</PackageTags>
<PackageReleaseNotes> <PackageReleaseNotes>
...@@ -12,18 +12,22 @@ ...@@ -12,18 +12,22 @@
<RootNamespace>SkyWalking.AspNetCore</RootNamespace> <RootNamespace>SkyWalking.AspNetCore</RootNamespace>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.AspNetCore\SkyWalking.Diagnostics.AspNetCore.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore.Npgsql\SkyWalking.Diagnostics.EntityFrameworkCore.Npgsql.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore.Pomelo.MySql\SkyWalking.Diagnostics.EntityFrameworkCore.Pomelo.MySql.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore.Sqlite\SkyWalking.Diagnostics.EntityFrameworkCore.Sqlite.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.HttpClient\SkyWalking.Diagnostics.HttpClient.csproj" /> <ProjectReference Include="..\SkyWalking.Diagnostics.HttpClient\SkyWalking.Diagnostics.HttpClient.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.SqlClient\SkyWalking.Diagnostics.SqlClient.csproj" /> <ProjectReference Include="..\SkyWalking.Diagnostics.SqlClient\SkyWalking.Diagnostics.SqlClient.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj"> <ProjectReference Include="..\SkyWalking.Utilities.Configuration\SkyWalking.Utilities.Configuration.csproj" />
<Project>{BF5579ED-113C-4EE6-AE03-9A9CA590C924}</Project> <ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
<Name>SkyWalking.Extensions.DependencyInjection</Name> <ProjectReference Include="..\SkyWalking.Utilities.Logging\SkyWalking.Utilities.Logging.csproj" />
</ProjectReference> <ProjectReference Include="..\SkyWalking.Transport.Grpc\SkyWalking.Transport.Grpc.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
\ No newline at end of file
using Microsoft.AspNetCore.Hosting;
using SkyWalking.AspNetCore;
[assembly: HostingStartup(typeof(SkyWalkingHostingStartup))]
namespace SkyWalking.AspNetCore
{
public class SkyWalkingHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices(services => services.AddSkyWalkingCore());
}
}
}
\ 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.Runtime.CompilerServices;
using Microsoft.Extensions.Options;
namespace SkyWalking.AspNetCore
{
public class SkyWalkingOptions : IOptions<SkyWalkingOptions>
{
public SkyWalkingOptions Value => this;
/// <summary>
/// Application code is showed in sky-walking-ui
/// </summary>
public string ApplicationCode
{
get;
set;
}
/// <summary>
/// Collector agent_gRPC/grpc service addresses.
/// By using this, no discovery mechanism provided. The agent only uses these addresses to uplink data.
/// Recommend to use this only when collector cluster IPs are unreachable from agent side. Such as:
/// 1. Agent and collector cluster are in different VPC in Cloud.
/// 2. Agent uplinks data to collector cluster through Internet.
/// Single collector:DirectServers="127.0.0.1:11800"
/// Collector cluster:DirectServers="10.2.45.126:11800,10.2.45.127:11800"
/// </summary>
public string DirectServers
{
get;
set;
}
/// <summary>
/// The number of sampled traces per 3 seconds
/// Negative number means sample traces as many as possible, most likely 100% , by default
///
/// </summary>
public int SamplePer3Secs
{
get;
set;
} = -1;
/// <summary>
/// The max number of segments in the memory queue waiting to be sent to collector.
/// It means that when the number of queued segments reachs this limit,
/// any more segments enqueued into the sending queue, will leads the same number of oldest queued segments dequeued and droped.
/// Zero or minus value means no limit.
/// </summary>
public int PendingSegmentsLimit
{
get;
set;
} = 300000;
/// <summary>
/// Set your own token to active auth
/// </summary>
public string Authentication
{
get;
set;
}
/// <summary>
/// Set certificate path to open ssl/tls
/// </summary>
public string CertificatePath
{
get;
set;
}
}
}
...@@ -21,8 +21,8 @@ namespace SkyWalking.Context ...@@ -21,8 +21,8 @@ namespace SkyWalking.Context
{ {
public class CarrierItemHead : CarrierItem public class CarrierItemHead : CarrierItem
{ {
public CarrierItemHead(CarrierItem next) : base(string.Empty, string.Empty, next) public CarrierItemHead(CarrierItem next, string @namespace) : base(string.Empty, string.Empty, next, @namespace)
{ {
} }
} }
} }
\ No newline at end of file
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.Dictionarys;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
...@@ -35,12 +34,12 @@ namespace SkyWalking.Context ...@@ -35,12 +34,12 @@ namespace SkyWalking.Context
/// <summary> /// <summary>
/// id of parent application instance /// id of parent application instance
/// </summary> /// </summary>
private int _parentApplicationInstanceId = DictionaryUtil.NullValue; private int _parentApplicationInstanceId = 0;
/// <summary> /// <summary>
/// id of first application instance in this distributed trace /// id of first application instance in this distributed trace
/// </summary> /// </summary>
private int _entryApplicationInstanceId = DictionaryUtil.NullValue; private int _entryApplicationInstanceId = 0;
/// <summary> /// <summary>
/// peer(ipv4/ipv6/hostname + port) of the server , from client side . /// peer(ipv4/ipv6/hostname + port) of the server , from client side .
...@@ -65,6 +64,12 @@ namespace SkyWalking.Context ...@@ -65,6 +64,12 @@ namespace SkyWalking.Context
private DistributedTraceId _primaryDistributedTraceId; private DistributedTraceId _primaryDistributedTraceId;
private readonly string _namespace;
public ContextCarrier(string @namespace)
{
_namespace = @namespace;
}
public DistributedTraceId DistributedTraceId => _primaryDistributedTraceId; public DistributedTraceId DistributedTraceId => _primaryDistributedTraceId;
...@@ -135,8 +140,8 @@ namespace SkyWalking.Context ...@@ -135,8 +140,8 @@ namespace SkyWalking.Context
return _traceSegmentId != null return _traceSegmentId != null
&& _traceSegmentId.IsValid && _traceSegmentId.IsValid
&& _spanId > -1 && _spanId > -1
&& _parentApplicationInstanceId != DictionaryUtil.NullValue && _parentApplicationInstanceId != 0
&& _entryApplicationInstanceId != DictionaryUtil.NullValue && _entryApplicationInstanceId != 0
&& !string.IsNullOrEmpty(_peerHost) && !string.IsNullOrEmpty(_peerHost)
&& !string.IsNullOrEmpty(_parentOperationName) && !string.IsNullOrEmpty(_parentOperationName)
&& !string.IsNullOrEmpty(_entryOperationName) && !string.IsNullOrEmpty(_entryOperationName)
...@@ -180,17 +185,14 @@ namespace SkyWalking.Context ...@@ -180,17 +185,14 @@ namespace SkyWalking.Context
PrimaryDistributedTraceId.Encode); PrimaryDistributedTraceId.Encode);
} }
public DistributedTraceId PrimaryDistributedTraceId public DistributedTraceId PrimaryDistributedTraceId => _primaryDistributedTraceId;
{
get { return _primaryDistributedTraceId; }
}
public CarrierItem Items public CarrierItem Items
{ {
get get
{ {
SW3CarrierItem carrierItem = new SW3CarrierItem(this, null); var carrierItem = new SW3CarrierItem(this, null, _namespace);
CarrierItemHead head = new CarrierItemHead(carrierItem); var head = new CarrierItemHead(carrierItem, _namespace);
return head; return head;
} }
} }
......
/* /*
* 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.
...@@ -16,22 +16,22 @@ ...@@ -16,22 +16,22 @@
* *
*/ */
using System; using SkyWalking.Config;
using System.Diagnostics;
using SkyWalking.Logging;
namespace SkyWalking.AspNet.Logging namespace SkyWalking.Context
{ {
internal class DebugLoggerFactoryAdapter : ILoggerFactory public class ContextCarrierFactory : IContextCarrierFactory
{ {
public DebugLoggerFactoryAdapter() private readonly InstrumentationConfig _config;
public ContextCarrierFactory(IConfigAccessor configAccessor)
{ {
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out)); _config = configAccessor.Get<InstrumentationConfig>();
} }
public ILogger CreateLogger(Type type) public IContextCarrier Create()
{ {
return new DebugLoggerAdapter(type); return new ContextCarrier(_config.Namespace);
} }
} }
} }
\ No newline at end of file
...@@ -16,16 +16,9 @@ ...@@ -16,16 +16,9 @@
* *
*/ */
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.Dictionarys;
using SkyWalking.Sampling;
using SkyWalking.Utils;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
...@@ -34,8 +27,15 @@ namespace SkyWalking.Context ...@@ -34,8 +27,15 @@ namespace SkyWalking.Context
/// We also provide the CONTEXT propagation based on ThreadLocal mechanism. /// We also provide the CONTEXT propagation based on ThreadLocal mechanism.
/// Meaning, each segment also related to singe thread. /// Meaning, each segment also related to singe thread.
/// </summary> /// </summary>
public class ContextManager : ITracingContextListener, IBootService, IIgnoreTracerContextListener public class ContextManager : ITracingContextListener, IIgnoreTracerContextListener
{ {
static ContextManager()
{
var manager = new ContextManager();
TracingContext.ListenerManager.Add(manager);
IgnoredTracerContext.ListenerManager.Add(manager);
}
private static readonly AsyncLocal<ITracerContext> _context = new AsyncLocal<ITracerContext>(); private static readonly AsyncLocal<ITracerContext> _context = new AsyncLocal<ITracerContext>();
private static ITracerContext GetOrCreateContext(string operationName, bool forceSampling) private static ITracerContext GetOrCreateContext(string operationName, bool forceSampling)
...@@ -50,18 +50,17 @@ namespace SkyWalking.Context ...@@ -50,18 +50,17 @@ namespace SkyWalking.Context
} }
else else
{ {
if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && if (RuntimeEnvironment.Instance.Initialized)
!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
{ {
var suffixIdx = operationName.LastIndexOf('.'); // var suffixIdx = operationName.LastIndexOf('.');
if (suffixIdx > -1 && AgentConfig.IgnoreSuffix.Contains(operationName.Substring(suffixIdx))) // if (suffixIdx > -1 && AgentConfig.IgnoreSuffix.Contains(operationName.Substring(suffixIdx)))
{ // {
_context.Value = new IgnoredTracerContext(); // _context.Value = new IgnoredTracerContext();
} // }
else // else
{ // {
var sampler = ServiceManager.Instance.GetService<SamplingService>(); var sampler = DefaultSampler.Instance;
if (forceSampling || sampler.TrySampling()) if (forceSampling || sampler.Sampled())
{ {
_context.Value = new TracingContext(); _context.Value = new TracingContext();
} }
...@@ -69,14 +68,13 @@ namespace SkyWalking.Context ...@@ -69,14 +68,13 @@ namespace SkyWalking.Context
{ {
_context.Value = new IgnoredTracerContext(); _context.Value = new IgnoredTracerContext();
} }
} // }
} }
else else
{ {
_context.Value = new IgnoredTracerContext(); _context.Value = new IgnoredTracerContext();
} }
} }
} }
return _context.Value; return _context.Value;
...@@ -103,7 +101,7 @@ namespace SkyWalking.Context ...@@ -103,7 +101,7 @@ namespace SkyWalking.Context
public static ISpan CreateEntrySpan(string operationName, IContextCarrier carrier) public static ISpan CreateEntrySpan(string operationName, IContextCarrier carrier)
{ {
var samplingService = ServiceManager.Instance.GetService<SamplingService>(); var samplingService = DefaultSampler.Instance;
if (carrier != null && carrier.IsValid) if (carrier != null && carrier.IsValid)
{ {
samplingService.ForceSampled(); samplingService.ForceSampled();
...@@ -115,7 +113,7 @@ namespace SkyWalking.Context ...@@ -115,7 +113,7 @@ namespace SkyWalking.Context
else else
{ {
var context = GetOrCreateContext(operationName, false); var context = GetOrCreateContext(operationName, false);
return context.CreateEntrySpan(operationName); return context.CreateEntrySpan(operationName);
} }
} }
...@@ -133,7 +131,7 @@ namespace SkyWalking.Context ...@@ -133,7 +131,7 @@ namespace SkyWalking.Context
context.Inject(carrier); context.Inject(carrier);
return span; return span;
} }
public static ISpan CreateExitSpan(string operationName, string remotePeer) public static ISpan CreateExitSpan(string operationName, string remotePeer)
{ {
var context = GetOrCreateContext(operationName, false); var context = GetOrCreateContext(operationName, false);
...@@ -173,28 +171,15 @@ namespace SkyWalking.Context ...@@ -173,28 +171,15 @@ namespace SkyWalking.Context
{ {
Context?.StopSpan(span); Context?.StopSpan(span);
} }
public void AfterFinished(ITraceSegment traceSegment) public void AfterFinished(ITraceSegment traceSegment)
{ {
_context.Value = null; _context.Value = null;
} }
public void Dispose()
{
}
public int Order { get; } = 1;
public Task Initialize(CancellationToken token)
{
TracingContext.ListenerManager.Add(this);
IgnoredTracerContext.ListenerManager.Add(this);
return TaskUtils.CompletedTask;
}
public void AfterFinish(ITracerContext tracerContext) public void AfterFinish(ITracerContext tracerContext)
{ {
_context.Value = null; _context.Value = null;
} }
} }
} }
\ No newline at end of file
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.Dictionarys;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
...@@ -39,7 +38,7 @@ namespace SkyWalking.Context ...@@ -39,7 +38,7 @@ namespace SkyWalking.Context
private string _parentOperationName; private string _parentOperationName;
private readonly DistributedTraceId _primaryDistributedTraceId; private readonly DistributedTraceId _primaryDistributedTraceId;
private int _entryApplicationInstanceId = DictionaryUtil.NullValue; private NullableValue _entryApplicationInstanceId = NullableValue.Null;
public ContextSnapshot(ID traceSegmentId, int spanId, IEnumerable<DistributedTraceId> distributedTraceIds) public ContextSnapshot(ID traceSegmentId, int spanId, IEnumerable<DistributedTraceId> distributedTraceIds)
{ {
...@@ -48,7 +47,6 @@ namespace SkyWalking.Context ...@@ -48,7 +47,6 @@ namespace SkyWalking.Context
_primaryDistributedTraceId = distributedTraceIds?.FirstOrDefault(); _primaryDistributedTraceId = distributedTraceIds?.FirstOrDefault();
} }
public string EntryOperationName public string EntryOperationName
{ {
get => _entryOperationName; get => _entryOperationName;
...@@ -65,8 +63,8 @@ namespace SkyWalking.Context ...@@ -65,8 +63,8 @@ namespace SkyWalking.Context
public int EntryApplicationInstanceId public int EntryApplicationInstanceId
{ {
get => _entryApplicationInstanceId; get => _entryApplicationInstanceId.Value;
set => _entryApplicationInstanceId = value; set => _entryApplicationInstanceId = new NullableValue(value);
} }
public int SpanId => _spanId; public int SpanId => _spanId;
...@@ -75,7 +73,7 @@ namespace SkyWalking.Context ...@@ -75,7 +73,7 @@ namespace SkyWalking.Context
public bool IsValid => _traceSegmentId != null public bool IsValid => _traceSegmentId != null
&& _spanId > -1 && _spanId > -1
&& _entryApplicationInstanceId != DictionaryUtil.NullValue && _entryApplicationInstanceId.HasValue
&& _primaryDistributedTraceId != null && _primaryDistributedTraceId != null
&& string.IsNullOrEmpty(_entryOperationName) && string.IsNullOrEmpty(_entryOperationName)
&& string.IsNullOrEmpty(_parentOperationName); && string.IsNullOrEmpty(_parentOperationName);
......
...@@ -18,9 +18,6 @@ ...@@ -18,9 +18,6 @@
using System; using System;
using System.Threading; using System.Threading;
using SkyWalking.Config;
using SkyWalking.Dictionarys;
using SkyWalking.Utils;
namespace SkyWalking.Context.Ids namespace SkyWalking.Context.Ids
{ {
...@@ -30,7 +27,7 @@ namespace SkyWalking.Context.Ids ...@@ -30,7 +27,7 @@ namespace SkyWalking.Context.Ids
public static ID Generate() public static ID Generate()
{ {
if (RemoteDownstreamConfig.Agent.ApplicationId == DictionaryUtil.NullValue) if (!RuntimeEnvironment.Instance.ApplicationInstanceId.HasValue)
{ {
throw new InvalidOperationException(); throw new InvalidOperationException();
} }
...@@ -38,7 +35,7 @@ namespace SkyWalking.Context.Ids ...@@ -38,7 +35,7 @@ namespace SkyWalking.Context.Ids
IDContext context = threadIdSequence.Value; IDContext context = threadIdSequence.Value;
return new ID( return new ID(
RemoteDownstreamConfig.Agent.ApplicationInstanceId, RuntimeEnvironment.Instance.ApplicationInstanceId.Value,
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId,
context.NextSeq() context.NextSeq()
); );
......
...@@ -22,15 +22,19 @@ namespace SkyWalking.Context ...@@ -22,15 +22,19 @@ namespace SkyWalking.Context
{ {
public class SW3CarrierItem : CarrierItem public class SW3CarrierItem : CarrierItem
{ {
public const String HEADER_NAME = "sw3"; private const string HEADER_NAME = "sw3";
private readonly IContextCarrier _carrier; private readonly IContextCarrier _carrier;
public SW3CarrierItem(IContextCarrier carrier, CarrierItem next) public SW3CarrierItem(IContextCarrier carrier, CarrierItem next, string @namespace)
: base(HEADER_NAME, carrier.Serialize(), next) : base(HEADER_NAME, carrier.Serialize(), next, @namespace)
{ {
_carrier = carrier; _carrier = carrier;
} }
public override string HeadValue { get => base.HeadValue; set => _carrier.Deserialize(value); } public override string HeadValue
{
get => base.HeadValue;
set => _carrier.Deserialize(value);
}
} }
} }
\ No newline at end of file
...@@ -16,8 +16,7 @@ ...@@ -16,8 +16,7 @@
* *
*/ */
using SkyWalking.Dictionarys; using SkyWalking.Components;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -119,7 +118,7 @@ namespace SkyWalking.Context.Trace ...@@ -119,7 +118,7 @@ namespace SkyWalking.Context.Trace
private void ClearWhenRestart() private void ClearWhenRestart()
{ {
_componentId = DictionaryUtil.NullValue; _componentId = 0;
_componentName = null; _componentName = null;
_layer = null; _layer = null;
_logs = null; _logs = null;
......
...@@ -17,11 +17,8 @@ ...@@ -17,11 +17,8 @@
*/ */
using System; using System;
using System.Collections.Generic; using SkyWalking.Transport;
using System.Text; using SkyWalking.Components;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -34,7 +31,7 @@ namespace SkyWalking.Context.Trace ...@@ -34,7 +31,7 @@ namespace SkyWalking.Context.Trace
: base(spanId, parentSpanId, operationName) : base(spanId, parentSpanId, operationName)
{ {
_peer = peer; _peer = peer;
_peerId = DictionaryUtil.NullValue; _peerId = 0;
} }
public ExitSpan(int spanId, int parentSpanId, int operationId, int peerId) public ExitSpan(int spanId, int parentSpanId, int operationId, int peerId)
...@@ -48,7 +45,7 @@ namespace SkyWalking.Context.Trace ...@@ -48,7 +45,7 @@ namespace SkyWalking.Context.Trace
: base(spanId, parentSpanId, operationId) : base(spanId, parentSpanId, operationId)
{ {
_peer = peer; _peer = peer;
_peerId = DictionaryUtil.NullValue; _peerId = 0;
} }
public ExitSpan(int spanId, int parentSpanId, String operationName, int peerId) public ExitSpan(int spanId, int parentSpanId, String operationName, int peerId)
...@@ -108,17 +105,12 @@ namespace SkyWalking.Context.Trace ...@@ -108,17 +105,12 @@ namespace SkyWalking.Context.Trace
public override ISpan SetComponent(string componentName) public override ISpan SetComponent(string componentName)
{ {
if (_stackDepth == 1) return _stackDepth == 1 ? base.SetComponent(componentName) : this;
{
return base.SetComponent(componentName);
}
return this;
} }
public override string OperationName public override string OperationName
{ {
get { return base.OperationName; } get => base.OperationName;
set set
{ {
if (_stackDepth == 1) if (_stackDepth == 1)
...@@ -130,7 +122,7 @@ namespace SkyWalking.Context.Trace ...@@ -130,7 +122,7 @@ namespace SkyWalking.Context.Trace
public override int OperationId public override int OperationId
{ {
get { return base.OperationId; } get => base.OperationId;
set set
{ {
if (_stackDepth == 1) if (_stackDepth == 1)
...@@ -140,18 +132,11 @@ namespace SkyWalking.Context.Trace ...@@ -140,18 +132,11 @@ namespace SkyWalking.Context.Trace
} }
} }
public override SpanObject Transform() public override SpanRequest Transform()
{ {
var spanObject = base.Transform(); var spanObject = base.Transform();
if (_peerId != DictionaryUtil.NullValue) spanObject.Peer = new StringOrIntValue(_peerId, _peer);
{
spanObject.PeerId = _peerId;
}
else
{
spanObject.Peer = _peer;
}
return spanObject; return spanObject;
} }
......
...@@ -18,8 +18,7 @@ ...@@ -18,8 +18,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using SkyWalking.Components;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
......
...@@ -18,10 +18,8 @@ ...@@ -18,10 +18,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Google.Protobuf; using SkyWalking.Transport;
using SkyWalking.Config;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -30,12 +28,11 @@ namespace SkyWalking.Context.Trace ...@@ -30,12 +28,11 @@ namespace SkyWalking.Context.Trace
private readonly IList<ITraceSegmentRef> _refs; private readonly IList<ITraceSegmentRef> _refs;
private readonly IList<AbstractTracingSpan> _spans; private readonly IList<AbstractTracingSpan> _spans;
private readonly DistributedTraceIdCollection _relatedGlobalTraces; private readonly DistributedTraceIdCollection _relatedGlobalTraces;
private bool _isSizeLimited = false; private bool _isSizeLimited;
public int ApplicationId => RuntimeEnvironment.Instance.ApplicationId.Value;
public int ApplicationId => RemoteDownstreamConfig.Agent.ApplicationId; public int ApplicationInstanceId => RuntimeEnvironment.Instance.ApplicationInstanceId.Value;
public int ApplicationInstanceId => RemoteDownstreamConfig.Agent.ApplicationInstanceId;
public IEnumerable<ITraceSegmentRef> Refs => _refs; public IEnumerable<ITraceSegmentRef> Refs => _refs;
...@@ -85,22 +82,22 @@ namespace SkyWalking.Context.Trace ...@@ -85,22 +82,22 @@ namespace SkyWalking.Context.Trace
_relatedGlobalTraces.Append(distributedTraceId); _relatedGlobalTraces.Append(distributedTraceId);
} }
public UpstreamSegment Transform() public TraceSegmentRequest Transform()
{ {
var upstreamSegment = new UpstreamSegment(); var upstreamSegment = new TraceSegmentRequest
upstreamSegment.GlobalTraceIds.AddRange(_relatedGlobalTraces.GetRelatedGlobalTraces() {
.Select(x => x.ToUniqueId())); UniqueIds = _relatedGlobalTraces.GetRelatedGlobalTraces()
.Select(x => x.ToUniqueId()).ToArray()
var traceSegment = new TraceSegmentObject {TraceSegmentId = TraceSegmentId.Transform()}; };
traceSegment.Spans.AddRange(_spans.Select(x => x.Transform()));
traceSegment.ApplicationId = ApplicationId;
traceSegment.ApplicationInstanceId = ApplicationInstanceId;
traceSegment.IsSizeLimited = _isSizeLimited;
upstreamSegment.Segment = traceSegment.ToByteString();
upstreamSegment.Segment = new TraceSegmentObjectRequest
{
SegmentId = TraceSegmentId.Transform(),
Spans = _spans.Select(x => x.Transform()).ToArray(),
ApplicationId = ApplicationId,
ApplicationInstanceId = ApplicationInstanceId
};
return upstreamSegment; return upstreamSegment;
} }
......
...@@ -17,26 +17,25 @@ ...@@ -17,26 +17,25 @@
*/ */
using System.Linq; using System.Linq;
using SkyWalking.Transport;
using SkyWalking.Config; using SkyWalking.Config;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
public class TraceSegmentRef : ITraceSegmentRef public class TraceSegmentRef : ITraceSegmentRef
{ {
private SegmentRefType _type; private readonly SegmentRefType _type;
private ID _traceSegmentId; private readonly ID _traceSegmentId;
private int _spanId = -1; private readonly int _spanId = -1;
private int _peerId = DictionaryUtil.NullValue; private readonly int _peerId = 0;
private string _peerHost; private readonly string _peerHost;
private int _entryApplicationInstanceId = DictionaryUtil.NullValue; private readonly int _entryApplicationInstanceId = 0;
private int _parentApplicationInstanceId = DictionaryUtil.NullValue; private readonly int _parentApplicationInstanceId = 0;
private string _entryOperationName; private readonly string _entryOperationName;
private int _entryOperationId = DictionaryUtil.NullValue; private readonly int _entryOperationId = 0;
private string _parentOperationName; private readonly string _parentOperationName;
private int _parentOperationId = DictionaryUtil.NullValue; private readonly int _parentOperationId = 0;
public TraceSegmentRef(IContextCarrier carrier) public TraceSegmentRef(IContextCarrier carrier)
{ {
...@@ -81,7 +80,7 @@ namespace SkyWalking.Context.Trace ...@@ -81,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 = RemoteDownstreamConfig.Agent.ApplicationInstanceId; _parentApplicationInstanceId = RuntimeEnvironment.Instance.ApplicationInstanceId.Value;
_entryApplicationInstanceId = contextSnapshot.EntryApplicationInstanceId; _entryApplicationInstanceId = contextSnapshot.EntryApplicationInstanceId;
string entryOperationName = contextSnapshot.EntryOperationName; string entryOperationName = contextSnapshot.EntryOperationName;
if (entryOperationName.First() == '#') if (entryOperationName.First() == '#')
...@@ -148,45 +147,29 @@ namespace SkyWalking.Context.Trace ...@@ -148,45 +147,29 @@ namespace SkyWalking.Context.Trace
public int EntryApplicationInstanceId => _entryApplicationInstanceId; public int EntryApplicationInstanceId => _entryApplicationInstanceId;
public TraceSegmentReference Transform() public TraceSegmentReferenceRequest Transform()
{ {
TraceSegmentReference traceSegmentReference = new TraceSegmentReference(); TraceSegmentReferenceRequest traceSegmentReference = new TraceSegmentReferenceRequest();
if (_type == SegmentRefType.CrossProcess) if (_type == SegmentRefType.CrossProcess)
{ {
traceSegmentReference.RefType = RefType.CrossProcess; traceSegmentReference.RefType = (int) SegmentRefType.CrossProcess;
if (_peerId == DictionaryUtil.NullValue) traceSegmentReference.NetworkAddress = new StringOrIntValue(_peerId, _peerHost);
{
traceSegmentReference.NetworkAddress = _peerHost;
}
else
{
traceSegmentReference.NetworkAddressId = _peerId;
}
} }
else else
{ {
traceSegmentReference.RefType = RefType.CrossThread; traceSegmentReference.RefType = (int) SegmentRefType.CrossThread;
traceSegmentReference.NetworkAddress = new StringOrIntValue();
} }
traceSegmentReference.ParentApplicationInstanceId = _parentApplicationInstanceId; traceSegmentReference.ParentApplicationInstanceId = _parentApplicationInstanceId;
traceSegmentReference.EntryApplicationInstanceId = _entryApplicationInstanceId; traceSegmentReference.EntryApplicationInstanceId = _entryApplicationInstanceId;
traceSegmentReference.ParentTraceSegmentId = _traceSegmentId.Transform(); traceSegmentReference.ParentTraceSegmentId = _traceSegmentId.Transform();
traceSegmentReference.ParentSpanId = _spanId; traceSegmentReference.ParentSpanId = _spanId;
if (_entryOperationId == DictionaryUtil.NullValue)
{ traceSegmentReference.EntryServiceName = new StringOrIntValue(_entryOperationId, _entryOperationName);
traceSegmentReference.EntryServiceName = _entryOperationName;
} traceSegmentReference.ParentServiceName = new StringOrIntValue(_parentOperationId, _parentOperationName);
else
{
traceSegmentReference.EntryServiceId = _entryOperationId;
}
if (_parentOperationId == DictionaryUtil.NullValue)
{
traceSegmentReference.ParentServiceName = _parentOperationName;
}
else
{
traceSegmentReference.ParentServiceId = _parentOperationId;
}
return traceSegmentReference; return traceSegmentReference;
} }
} }
......
...@@ -16,17 +16,15 @@ ...@@ -16,17 +16,15 @@
* *
*/ */
using System;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
public class TraceContextCarrierItem : CarrierItem public class TraceContextCarrierItem : CarrierItem
{ {
private const string HEAD_NAME = "Trace-Context"; private const string HEAD_NAME = "Trace-Context";
public TraceContextCarrierItem(String headValue, CarrierItem next) public TraceContextCarrierItem(string headValue, CarrierItem next, string @namespace)
: base(HEAD_NAME, headValue, next) : base(HEAD_NAME, headValue, next, @namespace)
{ {
} }
} }
} }
\ No newline at end of file
...@@ -20,10 +20,7 @@ using System; ...@@ -20,10 +20,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using SkyWalking.Boot;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.Dictionarys;
using SkyWalking.Sampling;
using SkyWalking.Utils; using SkyWalking.Utils;
namespace SkyWalking.Context namespace SkyWalking.Context
...@@ -38,7 +35,7 @@ namespace SkyWalking.Context ...@@ -38,7 +35,7 @@ namespace SkyWalking.Context
public TracingContext() public TracingContext()
{ {
_sampler = ServiceManager.Instance.GetService<SamplingService>(); _sampler = DefaultSampler.Instance;
_segment = new TraceSegment(); _segment = new TraceSegment();
_activeSpanStacks = new Stack<ISpan>(); _activeSpanStacks = new Stack<ISpan>();
} }
...@@ -62,7 +59,7 @@ namespace SkyWalking.Context ...@@ -62,7 +59,7 @@ namespace SkyWalking.Context
carrier.SpanId = span.SpanId; carrier.SpanId = span.SpanId;
carrier.ParentApplicationInstanceId = _segment.ApplicationInstanceId; carrier.ParentApplicationInstanceId = _segment.ApplicationInstanceId;
if (DictionaryUtil.IsNull(peerId)) if (peerId == 0)
{ {
carrier.PeerHost = peer; carrier.PeerHost = peer;
} }
...@@ -78,7 +75,7 @@ namespace SkyWalking.Context ...@@ -78,7 +75,7 @@ namespace SkyWalking.Context
carrier.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId; carrier.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId;
if (DictionaryUtil.IsNull(metaValue.operationId)) if (metaValue.operationId == 0)
{ {
carrier.EntryOperationName = metaValue.operationName; carrier.EntryOperationName = metaValue.operationName;
} }
...@@ -88,7 +85,7 @@ namespace SkyWalking.Context ...@@ -88,7 +85,7 @@ namespace SkyWalking.Context
} }
var parentOperationId = firstSpan.OperationId; var parentOperationId = firstSpan.OperationId;
if (DictionaryUtil.IsNull(parentOperationId)) if (parentOperationId == 0)
{ {
carrier.ParentOperationName = firstSpan.OperationName; carrier.ParentOperationName = firstSpan.OperationName;
} }
...@@ -121,7 +118,7 @@ namespace SkyWalking.Context ...@@ -121,7 +118,7 @@ namespace SkyWalking.Context
public IContextSnapshot Capture => InternalCapture(); public IContextSnapshot Capture => InternalCapture();
public ISpan ActiveSpan => InternalActiveSpan(); public ISpan ActiveSpan => InternalActiveSpan();
public IDictionary<string, object> Properties { get; } = new Dictionary<string, object>(); public IDictionary<string, object> Properties { get; } = new Dictionary<string, object>();
public void Continued(IContextSnapshot snapshot) public void Continued(IContextSnapshot snapshot)
...@@ -152,26 +149,15 @@ namespace SkyWalking.Context ...@@ -152,26 +149,15 @@ namespace SkyWalking.Context
if (parentSpan != null && parentSpan.IsEntry) if (parentSpan != null && parentSpan.IsEntry)
{ {
var entrySpan = (ISpan) DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName) parentSpan.OperationName = operationName;
.InCondition(id => return parentSpan.Start();
{
parentSpan.OperationId = id;
return parentSpan;
}, () =>
{
parentSpan.OperationName = operationName;
return parentSpan;
});
return entrySpan.Start();
} }
else else
{ {
var entrySpan = (ISpan) DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName) var entrySpan = new EntrySpan(_spanIdGenerator++, parentSpanId, operationName);
.InCondition(id => new EntrySpan(_spanIdGenerator++, parentSpanId, id),
() => new EntrySpan(_spanIdGenerator++, parentSpanId, operationName));
entrySpan.Start(); entrySpan.Start();
_activeSpanStacks.Push(entrySpan); _activeSpanStacks.Push(entrySpan);
return entrySpan; return entrySpan;
...@@ -192,10 +178,7 @@ namespace SkyWalking.Context ...@@ -192,10 +178,7 @@ namespace SkyWalking.Context
var parentSpanId = parentSpan?.SpanId ?? -1; var parentSpanId = parentSpan?.SpanId ?? -1;
var span = (ISpan) DictionaryManager.OperationName var span = new LocalSpan(_spanIdGenerator++, parentSpanId, operationName);
.FindOrPrepareForRegister(_segment.ApplicationId, operationName, false, false)
.InCondition(id => new LocalSpan(_spanIdGenerator++, parentSpanId, operationName),
() => new LocalSpan(_spanIdGenerator++, parentSpanId, operationName));
span.Start(); span.Start();
_activeSpanStacks.Push(span); _activeSpanStacks.Push(span);
return span; return span;
...@@ -214,30 +197,7 @@ namespace SkyWalking.Context ...@@ -214,30 +197,7 @@ namespace SkyWalking.Context
else else
{ {
var parentSpanId = parentSpan?.SpanId ?? -1; var parentSpanId = parentSpan?.SpanId ?? -1;
var exitSpan = (ISpan) DictionaryManager.NetworkAddress.Find(remotePeer) var exitSpan = IsLimitMechanismWorking() ? (ISpan)new NoopExitSpan(remotePeer) : new ExitSpan(_spanIdGenerator++, parentSpanId, operationName, remotePeer);
.InCondition(peerId =>
{
if (IsLimitMechanismWorking())
{
return new NoopExitSpan(peerId);
}
return DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName)
.InCondition(id => new ExitSpan(_spanIdGenerator++, parentSpanId, id, peerId),
() => new ExitSpan(_spanIdGenerator++, parentSpanId, operationName, peerId));
},
() =>
{
if (IsLimitMechanismWorking())
{
return new NoopExitSpan(remotePeer);
}
return DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName)
.InCondition(id => new ExitSpan(_spanIdGenerator++, parentSpanId, id, remotePeer),
() => new ExitSpan(_spanIdGenerator++, parentSpanId, operationName,
remotePeer));
});
_activeSpanStacks.Push(exitSpan); _activeSpanStacks.Push(exitSpan);
return exitSpan.Start(); return exitSpan.Start();
} }
...@@ -263,7 +223,6 @@ namespace SkyWalking.Context ...@@ -263,7 +223,6 @@ namespace SkyWalking.Context
{ {
_activeSpanStacks.Pop(); _activeSpanStacks.Pop();
} }
} }
else else
{ {
...@@ -283,7 +242,7 @@ namespace SkyWalking.Context ...@@ -283,7 +242,7 @@ namespace SkyWalking.Context
if (!_segment.HasRef && _segment.IsSingleSpanSegment) if (!_segment.HasRef && _segment.IsSingleSpanSegment)
{ {
if (!_sampler.TrySampling()) if (!_sampler.Sampled())
{ {
finishedSegment.IsIgnore = true; finishedSegment.IsIgnore = true;
} }
...@@ -321,7 +280,7 @@ namespace SkyWalking.Context ...@@ -321,7 +280,7 @@ namespace SkyWalking.Context
snapshot.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId; snapshot.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId;
if (DictionaryUtil.IsNull(metaValue.operationId)) if (metaValue.operationId == 0)
{ {
snapshot.EntryOperationName = metaValue.operationName; snapshot.EntryOperationName = metaValue.operationName;
} }
...@@ -332,7 +291,7 @@ namespace SkyWalking.Context ...@@ -332,7 +291,7 @@ namespace SkyWalking.Context
var parentSpan = _activeSpanStacks.Last(); var parentSpan = _activeSpanStacks.Last();
if (DictionaryUtil.IsNull(parentSpan.OperationId)) if (parentSpan.OperationId == 0)
{ {
snapshot.ParentOperationName = parentSpan.OperationName; snapshot.ParentOperationName = parentSpan.OperationName;
} }
...@@ -362,7 +321,7 @@ namespace SkyWalking.Context ...@@ -362,7 +321,7 @@ namespace SkyWalking.Context
private bool IsLimitMechanismWorking() private bool IsLimitMechanismWorking()
{ {
if (_spanIdGenerator < Config.AgentConfig.SpanLimitPerSegment) if (_spanIdGenerator < 300)
{ {
return false; return false;
} }
...@@ -388,11 +347,11 @@ namespace SkyWalking.Context ...@@ -388,11 +347,11 @@ namespace SkyWalking.Context
} }
noopSpan = null; noopSpan = null;
return true; return true;
} }
public static class ListenerManager public static class ListenerManager
{ {
private static readonly IList<ITracingContextListener> _listeners = new List<ITracingContextListener>(); private static readonly IList<ITracingContextListener> _listeners = new List<ITracingContextListener>();
......
/* /*
* 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.
...@@ -16,50 +16,48 @@ ...@@ -16,50 +16,48 @@
* *
*/ */
using System; using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Utils; using SkyWalking.Utils;
namespace SkyWalking.Sampling namespace SkyWalking
{ {
// ReSharper disable once ClassNeverInstantiated.Global public class DefaultSampler : ISampler
public class SamplingService :TimerService, ISampler
{ {
private readonly AtomicInteger _atomicInteger = new AtomicInteger(); public static DefaultSampler Instance { get; } = new DefaultSampler();
private readonly int _sample_N_Per_3_Secs = AgentConfig.SamplePer3Secs;
private readonly bool _sample_on = AgentConfig.SamplePer3Secs > 0; private readonly AtomicInteger _idx = new AtomicInteger();
private int _samplePer3Secs;
private bool _sample_on;
public bool TrySampling() public bool Sampled()
{ {
if (!_sample_on) if (!_sample_on)
{ {
return true; return true;
} }
return _atomicInteger.Increment() < _sample_N_Per_3_Secs; return _idx.Increment() < _samplePer3Secs;
} }
public void ForceSampled() public void ForceSampled()
{ {
if (_sample_on) if (_sample_on)
{ {
_atomicInteger.Increment(); _idx.Increment();
} }
} }
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(3); [MethodImpl(MethodImplOptions.Synchronized)]
internal void SetSamplePer3Secs(int samplePer3Secs)
protected override Task Execute(CancellationToken token)
{ {
if (_sample_on) _samplePer3Secs = samplePer3Secs;
{ _sample_on = samplePer3Secs > -1;
_atomicInteger.Value = 0; }
}
return TaskUtils.CompletedTask; internal void Reset()
{
_idx.Value = 0;
} }
} }
} }
\ No newline at end of file
...@@ -25,14 +25,14 @@ namespace SkyWalking.Diagnostics ...@@ -25,14 +25,14 @@ namespace SkyWalking.Diagnostics
internal class TracingDiagnosticMethod internal class TracingDiagnosticMethod
{ {
private readonly MethodInfo _method; private readonly MethodInfo _method;
private readonly ITracingDiagnosticProcessor _diagnosticProcessor; private readonly ITracingDiagnosticProcessor _tracingDiagnosticProcessor;
private readonly string _diagnosticName; private readonly string _diagnosticName;
private readonly IParameterResolver[] _parameterResolvers; private readonly IParameterResolver[] _parameterResolvers;
public TracingDiagnosticMethod(ITracingDiagnosticProcessor diagnosticProcessor, MethodInfo method, public TracingDiagnosticMethod(ITracingDiagnosticProcessor tracingDiagnosticProcessor, MethodInfo method,
string diagnosticName) string diagnosticName)
{ {
_diagnosticProcessor = diagnosticProcessor; _tracingDiagnosticProcessor = tracingDiagnosticProcessor;
_method = method; _method = method;
_diagnosticName = diagnosticName; _diagnosticName = diagnosticName;
_parameterResolvers = GetParameterResolvers(method).ToArray(); _parameterResolvers = GetParameterResolvers(method).ToArray();
...@@ -51,7 +51,7 @@ namespace SkyWalking.Diagnostics ...@@ -51,7 +51,7 @@ namespace SkyWalking.Diagnostics
args[i] = _parameterResolvers[i].Resolve(value); args[i] = _parameterResolvers[i].Resolve(value);
} }
_method.Invoke(_diagnosticProcessor, args); _method.Invoke(_tracingDiagnosticProcessor, args);
} }
private static IEnumerable<IParameterResolver> GetParameterResolvers(MethodInfo methodInfo) private static IEnumerable<IParameterResolver> GetParameterResolvers(MethodInfo methodInfo)
......
...@@ -26,15 +26,15 @@ namespace SkyWalking.Diagnostics ...@@ -26,15 +26,15 @@ namespace SkyWalking.Diagnostics
{ {
private readonly List<TracingDiagnosticMethod> _methods; private readonly List<TracingDiagnosticMethod> _methods;
public TracingDiagnosticMethodCollection(ITracingDiagnosticProcessor diagnosticProcessor) public TracingDiagnosticMethodCollection(ITracingDiagnosticProcessor tracingDiagnosticProcessor)
{ {
_methods = new List<TracingDiagnosticMethod>(); _methods = new List<TracingDiagnosticMethod>();
foreach (var method in diagnosticProcessor.GetType().GetMethods()) foreach (var method in tracingDiagnosticProcessor.GetType().GetMethods())
{ {
var diagnosticName = method.GetCustomAttribute<DiagnosticName>(); var diagnosticName = method.GetCustomAttribute<DiagnosticName>();
if(diagnosticName==null) if(diagnosticName==null)
continue; continue;
_methods.Add(new TracingDiagnosticMethod(diagnosticProcessor, method, diagnosticName.Name)); _methods.Add(new TracingDiagnosticMethod(tracingDiagnosticProcessor, method, diagnosticName.Name));
} }
} }
......
...@@ -26,12 +26,12 @@ namespace SkyWalking.Diagnostics ...@@ -26,12 +26,12 @@ namespace SkyWalking.Diagnostics
{ {
public class TracingDiagnosticProcessorObserver : IObserver<DiagnosticListener> public class TracingDiagnosticProcessorObserver : IObserver<DiagnosticListener>
{ {
private static readonly ILogger _logger = LogManager.GetLogger<TracingDiagnosticProcessorObserver>(); private readonly ILogger _logger;
private readonly IEnumerable<ITracingDiagnosticProcessor> _tracingDiagnosticProcessors; private readonly IEnumerable<ITracingDiagnosticProcessor> _tracingDiagnosticProcessors;
public TracingDiagnosticProcessorObserver(IEnumerable<ITracingDiagnosticProcessor> tracingDiagnosticProcessors) public TracingDiagnosticProcessorObserver(IEnumerable<ITracingDiagnosticProcessor> tracingDiagnosticProcessors, ILoggerFactory loggerFactory)
{ {
_logger = loggerFactory.CreateLogger(typeof(TracingDiagnosticProcessorObserver));
_tracingDiagnosticProcessors = tracingDiagnosticProcessors ?? _tracingDiagnosticProcessors = tracingDiagnosticProcessors ??
throw new ArgumentNullException(nameof(tracingDiagnosticProcessors)); throw new ArgumentNullException(nameof(tracingDiagnosticProcessors));
} }
...@@ -51,16 +51,16 @@ namespace SkyWalking.Diagnostics ...@@ -51,16 +51,16 @@ namespace SkyWalking.Diagnostics
if (listener.Name == diagnosticProcessor.ListenerName) if (listener.Name == diagnosticProcessor.ListenerName)
{ {
Subscribe(listener, diagnosticProcessor); Subscribe(listener, diagnosticProcessor);
_logger.Debug( _logger.Information(
$"TracingDiagnosticObserver subscribe diagnosticListener named [{diagnosticProcessor.ListenerName}]."); $"Loaded diagnostic listener [{diagnosticProcessor.ListenerName}].");
} }
} }
} }
protected virtual void Subscribe(DiagnosticListener listener, protected virtual void Subscribe(DiagnosticListener listener,
ITracingDiagnosticProcessor diagnosticProcessor) ITracingDiagnosticProcessor tracingDiagnosticProcessor)
{ {
listener.Subscribe(new TracingDiagnosticObserver(diagnosticProcessor)); listener.Subscribe(new TracingDiagnosticObserver(tracingDiagnosticProcessor));
} }
} }
} }
\ 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.Dictionarys
{
public class DictionaryManager
{
public static NetworkAddressDictionary NetworkAddress => NetworkAddressDictionary.Instance;
public static OperationNameDictionary OperationName => OperationNameDictionary.Instance;
}
}
\ 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.Net.NetworkInformation;
using System.Xml.Schema;
using SkyWalking.Config;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Dictionarys
{
public class OperationNameDictionary
{
private static readonly OperationNameDictionary _instance=new OperationNameDictionary();
public static OperationNameDictionary Instance => _instance;
private OperationNameDictionary()
{
}
private readonly ConcurrentDictionary<OperationNameKey,int> _operationNameDic=new ConcurrentDictionary<OperationNameKey, int>();
private readonly ConcurrentDictionary<OperationNameKey,object> _unRegisterOpNames=new ConcurrentDictionary<OperationNameKey, object>();
public PossibleFound FindOrPrepareForRegister(int applicationId, string operationName, bool isEntry,
bool isExit)
{
return internalFind(applicationId, operationName, isEntry, isExit, true);
}
public PossibleFound FindOnly(int applicationId, string operationName)
{
return internalFind(applicationId, operationName, false, false, false);
}
private PossibleFound internalFind(int applicationId, string operationName, bool isEntry, bool isExit,
bool registerWhenNotFound)
{
if (string.IsNullOrEmpty(operationName))
{
return NotFound.Instance;
}
var operationNameKey = new OperationNameKey(applicationId, operationName, isEntry, isExit);
if (_operationNameDic.TryGetValue(operationNameKey, out var id))
{
return new Found(id);
}
else
{
if (registerWhenNotFound && _operationNameDic.Count + _unRegisterOpNames.Count <
DictionaryConfig.OperationNameBufferSize)
{
_unRegisterOpNames.TryAdd(operationNameKey, null);
}
return NotFound.Instance;
}
}
public void SyncRemote(ServiceNameDiscoveryService.ServiceNameDiscoveryServiceClient serviceClient)
{
if (_unRegisterOpNames.Count > 0)
{
var serviceNameCollection = new ServiceNameCollection();
foreach (var opName in _unRegisterOpNames)
{
var serviceName = new ServiceNameElement();
serviceName.ApplicationId = opName.Key.ApplicationId;
serviceName.ServiceName = opName.Key.OperationName;
serviceName.SrcSpanType = opName.Key.SpanType;
serviceNameCollection.Elements.Add(serviceName);
}
var mapping = serviceClient.discovery(serviceNameCollection);
foreach (var item in mapping.Elements)
{
var element = item.Element;
var key = new OperationNameKey(element.ApplicationId, element.ServiceName,
SpanType.Entry == element.SrcSpanType, SpanType.Exit == element.SrcSpanType);
_unRegisterOpNames.TryRemove(key, out _);
_operationNameDic.TryAdd(key, item.ServiceId);
}
}
}
}
public class OperationNameKey : IEquatable<OperationNameKey>
{
private readonly int _applicationId;
private readonly string _operationName;
private readonly bool _isEntry;
private readonly bool _isExit;
public OperationNameKey(int applicationId, string operationName, bool isEntry, bool isExit)
{
_applicationId = applicationId;
_operationName = operationName;
_isEntry = isEntry;
_isExit = isExit;
}
public int ApplicationId => _applicationId;
public string OperationName => _operationName;
public bool Equals(OperationNameKey other)
{
if (other == null)
{
return false;
}
var isMatch = _applicationId == other._applicationId || _operationName == other._operationName;
return isMatch && _isEntry == other._isEntry && _isExit == other._isExit;
}
public override bool Equals(object obj)
{
var other = obj as OperationNameKey;
return Equals(other);
}
public override int GetHashCode()
{
var result = _applicationId;
result = 31 * result + _operationName.GetHashCode();
return result;
}
public SpanType SpanType
{
get
{
if (_isEntry)
{
return SpanType.Entry;
}
else if(_isExit)
{
return SpanType.Exit;
}
else
{
return SpanType.Local;
}
}
}
}
}
\ No newline at end of file
...@@ -26,7 +26,7 @@ namespace SkyWalking.Logging ...@@ -26,7 +26,7 @@ namespace SkyWalking.Logging
{ {
} }
public void Info(string message) public void Information(string message)
{ {
} }
......
...@@ -20,7 +20,7 @@ using System; ...@@ -20,7 +20,7 @@ using System;
namespace SkyWalking.Logging namespace SkyWalking.Logging
{ {
internal class NullLoggerFactory : ILoggerFactory public class NullLoggerFactory : ILoggerFactory
{ {
public ILogger CreateLogger(Type type) public ILogger CreateLogger(Type type)
{ {
......
...@@ -16,31 +16,31 @@ ...@@ -16,31 +16,31 @@
* *
*/ */
using Grpc.Core; //using Grpc.Core;
using SkyWalking.Utils; //using SkyWalking.Utils;
//
namespace SkyWalking.Remote.Authentication //namespace SkyWalking.Remote.Authentication
{ //{
internal static class AuthenticationInterceptors // internal static class AuthenticationInterceptors
{ // {
private const string header = "authentication"; // private const string header = "authentication";
//
public static AsyncAuthInterceptor CreateAuthInterceptor(string token) // public static AsyncAuthInterceptor CreateAuthInterceptor(string token)
{ // {
return (context, metadata) => // return (context, metadata) =>
{ // {
var entry = CreateTokenHeader(token); // var entry = CreateTokenHeader(token);
if (entry != null) // if (entry != null)
{ // {
metadata.Add(entry); // metadata.Add(entry);
} // }
return TaskUtils.CompletedTask; // return TaskUtils.CompletedTask;
}; // };
} // }
//
private static Metadata.Entry CreateTokenHeader(string token) // private static Metadata.Entry CreateTokenHeader(string token)
{ // {
return string.IsNullOrEmpty(token) ? null : new Metadata.Entry(header, token); // return string.IsNullOrEmpty(token) ? null : new Metadata.Entry(header, token);
} // }
} // }
} //}
/* ///*
* 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 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 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
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Collections.Generic; //using System.Collections.Generic;
using System.Diagnostics; //using System.Diagnostics;
using System.Linq; //using System.Linq;
using System.Net; //using System.Net;
using System.Net.Sockets; //using System.Net.Sockets;
using System.Threading; //using System.Threading;
using System.Threading.Tasks; //using System.Threading.Tasks;
using SkyWalking.Boot; //using SkyWalking.Boot;
using SkyWalking.Config; //using SkyWalking.Config;
using SkyWalking.Context; //using SkyWalking.Context;
using SkyWalking.Dictionarys; //using SkyWalking.Dictionarys;
using SkyWalking.Logging; //using SkyWalking.Logging;
using SkyWalking.NetworkProtocol; //using SkyWalking.NetworkProtocol;
using SkyWalking.Utils; //using SkyWalking.Utils;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcApplicationService : TimerService // public class GrpcApplicationService : TimerService
{ // {
private static readonly ILogger _logger = LogManager.GetLogger<GrpcApplicationService>(); // private static readonly ILogger Logger = LogManager.GetLogger<GrpcApplicationService>();
public override int Order { get; } = -1; // public override int Order { get; } = -1;
//
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15); // protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15);
//
protected override async Task Execute(CancellationToken token) // protected override async Task Execute(CancellationToken token)
{ // {
if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && // if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) &&
!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId)) // !DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
{ // {
return; // return;
} // }
//
if (string.IsNullOrEmpty(AgentConfig.ApplicationCode)) // if (string.IsNullOrEmpty(AgentConfig.ApplicationCode))
{ // {
return; // return;
} // }
//
if (!GrpcConnectionManager.Instance.Available) // if (!GrpcConnectionManager.Instance.Available)
{ // {
return; // return;
} // }
//
var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection(); // var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
//
if (availableConnection == null) // if (availableConnection == null)
{ // {
return; // return;
} // }
//
try // try
{ // {
await RegisterApplication(availableConnection, token); // await RegisterApplication(availableConnection, token);
await RegisterApplicationInstance(availableConnection, token); // await RegisterApplicationInstance(availableConnection, token);
} // }
catch (Exception exception) // catch (Exception exception)
{ // {
_logger.Warning($"Register application fail. {exception.Message}"); // Logger.Warning($"Register application fail. {exception.Message}");
availableConnection.Failure(); // availableConnection.Failure();
} // }
} // }
//
private async Task RegisterApplication(GrpcConnection availableConnection, CancellationToken token) // private async Task RegisterApplication(GrpcConnection availableConnection, CancellationToken token)
{ // {
if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId)) // if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId))
{ // {
var application = new Application {ApplicationCode = AgentConfig.ApplicationCode}; // var application = new Application {ApplicationCode = AgentConfig.ApplicationCode};
var applicationRegisterService = // var applicationRegisterService =
new ApplicationRegisterService.ApplicationRegisterServiceClient(availableConnection.GrpcChannel); // new ApplicationRegisterService.ApplicationRegisterServiceClient(availableConnection.GrpcChannel);
//
var retry = 0; // var retry = 0;
var applicationId = 0; // var applicationId = 0;
while (retry++ < 3 && DictionaryUtil.IsNull(applicationId)) // while (retry++ < 3 && DictionaryUtil.IsNull(applicationId))
{ // {
var applicationMapping = await applicationRegisterService.applicationCodeRegisterAsync(application); // var applicationMapping = await applicationRegisterService.applicationCodeRegisterAsync(application);
applicationId = applicationMapping?.Application?.Value ?? 0; // applicationId = applicationMapping?.Application?.Value ?? 0;
if (!DictionaryUtil.IsNull(applicationId)) // if (!DictionaryUtil.IsNull(applicationId))
{ // {
break; // break;
} // }
await Task.Delay(500, token); // await Task.Delay(500, token);
} // }
//
if (DictionaryUtil.IsNull(applicationId)) // if (DictionaryUtil.IsNull(applicationId))
{ // {
_logger.Warning( // Logger.Warning(
"Register application fail. Server response null."); // "Register application fail. Server response null.");
return; // return;
} // }
//
_logger.Info( // Logger.Information(
$"Register application success. [applicationCode] = {application.ApplicationCode}. [applicationId] = {applicationId}"); // $"Register application success. [applicationCode] = {application.ApplicationCode}. [applicationId] = {applicationId}");
RemoteDownstreamConfig.Agent.ApplicationId = applicationId; // RemoteDownstreamConfig.Agent.ApplicationId = applicationId;
} // }
} // }
//
private async Task RegisterApplicationInstance(GrpcConnection availableConnection, CancellationToken token) // private async Task RegisterApplicationInstance(GrpcConnection availableConnection, CancellationToken token)
{ // {
if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId)) // if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
{ // {
var instanceDiscoveryService = // var instanceDiscoveryService =
new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel); // new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel);
//
var agentUUID = Guid.NewGuid().ToString("N"); // var agentUUID = Guid.NewGuid().ToString("N");
var registerTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); // var registerTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//
var hostName = Dns.GetHostName(); // var hostName = Dns.GetHostName();
//
var osInfo = new OSInfo // var osInfo = new OSInfo
{ // {
Hostname = hostName, // Hostname = hostName,
OsName = PlatformInformation.GetOSName(), // OsName = PlatformInformation.GetOSName(),
ProcessNo = Process.GetCurrentProcess().Id // ProcessNo = Process.GetCurrentProcess().Id
}; // };
//
osInfo.Ipv4S.AddRange(GetIpV4S(hostName)); // osInfo.Ipv4S.AddRange(GetIpV4S(hostName));
//
var applicationInstance = new ApplicationInstance // var applicationInstance = new ApplicationInstance
{ // {
ApplicationId = RemoteDownstreamConfig.Agent.ApplicationId, // ApplicationId = RemoteDownstreamConfig.Agent.ApplicationId,
AgentUUID = agentUUID, // AgentUUID = agentUUID,
RegisterTime = registerTime, // RegisterTime = registerTime,
Osinfo = osInfo // Osinfo = osInfo
}; // };
//
var retry = 0; // var retry = 0;
var applicationInstanceId = 0; // var applicationInstanceId = 0;
while (retry++ < 5 && DictionaryUtil.IsNull(applicationInstanceId)) // while (retry++ < 5 && DictionaryUtil.IsNull(applicationInstanceId))
{ // {
var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance); // var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance);
applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId; // applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId;
if (!DictionaryUtil.IsNull(applicationInstanceId)) // if (!DictionaryUtil.IsNull(applicationInstanceId))
{ // {
break; // break;
} // }
//
await Task.Delay(500, token); // await Task.Delay(500, token);
} // }
//
if (!DictionaryUtil.IsNull(applicationInstanceId)) // if (!DictionaryUtil.IsNull(applicationInstanceId))
{ // {
RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId; // RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId;
_logger.Info( // Logger.Information(
$"Register application instance success. [applicationInstanceId] = {applicationInstanceId}"); // $"Register application instance success. [applicationInstanceId] = {applicationInstanceId}");
} // }
else // else
{ // {
_logger.Warning( // Logger.Warning(
"Register application instance fail. Server response null."); // "Register application instance fail. Server response null.");
} // }
} // }
} // }
//
private IEnumerable<string> GetIpV4S(string hostName) // private IEnumerable<string> GetIpV4S(string hostName)
{ // {
try // try
{ // {
//
var ipAddresses = Dns.GetHostAddresses(hostName); // var ipAddresses = Dns.GetHostAddresses(hostName);
var ipV4S = new List<string>(); // var ipV4S = new List<string>();
foreach (var ipAddress in ipAddresses.Where(x => x.AddressFamily == AddressFamily.InterNetwork)) // foreach (var ipAddress in ipAddresses.Where(x => x.AddressFamily == AddressFamily.InterNetwork))
ipV4S.Add(ipAddress.ToString()); // ipV4S.Add(ipAddress.ToString());
return ipV4S; // return ipV4S;
} // }
catch (Exception e) // catch (Exception e)
{ // {
_logger.Warning($"Get host addresses fail. {e.Message}"); // Logger.Warning($"Get host addresses fail. {e.Message}");
return new string[0]; // return new string[0];
} // }
} // }
} // }
} //}
\ No newline at end of file \ 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 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 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
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using Grpc.Core; //using Grpc.Core;
using SkyWalking.Remote.Authentication; //using SkyWalking.Remote.Authentication;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
internal class GrpcChannelBuilder // internal class GrpcChannelBuilder
{ // {
private string _token; // private string _token;
//
private string _server; // private string _server;
//
private string _rootCertificatePath; // private string _rootCertificatePath;
//
public GrpcChannelBuilder WithAuthenticationToken(string token) // public GrpcChannelBuilder WithAuthenticationToken(string token)
{ // {
_token = token; // _token = token;
return this; // return this;
} // }
//
public GrpcChannelBuilder WithServer(string server) // public GrpcChannelBuilder WithServer(string server)
{ // {
_server = server; // _server = server;
return this; // return this;
} // }
//
public GrpcChannelBuilder WithCredential(string rootCertificatePath) // public GrpcChannelBuilder WithCredential(string rootCertificatePath)
{ // {
_rootCertificatePath = rootCertificatePath; // _rootCertificatePath = rootCertificatePath;
return this; // return this;
} // }
//
public Channel Build() // public Channel Build()
{ // {
return new Channel(_server, GetCredentials()); // return new Channel(_server, GetCredentials());
} // }
//
private ChannelCredentials GetCredentials() // private ChannelCredentials GetCredentials()
{ // {
if (_rootCertificatePath != null) // if (_rootCertificatePath != null)
{ // {
var authInterceptor = AuthenticationInterceptors.CreateAuthInterceptor(_token); // var authInterceptor = AuthenticationInterceptors.CreateAuthInterceptor(_token);
return ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor(authInterceptor)); // return ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor(authInterceptor));
} // }
return ChannelCredentials.Insecure; //
} // return ChannelCredentials.Insecure;
} // }
} // }
//}
/* ///*
* 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 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 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
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Threading.Tasks; //using System.Threading.Tasks;
using Grpc.Core; //using Grpc.Core;
using SkyWalking.Logging; //using SkyWalking.Logging;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcConnection // public class GrpcConnection
{ // {
private static readonly ILogger _logger = LogManager.GetLogger<GrpcConnection>(); // private static readonly ILogger Logger = LogManager.GetLogger<GrpcConnection>();
//
public Channel GrpcChannel { get; } // public Channel GrpcChannel { get; }
//
public GrpcConnectionState State { get; private set; } = GrpcConnectionState.Idle; // public GrpcConnectionState State { get; private set; } = GrpcConnectionState.Idle;
//
public string Server { get; } // public string Server { get; }
//
public GrpcConnection(string server, string rootCertificatePath = null, string token = null) // public GrpcConnection(string server, string rootCertificatePath = null, string token = null)
{ // {
Server = server; // Server = server;
GrpcChannel = new GrpcChannelBuilder() // GrpcChannel = new GrpcChannelBuilder()
.WithServer(server) // .WithServer(server)
.WithCredential(rootCertificatePath) // .WithCredential(rootCertificatePath)
.WithAuthenticationToken(token) // .WithAuthenticationToken(token)
.Build(); // .Build();
} // }
//
public async Task<bool> ConnectAsync(TimeSpan timeout) // public async Task<bool> ConnectAsync(TimeSpan timeout)
{ // {
if (State == GrpcConnectionState.Ready) // if (State == GrpcConnectionState.Ready)
{ // {
return true; // return true;
} // }
State = GrpcConnectionState.Connecting; // State = GrpcConnectionState.Connecting;
try // try
{ // {
var deadLine = DateTime.UtcNow.AddSeconds(timeout.TotalSeconds); // var deadLine = DateTime.UtcNow.AddSeconds(timeout.TotalSeconds);
await GrpcChannel.ConnectAsync(deadLine); // await GrpcChannel.ConnectAsync(deadLine);
State = GrpcConnectionState.Ready; // State = GrpcConnectionState.Ready;
_logger.Info($"Grpc channel connect success. [Server] = {GrpcChannel.Target}"); // Logger.Information($"Grpc channel connect success. [Server] = {GrpcChannel.Target}");
} // }
catch (TaskCanceledException ex) // catch (TaskCanceledException ex)
{ // {
State = GrpcConnectionState.Failure; // State = GrpcConnectionState.Failure;
_logger.Warning($"Grpc channel connect timeout. {ex.Message}"); // Logger.Warning($"Grpc channel connect timeout. {ex.Message}");
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
State = GrpcConnectionState.Failure; // State = GrpcConnectionState.Failure;
_logger.Warning($"Grpc channel connect fail. {ex.Message}"); // Logger.Warning($"Grpc channel connect fail. {ex.Message}");
} // }
//
return State == GrpcConnectionState.Ready; // return State == GrpcConnectionState.Ready;
} // }
//
public async Task ShutdowmAsync() // public async Task ShutdowmAsync()
{ // {
try // try
{ // {
await GrpcChannel.ShutdownAsync(); // await GrpcChannel.ShutdownAsync();
} // }
catch (Exception e) // catch (Exception e)
{ // {
_logger.Debug($"Grpc channel shutdown fail. {e.Message}"); // Logger.Debug($"Grpc channel shutdown fail. {e.Message}");
} // }
finally // finally
{ // {
State = GrpcConnectionState.Shutdown; // State = GrpcConnectionState.Shutdown;
} // }
} // }
//
public bool CheckState() // public bool CheckState()
{ // {
return State == GrpcConnectionState.Ready && GrpcChannel.State == ChannelState.Ready; // return State == GrpcConnectionState.Ready && GrpcChannel.State == ChannelState.Ready;
} // }
//
public void Failure() // public void Failure()
{ // {
var currentState = State; // var currentState = State;
//
if (GrpcConnectionState.Ready == currentState) // if (GrpcConnectionState.Ready == currentState)
{ // {
_logger.Debug($"Grpc channel state changed. {State} -> {GrpcChannel.State}"); // Logger.Debug($"Grpc channel state changed. {State} -> {GrpcChannel.State}");
} // }
//
State = GrpcConnectionState.Failure; // State = GrpcConnectionState.Failure;
} // }
} // }
} //}
\ No newline at end of file \ 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 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 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
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Linq; //using System.Linq;
using System.Threading.Tasks; //using System.Threading.Tasks;
using SkyWalking.Config; //using SkyWalking.Config;
using SkyWalking.Logging; //using SkyWalking.Logging;
using SkyWalking.Utils; //using SkyWalking.Utils;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcConnectionManager // public class GrpcConnectionManager
{ // {
private static readonly ILogger _logger = LogManager.GetLogger<GrpcConnectionManager>(); // private static readonly ILogger Logger = LogManager.GetLogger<GrpcConnectionManager>();
//
public const string NotFoundErrorMessage = "Not found available connection."; // public const string NotFoundErrorMessage = "Not found available connection.";
//
public static GrpcConnectionManager Instance { get; } = new GrpcConnectionManager(); // public static GrpcConnectionManager Instance { get; } = new GrpcConnectionManager();
//
private readonly Random _random = new Random(); // private readonly Random _random = new Random();
private readonly AsyncLock _lock = new AsyncLock(); // private readonly AsyncLock _lock = new AsyncLock();
private GrpcConnection _connection; // private GrpcConnection _connection;
//
public bool Available => _connection != null && _connection.CheckState(); // public bool Available => _connection != null && _connection.CheckState();
//
private GrpcConnectionManager() // private GrpcConnectionManager()
{ // {
} // }
//
public async Task ConnectAsync(TimeSpan timeout) // public async Task ConnectAsync(TimeSpan timeout)
{ // {
// using async lock // // using async lock
using (await _lock.LockAsync()) // using (await _lock.LockAsync())
{ // {
if (_connection != null && _connection.CheckState()) // if (_connection != null && _connection.CheckState())
{ // {
return; // return;
} // }
//
if (_connection != null && !_connection.CheckState()) // if (_connection != null && !_connection.CheckState())
{ // {
await _connection.ShutdowmAsync(); // await _connection.ShutdowmAsync();
} // }
//
var metadata = GetServerMetadata(_connection?.Server); // var metadata = GetServerMetadata(_connection?.Server);
_connection = new GrpcConnection(metadata.Address, metadata.CertificatePath, metadata.Token); // _connection = new GrpcConnection(metadata.Address, metadata.CertificatePath, metadata.Token);
await _connection.ConnectAsync(timeout); // await _connection.ConnectAsync(timeout);
} // }
} // }
//
public async Task ShutdownAsync() // public async Task ShutdownAsync()
{ // {
await _connection?.ShutdowmAsync(); // await _connection?.ShutdowmAsync();
} // }
//
public GrpcConnection GetAvailableConnection() // public GrpcConnection GetAvailableConnection()
{ // {
var connection = _connection; // var connection = _connection;
if (connection == null || connection.State != GrpcConnectionState.Ready) // if (connection == null || connection.State != GrpcConnectionState.Ready)
{ // {
_logger.Debug(NotFoundErrorMessage); // Logger.Debug(NotFoundErrorMessage);
return null; // return null;
} // }
//
return connection; // return connection;
} // }
//
private ServerMetadata GetServerMetadata(string currentServer) // private ServerMetadata GetServerMetadata(string currentServer)
{ // {
return new ServerMetadata(GetServerAddress(currentServer), // return new ServerMetadata(GetServerAddress(currentServer),
CollectorConfig.CertificatePath, CollectorConfig.Authentication); // CollectorConfig.CertificatePath, CollectorConfig.Authentication);
} // }
//
private string GetServerAddress(string currentServer) // private string GetServerAddress(string currentServer)
{ // {
var servers = RemoteDownstreamConfig.Collector.gRPCServers.Distinct().ToArray(); // var servers = RemoteDownstreamConfig.Collector.gRPCServers.Distinct().ToArray();
if (servers.Length == 1) // if (servers.Length == 1)
{ // {
return servers[0]; // return servers[0];
} // }
//
if (currentServer != null) // if (currentServer != null)
{ // {
servers = servers.Where(x => x != currentServer).ToArray(); // servers = servers.Where(x => x != currentServer).ToArray();
} // }
//
var index = _random.Next() % servers.Length; // var index = _random.Next() % servers.Length;
return servers[index]; // return servers[index];
} // }
//
public struct ServerMetadata // public struct ServerMetadata
{ // {
public string Address { get; } // public string Address { get; }
//
public string Token { get; } // public string Token { get; }
//
public string CertificatePath { get; } // public string CertificatePath { get; }
//
public ServerMetadata(string address, string certificate, string token) // public ServerMetadata(string address, string certificate, string token)
{ // {
Address = address; // Address = address;
CertificatePath = certificate; // CertificatePath = certificate;
Token = token; // Token = token;
} // }
} // }
} // }
} //}
\ No newline at end of file \ 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 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 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
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Threading; //using System.Threading;
using System.Threading.Tasks; //using System.Threading.Tasks;
using SkyWalking.Boot; //using SkyWalking.Boot;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcConnectionService : TimerService // public class GrpcConnectionService : TimerService
{ // {
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15); // protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15);
//
protected override async Task Execute(CancellationToken token) // protected override async Task Execute(CancellationToken token)
{ // {
if (!GrpcConnectionManager.Instance.Available) // if (!GrpcConnectionManager.Instance.Available)
{ // {
// default timeout = 5s // // default timeout = 5s
await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(5)); // await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(5));
} // }
} // }
} // }
} //}
\ No newline at end of file \ 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 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 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
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public enum GrpcConnectionState // public enum GrpcConnectionState
{ // {
Idle, // Idle,
Connecting, // Connecting,
Ready, // Ready,
Failure, // Failure,
Shutdown // Shutdown
} // }
} //}
/* ///*
* 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 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 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
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Threading; //using System.Threading;
using System.Threading.Tasks; //using System.Threading.Tasks;
using SkyWalking.Boot; //using SkyWalking.Boot;
using SkyWalking.Config; //using SkyWalking.Config;
using SkyWalking.Dictionarys; //using SkyWalking.Dictionarys;
using SkyWalking.Logging; //using SkyWalking.Logging;
using SkyWalking.NetworkProtocol; //using SkyWalking.NetworkProtocol;
using SkyWalking.Utils; //using SkyWalking.Utils;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcHeartbeatService : TimerService // public class GrpcHeartbeatService : TimerService
{ // {
private static readonly ILogger _logger = LogManager.GetLogger<GrpcHeartbeatService>(); // private static readonly ILogger Logger = LogManager.GetLogger<GrpcHeartbeatService>();
protected override TimeSpan Interval { get; } = TimeSpan.FromMinutes(1); // protected override TimeSpan Interval { get; } = TimeSpan.FromMinutes(1);
//
protected override async Task Starting(CancellationToken token) // protected override async Task Starting(CancellationToken token)
{ // {
await Task.Delay(TimeSpan.FromMinutes(1), token); // await Task.Delay(TimeSpan.FromMinutes(1), token);
} // }
//
protected override async Task Execute(CancellationToken token) // protected override async Task Execute(CancellationToken token)
{ // {
if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId)) // if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
{ // {
_logger.Debug($"{DateTime.Now} Heartbeat fail. Application instance is not registered."); // Logger.Debug($"{DateTime.Now} Heartbeat fail. Application instance is not registered.");
return; // return;
} // }
//
var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection(); // var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
//
if (availableConnection == null) // if (availableConnection == null)
{ // {
_logger.Debug($"{DateTime.Now} Heartbeat fail. {GrpcConnectionManager.NotFoundErrorMessage}"); // Logger.Debug($"{DateTime.Now} Heartbeat fail. {GrpcConnectionManager.NotFoundErrorMessage}");
return; // return;
} // }
//
try // try
{ // {
var instanceDiscoveryService = // var instanceDiscoveryService =
new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel); // new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel);
//
var heartbeat = new ApplicationInstanceHeartbeat // var heartbeat = new ApplicationInstanceHeartbeat
{ // {
ApplicationInstanceId = RemoteDownstreamConfig.Agent.ApplicationInstanceId, // ApplicationInstanceId = RemoteDownstreamConfig.Agent.ApplicationInstanceId,
HeartbeatTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() // HeartbeatTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
}; // };
//
await instanceDiscoveryService.heartbeatAsync(heartbeat); // await instanceDiscoveryService.heartbeatAsync(heartbeat);
//
_logger.Debug($"{DateTime.Now} Heartbeat."); // Logger.Debug($"{DateTime.Now} Heartbeat.");
} // }
catch (Exception e) // catch (Exception e)
{ // {
_logger.Debug($"{DateTime.Now} Heartbeat fail. {e.Message}"); // Logger.Debug($"{DateTime.Now} Heartbeat fail. {e.Message}");
availableConnection.Failure(); // availableConnection.Failure();
} // }
} // }
} // }
} //}
\ No newline at end of file \ 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 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 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
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Threading; //using System.Threading;
using System.Threading.Tasks; //using System.Threading.Tasks;
using SkyWalking.Boot; //using SkyWalking.Boot;
using SkyWalking.Utils; //using SkyWalking.Utils;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcRuntimeService : TimerService // public class GrpcRuntimeService : TimerService
{ // {
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(120); // protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(120);
//
protected override Task Execute(CancellationToken token) // protected override Task Execute(CancellationToken token)
{ // {
// todo // // todo
return TaskUtils.CompletedTask; // return TaskUtils.CompletedTask;
} // }
} // }
} //}
\ No newline at end of file \ 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 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 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
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Collections.Concurrent; //using System.Collections.Concurrent;
using System.Collections.Generic; //using System.Collections.Generic;
using System.Linq; //using System.Linq;
using System.Threading; //using System.Threading;
using System.Threading.Tasks; //using System.Threading.Tasks;
using SkyWalking.Boot; //using SkyWalking.Boot;
using SkyWalking.Config; //using SkyWalking.Config;
using SkyWalking.Context; //using SkyWalking.Context;
using SkyWalking.Context.Trace; //using SkyWalking.Context.Trace;
using SkyWalking.Logging; //using SkyWalking.Logging;
using SkyWalking.NetworkProtocol; //using SkyWalking.NetworkProtocol;
using SkyWalking.Utils; //using SkyWalking.Utils;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcTraceSegmentService : TimerService, ITracingContextListener // public class GrpcTraceSegmentService : TimerService, ITracingContextListener
{ // {
private static readonly ILogger _logger = LogManager.GetLogger<GrpcTraceSegmentService>(); // private static readonly ILogger Logger = LogManager.GetLogger<GrpcTraceSegmentService>();
private static readonly ConcurrentQueue<ITraceSegment> _traceSegments // private static readonly ConcurrentQueue<ITraceSegment> _traceSegments
= new ConcurrentQueue<ITraceSegment>(); // = new ConcurrentQueue<ITraceSegment>();
//
public override void Dispose() // public override void Dispose()
{ // {
TracingContext.ListenerManager.Remove(this); // TracingContext.ListenerManager.Remove(this);
if (_traceSegments.Count > 0) // if (_traceSegments.Count > 0)
{ // {
BatchSendTraceSegments().ConfigureAwait(false).GetAwaiter().GetResult(); // BatchSendTraceSegments().ConfigureAwait(false).GetAwaiter().GetResult();
} // }
base.Dispose(); // base.Dispose();
} // }
//
public override int Order { get; } = 1; // public override int Order { get; } = 1;
//
protected override TimeSpan Interval => TimeSpan.FromSeconds(1); // protected override TimeSpan Interval => TimeSpan.FromSeconds(1);
//
protected override Task Initializing(CancellationToken token) // protected override Task Initializing(CancellationToken token)
{ // {
TracingContext.ListenerManager.Add(this); // TracingContext.ListenerManager.Add(this);
return base.Initializing(token); // return base.Initializing(token);
} // }
//
public void AfterFinished(ITraceSegment traceSegment) // public void AfterFinished(ITraceSegment traceSegment)
{ // {
if (traceSegment.IsIgnore) // if (traceSegment.IsIgnore)
{ // {
return; // return;
} // }
//
if (_traceSegments.Count >= AgentConfig.PendingSegmentsLimit && AgentConfig.PendingSegmentsLimit > 0) // if (_traceSegments.Count >= AgentConfig.PendingSegmentLimit && AgentConfig.PendingSegmentLimit > 0)
{ // {
_traceSegments.TryDequeue(out var v); // _traceSegments.TryDequeue(out var v);
} // }
_traceSegments.Enqueue(traceSegment); // _traceSegments.Enqueue(traceSegment);
} // }
//
protected async override Task Execute(CancellationToken token) // protected override async Task Execute(CancellationToken token)
{ // {
await BatchSendTraceSegments(); // await BatchSendTraceSegments();
} // }
//
private async Task BatchSendTraceSegments() // private async Task BatchSendTraceSegments()
{ // {
if (_traceSegments.Count == 0) // if (_traceSegments.Count == 0)
return; // return;
//
var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection(); // var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
if (availableConnection == null) // if (availableConnection == null)
{ // {
_logger.Warning( // Logger.Warning(
$"Transform and send UpstreamSegment to collector fail. {GrpcConnectionManager.NotFoundErrorMessage}"); // $"Transform and send UpstreamSegment to collector fail. {GrpcConnectionManager.NotFoundErrorMessage}");
return; // return;
} // }
//
try // try
{ // {
var traceSegmentService = // var traceSegmentService =
new TraceSegmentService.TraceSegmentServiceClient(availableConnection.GrpcChannel); // new TraceSegmentService.TraceSegmentServiceClient(availableConnection.GrpcChannel);
using (var asyncClientStreamingCall = traceSegmentService.collect()) // using (var asyncClientStreamingCall = traceSegmentService.collect())
{ // {
while (_traceSegments.TryDequeue(out var segment)) // while (_traceSegments.TryDequeue(out var segment))
{ // {
await asyncClientStreamingCall.RequestStream.WriteAsync(segment.Transform()); // await asyncClientStreamingCall.RequestStream.WriteAsync(segment.Transform());
_logger.Debug( // Logger.Debug(
$"Transform and send UpstreamSegment to collector. [TraceSegmentId] = {segment.TraceSegmentId} [GlobalTraceId] = {segment.RelatedGlobalTraces.FirstOrDefault()}"); // $"Transform and send UpstreamSegment to collector. [TraceSegmentId] = {segment.TraceSegmentId} [GlobalTraceId] = {segment.RelatedGlobalTraces.FirstOrDefault()}");
} // }
await asyncClientStreamingCall.RequestStream.CompleteAsync(); // await asyncClientStreamingCall.RequestStream.CompleteAsync();
await asyncClientStreamingCall.ResponseAsync; // await asyncClientStreamingCall.ResponseAsync;
} // }
} // }
catch (Exception e) // catch (Exception e)
{ // {
_logger.Warning($"Transform and send UpstreamSegment to collector fail. {e.Message}"); // Logger.Warning($"Transform and send UpstreamSegment to collector fail. {e.Message}");
availableConnection?.Failure(); // availableConnection?.Failure();
return; // return;
} // }
} // }
} // }
} //}
\ No newline at end of file \ 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;
namespace SkyWalking
{
public class RuntimeEnvironment : IRuntimeEnvironment
{
public static IRuntimeEnvironment Instance { get; } = new RuntimeEnvironment();
public NullableValue ApplicationId { get; internal set; }
public NullableValue ApplicationInstanceId { get; internal set; }
public bool Initialized => ApplicationId.HasValue && ApplicationInstanceId.HasValue;
public Guid AgentUUID { get; } = Guid.NewGuid();
public IEnvironmentProvider Environment { 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System; using System;
using SkyWalking.Logging; using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking.AspNet.Logging using SkyWalking.Config;
{ using SkyWalking.Logging;
internal class DebugLoggerAdapter : ILogger
{ namespace SkyWalking.Service
private readonly Type type; {
public class SamplingRefreshService : ExecutionService
public DebugLoggerAdapter(Type type) {
{ private readonly SamplingConfig _config;
this.type = type;
} public SamplingRefreshService(IConfigAccessor configAccessor, ISkyWalkingClient skyWalking,
IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
public void Debug(string message) : base(skyWalking, runtimeEnvironment, loggerFactory)
{ {
WriteLine("debug", message); _config = configAccessor.Get<SamplingConfig>();
} DefaultSampler.Instance.SetSamplePer3Secs(_config.SamplePer3Secs);
}
public void Info(string message)
{ protected override TimeSpan DueTime { get; } = TimeSpan.Zero;
WriteLine("info", message);
} protected override TimeSpan Period { get; } = TimeSpan.FromSeconds(3);
public void Warning(string message) protected override Task ExecuteAsync(CancellationToken cancellationToken)
{ {
WriteLine("warn", message); DefaultSampler.Instance.Reset();
} return Task.CompletedTask;
}
public void Error(string message, Exception exception) }
{
WriteLine("error", message + Environment.NewLine + exception);
}
public void Trace(string message)
{
WriteLine("trace", message);
}
private void WriteLine(string level, string message)
{
System.Diagnostics.Debug.WriteLine($"{DateTime.Now} : [{level}] [{type.Name}] {message}");
}
}
} }
\ 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.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Config;
using SkyWalking.Logging;
using SkyWalking.Transport;
using SkyWalking.Utils;
namespace SkyWalking.Service
{
public class ServiceDiscoveryService : ExecutionService
{
private readonly InstrumentationConfig _config;
protected override TimeSpan DueTime { get; } = TimeSpan.Zero;
protected override TimeSpan Period { get; } = TimeSpan.FromSeconds(30);
public ServiceDiscoveryService(IConfigAccessor configAccessor, ISkyWalkingClient client,
IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
: base(client, runtimeEnvironment, loggerFactory)
{
_config = configAccessor.Get<InstrumentationConfig>();
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
await RegisterApplication(cancellationToken);
await RegisterApplicationInstance(cancellationToken);
await Heartbeat(cancellationToken);
}
protected override bool CanExecute() => true;
private async Task RegisterApplication(CancellationToken cancellationToken)
{
if (!RuntimeEnvironment.ApplicationId.HasValue)
{
var value = await Polling(3, () => SkyWalking.RegisterApplicationAsync(_config.ApplicationCode, cancellationToken), cancellationToken);
if (value.HasValue && RuntimeEnvironment is RuntimeEnvironment environment)
{
environment.ApplicationId = value;
Logger.Information($"Registered Application[Id={environment.ApplicationId.Value}].");
}
}
}
private async Task RegisterApplicationInstance(CancellationToken cancellationToken)
{
if (RuntimeEnvironment.ApplicationId.HasValue && !RuntimeEnvironment.ApplicationInstanceId.HasValue)
{
var osInfoRequest = new AgentOsInfoRequest
{
HostName = DnsHelpers.GetHostName(),
IpAddress = DnsHelpers.GetIpV4s(),
OsName = PlatformInformation.GetOSName(),
ProcessNo = Process.GetCurrentProcess().Id
};
var value = await Polling(3,
() => SkyWalking.RegisterApplicationInstanceAsync(RuntimeEnvironment.ApplicationId.Value, RuntimeEnvironment.AgentUUID,
DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), osInfoRequest, cancellationToken), cancellationToken);
if (value.HasValue && RuntimeEnvironment is RuntimeEnvironment environment)
{
environment.ApplicationInstanceId = value;
Logger.Information($"Registered Application Instance[Id={environment.ApplicationInstanceId.Value}].");
}
}
}
private static async Task<NullableValue> Polling(int retry, Func<Task<NullableValue>> execute, CancellationToken cancellationToken)
{
var index = 0;
while (index++ < retry)
{
var value = await execute();
if (value.HasValue)
{
return value;
}
await Task.Delay(500, cancellationToken);
}
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
/* /*
* 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System; using System;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using SkyWalking.Logging; using SkyWalking.Config;
using SkyWalking.Utils; using SkyWalking.Context;
using SkyWalking.Context.Trace;
namespace SkyWalking.Boot using SkyWalking.Logging;
{ using SkyWalking.Transport;
public abstract class TimerService : IBootService
{ namespace SkyWalking.Service
private static readonly ILogger _logger = LogManager.GetLogger<TimerService>(); {
protected abstract TimeSpan Interval { get; } public class TraceSegmentTransportService : ExecutionService, ITracingContextListener
private Task _task; {
private readonly TransportConfig _config;
public virtual void Dispose() private readonly ITraceDispatcher _dispatcher;
{
} public TraceSegmentTransportService(IConfigAccessor configAccessor, ITraceDispatcher dispatcher,
ISkyWalkingClient skyWalking, IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
public virtual int Order { get; } = 2; : base(skyWalking, runtimeEnvironment, loggerFactory)
{
public async Task Initialize(CancellationToken token) _dispatcher = dispatcher;
{ _config = configAccessor.Get<TransportConfig>();
await Initializing(token); Period = TimeSpan.FromMilliseconds(_config.Interval);
_task = Task.Factory.StartNew(async () => TracingContext.ListenerManager.Add(this);
{ }
await Starting(token);
while (true) protected override TimeSpan DueTime { get; } = TimeSpan.FromSeconds(3);
{
try protected override TimeSpan Period { get; }
{
await Execute(token); protected override Task ExecuteAsync(CancellationToken cancellationToken)
} {
catch (Exception e) return _dispatcher.Flush(cancellationToken);
{ }
_logger.Error($"{GetType().Name} execute fail.", e);
} protected override Task Stopping(CancellationToken cancellationToke)
await Task.Delay(Interval, token); {
} _dispatcher.Close();
}, TracingContext.ListenerManager.Remove(this);
token, TaskCreationOptions.LongRunning, TaskScheduler.Default); return Task.CompletedTask;
} }
protected virtual Task Initializing(CancellationToken token) public void AfterFinished(ITraceSegment traceSegment)
{ {
return TaskUtils.CompletedTask; if (!traceSegment.IsIgnore)
} _dispatcher.Dispatch(traceSegment.Transform());
}
protected virtual Task Starting(CancellationToken token) }
{
return TaskUtils.CompletedTask;
}
protected abstract Task Execute(CancellationToken token);
}
} }
\ No newline at end of file
...@@ -3,22 +3,19 @@ ...@@ -3,22 +3,19 @@
<PropertyGroup> <PropertyGroup>
<Description>SkyWalking core components.</Description> <Description>SkyWalking core components.</Description>
<AssemblyTitle>SkyWalking.Core</AssemblyTitle> <AssemblyTitle>SkyWalking.Core</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net45;net451</TargetFrameworks>
<AssemblyName>SkyWalking.Core</AssemblyName> <AssemblyName>SkyWalking.Core</AssemblyName>
<PackageId>SkyWalking.Core</PackageId> <PackageId>SkyWalking.Core</PackageId>
<PackageTags>SkyWalking;APM</PackageTags> <PackageTags>SkyWalking;APM</PackageTags>
<PackageReleaseNotes> <PackageReleaseNotes>
</PackageReleaseNotes> </PackageReleaseNotes>
<RootNamespace>SkyWalking</RootNamespace> <RootNamespace>SkyWalking</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.NetworkProtocol.Trace\SkyWalking.NetworkProtocol.Trace.csproj" />
<ProjectReference Include="..\SkyWalking.NetworkProtocol\SkyWalking.NetworkProtocol.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.4.1" /> <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.5.0" />
<PackageReference Include="System.Runtime.InteropServices.RuntimeInformation" Version="4.3.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
\ 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.
...@@ -17,80 +17,58 @@ ...@@ -17,80 +17,58 @@
*/ */
using System; using System;
using System.Collections.Generic;
using System.Diagnostics; using System.Diagnostics;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Diagnostics; using SkyWalking.Diagnostics;
using SkyWalking.Logging; using SkyWalking.Logging;
using SkyWalking.Remote;
namespace SkyWalking.AspNetCore namespace SkyWalking
{ {
public class SkyWalkingHostedService : IHostedService public class SkyWalkingAgentStartup : ISkyWalkingAgentStartup
{ {
private readonly TracingDiagnosticProcessorObserver _diagnosticObserver; private readonly TracingDiagnosticProcessorObserver _observer;
private readonly IEnumerable<IExecutionService> _services;
private readonly ILogger _logger; private readonly ILogger _logger;
public SkyWalkingHostedService(IOptions<SkyWalkingOptions> options, IHostingEnvironment hostingEnvironment, public SkyWalkingAgentStartup(TracingDiagnosticProcessorObserver observer, IEnumerable<IExecutionService> services, ILoggerFactory loggerFactory)
TracingDiagnosticProcessorObserver diagnosticObserver, ILoggerFactory loggerFactory)
{ {
_observer = observer;
if (string.IsNullOrEmpty(options.Value.DirectServers)) _services = services;
{ _logger = loggerFactory.CreateLogger(typeof(SkyWalkingAgentStartup));
throw new ArgumentException("DirectServers cannot be empty or null.");
}
if (string.IsNullOrEmpty(options.Value.ApplicationCode))
{
options.Value.ApplicationCode = hostingEnvironment.ApplicationName;
}
LogManager.SetLoggerFactory(loggerFactory);
AgentConfig.ApplicationCode = options.Value.ApplicationCode;
CollectorConfig.DirectServers = options.Value.DirectServers;
AgentConfig.SamplePer3Secs = options.Value.SamplePer3Secs;
AgentConfig.PendingSegmentsLimit = options.Value.PendingSegmentsLimit;
CollectorConfig.Authentication = options.Value.Authentication;
CollectorConfig.CertificatePath = options.Value.CertificatePath;
_logger = LogManager.GetLogger<SkyWalkingHostedService>();
_diagnosticObserver = diagnosticObserver;
} }
public async Task StartAsync(CancellationToken cancellationToken) public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
{ {
_logger.Info("SkyWalking Agent starting..."); _logger.Information(Welcome());
try foreach (var service in _services)
{ await service.StartAsync(cancellationToken);
DiagnosticListener.AllListeners.Subscribe(_diagnosticObserver); DiagnosticListener.AllListeners.Subscribe(_observer);
await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(3)); _logger.Information("Started SkyWalking .NET Core Agent.");
await ServiceManager.Instance.Initialize();
_logger.Info("SkyWalking Agent started.");
}
catch (Exception e)
{
_logger.Error("SkyWalking Agent start fail.", e);
}
} }
public async Task StopAsync(CancellationToken cancellationToken) public async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken))
{ {
_logger.Info("SkyWalking Agent stopping..."); foreach (var service in _services)
try await service.StopAsync(cancellationToken);
{ _logger.Information("Stopped SkyWalking .NET Core Agent.");
ServiceManager.Instance.Dispose(); // ReSharper disable once MethodSupportsCancellation
await GrpcConnectionManager.Instance.ShutdownAsync(); await Task.Delay(TimeSpan.FromSeconds(2));
_logger.Info("SkyWalking Agent stopped."); }
}
catch (Exception e)
{
_logger.Error("SkyWalking Agent stop fail.", e);
}
private string Welcome()
{
var builder = new StringBuilder();
builder.AppendLine("Initializing ...");
builder.AppendLine();
builder.AppendLine("***************************************************************");
builder.AppendLine("* *");
builder.AppendLine("* Welcome to Apache SkyWalking *");
builder.AppendLine("* *");
builder.AppendLine("***************************************************************");
return builder.ToString();
} }
} }
} }
\ 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System; using System.Collections.Concurrent;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Threading;
using System.Runtime.CompilerServices; using System.Threading.Tasks;
using System.Threading; using SkyWalking.Config;
using System.Threading.Tasks; using SkyWalking.Logging;
using SkyWalking.Logging;
namespace SkyWalking.Transport
namespace SkyWalking.Boot {
{ public class AsyncQueueTraceDispatcher : ITraceDispatcher
public class ServiceManager : IDisposable {
{ private readonly ILogger _logger;
private static readonly ILogger _logger = LogManager.GetLogger<ServiceManager>(); private readonly TransportConfig _config;
private static readonly ServiceManager _instance = new ServiceManager(); private readonly ISkyWalkingClient _skyWalkingClient;
private readonly ConcurrentQueue<TraceSegmentRequest> _segmentQueue;
public static ServiceManager Instance => _instance; private readonly CancellationTokenSource _cancellation;
private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>(); public AsyncQueueTraceDispatcher(IConfigAccessor configAccessor, ISkyWalkingClient client, ILoggerFactory loggerFactory)
private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource(); {
_skyWalkingClient = client;
private ServiceManager() _logger = loggerFactory.CreateLogger(typeof(AsyncQueueTraceDispatcher));
{ _config = configAccessor.Get<TransportConfig>();
} _segmentQueue = new ConcurrentQueue<TraceSegmentRequest>();
_cancellation = new CancellationTokenSource();
private Type[] FindServiceTypes() }
{
return typeof(ServiceManager).Assembly.GetTypes().Where(x => public bool Dispatch(TraceSegmentRequest segment)
x.IsClass && !x.IsAbstract && typeof(IBootService).IsAssignableFrom(x)) {
.ToArray(); // todo performance optimization for ConcurrentQueue
} if (_config.PendingSegmentLimit < _segmentQueue.Count || _cancellation.IsCancellationRequested)
{
public object GetService(Type serviceType) return false;
{ }
_services.TryGetValue(serviceType, out var instance);
return instance; _segmentQueue.Enqueue(segment);
}
_logger.Debug($"Dispatch trace segment. [SegmentId]={segment.Segment.SegmentId}.");
public T GetService<T>() return true;
{ }
return (T) GetService(typeof(T));
} public Task Flush(CancellationToken token = default(CancellationToken))
{
public async Task Initialize() // todo performance optimization for ConcurrentQueue
{ //var queued = _segmentQueue.Count;
var types = FindServiceTypes(); //var limit = queued <= _config.PendingSegmentLimit ? queued : _config.PendingSegmentLimit;
var limit = _config.PendingSegmentLimit;
foreach (var service in types.Select(Activator.CreateInstance).OfType<IBootService>().OrderBy(x => x.Order)) var index = 0;
{ var segments = new List<TraceSegmentRequest>(limit);
try while (index++ < limit && _segmentQueue.TryDequeue(out var request))
{ {
await service.Initialize(_tokenSource.Token); segments.Add(request);
_services.Add(service.GetType(), service); }
_logger.Debug($"ServiceManager loaded {service.GetType()}.");
} // send async
catch (Exception e) if (segments.Count > 0)
{ _skyWalkingClient.CollectAsync(segments, token);
_logger.Error($"ServiceManager loaded {service.GetType()} fail.",e); return Task.CompletedTask;
} }
}
} public void Close()
{
[MethodImpl(MethodImplOptions.Synchronized)] _cancellation.Cancel();
public void Dispose() }
{ }
_tokenSource.Cancel();
foreach (var item in _services.Values)
{
try
{
var service = item as IBootService;
service?.Dispose();
_logger.Debug($"ServiceManager dispose {item.GetType()}.");
}
catch (Exception e)
{
_logger.Error($"ServiceManager dispose {item.GetType()} fail.", e);
}
}
_tokenSource.Dispose();
}
}
} }
\ 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.Linq;
using System.Net;
using System.Net.Sockets;
namespace SkyWalking.Utils
{
public static class DnsHelpers
{
public static string GetHostName()
{
return Dns.GetHostName();
}
public static string[] GetIpV4s()
{
try
{
var ipAddresses = Dns.GetHostAddresses(Dns.GetHostName());
return ipAddresses.Where(x => x.AddressFamily == AddressFamily.InterNetwork).Select(ipAddress => ipAddress.ToString()).ToArray();
}
catch
{
return new string[0];
}
}
}
}
\ No newline at end of file
using System; /*
* 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.Collections.Generic;
namespace SkyWalking.Utils namespace SkyWalking.Utils
{ {
internal static class EnumerableExtensions internal static class EnumerableExtensions
{ {
public static IEnumerable<T> Distinct<T,K>(this IEnumerable<T> source, Func<T,K> predicate) public static IEnumerable<T> Distinct<T, K>(this IEnumerable<T> source, Func<T, K> predicate)
{ {
HashSet<K> sets = new HashSet<K>(); HashSet<K> sets = new HashSet<K>();
foreach (var item in source) foreach (var item in source)
......
...@@ -23,7 +23,7 @@ namespace SkyWalking.Utils ...@@ -23,7 +23,7 @@ namespace SkyWalking.Utils
return OSX; return OSX;
} }
return "Unknow"; return "Unknown";
} }
} }
} }
...@@ -21,25 +21,34 @@ using System.Collections.Generic; ...@@ -21,25 +21,34 @@ using System.Collections.Generic;
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions; using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Abstractions;
using SkyWalking.Components;
using SkyWalking.Config;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Context.Tag; using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.Diagnostics; using SkyWalking.Diagnostics;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.AspNetCore.Diagnostics namespace SkyWalking.AspNetCore.Diagnostics
{ {
public class HostingDiagnosticProcessor : ITracingDiagnosticProcessor public class HostingTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{ {
public string ListenerName { get; } = "Microsoft.AspNetCore"; public string ListenerName { get; } = "Microsoft.AspNetCore";
private readonly InstrumentationConfig _config;
private readonly IContextCarrierFactory _contextCarrierFactory;
public HostingTracingDiagnosticProcessor(IConfigAccessor configAccessor,IContextCarrierFactory contextCarrierFactory)
{
_config = configAccessor.Get<InstrumentationConfig>();
_contextCarrierFactory = contextCarrierFactory;
}
[DiagnosticName("Microsoft.AspNetCore.Hosting.BeginRequest")] [DiagnosticName("Microsoft.AspNetCore.Hosting.BeginRequest")]
public void BeginRequest([Property] HttpContext httpContext) public void BeginRequest([Property] HttpContext httpContext)
{ {
var carrier = new ContextCarrier(); var carrier = _contextCarrierFactory.Create();
foreach (var item in carrier.Items) foreach (var item in carrier.Items)
item.HeadValue = httpContext.Request.Headers[item.HeadKey]; item.HeadValue = httpContext.Request.Headers[item.HeadKey];
var httpRequestSpan = ContextManager.CreateEntrySpan($"{Config.AgentConfig.ApplicationCode} {httpContext.Request.Path}", carrier); var httpRequestSpan = ContextManager.CreateEntrySpan($"{_config.ApplicationCode} {httpContext.Request.Path}", carrier);
httpRequestSpan.AsHttp(); httpRequestSpan.AsHttp();
httpRequestSpan.SetComponent(ComponentsDefine.AspNetCore); httpRequestSpan.SetComponent(ComponentsDefine.AspNetCore);
Tags.Url.Set(httpRequestSpan, httpContext.Request.Path); Tags.Url.Set(httpRequestSpan, httpContext.Request.Path);
...@@ -90,7 +99,7 @@ namespace SkyWalking.AspNetCore.Diagnostics ...@@ -90,7 +99,7 @@ namespace SkyWalking.AspNetCore.Diagnostics
ContextManager.ActiveSpan?.ErrorOccurred()?.Log(exception); ContextManager.ActiveSpan?.ErrorOccurred()?.Log(exception);
} }
[DiagnosticName("Microsoft.AspNetCore.Mvc.BeforeAction")] //[DiagnosticName("Microsoft.AspNetCore.Mvc.BeforeAction")]
public void BeforeAction([Property]ActionDescriptor actionDescriptor, [Property]HttpContext httpContext) public void BeforeAction([Property]ActionDescriptor actionDescriptor, [Property]HttpContext httpContext)
{ {
var span = httpContext.Items[HttpContextDiagnosticStrings.SpanKey] as ISpan; var span = httpContext.Items[HttpContextDiagnosticStrings.SpanKey] as ISpan;
...@@ -103,7 +112,7 @@ namespace SkyWalking.AspNetCore.Diagnostics ...@@ -103,7 +112,7 @@ namespace SkyWalking.AspNetCore.Diagnostics
span.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), events); span.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), events);
} }
[DiagnosticName("Microsoft.AspNetCore.Mvc.AfterAction")] //[DiagnosticName("Microsoft.AspNetCore.Mvc.AfterAction")]
public void AfterAction([Property]ActionDescriptor actionDescriptor, [Property]HttpContext httpContext) public void AfterAction([Property]ActionDescriptor actionDescriptor, [Property]HttpContext httpContext)
{ {
var span = httpContext.Items[HttpContextDiagnosticStrings.SpanKey] as ISpan; var span = httpContext.Items[HttpContextDiagnosticStrings.SpanKey] as ISpan;
......
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<Description>SkyWalking.Diagnostics.AspNetCore notifies Web Http requests.</Description>
<AssemblyTitle>SkyWalking.Diagnostics.AspNetCore</AssemblyTitle>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>SkyWalking.Diagnostics.AspNetCore</AssemblyName>
<PackageId>SkyWalking.Diagnostics.AspNetCore</PackageId>
<PackageTags>SkyWalking;APM;Diagnostics;AspNetCore</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
<RootNamespace>SkyWalking.Diagnostics.AspNetCore</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Http.Extensions" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.1.0" />
</ItemGroup>
</Project>
\ No newline at end of file
using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Utilities.DependencyInjection;
namespace SkyWalking.AspNetCore.Diagnostics
{
public static class SkyWalkingBuilderExtensions
{
public static SkyWalkingExtensions AddAspNetCoreHosting(this SkyWalkingExtensions extensions)
{
extensions.Services.AddSingleton<ITracingDiagnosticProcessor, HostingTracingDiagnosticProcessor>();
return extensions;
}
}
}
\ No newline at end of file
...@@ -19,10 +19,10 @@ ...@@ -19,10 +19,10 @@
using System; using System;
using DotNetCore.CAP.Diagnostics; using DotNetCore.CAP.Diagnostics;
using DotNetCore.CAP.Infrastructure; using DotNetCore.CAP.Infrastructure;
using SkyWalking.Components;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Context.Tag; using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
using CapEvents = DotNetCore.CAP.Diagnostics.CapDiagnosticListenerExtensions; using CapEvents = DotNetCore.CAP.Diagnostics.CapDiagnosticListenerExtensions;
...@@ -31,8 +31,9 @@ namespace SkyWalking.Diagnostics.CAP ...@@ -31,8 +31,9 @@ namespace SkyWalking.Diagnostics.CAP
/// <summary> /// <summary>
/// Diagnostics processor for listen and process releted events of CAP. /// Diagnostics processor for listen and process releted events of CAP.
/// </summary> /// </summary>
public class CapDiagnosticProcessor : ITracingDiagnosticProcessor public class CapTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{ {
private readonly IContextCarrierFactory _contextCarrierFactory;
private Func<BrokerEventData, string> _brokerOperationNameResolver; private Func<BrokerEventData, string> _brokerOperationNameResolver;
public string ListenerName => CapEvents.DiagnosticListenerName; public string ListenerName => CapEvents.DiagnosticListenerName;
...@@ -47,11 +48,16 @@ namespace SkyWalking.Diagnostics.CAP ...@@ -47,11 +48,16 @@ namespace SkyWalking.Diagnostics.CAP
set => _brokerOperationNameResolver = value ?? throw new ArgumentNullException(nameof(BrokerOperationNameResolver)); set => _brokerOperationNameResolver = value ?? throw new ArgumentNullException(nameof(BrokerOperationNameResolver));
} }
public CapTracingDiagnosticProcessor(IContextCarrierFactory contextCarrierFactory)
{
_contextCarrierFactory = contextCarrierFactory;
}
[DiagnosticName(CapEvents.CapBeforePublish)] [DiagnosticName(CapEvents.CapBeforePublish)]
public void CapBeforePublish([Object]BrokerPublishEventData eventData) public void CapBeforePublish([Object]BrokerPublishEventData eventData)
{ {
var operationName = BrokerOperationNameResolver(eventData); var operationName = BrokerOperationNameResolver(eventData);
var contextCarrier = new ContextCarrier(); var contextCarrier = _contextCarrierFactory.Create();
var peer = eventData.BrokerAddress; var peer = eventData.BrokerAddress;
var span = ContextManager.CreateExitSpan(operationName, contextCarrier, peer); var span = ContextManager.CreateExitSpan(operationName, contextCarrier, peer);
span.SetComponent(ComponentsDefine.CAP); span.SetComponent(ComponentsDefine.CAP);
...@@ -86,7 +92,7 @@ namespace SkyWalking.Diagnostics.CAP ...@@ -86,7 +92,7 @@ namespace SkyWalking.Diagnostics.CAP
public void CapBeforeConsume([Object]BrokerConsumeEventData eventData) public void CapBeforeConsume([Object]BrokerConsumeEventData eventData)
{ {
var operationName = BrokerOperationNameResolver(eventData); var operationName = BrokerOperationNameResolver(eventData);
var carrier = new ContextCarrier(); var carrier = _contextCarrierFactory.Create();
if (Helper.TryExtractTracingHeaders(eventData.BrokerTopicBody, out var headers, if (Helper.TryExtractTracingHeaders(eventData.BrokerTopicBody, out var headers,
out var removedHeadersJson)) out var removedHeadersJson))
......
...@@ -22,7 +22,7 @@ ...@@ -22,7 +22,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj" /> <ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
...@@ -18,22 +18,22 @@ ...@@ -18,22 +18,22 @@
using System; using System;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Extensions.DependencyInjection; using SkyWalking.Utilities.DependencyInjection;
namespace SkyWalking.Diagnostics.CAP namespace SkyWalking.Diagnostics.CAP
{ {
public static class SkyWalkingBuilderExtensions public static class SkyWalkingBuilderExtensions
{ {
public static SkyWalkingBuilder AddCap(this SkyWalkingBuilder builder) public static SkyWalkingExtensions AddCap(this SkyWalkingExtensions extensions)
{ {
if (builder == null) if (extensions == null)
{ {
throw new ArgumentNullException(nameof(builder)); throw new ArgumentNullException(nameof(extensions));
} }
builder.Services.AddSingleton<ITracingDiagnosticProcessor, CapDiagnosticProcessor>(); extensions.Services.AddSingleton<ITracingDiagnosticProcessor, CapTracingDiagnosticProcessor>();
return builder; return extensions;
} }
} }
} }
\ No newline at end of file
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
using System.Data.Common; using System.Data.Common;
using Npgsql; using Npgsql;
using SkyWalking.NetworkProtocol.Trace; using SkyWalking.Components;
namespace SkyWalking.Diagnostics.EntityFrameworkCore namespace SkyWalking.Diagnostics.EntityFrameworkCore
{ {
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj" /> <ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj" /> <ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.0.0" /> <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.0.0" />
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
using System.Data.Common; using System.Data.Common;
using MySql.Data.MySqlClient; using MySql.Data.MySqlClient;
using SkyWalking.NetworkProtocol.Trace; using SkyWalking.Components;
namespace SkyWalking.Diagnostics.EntityFrameworkCore namespace SkyWalking.Diagnostics.EntityFrameworkCore
{ {
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj" /> <ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj" /> <ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.1" /> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.1" />
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj" /> <ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj" /> <ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.0" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.0" />
......
...@@ -18,7 +18,7 @@ ...@@ -18,7 +18,7 @@
using System.Data.Common; using System.Data.Common;
using Microsoft.Data.Sqlite; using Microsoft.Data.Sqlite;
using SkyWalking.NetworkProtocol.Trace; using SkyWalking.Components;
namespace SkyWalking.Diagnostics.EntityFrameworkCore namespace SkyWalking.Diagnostics.EntityFrameworkCore
{ {
......
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics;
using SkyWalking.Components;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Diagnostics.EntityFrameworkCore namespace SkyWalking.Diagnostics.EntityFrameworkCore
{ {
......
...@@ -19,18 +19,16 @@ ...@@ -19,18 +19,16 @@
using System; using System;
using System.Data.Common; using System.Data.Common;
using System.Linq; using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Storage.Internal; using Microsoft.EntityFrameworkCore.Storage.Internal;
using SkyWalking.Config;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Context.Tag; using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
namespace SkyWalking.Diagnostics.EntityFrameworkCore namespace SkyWalking.Diagnostics.EntityFrameworkCore
{ {
public class EntityFrameworkCoreDiagnosticProcessor : ITracingDiagnosticProcessor public class EntityFrameworkCoreTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{ {
private const string TRACE_ORM = "TRACE_ORM"; private const string TRACE_ORM = "TRACE_ORM";
private Func<CommandEventData, string> _operationNameResolver; private Func<CommandEventData, string> _operationNameResolver;
...@@ -55,7 +53,7 @@ namespace SkyWalking.Diagnostics.EntityFrameworkCore ...@@ -55,7 +53,7 @@ namespace SkyWalking.Diagnostics.EntityFrameworkCore
set => _operationNameResolver = value ?? throw new ArgumentNullException(nameof(OperationNameResolver)); set => _operationNameResolver = value ?? throw new ArgumentNullException(nameof(OperationNameResolver));
} }
public EntityFrameworkCoreDiagnosticProcessor(IEfCoreSpanFactory spanFactory) public EntityFrameworkCoreTracingDiagnosticProcessor(IEfCoreSpanFactory spanFactory)
{ {
_efCoreSpanFactory = spanFactory; _efCoreSpanFactory = spanFactory;
} }
......
using System; using System.Data.Common;
using System.Data.Common; using SkyWalking.Components;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Diagnostics.EntityFrameworkCore namespace SkyWalking.Diagnostics.EntityFrameworkCore
{ {
......
...@@ -18,6 +18,6 @@ ...@@ -18,6 +18,6 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj" /> <ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
\ No newline at end of file
...@@ -18,29 +18,29 @@ ...@@ -18,29 +18,29 @@
using System; using System;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Extensions.DependencyInjection; using SkyWalking.Utilities.DependencyInjection;
namespace SkyWalking.Diagnostics.EntityFrameworkCore namespace SkyWalking.Diagnostics.EntityFrameworkCore
{ {
public static class SkyWalkingBuilderExtensions public static class SkyWalkingBuilderExtensions
{ {
public static SkyWalkingBuilder AddEntityFrameworkCore(this SkyWalkingBuilder builder, Action<DatabaseProviderBuilder> optionAction) public static SkyWalkingExtensions AddEntityFrameworkCore(this SkyWalkingExtensions extensions, Action<DatabaseProviderBuilder> optionAction)
{ {
if (builder == null) if (extensions == null)
{ {
throw new ArgumentNullException(nameof(builder)); throw new ArgumentNullException(nameof(extensions));
} }
builder.Services.AddSingleton<ITracingDiagnosticProcessor, EntityFrameworkCoreDiagnosticProcessor>(); extensions.Services.AddSingleton<ITracingDiagnosticProcessor, EntityFrameworkCoreTracingDiagnosticProcessor>();
builder.Services.AddSingleton<IEfCoreSpanFactory, EfCoreSpanFactory>(); extensions.Services.AddSingleton<IEfCoreSpanFactory, EfCoreSpanFactory>();
if (optionAction != null) if (optionAction != null)
{ {
var databaseProviderBuilder = new DatabaseProviderBuilder(builder.Services); var databaseProviderBuilder = new DatabaseProviderBuilder(extensions.Services);
optionAction(databaseProviderBuilder); optionAction(databaseProviderBuilder);
} }
return builder; return extensions;
} }
} }
} }
\ No newline at end of file
...@@ -18,21 +18,28 @@ ...@@ -18,21 +18,28 @@
using System; using System;
using System.Net.Http; using System.Net.Http;
using SkyWalking.Components;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Context.Tag; using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Diagnostics.HttpClient namespace SkyWalking.Diagnostics.HttpClient
{ {
public class HttpClientDiagnosticProcessor : ITracingDiagnosticProcessor public class HttpClientTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{ {
public string ListenerName { get; } = "HttpHandlerDiagnosticListener"; public string ListenerName { get; } = "HttpHandlerDiagnosticListener";
private readonly IContextCarrierFactory _contextCarrierFactory;
public HttpClientTracingDiagnosticProcessor(IContextCarrierFactory contextCarrierFactory)
{
_contextCarrierFactory = contextCarrierFactory;
}
[DiagnosticName("System.Net.Http.Request")] [DiagnosticName("System.Net.Http.Request")]
public void HttpRequest([Property(Name = "Request")] HttpRequestMessage request) public void HttpRequest([Property(Name = "Request")] HttpRequestMessage request)
{ {
var contextCarrier = new ContextCarrier(); var contextCarrier = _contextCarrierFactory.Create();
var peer = $"{request.RequestUri.Host}:{request.RequestUri.Port}"; var peer = $"{request.RequestUri.Host}:{request.RequestUri.Port}";
var span = ContextManager.CreateExitSpan(request.RequestUri.ToString(), contextCarrier, peer); var span = ContextManager.CreateExitSpan(request.RequestUri.ToString(), contextCarrier, peer);
Tags.Url.Set(span, request.RequestUri.ToString()); Tags.Url.Set(span, request.RequestUri.ToString());
......
...@@ -17,6 +17,6 @@ ...@@ -17,6 +17,6 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj" /> <ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
\ No newline at end of file
...@@ -18,22 +18,22 @@ ...@@ -18,22 +18,22 @@
using System; using System;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Extensions.DependencyInjection; using SkyWalking.Utilities.DependencyInjection;
namespace SkyWalking.Diagnostics.HttpClient namespace SkyWalking.Diagnostics.HttpClient
{ {
public static class SkyWalkingBuilderExtensions public static class SkyWalkingBuilderExtensions
{ {
public static SkyWalkingBuilder AddHttpClient(this SkyWalkingBuilder builder) public static SkyWalkingExtensions AddHttpClient(this SkyWalkingExtensions extensions)
{ {
if (builder == null) if (extensions == null)
{ {
throw new ArgumentNullException(nameof(builder)); throw new ArgumentNullException(nameof(extensions));
} }
builder.Services.AddSingleton<ITracingDiagnosticProcessor, HttpClientDiagnosticProcessor>(); extensions.Services.AddSingleton<ITracingDiagnosticProcessor, HttpClientTracingDiagnosticProcessor>();
return builder; return extensions;
} }
} }
} }
\ No newline at end of file
...@@ -14,7 +14,7 @@ ...@@ -14,7 +14,7 @@
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj" /> <ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" /> <PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
......
...@@ -18,22 +18,22 @@ ...@@ -18,22 +18,22 @@
using System; using System;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Extensions.DependencyInjection; using SkyWalking.Utilities.DependencyInjection;
namespace SkyWalking.Diagnostics.SqlClient namespace SkyWalking.Diagnostics.SqlClient
{ {
public static class SkyWalkingBuilderExtensions public static class SkyWalkingBuilderExtensions
{ {
public static SkyWalkingBuilder AddSqlClient(this SkyWalkingBuilder builder) public static SkyWalkingExtensions AddSqlClient(this SkyWalkingExtensions extensions)
{ {
if (builder == null) if (extensions == null)
{ {
throw new ArgumentNullException(nameof(builder)); throw new ArgumentNullException(nameof(extensions));
} }
builder.Services.AddSingleton<ITracingDiagnosticProcessor, SqlClientDiagnosticProcessor>(); extensions.Services.AddSingleton<ITracingDiagnosticProcessor, SqlClientTracingDiagnosticProcessor>();
return builder; return extensions;
} }
} }
} }
\ No newline at end of file
...@@ -19,14 +19,14 @@ ...@@ -19,14 +19,14 @@
using System; using System;
using System.Data.SqlClient; using System.Data.SqlClient;
using System.Linq; using System.Linq;
using SkyWalking.Components;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Context.Tag; using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Diagnostics.SqlClient namespace SkyWalking.Diagnostics.SqlClient
{ {
public class SqlClientDiagnosticProcessor : ITracingDiagnosticProcessor public class SqlClientTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{ {
private const string TRACE_ORM = "TRACE_ORM"; private const string TRACE_ORM = "TRACE_ORM";
public string ListenerName { get; } = SqlClientDiagnosticStrings.DiagnosticListenerName; public string ListenerName { get; } = SqlClientDiagnosticStrings.DiagnosticListenerName;
......
/*
* 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.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
namespace SkyWalking.NetworkProtocol.Trace
{
public class ComponentsDefine
{
public static readonly OfficialComponent HttpClient = new OfficialComponent(2, "HttpClient");
public static readonly OfficialComponent AspNetCore = new OfficialComponent(3001, "AspNetCore");
public static readonly OfficialComponent EntityFrameworkCore = new OfficialComponent(3002, "EntityFrameworkCore");
public static readonly OfficialComponent SqlClient = new OfficialComponent(3003, "SqlClient");
public static readonly OfficialComponent CAP = new OfficialComponent(3004, "CAP");
public static readonly OfficialComponent StackExchange_Redis = new OfficialComponent(3005, "StackExchange.Redis");
public static readonly OfficialComponent SqlServer = new OfficialComponent(3006, "SqlServer");
public static readonly OfficialComponent Npgsql = new OfficialComponent(3007, "Npgsql");
public static readonly OfficialComponent MySqlConnector = new OfficialComponent(3008, "MySqlConnector");
public static readonly OfficialComponent EntityFrameworkCore_InMemory = new OfficialComponent(3009, "EntityFrameworkCore.InMemory");
public static readonly OfficialComponent EntityFrameworkCore_SqlServer = new OfficialComponent(3010, "EntityFrameworkCore.SqlServer");
public static readonly OfficialComponent EntityFrameworkCore_Sqlite = new OfficialComponent(3011, "EntityFrameworkCore.Sqlite");
public static readonly OfficialComponent Pomelo_EntityFrameworkCore_MySql = new OfficialComponent(3012, "Pomelo.EntityFrameworkCore.MySql");
public static readonly OfficialComponent Npgsql_EntityFrameworkCore_PostgreSQL = new OfficialComponent(3013, "Npgsql.EntityFrameworkCore.PostgreSQL");
public static readonly OfficialComponent InMemoryDatabase = new OfficialComponent(3014, "InMemoryDatabase");
public static readonly OfficialComponent AspNet = new OfficialComponent(3015, "AspNet");
private static readonly ComponentsDefine _instance = new ComponentsDefine();
public ComponentsDefine Instance => _instance;
private readonly Dictionary<int, string> _components;
private ComponentsDefine()
{
_components = new Dictionary<int, string>();
AddComponent(AspNetCore);
AddComponent(EntityFrameworkCore);
AddComponent(SqlClient);
AddComponent(CAP);
AddComponent(StackExchange_Redis);
AddComponent(SqlServer);
AddComponent(Npgsql);
AddComponent(MySqlConnector);
AddComponent(EntityFrameworkCore_InMemory);
AddComponent(EntityFrameworkCore_SqlServer);
AddComponent(EntityFrameworkCore_Sqlite);
AddComponent(Pomelo_EntityFrameworkCore_MySql);
AddComponent(Npgsql_EntityFrameworkCore_PostgreSQL);
AddComponent(InMemoryDatabase);
AddComponent(AspNet);
}
private void AddComponent(OfficialComponent component)
{
_components[component.Id] = component.Name;
}
public string GetComponentName(int componentId)
{
if (_components.TryGetValue(componentId, out var value))
{
return value;
}
return null;
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<Description>SkyWalking trace protocol.</Description>
<AssemblyTitle>SkyWalking.NetworkProtocol.Trace</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
<AssemblyName>SkyWalking.NetworkProtocol.Trace</AssemblyName>
<PackageId>SkyWalking.NetworkProtocol.Trace</PackageId>
<PackageTags>SkyWalking</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
</PropertyGroup>
</Project>
\ No newline at end of file
...@@ -3,17 +3,19 @@ ...@@ -3,17 +3,19 @@
<PropertyGroup> <PropertyGroup>
<Description>SkyWalking gRPC protocol and generated codes.</Description> <Description>SkyWalking gRPC protocol and generated codes.</Description>
<AssemblyTitle>SkyWalking.NetworkProtocol</AssemblyTitle> <AssemblyTitle>SkyWalking.NetworkProtocol</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
<AssemblyName>SkyWalking.NetworkProtocol</AssemblyName> <AssemblyName>SkyWalking.NetworkProtocol</AssemblyName>
<PackageId>SkyWalking.NetworkProtocol</PackageId> <PackageId>SkyWalking.NetworkProtocol</PackageId>
<PackageTags>SkyWalking</PackageTags> <PackageTags>SkyWalking</PackageTags>
<PackageReleaseNotes> <PackageReleaseNotes>
</PackageReleaseNotes> </PackageReleaseNotes>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.5.1" /> <PackageReference Include="Google.Protobuf" Version="3.6.1" />
<PackageReference Include="Google.Protobuf.Tools" Version="3.5.1" /> <PackageReference Include="Google.Protobuf.Tools" Version="3.6.1" />
<PackageReference Include="Grpc" Version="1.9.0" /> <PackageReference Include="Grpc" Version="1.15.0-pre1" />
<PackageReference Include="Grpc.Tools" Version="1.9.0" /> <PackageReference Include="Grpc.Tools" Version="1.15.0-pre1" />
<PackageReference Include="System.Runtime" Version="4.3.0" />
<PackageReference Include="System.Threading.ThreadPool" Version="4.3.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
\ 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 Grpc.Core;
using SkyWalking.Config;
using SkyWalking.Logging;
namespace SkyWalking.Transport.Grpc
{
public class ConnectionManager
{
private readonly Random _random = new Random();
private readonly AsyncLock _lock = new AsyncLock();
private readonly ILogger _logger;
private readonly GrpcConfig _config;
private volatile Channel _channel;
private volatile ConnectionState _state;
private volatile string _server;
public bool Ready => _channel != null && _state == ConnectionState.Connected && _channel.State == ChannelState.Ready;
public ConnectionManager(ILoggerFactory loggerFactory, IConfigAccessor configAccessor)
{
_logger = loggerFactory.CreateLogger(typeof(ConnectionManager));
_config = configAccessor.Get<GrpcConfig>();
}
public async Task ConnectAsync()
{
using (await _lock.LockAsync())
{
if (Ready)
{
return;
}
if (_channel != null)
{
await ShutdownAsync();
}
EnsureServerAddress();
_channel = new Channel(_server, ChannelCredentials.Insecure);
try
{
var deadLine = DateTime.UtcNow.AddMilliseconds(_config.ConnectTimeout);
await _channel.ConnectAsync(deadLine);
_state = ConnectionState.Connected;
_logger.Information($"Connected collector server[{_channel.Target}].");
}
catch (TaskCanceledException ex)
{
_state = ConnectionState.Failure;
_logger.Error($"Connect collector timeout.", ex);
}
catch (Exception ex)
{
_state = ConnectionState.Failure;
_logger.Error($"Connect collector fail.", ex);
}
}
}
public async Task ShutdownAsync()
{
try
{
await _channel?.ShutdownAsync();
_logger.Information($"Shutdown connection[{_channel.Target}].");
}
catch (Exception e)
{
_logger.Error($"Shutdown connection fail.", e);
}
finally
{
_state = ConnectionState.Failure;
}
}
public void Failure(Exception exception)
{
var currentState = _state;
if (ConnectionState.Connected == currentState)
{
_logger.Warning($"Connection state changed. {_state} -> {_channel.State} . {exception.Message}");
}
_state = ConnectionState.Failure;
}
public Channel GetConnection()
{
if (Ready) return _channel;
_logger.Debug("Not found available gRPC connection.");
return null;
}
private void EnsureServerAddress()
{
var servers = _config.Servers.Split(',').ToArray();
if (servers.Length == 1)
{
_server = servers[0];
return;
}
if (_server != null)
{
servers = servers.Where(x => x != _server).ToArray();
}
var index = _random.Next() % servers.Length;
_server = servers[index];
}
}
public enum ConnectionState
{
Idle,
Connecting,
Connected,
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.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
/* /*
* 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using SkyWalking.NetworkProtocol; using System;
using SkyWalking.Config;
namespace SkyWalking.Context
{ namespace SkyWalking.Transport.Grpc
public class KeyValuePair {
{ [Config("SkyWalking", "Transport","gRPC")]
public string Key { get; } public class GrpcConfig
{
public string Value { get; } public string Servers { get; set; }
public KeyValuePair(string key, string value) public int ConnectTimeout { get; set; }
{
Key = key; public int Timeout { get; set; }
Value = value; }
}
public static class GrpcConfigExtensions
public KeyWithStringValue Transform() {
{ public static DateTime GetTimeout(this GrpcConfig config)
var keyWithStringValue = new KeyWithStringValue {
{ return DateTime.UtcNow.AddMilliseconds(config.Timeout);
Key = Key, }
Value = Value }
}; }
\ No newline at end of file
return keyWithStringValue;
}
}
}
/* /*
* 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.
...@@ -17,40 +17,34 @@ ...@@ -17,40 +17,34 @@
*/ */
using System; using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Logging;
namespace SkyWalking.Dictionarys namespace SkyWalking.Transport.Grpc
{ {
public abstract class PossibleFound public class GrpcStateCheckService : ExecutionService
{ {
private bool _found; private readonly ConnectionManager _connectionManager;
private int _value;
protected PossibleFound(int value) public GrpcStateCheckService(ConnectionManager connectionManager, ISkyWalkingClient skyWalking, IRuntimeEnvironment runtimeEnvironment,
ILoggerFactory loggerFactory) : base(
skyWalking, runtimeEnvironment, loggerFactory)
{ {
_found = true; _connectionManager = connectionManager;
_value = value;
} }
protected PossibleFound() protected override TimeSpan DueTime { get; } = TimeSpan.Zero;
{ protected override TimeSpan Period { get; } = TimeSpan.FromSeconds(15);
_found = false;
}
public virtual void InCondition(Action<int> foundCondition, Action notFoundCondition) protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{ {
if (_found) if (!_connectionManager.Ready)
{
foundCondition?.Invoke(_value);
}
else
{ {
notFoundCondition?.Invoke(); await _connectionManager.ConnectAsync();
} }
} }
public virtual object InCondition(Func<int, object> foundCondition, Func<object> notFoundCondition) protected override bool CanExecute() => !_connectionManager.Ready;
{
return _found ? foundCondition?.Invoke(_value) : notFoundCondition?.Invoke();
}
} }
} }
\ 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.
...@@ -16,20 +16,21 @@ ...@@ -16,20 +16,21 @@
* *
*/ */
#if NET45 || NET451 namespace SkyWalking.Transport.Grpc
using System.Runtime.Remoting.Messaging;
namespace SkyWalking.Utils
{ {
internal class AsyncLocal<T> public struct ServerMetadata
{ {
private static readonly string key = "sw-" + typeof(T).FullName; public string Address { get; }
public string Token { get; }
public string CertificatePath { get; }
public T Value public ServerMetadata(string address, string certificate, string token)
{ {
get => (T) CallContext.LogicalGetData(key); Address = address;
set => CallContext.LogicalSetData(key, value); CertificatePath = certificate;
Token = token;
} }
} }
} }
#endif \ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<Description>SkyWalking gRPC data transmitter.</Description>
<AssemblyTitle>SkyWalking.Transport.Grpc</AssemblyTitle>
<AssemblyName>SkyWalking.Transport.Grpc</AssemblyName>
<PackageId>SkyWalking.Transport.Grpc</PackageId>
<PackageTags>SkyWalking;Grpc</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.NetworkProtocol\SkyWalking.NetworkProtocol.csproj" />
</ItemGroup>
</Project>
...@@ -20,44 +20,44 @@ using System; ...@@ -20,44 +20,44 @@ using System;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
namespace SkyWalking.Utils namespace SkyWalking.Transport.Grpc
{ {
internal class AsyncLock internal class AsyncLock
{ {
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1); private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1);
private readonly Releaser _releaser; private readonly Release _release;
private readonly Task<Releaser> _releaserTask; private readonly Task<Release> _releaseTask;
public AsyncLock() public AsyncLock()
{ {
_releaser = new Releaser(this); _release = new Release(this);
_releaserTask = Task.FromResult(_releaser); _releaseTask = Task.FromResult(_release);
} }
public Task<Releaser> LockAsync(CancellationToken cancellationToken = default(CancellationToken)) public Task<Release> LockAsync(CancellationToken cancellationToken = default(CancellationToken))
{ {
var wait = _semaphore.WaitAsync(cancellationToken); var wait = _semaphore.WaitAsync(cancellationToken);
return wait.IsCompleted return wait.IsCompleted
? _releaserTask ? _releaseTask
: wait.ContinueWith( : wait.ContinueWith(
(_, state) => ((AsyncLock) state)._releaser, (_, state) => ((AsyncLock) state)._release,
this, CancellationToken.None, this, CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
} }
public Releaser Lock() public Release Lock()
{ {
_semaphore.Wait(); _semaphore.Wait();
return _releaser; return _release;
} }
public struct Releaser : IDisposable public struct Release : IDisposable
{ {
private readonly AsyncLock _toRelease; private readonly AsyncLock _toRelease;
internal Releaser(AsyncLock toRelease) internal Release(AsyncLock toRelease)
{ {
_toRelease = toRelease; _toRelease = toRelease;
} }
......
namespace SkyWalking.Transport.Grpc
{
internal static class ExceptionHelpers
{
public static readonly string RegisterApplicationError = "Register application fail.";
public static readonly string RegisterApplicationInstanceError = "Register application instance fail.";
public static readonly string HeartbeatError = "Heartbeat fail.";
public static readonly string CollectError = "Send trace segment fail.";
}
}
\ No newline at end of file
using System;
using System.Linq;
using Google.Protobuf;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Transport.Grpc
{
internal static class TraceSegmentHelpers
{
public static UpstreamSegment Map(TraceSegmentRequest request)
{
var upstreamSegment = new UpstreamSegment();
upstreamSegment.GlobalTraceIds.AddRange(request.UniqueIds.Select(MapToUniqueId).ToArray());
var traceSegment = new TraceSegmentObject
{
TraceSegmentId = MapToUniqueId(request.Segment.SegmentId),
ApplicationId = request.Segment.ApplicationId,
ApplicationInstanceId = request.Segment.ApplicationInstanceId,
IsSizeLimited = false
};
traceSegment.Spans.Add(request.Segment.Spans.Select(MapToSpan).ToArray());
upstreamSegment.Segment = traceSegment.ToByteString();
return upstreamSegment;
}
private static UniqueId MapToUniqueId(UniqueIdRequest uniqueIdRequest)
{
var uniqueId = new UniqueId();
uniqueId.IdParts.Add(uniqueIdRequest.Part1);
uniqueId.IdParts.Add(uniqueIdRequest.Part2);
uniqueId.IdParts.Add(uniqueIdRequest.Part3);
return uniqueId;
}
private static SpanObject MapToSpan(SpanRequest request)
{
var spanObject = new SpanObject
{
SpanId = request.SpanId,
ParentSpanId = request.ParentSpanId,
StartTime = request.StartTime,
EndTime = request.EndTime,
SpanType = (SpanType) request.SpanType,
SpanLayer = (SpanLayer) request.SpanLayer,
IsError = request.IsError
};
ReadStringOrIntValue(spanObject, request.Component, ComponentReader, ComponentIdReader);
ReadStringOrIntValue(spanObject, request.OperationName, OperationNameReader, OperationNameIdReader);
ReadStringOrIntValue(spanObject, request.Peer, PeerReader, PeerIdReader);
spanObject.Tags.Add(request.Tags.Select(x => new KeyWithStringValue {Key = x.Key, Value = x.Value}));
spanObject.Refs.AddRange(request.References.Select(MapToSegmentReference).ToArray());
spanObject.Logs.AddRange(request.Logs.Select(MapToLogMessage).ToArray());
return spanObject;
}
private static TraceSegmentReference MapToSegmentReference(TraceSegmentReferenceRequest referenceRequest)
{
var reference = new TraceSegmentReference
{
ParentApplicationInstanceId = referenceRequest.ParentApplicationInstanceId,
EntryApplicationInstanceId = referenceRequest.EntryApplicationInstanceId,
ParentSpanId = referenceRequest.ParentSpanId,
RefType = (RefType) referenceRequest.RefType,
ParentTraceSegmentId = MapToUniqueId(referenceRequest.ParentTraceSegmentId)
};
ReadStringOrIntValue(reference, referenceRequest.NetworkAddress, NetworkAddressReader, NetworkAddressIdReader);
ReadStringOrIntValue(reference, referenceRequest.EntryServiceName, EntryServiceReader, EntryServiceIdReader);
ReadStringOrIntValue(reference, referenceRequest.ParentServiceName, ParentServiceReader, ParentServiceIdReader);
return reference;
}
private static LogMessage MapToLogMessage(LogDataRequest request)
{
var logMessage = new LogMessage {Time = request.Timestamp};
logMessage.Data.AddRange(request.Data.Select(x => new KeyWithStringValue {Key = x.Key, Value = x.Value}).ToArray());
return logMessage;
}
private static void ReadStringOrIntValue<T>(T instance, StringOrIntValue stringOrIntValue, Action<T, string> stringValueReader, Action<T, int> intValueReader)
{
if (stringOrIntValue.HasStringValue)
{
stringValueReader.Invoke(instance, stringOrIntValue.GetStringValue());
}
else if (stringOrIntValue.HasIntValue)
{
intValueReader.Invoke(instance, stringOrIntValue.GetIntValue());
}
}
private static readonly Action<SpanObject, string> ComponentReader = (s, val) => s.Component = val;
private static readonly Action<SpanObject, int> ComponentIdReader = (s, val) => s.ComponentId = val;
private static readonly Action<SpanObject, string> OperationNameReader = (s, val) => s.OperationName = val;
private static readonly Action<SpanObject, int> OperationNameIdReader = (s, val) => s.OperationNameId = val;
private static readonly Action<SpanObject, string> PeerReader = (s, val) => s.Peer = val;
private static readonly Action<SpanObject, int> PeerIdReader = (s, val) => s.PeerId = val;
private static readonly Action<TraceSegmentReference, string> NetworkAddressReader = (s, val) => s.NetworkAddress = val;
private static readonly Action<TraceSegmentReference, int> NetworkAddressIdReader = (s, val) => s.NetworkAddressId = val;
private static readonly Action<TraceSegmentReference, string> EntryServiceReader = (s, val) => s.EntryServiceName = val;
private static readonly Action<TraceSegmentReference, int> EntryServiceIdReader = (s, val) => s.EntryServiceId = val;
private static readonly Action<TraceSegmentReference, string> ParentServiceReader = (s, val) => s.ParentServiceName = val;
private static readonly Action<TraceSegmentReference, int> ParentServiceIdReader = (s, val) => s.ParentServiceId = val;
}
}
\ 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System.Collections.Concurrent; using System;
using SkyWalking.Config; using System.Reflection;
using SkyWalking.Dictionarys; using Microsoft.Extensions.Configuration;
using SkyWalking.NetworkProtocol; using SkyWalking.Config;
namespace SkyWalking.Dictionarys // ReSharper disable StringLiteralTypo
{ namespace SkyWalking.Utilities.Configuration
public class NetworkAddressDictionary {
{ public class ConfigAccessor : IConfigAccessor
private static readonly NetworkAddressDictionary _instance = new NetworkAddressDictionary(); {
public static NetworkAddressDictionary Instance => _instance; private const string CONFIG_FILE_PATH = "SKYWALKING__CONFIG__PATH";
private readonly IConfiguration _configuration;
private NetworkAddressDictionary()
{ public ConfigAccessor(IEnvironmentProvider environmentProvider)
} {
var builder = new ConfigurationBuilder();
private readonly ConcurrentDictionary<string, int> _applicationDic = new ConcurrentDictionary<string, int>();
builder.AddSkyWalkingDefaultConfig();
private readonly ConcurrentDictionary<string, object> _unRegisterApps =
new ConcurrentDictionary<string, object>(); builder.AddJsonFile("appsettings.json", true).AddJsonFile($"appsettings.{environmentProvider.EnvironmentName}.json", true);
public PossibleFound Find(string networkAddress) builder.AddJsonFile("skywalking.json", true).AddJsonFile($"skywalking.{environmentProvider.EnvironmentName}.json", true);
{
if (_applicationDic.TryGetValue(networkAddress, out var id)) if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(CONFIG_FILE_PATH)))
{ {
return new Found(id); builder.AddJsonFile(Environment.GetEnvironmentVariable(CONFIG_FILE_PATH), false);
} }
if (_applicationDic.Count + _unRegisterApps.Count < DictionaryConfig.ApplicationCodeBufferSize) builder.AddEnvironmentVariables();
{
_unRegisterApps.TryAdd(networkAddress, null); _configuration = builder.Build();
} }
return NotFound.Instance; public T Get<T>() where T : class, new()
} {
var config = typeof(T).GetCustomAttribute<ConfigAttribute>();
public void SyncRemote(NetworkAddressRegisterService.NetworkAddressRegisterServiceClient serviceClient) var instance = Activator.CreateInstance<T>();
{ _configuration.GetSection(config.GetSections()).Bind(instance);
if (_unRegisterApps.Count <= 0) return; return instance;
var networkAddress = new NetworkAddresses(); }
networkAddress.Addresses.Add(_unRegisterApps.Keys);
var mapping = serviceClient.batchRegister(networkAddress); public T Value<T>(string key, params string[] sections)
if (mapping.AddressIds.Count <= 0) return; {
foreach (var id in mapping.AddressIds) var config = new ConfigAttribute(sections);
{ return _configuration.GetSection(config.GetSections()).GetValue<T>(key);
_unRegisterApps.TryRemove(id.Key, out _); }
_applicationDic.TryAdd(id.Key, id.Value); }
}
}
}
} }
\ 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.Linq;
using SkyWalking.Config;
namespace SkyWalking.Utilities.Configuration
{
public static class ConfigSectionExtensions
{
public static string GetSections(this ConfigAttribute config)
{
if (config.Sections == null || config.Sections.Length == 0)
{
return null;
}
return config.Sections.Length == 1 ? config.Sections[0] : config.Sections.Aggregate((x, y) => x + ":" + y);
}
}
}
\ 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.IO;
using SkyWalking.Dictionarys; using Microsoft.Extensions.Configuration;
namespace SkyWalking.Config namespace SkyWalking.Utilities.Configuration
{ {
/// <summary> internal static class ConfigurationBuilderExtensions
/// The <code>RemoteDownstreamConfig</code> includes configurations from collector side. {
/// All of them initialized null, Null-Value or empty collection. public static IConfigurationBuilder AddSkyWalkingDefaultConfig(this IConfigurationBuilder builder)
/// </summary> {
public static class RemoteDownstreamConfig var defaultLogFile = Path.Combine("logs", "SkyWalking-{Date}.log");
{ var defaultConfig = new Dictionary<string, string>
public static class Agent {
{ {"SkyWalking:Namespace", string.Empty},
public static int ApplicationId { get; set; } = DictionaryUtil.NullValue; {"SkyWalking:ApplicationCode", "My_Application"},
{"SkyWalking:SpanLimitPerSegment", "300"},
public static int ApplicationInstanceId { get; set; } = DictionaryUtil.NullValue; {"SkyWalking:Sampling:SamplePer3Secs", "-1"},
} {"SkyWalking:Logging:Level", "Info"},
{"SkyWalking:Logging:FilePath", defaultLogFile},
public static class Collector {"SkyWalking:Transport:Interval", "3000"},
{ {"SkyWalking:Transport:PendingSegmentLimit", "30000"},
private static IList<string> _grpcServers; {"SkyWalking:Transport:PendingSegmentTimeout", "1000"},
/// <summary> {"SkyWalking:Transport:gRPC:Servers", "localhost:11800"},
/// Collector GRPC-Service address. {"SkyWalking:Transport:gRPC:Timeout", "2000"},
/// </summary> {"SkyWalking:Transport:gRPC:ConnectTimeout", "10000"}
public static IList<string> gRPCServers };
{ return builder.AddInMemoryCollection(defaultConfig);
get => _grpcServers ?? CollectorConfig.DirectServers.Split(',').ToList(); }
set => _grpcServers = value; }
} }
} \ No newline at end of file
}
}
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<Description>SkyWalking configuration extensions.</Description>
<AssemblyTitle>SkyWalking.Utilities.Configuration</AssemblyTitle>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>SkyWalking.Utilities.Configuration</AssemblyName>
<PackageId>SkyWalking.Utilities.Configuration</PackageId>
<PackageTags>SkyWalking;APM;Diagnostics</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
<RootNamespace>SkyWalking.Utilities.Configuration</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="2.1.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.1.0" />
</ItemGroup>
</Project>
/* /*
* 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.
...@@ -16,15 +16,15 @@ ...@@ -16,15 +16,15 @@
* *
*/ */
namespace SkyWalking.Dictionarys using Microsoft.Extensions.DependencyInjection;
namespace SkyWalking.Utilities.DependencyInjection
{ {
public static class DictionaryUtil public static class ServiceCollectionExtensions
{ {
public static readonly int NullValue = 0; public static SkyWalkingExtensions AddSkyWalkingExtensions(this IServiceCollection services)
public static bool IsNull(int id)
{ {
return id == NullValue; return new SkyWalkingExtensions(services);
} }
} }
} }
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" /> <Import Project="..\..\build\common.props" />
<PropertyGroup> <PropertyGroup>
<Description>Microsoft.Extensions.DependencyInjection (IServiceCollection) support for SkyWalking.</Description> <Description>Microsoft.Utilities.DependencyInjection (IServiceCollection) support for SkyWalking.</Description>
<AssemblyTitle>SkyWalking.Extensions.DependencyInjection</AssemblyTitle> <AssemblyTitle>SkyWalking.Utilities.DependencyInjection</AssemblyTitle>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>SkyWalking.Extensions.DependencyInjection</AssemblyName> <AssemblyName>SkyWalking.Utilities.DependencyInjection</AssemblyName>
<PackageId>SkyWalking.Extensions.DependencyInjection</PackageId> <PackageId>SkyWalking.Utilities.DependencyInjection</PackageId>
<PackageTags>SkyWalking;APM;Diagnostics</PackageTags> <PackageTags>SkyWalking;APM;Diagnostics</PackageTags>
<PackageReleaseNotes> <PackageReleaseNotes>
</PackageReleaseNotes> </PackageReleaseNotes>
<RootNamespace>SkyWalking.Extensions.DependencyInjection</RootNamespace> <RootNamespace>SkyWalking.Utilities.DependencyInjection</RootNamespace>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
......
...@@ -18,13 +18,13 @@ ...@@ -18,13 +18,13 @@
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
namespace SkyWalking.Extensions.DependencyInjection namespace SkyWalking.Utilities.DependencyInjection
{ {
public class SkyWalkingBuilder public class SkyWalkingExtensions
{ {
public IServiceCollection Services { get; } public IServiceCollection Services { get; }
public SkyWalkingBuilder(IServiceCollection services) public SkyWalkingExtensions(IServiceCollection services)
{ {
Services = services; Services = services;
} }
......
/* /*
* 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System; using System;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using ILogger = SkyWalking.Logging.ILogger; using ILogger = SkyWalking.Logging.ILogger;
using MSLogger = Microsoft.Extensions.Logging.ILogger; using MSLogger = Microsoft.Extensions.Logging.ILogger;
namespace SkyWalking.AspNetCore.Logging namespace SkyWalking.Utilities.Logging
{ {
internal class LoggerAdapter : ILogger internal class DefaultLogger : ILogger
{ {
private readonly MSLogger _logger; private readonly MSLogger _readLogger;
public LoggerAdapter(MSLogger logger) public DefaultLogger(MSLogger readLogger)
{ {
_logger = logger; _readLogger = readLogger;
} }
public void Debug(string message) public void Debug(string message)
{ {
_logger.LogDebug(message); _readLogger.LogDebug(message);
} }
public void Info(string message) public void Information(string message)
{ {
_logger.LogInformation(message); _readLogger.LogInformation(message);
} }
public void Warning(string message) public void Warning(string message)
{ {
_logger.LogWarning(message); _readLogger.LogWarning(message);
} }
public void Error(string message, Exception exception) public void Error(string message, Exception exception)
{ {
_logger.LogError(exception, message); _readLogger.LogError(message + Environment.NewLine + exception);
} }
public void Trace(string message) public void Trace(string message)
{ {
_logger.LogTrace(message); _readLogger.LogTrace(message);
} }
} }
} }
\ 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System; using System;
using MSLoggerFactory= Microsoft.Extensions.Logging.ILoggerFactory; using Serilog;
using Microsoft.Extensions.Logging; using Serilog.Events;
using ILoggerFactory = SkyWalking.Logging.ILoggerFactory; using SkyWalking.Config;
using ILogger = SkyWalking.Logging.ILogger; using Microsoft.Extensions.Logging;
using ILogger = SkyWalking.Logging.ILogger;
namespace SkyWalking.AspNetCore.Logging using ILoggerFactory = SkyWalking.Logging.ILoggerFactory;
{ using MSLoggerFactory = Microsoft.Extensions.Logging.LoggerFactory;
internal class LoggerFactoryAdapter : ILoggerFactory
{ namespace SkyWalking.Utilities.Logging
private readonly MSLoggerFactory _loggerFactory; {
public class DefaultLoggerFactory : ILoggerFactory
public LoggerFactoryAdapter(MSLoggerFactory loggerFactory) {
{ private const string outputTemplate = @"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{ApplicationCode}] [{Level}] {SourceContext} : {Message}{NewLine}{Exception}";
_loggerFactory = loggerFactory; private readonly MSLoggerFactory _loggerFactory;
} private readonly LoggingConfig _loggingConfig;
public ILogger CreateLogger(Type type) public DefaultLoggerFactory(IConfigAccessor configAccessor)
{ {
return new LoggerAdapter(_loggerFactory.CreateLogger(type)); _loggingConfig = configAccessor.Get<LoggingConfig>();
} _loggerFactory = new MSLoggerFactory();
} var instrumentationConfig = configAccessor.Get<InstrumentationConfig>();
var level = EventLevel(_loggingConfig.Level);
_loggerFactory.AddSerilog(new LoggerConfiguration().
MinimumLevel.Verbose().
Enrich.WithProperty("SourceContext", null).
Enrich.WithProperty(nameof(instrumentationConfig.ApplicationCode), instrumentationConfig.ApplicationCode).
Enrich.FromLogContext().
WriteTo.RollingFile(_loggingConfig.FilePath, level, outputTemplate, null, 1073741824, 31, null, false, false, TimeSpan.FromMilliseconds(500)).
CreateLogger());
}
public ILogger CreateLogger(Type type)
{
return new DefaultLogger(_loggerFactory.CreateLogger(type));
}
private static LogEventLevel EventLevel(string level)
{
return LogEventLevel.TryParse<LogEventLevel>(level, out var logEventLevel) ? logEventLevel : LogEventLevel.Error;
}
}
} }
\ 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 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 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
* *
* http://www.apache.org/licenses/LICENSE-2.0 * http://www.apache.org/licenses/LICENSE-2.0
* *
* Unless required by applicable law or agreed to in writing, software * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and * See the License for the specific language governing permissions and
* limitations under the License. * limitations under the License.
* *
*/ */
using System; using SkyWalking.Config;
using System.Threading;
using System.Threading.Tasks; namespace SkyWalking.Utilities.Logging
{
namespace SkyWalking.Boot [Config("SkyWalking", "Logging")]
{ public class LoggingConfig
public interface IBootService : IDisposable {
{ public string Level { get; set; }
int Order { get; }
public string FilePath { get; set; }
Task Initialize(CancellationToken token); }
}
} }
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<Description>Microsoft.Utilities.Logging support for SkyWalking.</Description>
<AssemblyTitle>SkyWalking.Utilities.Logging</AssemblyTitle>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>SkyWalking.Utilities.Logging</AssemblyName>
<PackageId>SkyWalking.Utilities.Logging</PackageId>
<PackageTags>SkyWalking;APM;Diagnostics</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
<RootNamespace>SkyWalking.Utilities.Logging</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Logging" Version="2.1.1" />
<PackageReference Include="Serilog.Extensions.Logging" Version="2.0.2" />
<PackageReference Include="Serilog.Sinks.RollingFile" Version="3.3.0" />
</ItemGroup>
</Project>
using System; using System;
using System.Diagnostics; using System.Diagnostics;
using SkyWalking.Diagnostics; using SkyWalking.Diagnostics;
using SkyWalking.Logging;
using Xunit; using Xunit;
namespace SkyWalking.Core.Tests.Diagnostics namespace SkyWalking.Core.Tests.Diagnostics
...@@ -12,7 +13,7 @@ namespace SkyWalking.Core.Tests.Diagnostics ...@@ -12,7 +13,7 @@ namespace SkyWalking.Core.Tests.Diagnostics
{ {
var listener = new FakeDiagnosticListener(); var listener = new FakeDiagnosticListener();
var fakeProcessor = new FakeTracingDiagnosticProcessor(); var fakeProcessor = new FakeTracingDiagnosticProcessor();
var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[] {fakeProcessor}); var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[] {fakeProcessor},new NullLoggerFactory());
DiagnosticListener.AllListeners.Subscribe(observer); DiagnosticListener.AllListeners.Subscribe(observer);
var timeStamp = DateTime.Now; var timeStamp = DateTime.Now;
...@@ -23,7 +24,7 @@ namespace SkyWalking.Core.Tests.Diagnostics ...@@ -23,7 +24,7 @@ namespace SkyWalking.Core.Tests.Diagnostics
Timestamp = timeStamp Timestamp = timeStamp
}); });
Assert.Equal(timeStamp, fakeProcessor.Timestamp); Assert.Equal(timeStamp, fakeProcessor.Timestamp);
} }
[Fact] [Fact]
...@@ -31,18 +32,19 @@ namespace SkyWalking.Core.Tests.Diagnostics ...@@ -31,18 +32,19 @@ namespace SkyWalking.Core.Tests.Diagnostics
{ {
var listener = new FakeDiagnosticListener(); var listener = new FakeDiagnosticListener();
var fakeProcessor = new FakeTracingDiagnosticProcessor(); var fakeProcessor = new FakeTracingDiagnosticProcessor();
var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[] {fakeProcessor}); var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[] {fakeProcessor},
new NullLoggerFactory());
DiagnosticListener.AllListeners.Subscribe(observer); DiagnosticListener.AllListeners.Subscribe(observer);
var timeStamp = DateTime.Now; var timeStamp = DateTime.Now;
listener.Write(FakeDiagnosticListener.Executed, listener.Write(FakeDiagnosticListener.Executed,
new FakeDiagnosticListenerData new FakeDiagnosticListenerData
{ {
Name = FakeDiagnosticListener.Executed, Name = FakeDiagnosticListener.Executed,
Timestamp = timeStamp Timestamp = timeStamp
}); });
Assert.Equal(timeStamp, fakeProcessor.Timestamp); Assert.Equal(timeStamp, fakeProcessor.Timestamp);
} }
} }
......
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Data.Sqlite;
using Microsoft.EntityFrameworkCore;
using SkyWalking.Diagnostics.EntityFrameworkCore.Tests.Fakes;
using Xunit;
namespace SkyWalking.Diagnostics.EntityFrameworkCore.Tests
{
// ReSharper disable once InconsistentNaming
public class EFCoreDiagnosticProcessorTests : IDisposable
{
private readonly DbContextOptions<FakeDbContext> _options;
public EFCoreDiagnosticProcessorTests()
{
// In-memory database only exists while the connection is open
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
_options = new DbContextOptionsBuilder<FakeDbContext>()
.UseSqlite(connection)
.Options;
using (var dbContext = new FakeDbContext(_options))
{
dbContext.Database.EnsureCreated();
}
}
[Fact]
public void DbContext_Init_Success_Test()
{
using (var dbContext = new FakeDbContext(_options))
{
Assert.NotNull(dbContext);
}
}
[Fact]
public void DbContext_Works_Success_Test()
{
using (var dbContext = new FakeDbContext(_options))
{
dbContext.Users.Add(new FakeUser("Zhang", "San"));
dbContext.SaveChanges();
}
using (var dbContext = new FakeDbContext(_options))
{
Assert.Single(dbContext.Users);
}
}
[Fact]
public void EF_Diagnostics_Success_Test()
{
var processorObserver = new TracingDiagnosticProcessorObserver(new[]
{
new EntityFrameworkCoreDiagnosticProcessor(new EfCoreSpanFactory(new List<IEfCoreSpanMetadataProvider>()))
});
DiagnosticListener.AllListeners.Subscribe(processorObserver);
using (var tracerContextListener = new FakeIgnoreTracerContextListener())
{
try
{
using (var dbContext = new FakeDbContext(_options))
{
dbContext.Users.Add(new FakeUser("Zhang", "San"));
dbContext.SaveChanges();
}
}
catch
{
// ignored
}
Assert.Equal(1, tracerContextListener.Counter);
}
}
public void Dispose()
{
using (var context = new FakeDbContext(_options))
{
context.Database.EnsureDeleted();
}
}
}
}
using Microsoft.EntityFrameworkCore;
namespace SkyWalking.Diagnostics.EntityFrameworkCore.Tests.Fakes
{
public class FakeDbContext : DbContext
{
public FakeDbContext(DbContextOptions<FakeDbContext> options)
: base(options)
{
}
public DbSet<FakeUser> Users { get; set; }
}
}
using System;
using SkyWalking.Context;
namespace SkyWalking.Diagnostics.EntityFrameworkCore.Tests.Fakes
{
public class FakeIgnoreTracerContextListener : IIgnoreTracerContextListener ,IDisposable
{
public int Counter { get; set; }
public FakeIgnoreTracerContextListener()
{
IgnoredTracerContext.ListenerManager.Add(this);
}
public void AfterFinish(ITracerContext tracerContext)
{
Counter = Counter + 1;
}
public void Dispose()
{
IgnoredTracerContext.ListenerManager.Remove(this);
}
}
}
\ No newline at end of file
namespace SkyWalking.Diagnostics.EntityFrameworkCore.Tests.Fakes
{
public class FakeUser
{
public FakeUser()
{
}
public FakeUser(string firstName, string lastName)
{
}
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public override string ToString()
{
return $"Output for [User] - Id:{Id}, FirstName:{FirstName}, LastName:{LastName}";
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.6.0" />
<PackageReference Include="xunit" Version="2.3.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj" />
</ItemGroup>
</Project>
using System;
using SkyWalking.Context;
namespace SkyWalking.Diagnostics.HttpClient.Tests
{
public class FakeIgnoreTracerContextListener : IIgnoreTracerContextListener ,IDisposable
{
public int Counter { get; set; }
public FakeIgnoreTracerContextListener()
{
IgnoredTracerContext.ListenerManager.Add(this);
}
public void AfterFinish(ITracerContext tracerContext)
{
Counter = Counter + 1;
}
public void Dispose()
{
IgnoredTracerContext.ListenerManager.Remove(this);
}
}
}
\ No newline at end of file
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using SkyWalking.Config;
using Xunit;
namespace SkyWalking.Diagnostics.HttpClient.Tests
{
public class HttpClientDiagnosticTests
{
[Fact]
public async Task HttpClient_Request_Success_Test()
{
//Todo fix ci
/*AgentConfig.ApplicationCode = "HttpClientDiagnosticTests";
CollectorConfig.DirectServers = "HttpClientDiagnosticTests.xx:50000";
var httpClientDiagnosticProcessor = new HttpClientDiagnosticProcessor();
var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[]
{httpClientDiagnosticProcessor});
DiagnosticListener.AllListeners.Subscribe(observer);
using (var tracerContextListener = new FakeIgnoreTracerContextListener())
{
var httpClient = new System.Net.Http.HttpClient();
await httpClient.GetAsync("https://github.com");
Assert.Equal(1, tracerContextListener.Counter);
}*/
}
[Fact]
public async Task HttpClient_Request_Fail_Test()
{
AgentConfig.ApplicationCode = "HttpClientDiagnosticTests";
CollectorConfig.DirectServers = "HttpClientDiagnosticTests.xx:50000";
var httpClientDiagnosticProcessor = new HttpClientDiagnosticProcessor();
var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[]
{httpClientDiagnosticProcessor});
DiagnosticListener.AllListeners.Subscribe(observer);
using (var tracerContextListener = new FakeIgnoreTracerContextListener())
{
try
{
var httpClient = new System.Net.Http.HttpClient();
await httpClient.GetAsync("http://HttpClientDiagnosticTests.xx");
}
catch (Exception e)
{
}
Assert.Equal(1, tracerContextListener.Counter);
}
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.0</TargetFramework>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0" />
<PackageReference Include="xunit" Version="2.3.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.3.1" />
<DotNetCliToolReference Include="dotnet-xunit" Version="2.3.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\SkyWalking.Diagnostics.HttpClient\SkyWalking.Diagnostics.HttpClient.csproj" />
</ItemGroup>
</Project>
\ No newline at end of file
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