Commit 4146fcd7 authored by liuhaoyang's avatar liuhaoyang
parents aa45aacc fc346491
......@@ -23,3 +23,11 @@ deploy:
artifact: /artifacts\/packages\/.+\.nupkg/
on:
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
......@@ -76,9 +76,17 @@ public class BuildParameters
var suffix = versionQuality;
if (!IsTagged)
{
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;
Version =
......
<Project>
<PropertyGroup>
<VersionMajor>0</VersionMajor>
<VersionMinor>3</VersionMinor>
<VersionMinor>6</VersionMinor>
<VersionPatch>0</VersionPatch>
<VersionQuality></VersionQuality>
<VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix>
......
......@@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SkyWalking.Sample.AspNet</RootNamespace>
<AssemblyName>SkyWalking.Sample.AspNet</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
......
......@@ -12,4 +12,17 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</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>
\ No newline at end of file
......@@ -25,13 +25,6 @@ namespace SkyWalking.Sample.Backend
{
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:");
sqliteConnection.Open();
......
......@@ -11,5 +11,8 @@
"Default": "Warning"
}
}
},
"SkyWalking": {
"ApplicationCode": "asp-net-core-backend"
}
}
......@@ -9,7 +9,7 @@ namespace SkyWalking.Sample.Frontend.Controllers
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
[HttpGet("/values")]
public async Task<IEnumerable<string>> Get()
{
await new HttpClient().GetAsync("http://localhost:5002/api/values");
......
......@@ -11,4 +11,10 @@
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
\ No newline at end of file
......@@ -19,12 +19,6 @@ namespace SkyWalking.Sample.Frontend
public void ConfigureServices(IServiceCollection services)
{
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.
......
......@@ -11,6 +11,9 @@
"Default": "Warning"
}
}
},
"SkyWalking": {
"ApplicationCode": "asp-net-core-frontend"
}
}
......@@ -22,8 +22,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{613F0980-9
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Core.Tests", "test\SkyWalking.Core.Tests\SkyWalking.Core.Tests.csproj", "{3915A2C2-7174-4651-A4F1-D45CD109916A}"
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}"
EndProject
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"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SkyWalking.Diagnostics.HttpClient", "src\SkyWalking.Diagnostics.HttpClient\SkyWalking.Diagnostics.HttpClient.csproj", "{49DEFCA8-4289-4875-B6A5-35D84B3D2290}"
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}"
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}"
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}"
EndProject
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
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Sample.AspNet", "sample\SkyWalking.Sample.AspNet\SkyWalking.Sample.AspNet.csproj", "{C3649845-E458-448D-B97D-C7E231E1D040}"
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
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -84,10 +90,6 @@ Global
{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.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.Build.0 = Debug|Any CPU
{D75B68C5-6788-4871-A63F-F6EB48FB0DC5}.Release|Any CPU.ActiveCfg = Release|Any CPU
......@@ -104,26 +106,14 @@ Global
{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.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.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.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.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.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.Build.0 = Debug|Any CPU
{44DFFDF7-5935-475A-825F-2C0298464117}.Release|Any CPU.ActiveCfg = Release|Any CPU
......@@ -148,6 +138,26 @@ Global
{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.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
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......@@ -157,17 +167,13 @@ Global
{C3860B5F-21D0-429F-8A00-B0C0F4573DF7} = {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}
{50BE8184-EC7A-4257-AF54-764C0E61276F} = {CBFF7EE0-69D7-4D6A-9BBD-8E567FF4D810}
{79ED86A5-E9B9-49B2-9354-C911C079D03E} = {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}
{80A67B09-83F2-477F-907F-95FFF5B8FEAF} = {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}
{BF5579ED-113C-4EE6-AE03-9A9CA590C924} = {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}
{A4E67E09-3156-4D30-B451-F24F706E96C4} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{CD334460-8E61-41EB-9762-62C6A342CACB} = {A4E67E09-3156-4D30-B451-F24F706E96C4}
......@@ -176,6 +182,13 @@ Global
{F8D96C30-369C-4FCB-B5B2-02EAA74199C9} = {A4E67E09-3156-4D30-B451-F24F706E96C4}
{3A454A8A-A1B7-4C6D-BE08-52D956F95CC1} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{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
GlobalSection(ExtensibilityGlobals) = postSolution
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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -16,7 +16,7 @@
*
*/
namespace SkyWalking.NetworkProtocol.Trace
namespace SkyWalking.Components
{
/// <summary>
/// The <code>Component</code> represents component library , which has been supported by skywalking
......@@ -24,6 +24,7 @@ namespace SkyWalking.NetworkProtocol.Trace
public interface IComponent
{
int Id { get; }
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.
......@@ -16,7 +16,7 @@
*
*/
namespace SkyWalking.NetworkProtocol.Trace
namespace SkyWalking.Components
{
public class OfficialComponent : IComponent
{
......
/*
* 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
* 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 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
*
......@@ -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()
: base()
public string[] Sections { get; }
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
* 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 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
*
......@@ -18,10 +18,10 @@
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
* 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 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
*
......@@ -16,15 +16,11 @@
*
*/
using SkyWalking.Dictionarys;
namespace SkyWalking.Dictionarys
namespace SkyWalking.Config
{
public class Found : PossibleFound
{
public Found(int value)
: base(value)
[Config("SkyWalking", "Sampling")]
public class SamplingConfig
{
}
public int SamplePer3Secs { get; set; } = -1;
}
}
\ 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 @@
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using SkyWalking.Config;
namespace SkyWalking.Context
{
public class CarrierItem : IEnumerable<CarrierItem>
{
private string _headKey;
private readonly string _headKey;
private string _headValue;
private CarrierItem _next;
private readonly CarrierItem _next;
public virtual string HeadKey
{
get
{
return _headKey;
}
}
public virtual string HeadKey => _headKey;
public virtual string HeadValue
{
get
{
return _headValue;
}
set
{
_headValue = value;
}
get => _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 = headKey;
}
else
{
_headKey = $"{AgentConfig.Namespace}-{headKey}";
}
_headKey = string.IsNullOrEmpty(@namespace) ? headKey : $"{@namespace}-{headKey}";
_headValue = headValue;
_next = next;
}
......@@ -82,17 +59,16 @@ namespace SkyWalking.Context
private class Enumerator : IEnumerator<CarrierItem>
{
private CarrierItem _head;
private CarrierItem _current;
private readonly CarrierItem _head;
public CarrierItem Current => _current;
public CarrierItem Current { get; private set; }
object IEnumerator.Current => _current;
object IEnumerator.Current => Current;
public Enumerator(CarrierItem head)
{
_head = head;
_current = head;
Current = head;
}
public void Dispose()
......@@ -101,18 +77,19 @@ namespace SkyWalking.Context
public bool MoveNext()
{
var next = _current._next;
var next = Current._next;
if (next == null)
{
return false;
}
_current = next;
Current = next;
return true;
}
public void Reset()
{
_current = _head;
Current = _head;
}
}
}
......
/*
/*
* 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.
......@@ -16,12 +16,10 @@
*
*/
using System.Threading.Tasks;
namespace SkyWalking.Utils
namespace SkyWalking.Context
{
internal static class TaskUtils
public interface IContextCarrierFactory
{
public static readonly Task CompletedTask = Task.FromResult(0);
IContextCarrier Create();
}
}
\ No newline at end of file
......@@ -18,11 +18,12 @@
using System;
using SkyWalking.NetworkProtocol;
using SkyWalking.Transport;
namespace SkyWalking.Context.Ids
{
/// <inheritdoc />
/// <summary>
/// The <code>DistributedTraceId</code> presents a distributed call chain.
/// This call chain has an unique (service) entrance,
......@@ -34,50 +35,35 @@ namespace SkyWalking.Context.Ids
{
private readonly ID _id;
public DistributedTraceId(ID id)
protected DistributedTraceId(ID id)
{
_id = id;
}
public DistributedTraceId(string id)
protected DistributedTraceId(string id)
{
_id = new ID(id);
}
public string Encode
{
get
{
return _id?.Encode;
}
}
public string Encode => _id?.Encode;
public UniqueId ToUniqueId()
{
return _id?.Transform();
}
public UniqueIdRequest ToUniqueId() => _id?.Transform();
public bool Equals(DistributedTraceId other)
{
if (other == null)
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)
{
DistributedTraceId id = obj as DistributedTraceId;
var id = obj as DistributedTraceId;
return Equals(id);
}
public override int GetHashCode()
{
return _id != null ? _id.GetHashCode() : 0;
}
public override int GetHashCode() => _id != null ? _id.GetHashCode() : 0;
public override string ToString()
{
return _id?.ToString();
}
public override string ToString() => _id?.ToString();
}
}
......@@ -17,7 +17,7 @@
*/
using System;
using SkyWalking.NetworkProtocol;
using SkyWalking.Transport;
namespace SkyWalking.Context.Ids
{
......@@ -26,35 +26,18 @@ namespace SkyWalking.Context.Ids
private readonly long _part1;
private readonly long _part2;
private readonly long _part3;
private readonly bool _isValid;
private string _encoding;
public bool IsValid
{
get
{
return _isValid;
}
}
public bool IsValid { get; }
public string Encode
{
get
{
if (_encoding == null)
{
_encoding = ToString();
}
return _encoding;
}
}
public string Encode => _encoding ?? (_encoding = ToString());
public ID(long part1, long part2, long part3)
{
_part1 = part1;
_part2 = part2;
_part3 = part3;
_isValid = true;
IsValid = true;
}
public ID(string encodingString)
......@@ -68,17 +51,17 @@ namespace SkyWalking.Context.Ids
{
if (part == 0)
{
_isValid = long.TryParse(idParts[part], out _part1);
IsValid = long.TryParse(idParts[part], out _part1);
}
else if (part == 1)
{
_isValid = long.TryParse(idParts[part], out _part2);
IsValid = long.TryParse(idParts[part], out _part2);
}
else
{
_isValid = long.TryParse(idParts[part], out _part3);
IsValid = long.TryParse(idParts[part], out _part3);
}
if (!_isValid)
if (!IsValid)
{
break;
}
......@@ -92,7 +75,7 @@ namespace SkyWalking.Context.Ids
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)(_part3 ^ (_part3 >> 32));
return result;
......@@ -100,7 +83,7 @@ namespace SkyWalking.Context.Ids
public override bool Equals(object obj)
{
ID id = obj as ID;
var id = obj as ID;
return Equals(id);
}
......@@ -117,12 +100,9 @@ namespace SkyWalking.Context.Ids
return _part3 == other._part3;
}
public UniqueId Transform()
public UniqueIdRequest Transform()
{
UniqueId uniqueId = new UniqueId();
uniqueId.IdParts.Add(_part1);
uniqueId.IdParts.Add(_part2);
uniqueId.IdParts.Add(_part3);
var uniqueId = new UniqueIdRequest {Part1 = _part1, Part2 = _part2, Part3 = _part3};
return uniqueId;
}
}
......
......@@ -18,11 +18,8 @@
using System;
using System.Collections.Generic;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
using SkyWalking.NetworkProtocol.Trace;
using System.Linq;
using SkyWalking.Utils;
using SkyWalking.Transport;
using SkyWalking.Components;
namespace SkyWalking.Context.Trace
{
......@@ -31,8 +28,8 @@ namespace SkyWalking.Context.Trace
/// </summary>
public abstract class AbstractTracingSpan : ISpan
{
protected int _spanId;
protected int _parnetSpanId;
protected readonly int _spanId;
protected readonly int _parnetSpanId;
protected Dictionary<string, string> _tags;
protected string _operationName;
protected int _operationId;
......@@ -69,7 +66,6 @@ namespace SkyWalking.Context.Trace
protected AbstractTracingSpan(int spanId, int parentSpanId, string operationName)
{
_operationName = operationName;
_operationId = DictionaryUtil.NullValue;
_spanId = spanId;
_parnetSpanId = parentSpanId;
}
......@@ -90,23 +86,17 @@ namespace SkyWalking.Context.Trace
public virtual string OperationName
{
get
{
return _operationName;
}
get => _operationName;
set
{
_operationName = value;
_operationId = DictionaryUtil.NullValue;
_operationId = 0;
}
}
public virtual int OperationId
{
get
{
return _operationId;
}
get => _operationId;
set
{
_operationId = value;
......@@ -132,6 +122,7 @@ namespace SkyWalking.Context.Trace
{
_tags = new Dictionary<string, string>();
}
_tags.Add(key, value);
return this;
}
......@@ -166,11 +157,12 @@ namespace SkyWalking.Context.Trace
public virtual ISpan Log(long timestamp, IDictionary<string, object> events)
{
EnsureLogs();
LogDataEntity.Builder builder = new LogDataEntity.Builder();
var builder = new LogDataEntity.Builder();
foreach (var @event in events)
{
builder.Add(@event.Key, @event.Value.ToString());
}
_logs.Add(builder.Build(timestamp));
return this;
}
......@@ -193,6 +185,7 @@ namespace SkyWalking.Context.Trace
{
_refs = new List<ITraceSegmentRef>();
}
if (!_refs.Contains(traceSegmentRef))
{
_refs.Add(traceSegmentRef);
......@@ -211,69 +204,58 @@ namespace SkyWalking.Context.Trace
return true;
}
public virtual SpanObject Transform()
public virtual SpanRequest Transform()
{
SpanObject spanObject = new SpanObject();
spanObject.SpanId = _spanId;
spanObject.ParentSpanId = _parnetSpanId;
spanObject.StartTime = _startTime;
spanObject.EndTime = _endTime;
if (_operationId != DictionaryUtil.NullValue)
var spanRequest = new SpanRequest
{
spanObject.OperationNameId = _operationId;
}
else
{
spanObject.OperationName = _operationName;
}
SpanId = _spanId,
ParentSpanId = _parnetSpanId,
StartTime = _startTime,
EndTime = _endTime,
OperationName = new StringOrIntValue(_operationId, _operationName),
Component = new StringOrIntValue(_componentId, _componentName),
IsError = _errorOccurred
};
if (IsEntry)
{
spanObject.SpanType = SpanType.Entry;
spanRequest.SpanType = 0;
}
else if (IsExit)
{
spanObject.SpanType = SpanType.Exit;
spanRequest.SpanType = 1;
}
else
{
spanObject.SpanType = SpanType.Local;
spanRequest.SpanType = 2;
}
if (_layer.HasValue)
{
spanObject.SpanLayer = (NetworkProtocol.SpanLayer)((int)_layer.Value);
}
if (_componentId != DictionaryUtil.NullValue)
{
spanObject.ComponentId = _componentId;
}
else
{
spanObject.Component = _componentName;
spanRequest.SpanLayer = (int) _layer.Value;
}
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)
{
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()
......
......@@ -18,8 +18,7 @@
using System;
using System.Collections.Generic;
using System.Text;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Components;
namespace SkyWalking.Context.Trace
{
......@@ -36,7 +35,7 @@ namespace SkyWalking.Context.Trace
ISpan SetComponent(IComponent component);
/// <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.
/// </summary>
/// <param name="componentName"></param>
......
......@@ -17,8 +17,8 @@
*/
using System.Collections.Generic;
using SkyWalking.Transport;
using SkyWalking.Context.Ids;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Context.Trace
{
......@@ -48,6 +48,6 @@ namespace SkyWalking.Context.Trace
void RelatedGlobalTrace(DistributedTraceId distributedTraceId);
UpstreamSegment Transform();
TraceSegmentRequest Transform();
}
}
......@@ -17,7 +17,7 @@
*/
using System;
using SkyWalking.NetworkProtocol;
using SkyWalking.Transport;
namespace SkyWalking.Context.Trace
{
......@@ -29,6 +29,6 @@ namespace SkyWalking.Context.Trace
int EntryApplicationInstanceId { get; }
TraceSegmentReference Transform();
TraceSegmentReferenceRequest Transform();
}
}
\ No newline at end of file
......@@ -18,14 +18,14 @@
using System.Collections.Generic;
using System.Collections.ObjectModel;
using SkyWalking.NetworkProtocol;
using SkyWalking.Transport;
namespace SkyWalking.Context.Trace
{
public class LogDataEntity
{
private long _timestamp = 0;
private Dictionary<string, string> _logs;
private readonly long _timestamp;
private readonly Dictionary<string, string> _logs;
private LogDataEntity(long timestamp, Dictionary<string, string> logs)
{
......@@ -33,14 +33,11 @@ namespace SkyWalking.Context.Trace
_logs = logs;
}
public IReadOnlyDictionary<string, string> Logs
{
get { return new ReadOnlyDictionary<string, string>(_logs); }
}
public IReadOnlyDictionary<string, string> Logs => new ReadOnlyDictionary<string, string>(_logs);
public class Builder
{
private Dictionary<string, string> _logs;
private readonly Dictionary<string, string> _logs;
public Builder()
{
......@@ -66,13 +63,13 @@ namespace SkyWalking.Context.Trace
}
}
public LogMessage Transform()
public LogDataRequest Transform()
{
LogMessage logMessage = new LogMessage();
logMessage.Time = _timestamp;
var logMessage = new LogDataRequest();
logMessage.Timestamp = _timestamp;
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;
......
......@@ -20,7 +20,7 @@ namespace SkyWalking.Context.Trace
{
public enum SegmentRefType
{
CrossProcess,
CrossThread
CrossProcess = 0,
CrossThread = 1
}
}
\ 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.
......@@ -17,66 +17,65 @@
*/
using System;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Configuration;
using SkyWalking.AspNet.Logging;
using SkyWalking.Boot;
using SkyWalking.Config;
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();
LogManager.SetLoggerFactory(new DebugLoggerFactoryAdapter());
AsyncContext.Run(async () => await StartAsync());
SkyWalking = skyWalking;
RuntimeEnvironment = runtimeEnvironment;
Logger = loggerFactory.CreateLogger(GetType());
}
private async Task StartAsync()
public Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(3));
await ServiceManager.Instance.Initialize();
_cancellationTokenSource = new CancellationTokenSource();
var source = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, cancellationToken);
_timer = new Timer(Callback, source, DueTime, Period);
Logger.Information($"Loaded instrument service [{GetType().FullName}].");
return Task.CompletedTask;
}
private void LoadConfigurationSetting()
public async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken))
{
CollectorConfig.DirectServers = GetAppSetting(nameof(CollectorConfig.DirectServers), true);
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;
_cancellationTokenSource?.Cancel();
await Stopping(cancellationToken);
Logger.Information($"Stopped instrument service {GetType().Name}.");
}
var pendingSegmentsLimit = GetAppSetting(nameof(AgentConfig.PendingSegmentsLimit), false);
if(int.TryParse(pendingSegmentsLimit, out v))
public void Dispose()
{
AgentConfig.PendingSegmentsLimit = v;
}
_timer?.Dispose();
}
private string GetAppSetting(string key, bool @throw)
private async void Callback(object state)
{
var value = WebConfigurationManager.AppSettings[key];
if (@throw && string.IsNullOrEmpty(value))
if (state is CancellationTokenSource token && !token.IsCancellationRequested && CanExecute())
{
throw new InvalidOperationException($"Cannot read valid '{key}' in AppSettings.");
await ExecuteAsync(token.Token);
}
return value;
}
public void Dispose()
{
AsyncContext.Run(async () => await GrpcConnectionManager.Instance.ShutdownAsync());
ServiceManager.Instance.Dispose();
}
protected virtual bool CanExecute() => RuntimeEnvironment.Initialized;
protected virtual Task Stopping(CancellationToken cancellationToke) => Task.CompletedTask;
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 @@
*
*/
using SkyWalking.Boot;
namespace SkyWalking.Sampling
namespace SkyWalking
{
public interface ISampler : IBootService
public interface ISampler
{
bool TrySampling();
bool Sampled();
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 @@
*
*/
namespace SkyWalking.Diagnostics
namespace SkyWalking
{
public interface ITracingDiagnosticProcessor
{
......
......@@ -24,7 +24,7 @@ namespace SkyWalking.Logging
{
void Debug(string message);
void Info(string message);
void Information(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 @@
<PropertyGroup>
<Description>SkyWalking Core abstractions and interfaces for apm agent.</Description>
<AssemblyTitle>SkyWalking.Abstractions</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net45;net451</TargetFrameworks>
<AssemblyName>SkyWalking.Abstractions</AssemblyName>
<PackageId>SkyWalking.Abstractions</PackageId>
<PackageTags>SkyWalking;APM</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
<RootNamespace>SkyWalking</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.NetworkProtocol.Trace\SkyWalking.NetworkProtocol.Trace.csproj" />
<ProjectReference Include="..\SkyWalking.NetworkProtocol\SkyWalking.NetworkProtocol.csproj" />
</ItemGroup>
</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;
namespace SkyWalking.AspNet
{
internal class AsyncContext
internal static class AsyncContext
{
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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -18,15 +18,17 @@
using System;
namespace SkyWalking.Utils
namespace SkyWalking.AspNet
{
#if NET45 || NET451
public static class DateTimeOffsetExtensions
internal class HostingEnvironmentProvider : IEnvironmentProvider
{
public static long ToUnixTimeMilliseconds(this DateTimeOffset dateTimeOffset)
private const string ENVIRONMENT_KEY = "ASPNET__ENVIRONMENT";
public string EnvironmentName { get; }
public HostingEnvironmentProvider()
{
return dateTimeOffset.UtcDateTime.Ticks / 10000L - 62135596800000L;
EnvironmentName = Environment.GetEnvironmentVariable(ENVIRONMENT_KEY) ?? "Production";
}
}
#endif
}
\ No newline at end of file
......@@ -20,30 +20,38 @@ using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Components;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.AspNet
{
public class HttpTracingHandler : DelegatingHandler
{
private readonly IContextCarrierFactory _contextCarrierFactory;
public HttpTracingHandler()
: this(new HttpClientHandler())
{
}
public HttpTracingHandler(HttpMessageHandler innerHandler)
: this(innerHandler, CommonServiceLocator.ServiceLocator.Current.GetInstance<IContextCarrierFactory>())
{
}
private HttpTracingHandler(HttpMessageHandler innerHandler, IContextCarrierFactory contextCarrierFactory)
{
InnerHandler = innerHandler;
_contextCarrierFactory = contextCarrierFactory;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
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);
try
{
......
/*
/*
* 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.
......@@ -16,30 +16,34 @@
*
*/
using CommonServiceLocator;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SkyWalking.AspNetCore.Diagnostics;
using SkyWalking.AspNetCore.Logging;
using SkyWalking.Diagnostics;
using SkyWalking.Extensions.DependencyInjection;
using SkyWalking.Logging;
namespace SkyWalking.AspNetCore
namespace SkyWalking.AspNet
{
internal static class SkyWalkingBuilderExtensions
{
public static SkyWalkingBuilder AddHosting(this SkyWalkingBuilder builder)
internal class ServiceProviderLocator : IServiceLocator
{
builder.Services.AddSingleton<IHostedService, SkyWalkingHostedService>();
builder.Services.AddSingleton<ITracingDiagnosticProcessor, HostingDiagnosticProcessor>();
builder.Services.AddSingleton<ILoggerFactory, LoggerFactoryAdapter>();
return builder;
}
private readonly IServiceProvider _serviceProvider;
public static SkyWalkingBuilder AddDiagnostics(this SkyWalkingBuilder builder)
public ServiceProviderLocator(IServiceProvider serviceProvider)
{
builder.Services.AddSingleton<TracingDiagnosticProcessorObserver>();
return builder;
_serviceProvider = serviceProvider;
}
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">
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<TargetFrameworks>net45;net451;net452;net46;net461;net462;net47;net471</TargetFrameworks>
<TargetFrameworks>net461;net462;net47;net471</TargetFrameworks>
</PropertyGroup>
<PropertyGroup>
<AssemblyName>SkyWalking.AspNet</AssemblyName>
......@@ -13,13 +13,20 @@
</PropertyGroup>
<ItemGroup>
<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>
<Reference Include="System.Configuration" />
<Reference Include="System.Web" />
<Reference Include="System.Net.Http"/>
<Reference Include="System.Net.Http" />
</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" />
</ItemGroup>
</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 @@
*
*/
using System;
using System.Collections.Generic;
using CommonServiceLocator;
using Microsoft.Extensions.DependencyInjection;
using System.Web;
using SkyWalking.Boot;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Remote;
using SkyWalking.Utils;
using SkyWalking.AspNet.Extensions;
namespace SkyWalking.AspNet
{
public class SkyWalkingModule : IHttpModule
{
private readonly SkyWalkingStartup _skyWalkingStartup = new SkyWalkingStartup();
public void Dispose()
public SkyWalkingModule()
{
_skyWalkingStartup.Dispose();
var serviceProvider = new ServiceCollection().AddSkyWalkingCore().BuildServiceProvider();
var serviceLocatorProvider = new ServiceProviderLocator(serviceProvider);
ServiceLocator.SetLocatorProvider(() => serviceLocatorProvider);
}
public void Init(HttpApplication application)
{
_skyWalkingStartup.Start();
application.BeginRequest += ApplicationOnBeginRequest;
application.EndRequest += ApplicationOnEndRequest;
}
private void ApplicationOnBeginRequest(object sender, EventArgs e)
{
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 startup = ServiceLocator.Current.GetInstance<ISkyWalkingAgentStartup>();
AsyncContext.Run(() => startup.StartAsync());
var requestCallback = ServiceLocator.Current.GetInstance<SkyWalkingApplicationRequestCallback>();
application.BeginRequest += requestCallback.ApplicationOnBeginRequest;
application.EndRequest += requestCallback.ApplicationOnEndRequest;
}
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>
public void Dispose()
{
{"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 @@
*/
using System;
using Microsoft.Extensions.Configuration;
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.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
{
public static class ServiceCollectionExtensions
internal static class ServiceCollectionExtensions
{
public static SkyWalkingBuilder AddSkyWalking(this IServiceCollection services,
Action<SkyWalkingOptions> options)
public static IServiceCollection AddSkyWalkingCore(this IServiceCollection services)
{
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,
IConfiguration configuration)
private static IServiceCollection AddGrpcTransport(this IServiceCollection services)
{
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)
{
throw new ArgumentNullException(nameof(services));
}
var builder = new SkyWalkingBuilder(services);
builder.AddHosting().AddDiagnostics().AddHttpClient().AddSqlClient();
return builder;
services.AddSingleton<ILoggerFactory, DefaultLoggerFactory>();
return services;
}
}
}
\ 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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -16,29 +16,29 @@
*
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace SkyWalking.Logging
namespace SkyWalking.AspNetCore
{
public static class LogManager
public class InstrumentationHostedService : IHostedService
{
private static readonly ILoggerFactory defaultLoggerFactory = new NullLoggerFactory();
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 @@
<Description>SkyWalking ASP.NET Core Agent.</Description>
<AssemblyTitle>SkyWalking.AspNetCore</AssemblyTitle>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>SkyWalking.AspNetCore</AssemblyName>
<AssemblyName>SkyWalking_AspNetCore</AssemblyName>
<PackageId>SkyWalking.AspNetCore</PackageId>
<PackageTags>SkyWalking;APM</PackageTags>
<PackageReleaseNotes>
......@@ -12,18 +12,22 @@
<RootNamespace>SkyWalking.AspNetCore</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.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.SqlClient\SkyWalking.Diagnostics.SqlClient.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj">
<Project>{BF5579ED-113C-4EE6-AE03-9A9CA590C924}</Project>
<Name>SkyWalking.Extensions.DependencyInjection</Name>
</ProjectReference>
<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" />
<ProjectReference Include="..\SkyWalking.Transport.Grpc\SkyWalking.Transport.Grpc.csproj" />
</ItemGroup>
</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,7 +21,7 @@ namespace SkyWalking.Context
{
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)
{
}
}
......
......@@ -19,7 +19,6 @@
using System.Collections.Generic;
using System.Linq;
using SkyWalking.Context.Ids;
using SkyWalking.Dictionarys;
namespace SkyWalking.Context
{
......@@ -35,12 +34,12 @@ namespace SkyWalking.Context
/// <summary>
/// id of parent application instance
/// </summary>
private int _parentApplicationInstanceId = DictionaryUtil.NullValue;
private int _parentApplicationInstanceId = 0;
/// <summary>
/// id of first application instance in this distributed trace
/// </summary>
private int _entryApplicationInstanceId = DictionaryUtil.NullValue;
private int _entryApplicationInstanceId = 0;
/// <summary>
/// peer(ipv4/ipv6/hostname + port) of the server , from client side .
......@@ -65,6 +64,12 @@ namespace SkyWalking.Context
private DistributedTraceId _primaryDistributedTraceId;
private readonly string _namespace;
public ContextCarrier(string @namespace)
{
_namespace = @namespace;
}
public DistributedTraceId DistributedTraceId => _primaryDistributedTraceId;
......@@ -135,8 +140,8 @@ namespace SkyWalking.Context
return _traceSegmentId != null
&& _traceSegmentId.IsValid
&& _spanId > -1
&& _parentApplicationInstanceId != DictionaryUtil.NullValue
&& _entryApplicationInstanceId != DictionaryUtil.NullValue
&& _parentApplicationInstanceId != 0
&& _entryApplicationInstanceId != 0
&& !string.IsNullOrEmpty(_peerHost)
&& !string.IsNullOrEmpty(_parentOperationName)
&& !string.IsNullOrEmpty(_entryOperationName)
......@@ -180,17 +185,14 @@ namespace SkyWalking.Context
PrimaryDistributedTraceId.Encode);
}
public DistributedTraceId PrimaryDistributedTraceId
{
get { return _primaryDistributedTraceId; }
}
public DistributedTraceId PrimaryDistributedTraceId => _primaryDistributedTraceId;
public CarrierItem Items
{
get
{
SW3CarrierItem carrierItem = new SW3CarrierItem(this, null);
CarrierItemHead head = new CarrierItemHead(carrierItem);
var carrierItem = new SW3CarrierItem(this, null, _namespace);
var head = new CarrierItemHead(carrierItem, _namespace);
return head;
}
}
......
/*
/*
* 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.
......@@ -16,22 +16,22 @@
*
*/
using System;
using System.Diagnostics;
using SkyWalking.Logging;
using SkyWalking.Config;
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 @@
*
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Context.Trace;
using SkyWalking.Dictionarys;
using SkyWalking.Sampling;
using SkyWalking.Utils;
namespace SkyWalking.Context
{
......@@ -34,8 +27,15 @@ namespace SkyWalking.Context
/// We also provide the CONTEXT propagation based on ThreadLocal mechanism.
/// Meaning, each segment also related to singe thread.
/// </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 ITracerContext GetOrCreateContext(string operationName, bool forceSampling)
......@@ -50,18 +50,17 @@ namespace SkyWalking.Context
}
else
{
if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) &&
!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
if (RuntimeEnvironment.Instance.Initialized)
{
var suffixIdx = operationName.LastIndexOf('.');
if (suffixIdx > -1 && AgentConfig.IgnoreSuffix.Contains(operationName.Substring(suffixIdx)))
{
_context.Value = new IgnoredTracerContext();
}
else
{
var sampler = ServiceManager.Instance.GetService<SamplingService>();
if (forceSampling || sampler.TrySampling())
// var suffixIdx = operationName.LastIndexOf('.');
// if (suffixIdx > -1 && AgentConfig.IgnoreSuffix.Contains(operationName.Substring(suffixIdx)))
// {
// _context.Value = new IgnoredTracerContext();
// }
// else
// {
var sampler = DefaultSampler.Instance;
if (forceSampling || sampler.Sampled())
{
_context.Value = new TracingContext();
}
......@@ -69,14 +68,13 @@ namespace SkyWalking.Context
{
_context.Value = new IgnoredTracerContext();
}
}
// }
}
else
{
_context.Value = new IgnoredTracerContext();
}
}
}
return _context.Value;
......@@ -103,7 +101,7 @@ namespace SkyWalking.Context
public static ISpan CreateEntrySpan(string operationName, IContextCarrier carrier)
{
var samplingService = ServiceManager.Instance.GetService<SamplingService>();
var samplingService = DefaultSampler.Instance;
if (carrier != null && carrier.IsValid)
{
samplingService.ForceSampled();
......@@ -179,19 +177,6 @@ namespace SkyWalking.Context
_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)
{
_context.Value = null;
......
......@@ -19,7 +19,6 @@
using System.Collections.Generic;
using System.Linq;
using SkyWalking.Context.Ids;
using SkyWalking.Dictionarys;
namespace SkyWalking.Context
{
......@@ -39,7 +38,7 @@ namespace SkyWalking.Context
private string _parentOperationName;
private readonly DistributedTraceId _primaryDistributedTraceId;
private int _entryApplicationInstanceId = DictionaryUtil.NullValue;
private NullableValue _entryApplicationInstanceId = NullableValue.Null;
public ContextSnapshot(ID traceSegmentId, int spanId, IEnumerable<DistributedTraceId> distributedTraceIds)
{
......@@ -48,7 +47,6 @@ namespace SkyWalking.Context
_primaryDistributedTraceId = distributedTraceIds?.FirstOrDefault();
}
public string EntryOperationName
{
get => _entryOperationName;
......@@ -65,8 +63,8 @@ namespace SkyWalking.Context
public int EntryApplicationInstanceId
{
get => _entryApplicationInstanceId;
set => _entryApplicationInstanceId = value;
get => _entryApplicationInstanceId.Value;
set => _entryApplicationInstanceId = new NullableValue(value);
}
public int SpanId => _spanId;
......@@ -75,7 +73,7 @@ namespace SkyWalking.Context
public bool IsValid => _traceSegmentId != null
&& _spanId > -1
&& _entryApplicationInstanceId != DictionaryUtil.NullValue
&& _entryApplicationInstanceId.HasValue
&& _primaryDistributedTraceId != null
&& string.IsNullOrEmpty(_entryOperationName)
&& string.IsNullOrEmpty(_parentOperationName);
......
......@@ -18,9 +18,6 @@
using System;
using System.Threading;
using SkyWalking.Config;
using SkyWalking.Dictionarys;
using SkyWalking.Utils;
namespace SkyWalking.Context.Ids
{
......@@ -30,7 +27,7 @@ namespace SkyWalking.Context.Ids
public static ID Generate()
{
if (RemoteDownstreamConfig.Agent.ApplicationId == DictionaryUtil.NullValue)
if (!RuntimeEnvironment.Instance.ApplicationInstanceId.HasValue)
{
throw new InvalidOperationException();
}
......@@ -38,7 +35,7 @@ namespace SkyWalking.Context.Ids
IDContext context = threadIdSequence.Value;
return new ID(
RemoteDownstreamConfig.Agent.ApplicationInstanceId,
RuntimeEnvironment.Instance.ApplicationInstanceId.Value,
Thread.CurrentThread.ManagedThreadId,
context.NextSeq()
);
......
......@@ -22,15 +22,19 @@ namespace SkyWalking.Context
{
public class SW3CarrierItem : CarrierItem
{
public const String HEADER_NAME = "sw3";
private const string HEADER_NAME = "sw3";
private readonly IContextCarrier _carrier;
public SW3CarrierItem(IContextCarrier carrier, CarrierItem next)
: base(HEADER_NAME, carrier.Serialize(), next)
public SW3CarrierItem(IContextCarrier carrier, CarrierItem next, string @namespace)
: base(HEADER_NAME, carrier.Serialize(), next, @namespace)
{
_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 @@
*
*/
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Components;
namespace SkyWalking.Context.Trace
{
......@@ -119,7 +118,7 @@ namespace SkyWalking.Context.Trace
private void ClearWhenRestart()
{
_componentId = DictionaryUtil.NullValue;
_componentId = 0;
_componentName = null;
_layer = null;
_logs = null;
......
......@@ -17,11 +17,8 @@
*/
using System;
using System.Collections.Generic;
using System.Text;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Transport;
using SkyWalking.Components;
namespace SkyWalking.Context.Trace
{
......@@ -34,7 +31,7 @@ namespace SkyWalking.Context.Trace
: base(spanId, parentSpanId, operationName)
{
_peer = peer;
_peerId = DictionaryUtil.NullValue;
_peerId = 0;
}
public ExitSpan(int spanId, int parentSpanId, int operationId, int peerId)
......@@ -48,7 +45,7 @@ namespace SkyWalking.Context.Trace
: base(spanId, parentSpanId, operationId)
{
_peer = peer;
_peerId = DictionaryUtil.NullValue;
_peerId = 0;
}
public ExitSpan(int spanId, int parentSpanId, String operationName, int peerId)
......@@ -108,17 +105,12 @@ namespace SkyWalking.Context.Trace
public override ISpan SetComponent(string componentName)
{
if (_stackDepth == 1)
{
return base.SetComponent(componentName);
}
return this;
return _stackDepth == 1 ? base.SetComponent(componentName) : this;
}
public override string OperationName
{
get { return base.OperationName; }
get => base.OperationName;
set
{
if (_stackDepth == 1)
......@@ -130,7 +122,7 @@ namespace SkyWalking.Context.Trace
public override int OperationId
{
get { return base.OperationId; }
get => base.OperationId;
set
{
if (_stackDepth == 1)
......@@ -140,18 +132,11 @@ namespace SkyWalking.Context.Trace
}
}
public override SpanObject Transform()
public override SpanRequest Transform()
{
var spanObject = base.Transform();
if (_peerId != DictionaryUtil.NullValue)
{
spanObject.PeerId = _peerId;
}
else
{
spanObject.Peer = _peer;
}
spanObject.Peer = new StringOrIntValue(_peerId, _peer);
return spanObject;
}
......
......@@ -18,8 +18,7 @@
using System;
using System.Collections.Generic;
using System.Text;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Components;
namespace SkyWalking.Context.Trace
{
......
......@@ -18,10 +18,8 @@
using System.Collections.Generic;
using System.Linq;
using Google.Protobuf;
using SkyWalking.Config;
using SkyWalking.Transport;
using SkyWalking.Context.Ids;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Context.Trace
{
......@@ -30,12 +28,11 @@ namespace SkyWalking.Context.Trace
private readonly IList<ITraceSegmentRef> _refs;
private readonly IList<AbstractTracingSpan> _spans;
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 => RemoteDownstreamConfig.Agent.ApplicationInstanceId;
public int ApplicationInstanceId => RuntimeEnvironment.Instance.ApplicationInstanceId.Value;
public IEnumerable<ITraceSegmentRef> Refs => _refs;
......@@ -85,21 +82,21 @@ namespace SkyWalking.Context.Trace
_relatedGlobalTraces.Append(distributedTraceId);
}
public UpstreamSegment Transform()
public TraceSegmentRequest Transform()
{
var upstreamSegment = new UpstreamSegment();
upstreamSegment.GlobalTraceIds.AddRange(_relatedGlobalTraces.GetRelatedGlobalTraces()
.Select(x => x.ToUniqueId()));
var traceSegment = new TraceSegmentObject {TraceSegmentId = TraceSegmentId.Transform()};
traceSegment.Spans.AddRange(_spans.Select(x => x.Transform()));
traceSegment.ApplicationId = ApplicationId;
traceSegment.ApplicationInstanceId = ApplicationInstanceId;
traceSegment.IsSizeLimited = _isSizeLimited;
var upstreamSegment = new TraceSegmentRequest
{
UniqueIds = _relatedGlobalTraces.GetRelatedGlobalTraces()
.Select(x => x.ToUniqueId()).ToArray()
};
upstreamSegment.Segment = traceSegment.ToByteString();
upstreamSegment.Segment = new TraceSegmentObjectRequest
{
SegmentId = TraceSegmentId.Transform(),
Spans = _spans.Select(x => x.Transform()).ToArray(),
ApplicationId = ApplicationId,
ApplicationInstanceId = ApplicationInstanceId
};
return upstreamSegment;
}
......
......@@ -17,26 +17,25 @@
*/
using System.Linq;
using SkyWalking.Transport;
using SkyWalking.Config;
using SkyWalking.Context.Ids;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Context.Trace
{
public class TraceSegmentRef : ITraceSegmentRef
{
private SegmentRefType _type;
private ID _traceSegmentId;
private int _spanId = -1;
private int _peerId = DictionaryUtil.NullValue;
private string _peerHost;
private int _entryApplicationInstanceId = DictionaryUtil.NullValue;
private int _parentApplicationInstanceId = DictionaryUtil.NullValue;
private string _entryOperationName;
private int _entryOperationId = DictionaryUtil.NullValue;
private string _parentOperationName;
private int _parentOperationId = DictionaryUtil.NullValue;
private readonly SegmentRefType _type;
private readonly ID _traceSegmentId;
private readonly int _spanId = -1;
private readonly int _peerId = 0;
private readonly string _peerHost;
private readonly int _entryApplicationInstanceId = 0;
private readonly int _parentApplicationInstanceId = 0;
private readonly string _entryOperationName;
private readonly int _entryOperationId = 0;
private readonly string _parentOperationName;
private readonly int _parentOperationId = 0;
public TraceSegmentRef(IContextCarrier carrier)
{
......@@ -81,7 +80,7 @@ namespace SkyWalking.Context.Trace
_type = SegmentRefType.CrossThread;
_traceSegmentId = contextSnapshot.TraceSegmentId;
_spanId = contextSnapshot.SpanId;
_parentApplicationInstanceId = RemoteDownstreamConfig.Agent.ApplicationInstanceId;
_parentApplicationInstanceId = RuntimeEnvironment.Instance.ApplicationInstanceId.Value;
_entryApplicationInstanceId = contextSnapshot.EntryApplicationInstanceId;
string entryOperationName = contextSnapshot.EntryOperationName;
if (entryOperationName.First() == '#')
......@@ -148,45 +147,29 @@ namespace SkyWalking.Context.Trace
public int EntryApplicationInstanceId => _entryApplicationInstanceId;
public TraceSegmentReference Transform()
public TraceSegmentReferenceRequest Transform()
{
TraceSegmentReference traceSegmentReference = new TraceSegmentReference();
TraceSegmentReferenceRequest traceSegmentReference = new TraceSegmentReferenceRequest();
if (_type == SegmentRefType.CrossProcess)
{
traceSegmentReference.RefType = RefType.CrossProcess;
if (_peerId == DictionaryUtil.NullValue)
{
traceSegmentReference.NetworkAddress = _peerHost;
}
else
{
traceSegmentReference.NetworkAddressId = _peerId;
}
traceSegmentReference.RefType = (int) SegmentRefType.CrossProcess;
traceSegmentReference.NetworkAddress = new StringOrIntValue(_peerId, _peerHost);
}
else
{
traceSegmentReference.RefType = RefType.CrossThread;
traceSegmentReference.RefType = (int) SegmentRefType.CrossThread;
traceSegmentReference.NetworkAddress = new StringOrIntValue();
}
traceSegmentReference.ParentApplicationInstanceId = _parentApplicationInstanceId;
traceSegmentReference.EntryApplicationInstanceId = _entryApplicationInstanceId;
traceSegmentReference.ParentTraceSegmentId = _traceSegmentId.Transform();
traceSegmentReference.ParentSpanId = _spanId;
if (_entryOperationId == DictionaryUtil.NullValue)
{
traceSegmentReference.EntryServiceName = _entryOperationName;
}
else
{
traceSegmentReference.EntryServiceId = _entryOperationId;
}
if (_parentOperationId == DictionaryUtil.NullValue)
{
traceSegmentReference.ParentServiceName = _parentOperationName;
}
else
{
traceSegmentReference.ParentServiceId = _parentOperationId;
}
traceSegmentReference.EntryServiceName = new StringOrIntValue(_entryOperationId, _entryOperationName);
traceSegmentReference.ParentServiceName = new StringOrIntValue(_parentOperationId, _parentOperationName);
return traceSegmentReference;
}
}
......
......@@ -16,16 +16,14 @@
*
*/
using System;
namespace SkyWalking.Context
{
public class TraceContextCarrierItem : CarrierItem
{
private const string HEAD_NAME = "Trace-Context";
public TraceContextCarrierItem(String headValue, CarrierItem next)
: base(HEAD_NAME, headValue, next)
public TraceContextCarrierItem(string headValue, CarrierItem next, string @namespace)
: base(HEAD_NAME, headValue, next, @namespace)
{
}
}
......
......@@ -20,10 +20,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using SkyWalking.Boot;
using SkyWalking.Context.Trace;
using SkyWalking.Dictionarys;
using SkyWalking.Sampling;
using SkyWalking.Utils;
namespace SkyWalking.Context
......@@ -38,7 +35,7 @@ namespace SkyWalking.Context
public TracingContext()
{
_sampler = ServiceManager.Instance.GetService<SamplingService>();
_sampler = DefaultSampler.Instance;
_segment = new TraceSegment();
_activeSpanStacks = new Stack<ISpan>();
}
......@@ -62,7 +59,7 @@ namespace SkyWalking.Context
carrier.SpanId = span.SpanId;
carrier.ParentApplicationInstanceId = _segment.ApplicationInstanceId;
if (DictionaryUtil.IsNull(peerId))
if (peerId == 0)
{
carrier.PeerHost = peer;
}
......@@ -78,7 +75,7 @@ namespace SkyWalking.Context
carrier.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId;
if (DictionaryUtil.IsNull(metaValue.operationId))
if (metaValue.operationId == 0)
{
carrier.EntryOperationName = metaValue.operationName;
}
......@@ -88,7 +85,7 @@ namespace SkyWalking.Context
}
var parentOperationId = firstSpan.OperationId;
if (DictionaryUtil.IsNull(parentOperationId))
if (parentOperationId == 0)
{
carrier.ParentOperationName = firstSpan.OperationName;
}
......@@ -151,24 +148,13 @@ namespace SkyWalking.Context
var parentSpanId = parentSpan?.SpanId ?? -1;
if (parentSpan != null && parentSpan.IsEntry)
{
var entrySpan = (ISpan) DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName)
.InCondition(id =>
{
parentSpan.OperationId = id;
return parentSpan;
}, () =>
{
parentSpan.OperationName = operationName;
return parentSpan;
});
return entrySpan.Start();
return parentSpan.Start();
}
else
{
var entrySpan = (ISpan) DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName)
.InCondition(id => new EntrySpan(_spanIdGenerator++, parentSpanId, id),
() => new EntrySpan(_spanIdGenerator++, parentSpanId, operationName));
var entrySpan = new EntrySpan(_spanIdGenerator++, parentSpanId, operationName);
entrySpan.Start();
......@@ -192,10 +178,7 @@ namespace SkyWalking.Context
var parentSpanId = parentSpan?.SpanId ?? -1;
var span = (ISpan) DictionaryManager.OperationName
.FindOrPrepareForRegister(_segment.ApplicationId, operationName, false, false)
.InCondition(id => new LocalSpan(_spanIdGenerator++, parentSpanId, operationName),
() => new LocalSpan(_spanIdGenerator++, parentSpanId, operationName));
var span = new LocalSpan(_spanIdGenerator++, parentSpanId, operationName);
span.Start();
_activeSpanStacks.Push(span);
return span;
......@@ -214,30 +197,7 @@ namespace SkyWalking.Context
else
{
var parentSpanId = parentSpan?.SpanId ?? -1;
var exitSpan = (ISpan) DictionaryManager.NetworkAddress.Find(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));
});
var exitSpan = IsLimitMechanismWorking() ? (ISpan)new NoopExitSpan(remotePeer) : new ExitSpan(_spanIdGenerator++, parentSpanId, operationName, remotePeer);
_activeSpanStacks.Push(exitSpan);
return exitSpan.Start();
}
......@@ -263,7 +223,6 @@ namespace SkyWalking.Context
{
_activeSpanStacks.Pop();
}
}
else
{
......@@ -283,7 +242,7 @@ namespace SkyWalking.Context
if (!_segment.HasRef && _segment.IsSingleSpanSegment)
{
if (!_sampler.TrySampling())
if (!_sampler.Sampled())
{
finishedSegment.IsIgnore = true;
}
......@@ -321,7 +280,7 @@ namespace SkyWalking.Context
snapshot.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId;
if (DictionaryUtil.IsNull(metaValue.operationId))
if (metaValue.operationId == 0)
{
snapshot.EntryOperationName = metaValue.operationName;
}
......@@ -332,7 +291,7 @@ namespace SkyWalking.Context
var parentSpan = _activeSpanStacks.Last();
if (DictionaryUtil.IsNull(parentSpan.OperationId))
if (parentSpan.OperationId == 0)
{
snapshot.ParentOperationName = parentSpan.OperationName;
}
......@@ -362,7 +321,7 @@ namespace SkyWalking.Context
private bool IsLimitMechanismWorking()
{
if (_spanIdGenerator < Config.AgentConfig.SpanLimitPerSegment)
if (_spanIdGenerator < 300)
{
return false;
}
......
/*
/*
* 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.
......@@ -16,50 +16,48 @@
*
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using System.Runtime.CompilerServices;
using SkyWalking.Utils;
namespace SkyWalking.Sampling
namespace SkyWalking
{
// ReSharper disable once ClassNeverInstantiated.Global
public class SamplingService :TimerService, ISampler
public class DefaultSampler : ISampler
{
private readonly AtomicInteger _atomicInteger = new AtomicInteger();
private readonly int _sample_N_Per_3_Secs = AgentConfig.SamplePer3Secs;
private readonly bool _sample_on = AgentConfig.SamplePer3Secs > 0;
public static DefaultSampler Instance { get; } = new DefaultSampler();
public bool TrySampling()
private readonly AtomicInteger _idx = new AtomicInteger();
private int _samplePer3Secs;
private bool _sample_on;
public bool Sampled()
{
if (!_sample_on)
{
return true;
}
return _atomicInteger.Increment() < _sample_N_Per_3_Secs;
return _idx.Increment() < _samplePer3Secs;
}
public void ForceSampled()
{
if (_sample_on)
{
_atomicInteger.Increment();
_idx.Increment();
}
}
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(3);
protected override Task Execute(CancellationToken token)
[MethodImpl(MethodImplOptions.Synchronized)]
internal void SetSamplePer3Secs(int samplePer3Secs)
{
if (_sample_on)
{
_atomicInteger.Value = 0;
_samplePer3Secs = samplePer3Secs;
_sample_on = samplePer3Secs > -1;
}
return TaskUtils.CompletedTask;
internal void Reset()
{
_idx.Value = 0;
}
}
}
\ No newline at end of file
......@@ -25,14 +25,14 @@ namespace SkyWalking.Diagnostics
internal class TracingDiagnosticMethod
{
private readonly MethodInfo _method;
private readonly ITracingDiagnosticProcessor _diagnosticProcessor;
private readonly ITracingDiagnosticProcessor _tracingDiagnosticProcessor;
private readonly string _diagnosticName;
private readonly IParameterResolver[] _parameterResolvers;
public TracingDiagnosticMethod(ITracingDiagnosticProcessor diagnosticProcessor, MethodInfo method,
public TracingDiagnosticMethod(ITracingDiagnosticProcessor tracingDiagnosticProcessor, MethodInfo method,
string diagnosticName)
{
_diagnosticProcessor = diagnosticProcessor;
_tracingDiagnosticProcessor = tracingDiagnosticProcessor;
_method = method;
_diagnosticName = diagnosticName;
_parameterResolvers = GetParameterResolvers(method).ToArray();
......@@ -51,7 +51,7 @@ namespace SkyWalking.Diagnostics
args[i] = _parameterResolvers[i].Resolve(value);
}
_method.Invoke(_diagnosticProcessor, args);
_method.Invoke(_tracingDiagnosticProcessor, args);
}
private static IEnumerable<IParameterResolver> GetParameterResolvers(MethodInfo methodInfo)
......
......@@ -26,15 +26,15 @@ namespace SkyWalking.Diagnostics
{
private readonly List<TracingDiagnosticMethod> _methods;
public TracingDiagnosticMethodCollection(ITracingDiagnosticProcessor diagnosticProcessor)
public TracingDiagnosticMethodCollection(ITracingDiagnosticProcessor tracingDiagnosticProcessor)
{
_methods = new List<TracingDiagnosticMethod>();
foreach (var method in diagnosticProcessor.GetType().GetMethods())
foreach (var method in tracingDiagnosticProcessor.GetType().GetMethods())
{
var diagnosticName = method.GetCustomAttribute<DiagnosticName>();
if(diagnosticName==null)
continue;
_methods.Add(new TracingDiagnosticMethod(diagnosticProcessor, method, diagnosticName.Name));
_methods.Add(new TracingDiagnosticMethod(tracingDiagnosticProcessor, method, diagnosticName.Name));
}
}
......
......@@ -26,12 +26,12 @@ namespace SkyWalking.Diagnostics
{
public class TracingDiagnosticProcessorObserver : IObserver<DiagnosticListener>
{
private static readonly ILogger _logger = LogManager.GetLogger<TracingDiagnosticProcessorObserver>();
private readonly ILogger _logger;
private readonly IEnumerable<ITracingDiagnosticProcessor> _tracingDiagnosticProcessors;
public TracingDiagnosticProcessorObserver(IEnumerable<ITracingDiagnosticProcessor> tracingDiagnosticProcessors)
public TracingDiagnosticProcessorObserver(IEnumerable<ITracingDiagnosticProcessor> tracingDiagnosticProcessors, ILoggerFactory loggerFactory)
{
_logger = loggerFactory.CreateLogger(typeof(TracingDiagnosticProcessorObserver));
_tracingDiagnosticProcessors = tracingDiagnosticProcessors ??
throw new ArgumentNullException(nameof(tracingDiagnosticProcessors));
}
......@@ -51,16 +51,16 @@ namespace SkyWalking.Diagnostics
if (listener.Name == diagnosticProcessor.ListenerName)
{
Subscribe(listener, diagnosticProcessor);
_logger.Debug(
$"TracingDiagnosticObserver subscribe diagnosticListener named [{diagnosticProcessor.ListenerName}].");
_logger.Information(
$"Loaded diagnostic listener [{diagnosticProcessor.ListenerName}].");
}
}
}
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
{
}
public void Info(string message)
public void Information(string message)
{
}
......
......@@ -20,7 +20,7 @@ using System;
namespace SkyWalking.Logging
{
internal class NullLoggerFactory : ILoggerFactory
public class NullLoggerFactory : ILoggerFactory
{
public ILogger CreateLogger(Type type)
{
......
......@@ -16,31 +16,31 @@
*
*/
using Grpc.Core;
using SkyWalking.Utils;
namespace SkyWalking.Remote.Authentication
{
internal static class AuthenticationInterceptors
{
private const string header = "authentication";
public static AsyncAuthInterceptor CreateAuthInterceptor(string token)
{
return (context, metadata) =>
{
var entry = CreateTokenHeader(token);
if (entry != null)
{
metadata.Add(entry);
}
return TaskUtils.CompletedTask;
};
}
private static Metadata.Entry CreateTokenHeader(string token)
{
return string.IsNullOrEmpty(token) ? null : new Metadata.Entry(header, token);
}
}
}
//using Grpc.Core;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote.Authentication
//{
// internal static class AuthenticationInterceptors
// {
// private const string header = "authentication";
//
// public static AsyncAuthInterceptor CreateAuthInterceptor(string token)
// {
// return (context, metadata) =>
// {
// var entry = CreateTokenHeader(token);
// if (entry != null)
// {
// metadata.Add(entry);
// }
// return TaskUtils.CompletedTask;
// };
// }
//
// private static Metadata.Entry CreateTokenHeader(string token)
// {
// return string.IsNullOrEmpty(token) ? null : new Metadata.Entry(header, token);
// }
// }
//}
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Dictionarys;
using SkyWalking.Logging;
using SkyWalking.NetworkProtocol;
using SkyWalking.Utils;
namespace SkyWalking.Remote
{
public class GrpcApplicationService : TimerService
{
private static readonly ILogger _logger = LogManager.GetLogger<GrpcApplicationService>();
public override int Order { get; } = -1;
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15);
protected override async Task Execute(CancellationToken token)
{
if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) &&
!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
{
return;
}
if (string.IsNullOrEmpty(AgentConfig.ApplicationCode))
{
return;
}
if (!GrpcConnectionManager.Instance.Available)
{
return;
}
var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
if (availableConnection == null)
{
return;
}
try
{
await RegisterApplication(availableConnection, token);
await RegisterApplicationInstance(availableConnection, token);
}
catch (Exception exception)
{
_logger.Warning($"Register application fail. {exception.Message}");
availableConnection.Failure();
}
}
private async Task RegisterApplication(GrpcConnection availableConnection, CancellationToken token)
{
if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId))
{
var application = new Application {ApplicationCode = AgentConfig.ApplicationCode};
var applicationRegisterService =
new ApplicationRegisterService.ApplicationRegisterServiceClient(availableConnection.GrpcChannel);
var retry = 0;
var applicationId = 0;
while (retry++ < 3 && DictionaryUtil.IsNull(applicationId))
{
var applicationMapping = await applicationRegisterService.applicationCodeRegisterAsync(application);
applicationId = applicationMapping?.Application?.Value ?? 0;
if (!DictionaryUtil.IsNull(applicationId))
{
break;
}
await Task.Delay(500, token);
}
if (DictionaryUtil.IsNull(applicationId))
{
_logger.Warning(
"Register application fail. Server response null.");
return;
}
_logger.Info(
$"Register application success. [applicationCode] = {application.ApplicationCode}. [applicationId] = {applicationId}");
RemoteDownstreamConfig.Agent.ApplicationId = applicationId;
}
}
private async Task RegisterApplicationInstance(GrpcConnection availableConnection, CancellationToken token)
{
if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
{
var instanceDiscoveryService =
new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel);
var agentUUID = Guid.NewGuid().ToString("N");
var registerTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var hostName = Dns.GetHostName();
var osInfo = new OSInfo
{
Hostname = hostName,
OsName = PlatformInformation.GetOSName(),
ProcessNo = Process.GetCurrentProcess().Id
};
osInfo.Ipv4S.AddRange(GetIpV4S(hostName));
var applicationInstance = new ApplicationInstance
{
ApplicationId = RemoteDownstreamConfig.Agent.ApplicationId,
AgentUUID = agentUUID,
RegisterTime = registerTime,
Osinfo = osInfo
};
var retry = 0;
var applicationInstanceId = 0;
while (retry++ < 5 && DictionaryUtil.IsNull(applicationInstanceId))
{
var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance);
applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId;
if (!DictionaryUtil.IsNull(applicationInstanceId))
{
break;
}
await Task.Delay(500, token);
}
if (!DictionaryUtil.IsNull(applicationInstanceId))
{
RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId;
_logger.Info(
$"Register application instance success. [applicationInstanceId] = {applicationInstanceId}");
}
else
{
_logger.Warning(
"Register application instance fail. Server response null.");
}
}
}
private IEnumerable<string> GetIpV4S(string hostName)
{
try
{
var ipAddresses = Dns.GetHostAddresses(hostName);
var ipV4S = new List<string>();
foreach (var ipAddress in ipAddresses.Where(x => x.AddressFamily == AddressFamily.InterNetwork))
ipV4S.Add(ipAddress.ToString());
return ipV4S;
}
catch (Exception e)
{
_logger.Warning($"Get host addresses fail. {e.Message}");
return new string[0];
}
}
}
}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// */
//
//using System;
//using System.Collections.Generic;
//using System.Diagnostics;
//using System.Linq;
//using System.Net;
//using System.Net.Sockets;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//using SkyWalking.Config;
//using SkyWalking.Context;
//using SkyWalking.Dictionarys;
//using SkyWalking.Logging;
//using SkyWalking.NetworkProtocol;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcApplicationService : TimerService
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcApplicationService>();
// public override int Order { get; } = -1;
//
// protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15);
//
// protected override async Task Execute(CancellationToken token)
// {
// if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) &&
// !DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
// {
// return;
// }
//
// if (string.IsNullOrEmpty(AgentConfig.ApplicationCode))
// {
// return;
// }
//
// if (!GrpcConnectionManager.Instance.Available)
// {
// return;
// }
//
// var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
//
// if (availableConnection == null)
// {
// return;
// }
//
// try
// {
// await RegisterApplication(availableConnection, token);
// await RegisterApplicationInstance(availableConnection, token);
// }
// catch (Exception exception)
// {
// Logger.Warning($"Register application fail. {exception.Message}");
// availableConnection.Failure();
// }
// }
//
// private async Task RegisterApplication(GrpcConnection availableConnection, CancellationToken token)
// {
// if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId))
// {
// var application = new Application {ApplicationCode = AgentConfig.ApplicationCode};
// var applicationRegisterService =
// new ApplicationRegisterService.ApplicationRegisterServiceClient(availableConnection.GrpcChannel);
//
// var retry = 0;
// var applicationId = 0;
// while (retry++ < 3 && DictionaryUtil.IsNull(applicationId))
// {
// var applicationMapping = await applicationRegisterService.applicationCodeRegisterAsync(application);
// applicationId = applicationMapping?.Application?.Value ?? 0;
// if (!DictionaryUtil.IsNull(applicationId))
// {
// break;
// }
// await Task.Delay(500, token);
// }
//
// if (DictionaryUtil.IsNull(applicationId))
// {
// Logger.Warning(
// "Register application fail. Server response null.");
// return;
// }
//
// Logger.Information(
// $"Register application success. [applicationCode] = {application.ApplicationCode}. [applicationId] = {applicationId}");
// RemoteDownstreamConfig.Agent.ApplicationId = applicationId;
// }
// }
//
// private async Task RegisterApplicationInstance(GrpcConnection availableConnection, CancellationToken token)
// {
// if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
// {
// var instanceDiscoveryService =
// new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel);
//
// var agentUUID = Guid.NewGuid().ToString("N");
// var registerTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
//
// var hostName = Dns.GetHostName();
//
// var osInfo = new OSInfo
// {
// Hostname = hostName,
// OsName = PlatformInformation.GetOSName(),
// ProcessNo = Process.GetCurrentProcess().Id
// };
//
// osInfo.Ipv4S.AddRange(GetIpV4S(hostName));
//
// var applicationInstance = new ApplicationInstance
// {
// ApplicationId = RemoteDownstreamConfig.Agent.ApplicationId,
// AgentUUID = agentUUID,
// RegisterTime = registerTime,
// Osinfo = osInfo
// };
//
// var retry = 0;
// var applicationInstanceId = 0;
// while (retry++ < 5 && DictionaryUtil.IsNull(applicationInstanceId))
// {
// var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance);
// applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId;
// if (!DictionaryUtil.IsNull(applicationInstanceId))
// {
// break;
// }
//
// await Task.Delay(500, token);
// }
//
// if (!DictionaryUtil.IsNull(applicationInstanceId))
// {
// RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId;
// Logger.Information(
// $"Register application instance success. [applicationInstanceId] = {applicationInstanceId}");
// }
// else
// {
// Logger.Warning(
// "Register application instance fail. Server response null.");
// }
// }
// }
//
// private IEnumerable<string> GetIpV4S(string hostName)
// {
// try
// {
//
// var ipAddresses = Dns.GetHostAddresses(hostName);
// var ipV4S = new List<string>();
// foreach (var ipAddress in ipAddresses.Where(x => x.AddressFamily == AddressFamily.InterNetwork))
// ipV4S.Add(ipAddress.ToString());
// return ipV4S;
// }
// catch (Exception e)
// {
// Logger.Warning($"Get host addresses fail. {e.Message}");
// return new string[0];
// }
// }
// }
//}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using Grpc.Core;
using SkyWalking.Remote.Authentication;
namespace SkyWalking.Remote
{
internal class GrpcChannelBuilder
{
private string _token;
private string _server;
private string _rootCertificatePath;
public GrpcChannelBuilder WithAuthenticationToken(string token)
{
_token = token;
return this;
}
public GrpcChannelBuilder WithServer(string server)
{
_server = server;
return this;
}
public GrpcChannelBuilder WithCredential(string rootCertificatePath)
{
_rootCertificatePath = rootCertificatePath;
return this;
}
public Channel Build()
{
return new Channel(_server, GetCredentials());
}
private ChannelCredentials GetCredentials()
{
if (_rootCertificatePath != null)
{
var authInterceptor = AuthenticationInterceptors.CreateAuthInterceptor(_token);
return ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor(authInterceptor));
}
return ChannelCredentials.Insecure;
}
}
}
///*
// * Licensed to the OpenSkywalking under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// */
//
//using Grpc.Core;
//using SkyWalking.Remote.Authentication;
//
//namespace SkyWalking.Remote
//{
// internal class GrpcChannelBuilder
// {
// private string _token;
//
// private string _server;
//
// private string _rootCertificatePath;
//
// public GrpcChannelBuilder WithAuthenticationToken(string token)
// {
// _token = token;
// return this;
// }
//
// public GrpcChannelBuilder WithServer(string server)
// {
// _server = server;
// return this;
// }
//
// public GrpcChannelBuilder WithCredential(string rootCertificatePath)
// {
// _rootCertificatePath = rootCertificatePath;
// return this;
// }
//
// public Channel Build()
// {
// return new Channel(_server, GetCredentials());
// }
//
// private ChannelCredentials GetCredentials()
// {
// if (_rootCertificatePath != null)
// {
// var authInterceptor = AuthenticationInterceptors.CreateAuthInterceptor(_token);
// return ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor(authInterceptor));
// }
//
// return ChannelCredentials.Insecure;
// }
// }
//}
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Threading.Tasks;
using Grpc.Core;
using SkyWalking.Logging;
namespace SkyWalking.Remote
{
public class GrpcConnection
{
private static readonly ILogger _logger = LogManager.GetLogger<GrpcConnection>();
public Channel GrpcChannel { get; }
public GrpcConnectionState State { get; private set; } = GrpcConnectionState.Idle;
public string Server { get; }
public GrpcConnection(string server, string rootCertificatePath = null, string token = null)
{
Server = server;
GrpcChannel = new GrpcChannelBuilder()
.WithServer(server)
.WithCredential(rootCertificatePath)
.WithAuthenticationToken(token)
.Build();
}
public async Task<bool> ConnectAsync(TimeSpan timeout)
{
if (State == GrpcConnectionState.Ready)
{
return true;
}
State = GrpcConnectionState.Connecting;
try
{
var deadLine = DateTime.UtcNow.AddSeconds(timeout.TotalSeconds);
await GrpcChannel.ConnectAsync(deadLine);
State = GrpcConnectionState.Ready;
_logger.Info($"Grpc channel connect success. [Server] = {GrpcChannel.Target}");
}
catch (TaskCanceledException ex)
{
State = GrpcConnectionState.Failure;
_logger.Warning($"Grpc channel connect timeout. {ex.Message}");
}
catch (Exception ex)
{
State = GrpcConnectionState.Failure;
_logger.Warning($"Grpc channel connect fail. {ex.Message}");
}
return State == GrpcConnectionState.Ready;
}
public async Task ShutdowmAsync()
{
try
{
await GrpcChannel.ShutdownAsync();
}
catch (Exception e)
{
_logger.Debug($"Grpc channel shutdown fail. {e.Message}");
}
finally
{
State = GrpcConnectionState.Shutdown;
}
}
public bool CheckState()
{
return State == GrpcConnectionState.Ready && GrpcChannel.State == ChannelState.Ready;
}
public void Failure()
{
var currentState = State;
if (GrpcConnectionState.Ready == currentState)
{
_logger.Debug($"Grpc channel state changed. {State} -> {GrpcChannel.State}");
}
State = GrpcConnectionState.Failure;
}
}
}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// */
//
//using System;
//using System.Threading.Tasks;
//using Grpc.Core;
//using SkyWalking.Logging;
//
//namespace SkyWalking.Remote
//{
// public class GrpcConnection
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcConnection>();
//
// public Channel GrpcChannel { get; }
//
// public GrpcConnectionState State { get; private set; } = GrpcConnectionState.Idle;
//
// public string Server { get; }
//
// public GrpcConnection(string server, string rootCertificatePath = null, string token = null)
// {
// Server = server;
// GrpcChannel = new GrpcChannelBuilder()
// .WithServer(server)
// .WithCredential(rootCertificatePath)
// .WithAuthenticationToken(token)
// .Build();
// }
//
// public async Task<bool> ConnectAsync(TimeSpan timeout)
// {
// if (State == GrpcConnectionState.Ready)
// {
// return true;
// }
// State = GrpcConnectionState.Connecting;
// try
// {
// var deadLine = DateTime.UtcNow.AddSeconds(timeout.TotalSeconds);
// await GrpcChannel.ConnectAsync(deadLine);
// State = GrpcConnectionState.Ready;
// Logger.Information($"Grpc channel connect success. [Server] = {GrpcChannel.Target}");
// }
// catch (TaskCanceledException ex)
// {
// State = GrpcConnectionState.Failure;
// Logger.Warning($"Grpc channel connect timeout. {ex.Message}");
// }
// catch (Exception ex)
// {
// State = GrpcConnectionState.Failure;
// Logger.Warning($"Grpc channel connect fail. {ex.Message}");
// }
//
// return State == GrpcConnectionState.Ready;
// }
//
// public async Task ShutdowmAsync()
// {
// try
// {
// await GrpcChannel.ShutdownAsync();
// }
// catch (Exception e)
// {
// Logger.Debug($"Grpc channel shutdown fail. {e.Message}");
// }
// finally
// {
// State = GrpcConnectionState.Shutdown;
// }
// }
//
// public bool CheckState()
// {
// return State == GrpcConnectionState.Ready && GrpcChannel.State == ChannelState.Ready;
// }
//
// public void Failure()
// {
// var currentState = State;
//
// if (GrpcConnectionState.Ready == currentState)
// {
// Logger.Debug($"Grpc channel state changed. {State} -> {GrpcChannel.State}");
// }
//
// State = GrpcConnectionState.Failure;
// }
// }
//}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Linq;
using System.Threading.Tasks;
using SkyWalking.Config;
using SkyWalking.Logging;
using SkyWalking.Utils;
namespace SkyWalking.Remote
{
public class GrpcConnectionManager
{
private static readonly ILogger _logger = LogManager.GetLogger<GrpcConnectionManager>();
public const string NotFoundErrorMessage = "Not found available connection.";
public static GrpcConnectionManager Instance { get; } = new GrpcConnectionManager();
private readonly Random _random = new Random();
private readonly AsyncLock _lock = new AsyncLock();
private GrpcConnection _connection;
public bool Available => _connection != null && _connection.CheckState();
private GrpcConnectionManager()
{
}
public async Task ConnectAsync(TimeSpan timeout)
{
// using async lock
using (await _lock.LockAsync())
{
if (_connection != null && _connection.CheckState())
{
return;
}
if (_connection != null && !_connection.CheckState())
{
await _connection.ShutdowmAsync();
}
var metadata = GetServerMetadata(_connection?.Server);
_connection = new GrpcConnection(metadata.Address, metadata.CertificatePath, metadata.Token);
await _connection.ConnectAsync(timeout);
}
}
public async Task ShutdownAsync()
{
await _connection?.ShutdowmAsync();
}
public GrpcConnection GetAvailableConnection()
{
var connection = _connection;
if (connection == null || connection.State != GrpcConnectionState.Ready)
{
_logger.Debug(NotFoundErrorMessage);
return null;
}
return connection;
}
private ServerMetadata GetServerMetadata(string currentServer)
{
return new ServerMetadata(GetServerAddress(currentServer),
CollectorConfig.CertificatePath, CollectorConfig.Authentication);
}
private string GetServerAddress(string currentServer)
{
var servers = RemoteDownstreamConfig.Collector.gRPCServers.Distinct().ToArray();
if (servers.Length == 1)
{
return servers[0];
}
if (currentServer != null)
{
servers = servers.Where(x => x != currentServer).ToArray();
}
var index = _random.Next() % servers.Length;
return servers[index];
}
public struct ServerMetadata
{
public string Address { get; }
public string Token { get; }
public string CertificatePath { get; }
public ServerMetadata(string address, string certificate, string token)
{
Address = address;
CertificatePath = certificate;
Token = token;
}
}
}
}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// */
//
//using System;
//using System.Linq;
//using System.Threading.Tasks;
//using SkyWalking.Config;
//using SkyWalking.Logging;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcConnectionManager
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcConnectionManager>();
//
// public const string NotFoundErrorMessage = "Not found available connection.";
//
// public static GrpcConnectionManager Instance { get; } = new GrpcConnectionManager();
//
// private readonly Random _random = new Random();
// private readonly AsyncLock _lock = new AsyncLock();
// private GrpcConnection _connection;
//
// public bool Available => _connection != null && _connection.CheckState();
//
// private GrpcConnectionManager()
// {
// }
//
// public async Task ConnectAsync(TimeSpan timeout)
// {
// // using async lock
// using (await _lock.LockAsync())
// {
// if (_connection != null && _connection.CheckState())
// {
// return;
// }
//
// if (_connection != null && !_connection.CheckState())
// {
// await _connection.ShutdowmAsync();
// }
//
// var metadata = GetServerMetadata(_connection?.Server);
// _connection = new GrpcConnection(metadata.Address, metadata.CertificatePath, metadata.Token);
// await _connection.ConnectAsync(timeout);
// }
// }
//
// public async Task ShutdownAsync()
// {
// await _connection?.ShutdowmAsync();
// }
//
// public GrpcConnection GetAvailableConnection()
// {
// var connection = _connection;
// if (connection == null || connection.State != GrpcConnectionState.Ready)
// {
// Logger.Debug(NotFoundErrorMessage);
// return null;
// }
//
// return connection;
// }
//
// private ServerMetadata GetServerMetadata(string currentServer)
// {
// return new ServerMetadata(GetServerAddress(currentServer),
// CollectorConfig.CertificatePath, CollectorConfig.Authentication);
// }
//
// private string GetServerAddress(string currentServer)
// {
// var servers = RemoteDownstreamConfig.Collector.gRPCServers.Distinct().ToArray();
// if (servers.Length == 1)
// {
// return servers[0];
// }
//
// if (currentServer != null)
// {
// servers = servers.Where(x => x != currentServer).ToArray();
// }
//
// var index = _random.Next() % servers.Length;
// return servers[index];
// }
//
// public struct ServerMetadata
// {
// public string Address { get; }
//
// public string Token { get; }
//
// public string CertificatePath { get; }
//
// public ServerMetadata(string address, string certificate, string token)
// {
// Address = address;
// CertificatePath = certificate;
// Token = token;
// }
// }
// }
//}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
namespace SkyWalking.Remote
{
public class GrpcConnectionService : TimerService
{
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15);
protected override async Task Execute(CancellationToken token)
{
if (!GrpcConnectionManager.Instance.Available)
{
// default timeout = 5s
await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(5));
}
}
}
}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// */
//
//using System;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//
//namespace SkyWalking.Remote
//{
// public class GrpcConnectionService : TimerService
// {
// protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15);
//
// protected override async Task Execute(CancellationToken token)
// {
// if (!GrpcConnectionManager.Instance.Available)
// {
// // default timeout = 5s
// await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(5));
// }
// }
// }
//}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace SkyWalking.Remote
{
public enum GrpcConnectionState
{
Idle,
Connecting,
Ready,
Failure,
Shutdown
}
}
///*
// * Licensed to the OpenSkywalking under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// */
//
//namespace SkyWalking.Remote
//{
// public enum GrpcConnectionState
// {
// Idle,
// Connecting,
// Ready,
// Failure,
// Shutdown
// }
//}
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Dictionarys;
using SkyWalking.Logging;
using SkyWalking.NetworkProtocol;
using SkyWalking.Utils;
namespace SkyWalking.Remote
{
public class GrpcHeartbeatService : TimerService
{
private static readonly ILogger _logger = LogManager.GetLogger<GrpcHeartbeatService>();
protected override TimeSpan Interval { get; } = TimeSpan.FromMinutes(1);
protected override async Task Starting(CancellationToken token)
{
await Task.Delay(TimeSpan.FromMinutes(1), token);
}
protected override async Task Execute(CancellationToken token)
{
if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
{
_logger.Debug($"{DateTime.Now} Heartbeat fail. Application instance is not registered.");
return;
}
var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
if (availableConnection == null)
{
_logger.Debug($"{DateTime.Now} Heartbeat fail. {GrpcConnectionManager.NotFoundErrorMessage}");
return;
}
try
{
var instanceDiscoveryService =
new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel);
var heartbeat = new ApplicationInstanceHeartbeat
{
ApplicationInstanceId = RemoteDownstreamConfig.Agent.ApplicationInstanceId,
HeartbeatTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
};
await instanceDiscoveryService.heartbeatAsync(heartbeat);
_logger.Debug($"{DateTime.Now} Heartbeat.");
}
catch (Exception e)
{
_logger.Debug($"{DateTime.Now} Heartbeat fail. {e.Message}");
availableConnection.Failure();
}
}
}
}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// */
//
//using System;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//using SkyWalking.Config;
//using SkyWalking.Dictionarys;
//using SkyWalking.Logging;
//using SkyWalking.NetworkProtocol;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcHeartbeatService : TimerService
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcHeartbeatService>();
// protected override TimeSpan Interval { get; } = TimeSpan.FromMinutes(1);
//
// protected override async Task Starting(CancellationToken token)
// {
// await Task.Delay(TimeSpan.FromMinutes(1), token);
// }
//
// protected override async Task Execute(CancellationToken token)
// {
// if (DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
// {
// Logger.Debug($"{DateTime.Now} Heartbeat fail. Application instance is not registered.");
// return;
// }
//
// var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
//
// if (availableConnection == null)
// {
// Logger.Debug($"{DateTime.Now} Heartbeat fail. {GrpcConnectionManager.NotFoundErrorMessage}");
// return;
// }
//
// try
// {
// var instanceDiscoveryService =
// new InstanceDiscoveryService.InstanceDiscoveryServiceClient(availableConnection.GrpcChannel);
//
// var heartbeat = new ApplicationInstanceHeartbeat
// {
// ApplicationInstanceId = RemoteDownstreamConfig.Agent.ApplicationInstanceId,
// HeartbeatTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
// };
//
// await instanceDiscoveryService.heartbeatAsync(heartbeat);
//
// Logger.Debug($"{DateTime.Now} Heartbeat.");
// }
// catch (Exception e)
// {
// Logger.Debug($"{DateTime.Now} Heartbeat fail. {e.Message}");
// availableConnection.Failure();
// }
// }
// }
//}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Utils;
namespace SkyWalking.Remote
{
public class GrpcRuntimeService : TimerService
{
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(120);
protected override Task Execute(CancellationToken token)
{
// todo
return TaskUtils.CompletedTask;
}
}
}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// */
//
//using System;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcRuntimeService : TimerService
// {
// protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(120);
//
// protected override Task Execute(CancellationToken token)
// {
// // todo
// return TaskUtils.CompletedTask;
// }
// }
//}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Context.Trace;
using SkyWalking.Logging;
using SkyWalking.NetworkProtocol;
using SkyWalking.Utils;
namespace SkyWalking.Remote
{
public class GrpcTraceSegmentService : TimerService, ITracingContextListener
{
private static readonly ILogger _logger = LogManager.GetLogger<GrpcTraceSegmentService>();
private static readonly ConcurrentQueue<ITraceSegment> _traceSegments
= new ConcurrentQueue<ITraceSegment>();
public override void Dispose()
{
TracingContext.ListenerManager.Remove(this);
if (_traceSegments.Count > 0)
{
BatchSendTraceSegments().ConfigureAwait(false).GetAwaiter().GetResult();
}
base.Dispose();
}
public override int Order { get; } = 1;
protected override TimeSpan Interval => TimeSpan.FromSeconds(1);
protected override Task Initializing(CancellationToken token)
{
TracingContext.ListenerManager.Add(this);
return base.Initializing(token);
}
public void AfterFinished(ITraceSegment traceSegment)
{
if (traceSegment.IsIgnore)
{
return;
}
if (_traceSegments.Count >= AgentConfig.PendingSegmentsLimit && AgentConfig.PendingSegmentsLimit > 0)
{
_traceSegments.TryDequeue(out var v);
}
_traceSegments.Enqueue(traceSegment);
}
protected async override Task Execute(CancellationToken token)
{
await BatchSendTraceSegments();
}
private async Task BatchSendTraceSegments()
{
if (_traceSegments.Count == 0)
return;
var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
if (availableConnection == null)
{
_logger.Warning(
$"Transform and send UpstreamSegment to collector fail. {GrpcConnectionManager.NotFoundErrorMessage}");
return;
}
try
{
var traceSegmentService =
new TraceSegmentService.TraceSegmentServiceClient(availableConnection.GrpcChannel);
using (var asyncClientStreamingCall = traceSegmentService.collect())
{
while (_traceSegments.TryDequeue(out var segment))
{
await asyncClientStreamingCall.RequestStream.WriteAsync(segment.Transform());
_logger.Debug(
$"Transform and send UpstreamSegment to collector. [TraceSegmentId] = {segment.TraceSegmentId} [GlobalTraceId] = {segment.RelatedGlobalTraces.FirstOrDefault()}");
}
await asyncClientStreamingCall.RequestStream.CompleteAsync();
await asyncClientStreamingCall.ResponseAsync;
}
}
catch (Exception e)
{
_logger.Warning($"Transform and send UpstreamSegment to collector fail. {e.Message}");
availableConnection?.Failure();
return;
}
}
}
}
\ No newline at end of file
///*
// * Licensed to the OpenSkywalking under one or more
// * contributor license agreements. See the NOTICE file distributed with
// * this work for additional information regarding copyright ownership.
// * The ASF licenses this file to You under the Apache License, Version 2.0
// * (the "License"); you may not use this file except in compliance with
// * the License. You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// *
// */
//
//using System;
//using System.Collections.Concurrent;
//using System.Collections.Generic;
//using System.Linq;
//using System.Threading;
//using System.Threading.Tasks;
//using SkyWalking.Boot;
//using SkyWalking.Config;
//using SkyWalking.Context;
//using SkyWalking.Context.Trace;
//using SkyWalking.Logging;
//using SkyWalking.NetworkProtocol;
//using SkyWalking.Utils;
//
//namespace SkyWalking.Remote
//{
// public class GrpcTraceSegmentService : TimerService, ITracingContextListener
// {
// private static readonly ILogger Logger = LogManager.GetLogger<GrpcTraceSegmentService>();
// private static readonly ConcurrentQueue<ITraceSegment> _traceSegments
// = new ConcurrentQueue<ITraceSegment>();
//
// public override void Dispose()
// {
// TracingContext.ListenerManager.Remove(this);
// if (_traceSegments.Count > 0)
// {
// BatchSendTraceSegments().ConfigureAwait(false).GetAwaiter().GetResult();
// }
// base.Dispose();
// }
//
// public override int Order { get; } = 1;
//
// protected override TimeSpan Interval => TimeSpan.FromSeconds(1);
//
// protected override Task Initializing(CancellationToken token)
// {
// TracingContext.ListenerManager.Add(this);
// return base.Initializing(token);
// }
//
// public void AfterFinished(ITraceSegment traceSegment)
// {
// if (traceSegment.IsIgnore)
// {
// return;
// }
//
// if (_traceSegments.Count >= AgentConfig.PendingSegmentLimit && AgentConfig.PendingSegmentLimit > 0)
// {
// _traceSegments.TryDequeue(out var v);
// }
// _traceSegments.Enqueue(traceSegment);
// }
//
// protected override async Task Execute(CancellationToken token)
// {
// await BatchSendTraceSegments();
// }
//
// private async Task BatchSendTraceSegments()
// {
// if (_traceSegments.Count == 0)
// return;
//
// var availableConnection = GrpcConnectionManager.Instance.GetAvailableConnection();
// if (availableConnection == null)
// {
// Logger.Warning(
// $"Transform and send UpstreamSegment to collector fail. {GrpcConnectionManager.NotFoundErrorMessage}");
// return;
// }
//
// try
// {
// var traceSegmentService =
// new TraceSegmentService.TraceSegmentServiceClient(availableConnection.GrpcChannel);
// using (var asyncClientStreamingCall = traceSegmentService.collect())
// {
// while (_traceSegments.TryDequeue(out var segment))
// {
// await asyncClientStreamingCall.RequestStream.WriteAsync(segment.Transform());
// Logger.Debug(
// $"Transform and send UpstreamSegment to collector. [TraceSegmentId] = {segment.TraceSegmentId} [GlobalTraceId] = {segment.RelatedGlobalTraces.FirstOrDefault()}");
// }
// await asyncClientStreamingCall.RequestStream.CompleteAsync();
// await asyncClientStreamingCall.ResponseAsync;
// }
// }
// catch (Exception e)
// {
// Logger.Warning($"Transform and send UpstreamSegment to collector fail. {e.Message}");
// availableConnection?.Failure();
// return;
// }
// }
// }
//}
\ No newline at end of file
/*
* 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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -17,47 +17,33 @@
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Config;
using SkyWalking.Logging;
namespace SkyWalking.AspNet.Logging
namespace SkyWalking.Service
{
internal class DebugLoggerAdapter : ILogger
public class SamplingRefreshService : ExecutionService
{
private readonly Type type;
private readonly SamplingConfig _config;
public DebugLoggerAdapter(Type type)
public SamplingRefreshService(IConfigAccessor configAccessor, ISkyWalkingClient skyWalking,
IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
: base(skyWalking, runtimeEnvironment, loggerFactory)
{
this.type = type;
_config = configAccessor.Get<SamplingConfig>();
DefaultSampler.Instance.SetSamplePer3Secs(_config.SamplePer3Secs);
}
public void Debug(string message)
{
WriteLine("debug", message);
}
protected override TimeSpan DueTime { get; } = TimeSpan.Zero;
public void Info(string message)
{
WriteLine("info", message);
}
public void Warning(string message)
{
WriteLine("warn", message);
}
public void Error(string message, Exception exception)
{
WriteLine("error", message + Environment.NewLine + exception);
}
public void Trace(string message)
{
WriteLine("trace", message);
}
protected override TimeSpan Period { get; } = TimeSpan.FromSeconds(3);
private void WriteLine(string level, string message)
protected override Task ExecuteAsync(CancellationToken cancellationToken)
{
System.Diagnostics.Debug.WriteLine($"{DateTime.Now} : [{level}] [{type.Name}] {message}");
DefaultSampler.Instance.Reset();
return Task.CompletedTask;
}
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -19,55 +19,49 @@
using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Context.Trace;
using SkyWalking.Logging;
using SkyWalking.Utils;
using SkyWalking.Transport;
namespace SkyWalking.Boot
namespace SkyWalking.Service
{
public abstract class TimerService : IBootService
public class TraceSegmentTransportService : ExecutionService, ITracingContextListener
{
private static readonly ILogger _logger = LogManager.GetLogger<TimerService>();
protected abstract TimeSpan Interval { get; }
private Task _task;
private readonly TransportConfig _config;
private readonly ITraceDispatcher _dispatcher;
public virtual void Dispose()
public TraceSegmentTransportService(IConfigAccessor configAccessor, ITraceDispatcher dispatcher,
ISkyWalkingClient skyWalking, IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
: base(skyWalking, runtimeEnvironment, loggerFactory)
{
_dispatcher = dispatcher;
_config = configAccessor.Get<TransportConfig>();
Period = TimeSpan.FromMilliseconds(_config.Interval);
TracingContext.ListenerManager.Add(this);
}
public virtual int Order { get; } = 2;
protected override TimeSpan DueTime { get; } = TimeSpan.FromSeconds(3);
public async Task Initialize(CancellationToken token)
{
await Initializing(token);
_task = Task.Factory.StartNew(async () =>
{
await Starting(token);
while (true)
{
try
{
await Execute(token);
}
catch (Exception e)
protected override TimeSpan Period { get; }
protected override Task ExecuteAsync(CancellationToken cancellationToken)
{
_logger.Error($"{GetType().Name} execute fail.", e);
}
await Task.Delay(Interval, token);
}
},
token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
return _dispatcher.Flush(cancellationToken);
}
protected virtual Task Initializing(CancellationToken token)
protected override Task Stopping(CancellationToken cancellationToke)
{
return TaskUtils.CompletedTask;
_dispatcher.Close();
TracingContext.ListenerManager.Remove(this);
return Task.CompletedTask;
}
protected virtual Task Starting(CancellationToken token)
public void AfterFinished(ITraceSegment traceSegment)
{
return TaskUtils.CompletedTask;
if (!traceSegment.IsIgnore)
_dispatcher.Dispatch(traceSegment.Transform());
}
protected abstract Task Execute(CancellationToken token);
}
}
\ No newline at end of file
......@@ -3,22 +3,19 @@
<PropertyGroup>
<Description>SkyWalking core components.</Description>
<AssemblyTitle>SkyWalking.Core</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net45;net451</TargetFrameworks>
<AssemblyName>SkyWalking.Core</AssemblyName>
<PackageId>SkyWalking.Core</PackageId>
<PackageTags>SkyWalking;APM</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
<RootNamespace>SkyWalking</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<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>
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.4.1" />
<PackageReference Include="System.Runtime.InteropServices.RuntimeInformation" Version="4.3.0" />
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.5.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup>
</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.
......@@ -17,80 +17,58 @@
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
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.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;
public SkyWalkingHostedService(IOptions<SkyWalkingOptions> options, IHostingEnvironment hostingEnvironment,
TracingDiagnosticProcessorObserver diagnosticObserver, ILoggerFactory loggerFactory)
public SkyWalkingAgentStartup(TracingDiagnosticProcessorObserver observer, IEnumerable<IExecutionService> services, ILoggerFactory loggerFactory)
{
if (string.IsNullOrEmpty(options.Value.DirectServers))
{
throw new ArgumentException("DirectServers cannot be empty or null.");
_observer = observer;
_services = services;
_logger = loggerFactory.CreateLogger(typeof(SkyWalkingAgentStartup));
}
if (string.IsNullOrEmpty(options.Value.ApplicationCode))
public async Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
{
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;
_logger.Information(Welcome());
foreach (var service in _services)
await service.StartAsync(cancellationToken);
DiagnosticListener.AllListeners.Subscribe(_observer);
_logger.Information("Started SkyWalking .NET Core Agent.");
}
public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.Info("SkyWalking Agent starting...");
try
{
DiagnosticListener.AllListeners.Subscribe(_diagnosticObserver);
await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(3));
await ServiceManager.Instance.Initialize();
_logger.Info("SkyWalking Agent started.");
}
catch (Exception e)
public async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken))
{
_logger.Error("SkyWalking Agent start fail.", e);
}
foreach (var service in _services)
await service.StopAsync(cancellationToken);
_logger.Information("Stopped SkyWalking .NET Core Agent.");
// ReSharper disable once MethodSupportsCancellation
await Task.Delay(TimeSpan.FromSeconds(2));
}
public async Task StopAsync(CancellationToken cancellationToken)
{
_logger.Info("SkyWalking Agent stopping...");
try
{
ServiceManager.Instance.Dispose();
await GrpcConnectionManager.Instance.ShutdownAsync();
_logger.Info("SkyWalking Agent stopped.");
}
catch (Exception e)
private string Welcome()
{
_logger.Error("SkyWalking Agent stop fail.", e);
}
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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -16,85 +16,68 @@
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Config;
using SkyWalking.Logging;
namespace SkyWalking.Boot
namespace SkyWalking.Transport
{
public class ServiceManager : IDisposable
public class AsyncQueueTraceDispatcher : ITraceDispatcher
{
private static readonly ILogger _logger = LogManager.GetLogger<ServiceManager>();
private static readonly ServiceManager _instance = new ServiceManager();
private readonly ILogger _logger;
private readonly TransportConfig _config;
private readonly ISkyWalkingClient _skyWalkingClient;
private readonly ConcurrentQueue<TraceSegmentRequest> _segmentQueue;
private readonly CancellationTokenSource _cancellation;
public static ServiceManager Instance => _instance;
private readonly Dictionary<Type, object> _services = new Dictionary<Type, object>();
private readonly CancellationTokenSource _tokenSource = new CancellationTokenSource();
private ServiceManager()
public AsyncQueueTraceDispatcher(IConfigAccessor configAccessor, ISkyWalkingClient client, ILoggerFactory loggerFactory)
{
_skyWalkingClient = client;
_logger = loggerFactory.CreateLogger(typeof(AsyncQueueTraceDispatcher));
_config = configAccessor.Get<TransportConfig>();
_segmentQueue = new ConcurrentQueue<TraceSegmentRequest>();
_cancellation = new CancellationTokenSource();
}
private Type[] FindServiceTypes()
public bool Dispatch(TraceSegmentRequest segment)
{
return typeof(ServiceManager).Assembly.GetTypes().Where(x =>
x.IsClass && !x.IsAbstract && typeof(IBootService).IsAssignableFrom(x))
.ToArray();
}
public object GetService(Type serviceType)
// todo performance optimization for ConcurrentQueue
if (_config.PendingSegmentLimit < _segmentQueue.Count || _cancellation.IsCancellationRequested)
{
_services.TryGetValue(serviceType, out var instance);
return instance;
return false;
}
public T GetService<T>()
{
return (T) GetService(typeof(T));
}
_segmentQueue.Enqueue(segment);
public async Task Initialize()
{
var types = FindServiceTypes();
_logger.Debug($"Dispatch trace segment. [SegmentId]={segment.Segment.SegmentId}.");
return true;
}
foreach (var service in types.Select(Activator.CreateInstance).OfType<IBootService>().OrderBy(x => x.Order))
{
try
public Task Flush(CancellationToken token = default(CancellationToken))
{
await service.Initialize(_tokenSource.Token);
_services.Add(service.GetType(), service);
_logger.Debug($"ServiceManager loaded {service.GetType()}.");
}
catch (Exception e)
// todo performance optimization for ConcurrentQueue
//var queued = _segmentQueue.Count;
//var limit = queued <= _config.PendingSegmentLimit ? queued : _config.PendingSegmentLimit;
var limit = _config.PendingSegmentLimit;
var index = 0;
var segments = new List<TraceSegmentRequest>(limit);
while (index++ < limit && _segmentQueue.TryDequeue(out var request))
{
_logger.Error($"ServiceManager loaded {service.GetType()} fail.",e);
}
}
segments.Add(request);
}
[MethodImpl(MethodImplOptions.Synchronized)]
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()}.");
// send async
if (segments.Count > 0)
_skyWalkingClient.CollectAsync(segments, token);
return Task.CompletedTask;
}
catch (Exception e)
public void Close()
{
_logger.Error($"ServiceManager dispose {item.GetType()} fail.", e);
}
}
_tokenSource.Dispose();
_cancellation.Cancel();
}
}
}
\ 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;
namespace SkyWalking.Utils
{
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>();
foreach (var item in source)
......
......@@ -23,7 +23,7 @@ namespace SkyWalking.Utils
return OSX;
}
return "Unknow";
return "Unknown";
}
}
}
......@@ -21,25 +21,34 @@ using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Mvc.Abstractions;
using SkyWalking.Components;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.Diagnostics;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.AspNetCore.Diagnostics
{
public class HostingDiagnosticProcessor : ITracingDiagnosticProcessor
public class HostingTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{
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")]
public void BeginRequest([Property] HttpContext httpContext)
{
var carrier = new ContextCarrier();
var carrier = _contextCarrierFactory.Create();
foreach (var item in carrier.Items)
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.SetComponent(ComponentsDefine.AspNetCore);
Tags.Url.Set(httpRequestSpan, httpContext.Request.Path);
......@@ -90,7 +99,7 @@ namespace SkyWalking.AspNetCore.Diagnostics
ContextManager.ActiveSpan?.ErrorOccurred()?.Log(exception);
}
[DiagnosticName("Microsoft.AspNetCore.Mvc.BeforeAction")]
//[DiagnosticName("Microsoft.AspNetCore.Mvc.BeforeAction")]
public void BeforeAction([Property]ActionDescriptor actionDescriptor, [Property]HttpContext httpContext)
{
var span = httpContext.Items[HttpContextDiagnosticStrings.SpanKey] as ISpan;
......@@ -103,7 +112,7 @@ namespace SkyWalking.AspNetCore.Diagnostics
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)
{
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 @@
using System;
using DotNetCore.CAP.Diagnostics;
using DotNetCore.CAP.Infrastructure;
using SkyWalking.Components;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
using CapEvents = DotNetCore.CAP.Diagnostics.CapDiagnosticListenerExtensions;
......@@ -31,8 +31,9 @@ namespace SkyWalking.Diagnostics.CAP
/// <summary>
/// Diagnostics processor for listen and process releted events of CAP.
/// </summary>
public class CapDiagnosticProcessor : ITracingDiagnosticProcessor
public class CapTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{
private readonly IContextCarrierFactory _contextCarrierFactory;
private Func<BrokerEventData, string> _brokerOperationNameResolver;
public string ListenerName => CapEvents.DiagnosticListenerName;
......@@ -47,11 +48,16 @@ namespace SkyWalking.Diagnostics.CAP
set => _brokerOperationNameResolver = value ?? throw new ArgumentNullException(nameof(BrokerOperationNameResolver));
}
public CapTracingDiagnosticProcessor(IContextCarrierFactory contextCarrierFactory)
{
_contextCarrierFactory = contextCarrierFactory;
}
[DiagnosticName(CapEvents.CapBeforePublish)]
public void CapBeforePublish([Object]BrokerPublishEventData eventData)
{
var operationName = BrokerOperationNameResolver(eventData);
var contextCarrier = new ContextCarrier();
var contextCarrier = _contextCarrierFactory.Create();
var peer = eventData.BrokerAddress;
var span = ContextManager.CreateExitSpan(operationName, contextCarrier, peer);
span.SetComponent(ComponentsDefine.CAP);
......@@ -86,7 +92,7 @@ namespace SkyWalking.Diagnostics.CAP
public void CapBeforeConsume([Object]BrokerConsumeEventData eventData)
{
var operationName = BrokerOperationNameResolver(eventData);
var carrier = new ContextCarrier();
var carrier = _contextCarrierFactory.Create();
if (Helper.TryExtractTracingHeaders(eventData.BrokerTopicBody, out var headers,
out var removedHeadersJson))
......
......@@ -22,7 +22,7 @@
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.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>
</Project>
......@@ -18,22 +18,22 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Extensions.DependencyInjection;
using SkyWalking.Utilities.DependencyInjection;
namespace SkyWalking.Diagnostics.CAP
{
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 @@
using System.Data.Common;
using Npgsql;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Components;
namespace SkyWalking.Diagnostics.EntityFrameworkCore
{
......
......@@ -15,7 +15,7 @@
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.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>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="2.0.0" />
......
......@@ -18,7 +18,7 @@
using System.Data.Common;
using MySql.Data.MySqlClient;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Components;
namespace SkyWalking.Diagnostics.EntityFrameworkCore
{
......
......@@ -15,7 +15,7 @@
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.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>
<PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.1" />
......
......@@ -15,7 +15,7 @@
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.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>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="2.0.0" />
......
......@@ -18,7 +18,7 @@
using System.Data.Common;
using Microsoft.Data.Sqlite;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Components;
namespace SkyWalking.Diagnostics.EntityFrameworkCore
{
......
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore.Diagnostics;
using SkyWalking.Components;
using SkyWalking.Context;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Diagnostics.EntityFrameworkCore
{
......
......@@ -19,18 +19,16 @@
using System;
using System.Data.Common;
using System.Linq;
using System.Runtime.InteropServices.ComTypes;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
namespace SkyWalking.Diagnostics.EntityFrameworkCore
{
public class EntityFrameworkCoreDiagnosticProcessor : ITracingDiagnosticProcessor
public class EntityFrameworkCoreTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{
private const string TRACE_ORM = "TRACE_ORM";
private Func<CommandEventData, string> _operationNameResolver;
......@@ -55,7 +53,7 @@ namespace SkyWalking.Diagnostics.EntityFrameworkCore
set => _operationNameResolver = value ?? throw new ArgumentNullException(nameof(OperationNameResolver));
}
public EntityFrameworkCoreDiagnosticProcessor(IEfCoreSpanFactory spanFactory)
public EntityFrameworkCoreTracingDiagnosticProcessor(IEfCoreSpanFactory spanFactory)
{
_efCoreSpanFactory = spanFactory;
}
......
using System;
using System.Data.Common;
using SkyWalking.NetworkProtocol.Trace;
using System.Data.Common;
using SkyWalking.Components;
namespace SkyWalking.Diagnostics.EntityFrameworkCore
{
......
......@@ -18,6 +18,6 @@
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.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>
</Project>
\ No newline at end of file
......@@ -18,29 +18,29 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Extensions.DependencyInjection;
using SkyWalking.Utilities.DependencyInjection;
namespace SkyWalking.Diagnostics.EntityFrameworkCore
{
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>();
builder.Services.AddSingleton<IEfCoreSpanFactory, EfCoreSpanFactory>();
extensions.Services.AddSingleton<ITracingDiagnosticProcessor, EntityFrameworkCoreTracingDiagnosticProcessor>();
extensions.Services.AddSingleton<IEfCoreSpanFactory, EfCoreSpanFactory>();
if (optionAction != null)
{
var databaseProviderBuilder = new DatabaseProviderBuilder(builder.Services);
var databaseProviderBuilder = new DatabaseProviderBuilder(extensions.Services);
optionAction(databaseProviderBuilder);
}
return builder;
return extensions;
}
}
}
\ No newline at end of file
......@@ -18,21 +18,28 @@
using System;
using System.Net.Http;
using SkyWalking.Components;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Diagnostics.HttpClient
{
public class HttpClientDiagnosticProcessor : ITracingDiagnosticProcessor
public class HttpClientTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{
public string ListenerName { get; } = "HttpHandlerDiagnosticListener";
private readonly IContextCarrierFactory _contextCarrierFactory;
public HttpClientTracingDiagnosticProcessor(IContextCarrierFactory contextCarrierFactory)
{
_contextCarrierFactory = contextCarrierFactory;
}
[DiagnosticName("System.Net.Http.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 span = ContextManager.CreateExitSpan(request.RequestUri.ToString(), contextCarrier, peer);
Tags.Url.Set(span, request.RequestUri.ToString());
......
......@@ -17,6 +17,6 @@
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.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>
</Project>
\ No newline at end of file
......@@ -18,22 +18,22 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Extensions.DependencyInjection;
using SkyWalking.Utilities.DependencyInjection;
namespace SkyWalking.Diagnostics.HttpClient
{
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 @@
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.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>
<PackageReference Include="System.Data.SqlClient" Version="4.4.0" />
......
......@@ -18,22 +18,22 @@
using System;
using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Extensions.DependencyInjection;
using SkyWalking.Utilities.DependencyInjection;
namespace SkyWalking.Diagnostics.SqlClient
{
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 @@
using System;
using System.Data.SqlClient;
using System.Linq;
using SkyWalking.Components;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Diagnostics.SqlClient
{
public class SqlClientDiagnosticProcessor : ITracingDiagnosticProcessor
public class SqlClientTracingDiagnosticProcessor : ITracingDiagnosticProcessor
{
private const string TRACE_ORM = "TRACE_ORM";
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 @@
<PropertyGroup>
<Description>SkyWalking gRPC protocol and generated codes.</Description>
<AssemblyTitle>SkyWalking.NetworkProtocol</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
<AssemblyName>SkyWalking.NetworkProtocol</AssemblyName>
<PackageId>SkyWalking.NetworkProtocol</PackageId>
<PackageTags>SkyWalking</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Protobuf" Version="3.5.1" />
<PackageReference Include="Google.Protobuf.Tools" Version="3.5.1" />
<PackageReference Include="Grpc" Version="1.9.0" />
<PackageReference Include="Grpc.Tools" Version="1.9.0" />
<PackageReference Include="Google.Protobuf" Version="3.6.1" />
<PackageReference Include="Google.Protobuf.Tools" Version="3.6.1" />
<PackageReference Include="Grpc" Version="1.15.0-pre1" />
<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>
</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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -16,31 +16,26 @@
*
*/
using SkyWalking.NetworkProtocol;
using System;
using SkyWalking.Config;
namespace SkyWalking.Context
namespace SkyWalking.Transport.Grpc
{
public class KeyValuePair
[Config("SkyWalking", "Transport","gRPC")]
public class GrpcConfig
{
public string Key { get; }
public string Servers { get; set; }
public string Value { get; }
public int ConnectTimeout { get; set; }
public KeyValuePair(string key, string value)
{
Key = key;
Value = value;
public int Timeout { get; set; }
}
public KeyWithStringValue Transform()
public static class GrpcConfigExtensions
{
var keyWithStringValue = new KeyWithStringValue
public static DateTime GetTimeout(this GrpcConfig config)
{
Key = Key,
Value = Value
};
return keyWithStringValue;
return DateTime.UtcNow.AddMilliseconds(config.Timeout);
}
}
}
\ 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.
......@@ -17,40 +17,34 @@
*/
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 int _value;
private readonly ConnectionManager _connectionManager;
protected PossibleFound(int value)
public GrpcStateCheckService(ConnectionManager connectionManager, ISkyWalkingClient skyWalking, IRuntimeEnvironment runtimeEnvironment,
ILoggerFactory loggerFactory) : base(
skyWalking, runtimeEnvironment, loggerFactory)
{
_found = true;
_value = value;
_connectionManager = connectionManager;
}
protected PossibleFound()
{
_found = false;
}
protected override TimeSpan DueTime { get; } = TimeSpan.Zero;
protected override TimeSpan Period { get; } = TimeSpan.FromSeconds(15);
public virtual void InCondition(Action<int> foundCondition, Action notFoundCondition)
{
if (_found)
protected override async Task ExecuteAsync(CancellationToken cancellationToken)
{
foundCondition?.Invoke(_value);
}
else
if (!_connectionManager.Ready)
{
notFoundCondition?.Invoke();
await _connectionManager.ConnectAsync();
}
}
public virtual object InCondition(Func<int, object> foundCondition, Func<object> notFoundCondition)
{
return _found ? foundCondition?.Invoke(_value) : notFoundCondition?.Invoke();
}
protected override bool CanExecute() => !_connectionManager.Ready;
}
}
\ 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.
......@@ -16,20 +16,21 @@
*
*/
#if NET45 || NET451
using System.Runtime.Remoting.Messaging;
namespace SkyWalking.Utils
namespace SkyWalking.Transport.Grpc
{
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);
set => CallContext.LogicalSetData(key, value);
Address = address;
CertificatePath = certificate;
Token = token;
}
}
}
\ No newline at end of file
#endif
<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;
using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking.Utils
namespace SkyWalking.Transport.Grpc
{
internal class AsyncLock
{
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1);
private readonly Releaser _releaser;
private readonly Task<Releaser> _releaserTask;
private readonly Release _release;
private readonly Task<Release> _releaseTask;
public AsyncLock()
{
_releaser = new Releaser(this);
_releaserTask = Task.FromResult(_releaser);
_release = new Release(this);
_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);
return wait.IsCompleted
? _releaserTask
? _releaseTask
: wait.ContinueWith(
(_, state) => ((AsyncLock) state)._releaser,
(_, state) => ((AsyncLock) state)._release,
this, CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
public Releaser Lock()
public Release Lock()
{
_semaphore.Wait();
return _releaser;
return _release;
}
public struct Releaser : IDisposable
public struct Release : IDisposable
{
private readonly AsyncLock _toRelease;
internal Releaser(AsyncLock toRelease)
internal Release(AsyncLock 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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -16,54 +16,61 @@
*
*/
using System.Collections.Concurrent;
using System;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Extensions.Configuration;
using SkyWalking.Config;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
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)
{
if (_applicationDic.TryGetValue(networkAddress, out var id))
{
return new Found(id);
}
builder.AddJsonFile("skywalking.json", true).AddJsonFile($"skywalking.{environmentProvider.EnvironmentName}.json", true);
if (_applicationDic.Count + _unRegisterApps.Count < DictionaryConfig.ApplicationCodeBufferSize)
if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(CONFIG_FILE_PATH)))
{
_unRegisterApps.TryAdd(networkAddress, null);
builder.AddJsonFile(Environment.GetEnvironmentVariable(CONFIG_FILE_PATH), false);
}
return NotFound.Instance;
builder.AddEnvironmentVariables();
_configuration = builder.Build();
}
public void SyncRemote(NetworkAddressRegisterService.NetworkAddressRegisterServiceClient serviceClient)
public T Get<T>() where T : class, new()
{
if (_unRegisterApps.Count <= 0) return;
var networkAddress = new NetworkAddresses();
networkAddress.Addresses.Add(_unRegisterApps.Keys);
var mapping = serviceClient.batchRegister(networkAddress);
if (mapping.AddressIds.Count <= 0) return;
foreach (var id in mapping.AddressIds)
var config = typeof(T).GetCustomAttribute<ConfigAttribute>();
var instance = New<T>.Instance();
_configuration.GetSection(config.GetSections()).Bind(instance);
return instance;
}
public T Value<T>(string key, params string[] sections)
{
_unRegisterApps.TryRemove(id.Key, out _);
_applicationDic.TryAdd(id.Key, id.Value);
var config = new ConfigAttribute(sections);
return _configuration.GetSection(config.GetSections()).GetValue<T>(key);
}
//hign performance
private static class New<T> where T : new()
{
public static readonly Func<T> Instance = Expression.Lambda<Func<T>>
(
Expression.New(typeof(T))
).Compile();
}
}
}
\ 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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -17,35 +17,32 @@
*/
using System.Collections.Generic;
using System.Linq;
using SkyWalking.Dictionarys;
using System.IO;
using Microsoft.Extensions.Configuration;
namespace SkyWalking.Config
namespace SkyWalking.Utilities.Configuration
{
/// <summary>
/// The <code>RemoteDownstreamConfig</code> includes configurations from collector side.
/// All of them initialized null, Null-Value or empty collection.
/// </summary>
public static class RemoteDownstreamConfig
internal static class ConfigurationBuilderExtensions
{
public static class Agent
public static IConfigurationBuilder AddSkyWalkingDefaultConfig(this IConfigurationBuilder builder)
{
public static int ApplicationId { get; set; } = DictionaryUtil.NullValue;
public static int ApplicationInstanceId { get; set; } = DictionaryUtil.NullValue;
}
public static class Collector
var defaultLogFile = Path.Combine("logs", "SkyWalking-{Date}.log");
var defaultConfig = new Dictionary<string, string>
{
private static IList<string> _grpcServers;
/// <summary>
/// Collector GRPC-Service address.
/// </summary>
public static IList<string> gRPCServers
{
get => _grpcServers ?? CollectorConfig.DirectServers.Split(',').ToList();
set => _grpcServers = value;
}
{"SkyWalking:Namespace", string.Empty},
{"SkyWalking:ApplicationCode", "My_Application"},
{"SkyWalking:SpanLimitPerSegment", "300"},
{"SkyWalking:Sampling:SamplePer3Secs", "-1"},
{"SkyWalking:Logging:Level", "Info"},
{"SkyWalking:Logging:FilePath", defaultLogFile},
{"SkyWalking:Transport:Interval", "3000"},
{"SkyWalking:Transport:PendingSegmentLimit", "30000"},
{"SkyWalking:Transport:PendingSegmentTimeout", "1000"},
{"SkyWalking:Transport:gRPC:Servers", "localhost:11800"},
{"SkyWalking:Transport:gRPC:Timeout", "2000"},
{"SkyWalking:Transport:gRPC:ConnectTimeout", "10000"}
};
return builder.AddInMemoryCollection(defaultConfig);
}
}
}
\ 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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -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 bool IsNull(int id)
public static SkyWalkingExtensions AddSkyWalkingExtensions(this IServiceCollection services)
{
return id == NullValue;
return new SkyWalkingExtensions(services);
}
}
}
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<Description>Microsoft.Extensions.DependencyInjection (IServiceCollection) support for SkyWalking.</Description>
<AssemblyTitle>SkyWalking.Extensions.DependencyInjection</AssemblyTitle>
<Description>Microsoft.Utilities.DependencyInjection (IServiceCollection) support for SkyWalking.</Description>
<AssemblyTitle>SkyWalking.Utilities.DependencyInjection</AssemblyTitle>
<TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>SkyWalking.Extensions.DependencyInjection</AssemblyName>
<PackageId>SkyWalking.Extensions.DependencyInjection</PackageId>
<AssemblyName>SkyWalking.Utilities.DependencyInjection</AssemblyName>
<PackageId>SkyWalking.Utilities.DependencyInjection</PackageId>
<PackageTags>SkyWalking;APM;Diagnostics</PackageTags>
<PackageReleaseNotes>
</PackageReleaseNotes>
<RootNamespace>SkyWalking.Extensions.DependencyInjection</RootNamespace>
<RootNamespace>SkyWalking.Utilities.DependencyInjection</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
......
......@@ -18,13 +18,13 @@
using Microsoft.Extensions.DependencyInjection;
namespace SkyWalking.Extensions.DependencyInjection
namespace SkyWalking.Utilities.DependencyInjection
{
public class SkyWalkingBuilder
public class SkyWalkingExtensions
{
public IServiceCollection Services { get; }
public SkyWalkingBuilder(IServiceCollection services)
public SkyWalkingExtensions(IServiceCollection services)
{
Services = services;
}
......
/*
/*
* 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.
......@@ -21,40 +21,40 @@ using Microsoft.Extensions.Logging;
using ILogger = SkyWalking.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)
{
_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)
{
_logger.LogWarning(message);
_readLogger.LogWarning(message);
}
public void Error(string message, Exception exception)
{
_logger.LogError(exception, message);
_readLogger.LogError(message + Environment.NewLine + exception);
}
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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -17,25 +17,47 @@
*/
using System;
using MSLoggerFactory= Microsoft.Extensions.Logging.ILoggerFactory;
using Serilog;
using Serilog.Events;
using SkyWalking.Config;
using Microsoft.Extensions.Logging;
using ILoggerFactory = SkyWalking.Logging.ILoggerFactory;
using ILogger = SkyWalking.Logging.ILogger;
using ILoggerFactory = SkyWalking.Logging.ILoggerFactory;
using MSLoggerFactory = Microsoft.Extensions.Logging.LoggerFactory;
namespace SkyWalking.AspNetCore.Logging
namespace SkyWalking.Utilities.Logging
{
internal class LoggerFactoryAdapter : ILoggerFactory
public class DefaultLoggerFactory : ILoggerFactory
{
private const string outputTemplate = @"{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{ApplicationCode}] [{Level}] {SourceContext} : {Message}{NewLine}{Exception}";
private readonly MSLoggerFactory _loggerFactory;
private readonly LoggingConfig _loggingConfig;
public LoggerFactoryAdapter(MSLoggerFactory loggerFactory)
public DefaultLoggerFactory(IConfigAccessor configAccessor)
{
_loggerFactory = loggerFactory;
_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 LoggerAdapter(_loggerFactory.CreateLogger(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
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
......@@ -16,16 +16,15 @@
*
*/
using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Config;
namespace SkyWalking.Boot
namespace SkyWalking.Utilities.Logging
{
public interface IBootService : IDisposable
[Config("SkyWalking", "Logging")]
public class LoggingConfig
{
int Order { get; }
public string Level { get; set; }
Task Initialize(CancellationToken token);
public string FilePath { get; set; }
}
}
\ 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.Diagnostics;
using SkyWalking.Diagnostics;
using SkyWalking.Logging;
using Xunit;
namespace SkyWalking.Core.Tests.Diagnostics
......@@ -12,7 +13,7 @@ namespace SkyWalking.Core.Tests.Diagnostics
{
var listener = new FakeDiagnosticListener();
var fakeProcessor = new FakeTracingDiagnosticProcessor();
var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[] {fakeProcessor});
var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[] {fakeProcessor},new NullLoggerFactory());
DiagnosticListener.AllListeners.Subscribe(observer);
var timeStamp = DateTime.Now;
......@@ -31,7 +32,8 @@ namespace SkyWalking.Core.Tests.Diagnostics
{
var listener = new FakeDiagnosticListener();
var fakeProcessor = new FakeTracingDiagnosticProcessor();
var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[] {fakeProcessor});
var observer = new TracingDiagnosticProcessorObserver(new ITracingDiagnosticProcessor[] {fakeProcessor},
new NullLoggerFactory());
DiagnosticListener.AllListeners.Subscribe(observer);
var timeStamp = DateTime.Now;
......
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