Commit 4146fcd7 authored by liuhaoyang's avatar liuhaoyang
parents aa45aacc fc346491
...@@ -23,3 +23,11 @@ deploy: ...@@ -23,3 +23,11 @@ deploy:
artifact: /artifacts\/packages\/.+\.nupkg/ artifact: /artifacts\/packages\/.+\.nupkg/
on: on:
branch: master branch: master
- provider: NuGet
server: https://api.nuget.org/v3/index.json
api_key:
secure: 6N8pLjIHa7SK3l+Lj7b1qKk7CvKdZdQyj9ZNTaUjfPSd+/SL8PuSHq+ysNKaMHAF
skip_symbols: true
artifact: /artifacts\/packages\/.+\.nupkg/
on:
appveyor_repo_tag: true
...@@ -76,9 +76,17 @@ public class BuildParameters ...@@ -76,9 +76,17 @@ public class BuildParameters
var suffix = versionQuality; var suffix = versionQuality;
if (!IsTagged) 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 += (IsCI ? "preview-" : "dev-") + Util.CreateStamp();
} }
}
suffix = string.IsNullOrWhiteSpace(suffix) ? null : suffix; suffix = string.IsNullOrWhiteSpace(suffix) ? null : suffix;
Version = Version =
......
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<VersionMajor>0</VersionMajor> <VersionMajor>0</VersionMajor>
<VersionMinor>3</VersionMinor> <VersionMinor>6</VersionMinor>
<VersionPatch>0</VersionPatch> <VersionPatch>0</VersionPatch>
<VersionQuality></VersionQuality> <VersionQuality></VersionQuality>
<VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix> <VersionPrefix>$(VersionMajor).$(VersionMinor).$(VersionPatch)</VersionPrefix>
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
<AppDesignerFolder>Properties</AppDesignerFolder> <AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SkyWalking.Sample.AspNet</RootNamespace> <RootNamespace>SkyWalking.Sample.AspNet</RootNamespace>
<AssemblyName>SkyWalking.Sample.AspNet</AssemblyName> <AssemblyName>SkyWalking.Sample.AspNet</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment> <FileAlignment>512</FileAlignment>
</PropertyGroup> </PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
......
...@@ -12,4 +12,17 @@ ...@@ -12,4 +12,17 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Update="appsettings.Development.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
<ItemGroup>
<Folder Include="logs" />
</ItemGroup>
</Project> </Project>
\ No newline at end of file
...@@ -25,13 +25,6 @@ namespace SkyWalking.Sample.Backend ...@@ -25,13 +25,6 @@ namespace SkyWalking.Sample.Backend
{ {
services.AddMvc(); services.AddMvc();
services.AddSkyWalking(option =>
{
option.DirectServers = "localhost:11800";
option.ApplicationCode = "asp-net-core-backend";
}).
AddEntityFrameworkCore(c => { c.AddSqlite(); });
var sqliteConnection = new SqliteConnection("DataSource=:memory:"); var sqliteConnection = new SqliteConnection("DataSource=:memory:");
sqliteConnection.Open(); sqliteConnection.Open();
......
...@@ -11,5 +11,8 @@ ...@@ -11,5 +11,8 @@
"Default": "Warning" "Default": "Warning"
} }
} }
},
"SkyWalking": {
"ApplicationCode": "asp-net-core-backend"
} }
} }
...@@ -9,7 +9,7 @@ namespace SkyWalking.Sample.Frontend.Controllers ...@@ -9,7 +9,7 @@ namespace SkyWalking.Sample.Frontend.Controllers
public class ValuesController : Controller public class ValuesController : Controller
{ {
// GET api/values // GET api/values
[HttpGet] [HttpGet("/values")]
public async Task<IEnumerable<string>> Get() public async Task<IEnumerable<string>> Get()
{ {
await new HttpClient().GetAsync("http://localhost:5002/api/values"); await new HttpClient().GetAsync("http://localhost:5002/api/values");
......
...@@ -11,4 +11,10 @@ ...@@ -11,4 +11,10 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<Content Update="appsettings.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project> </Project>
\ No newline at end of file
...@@ -19,12 +19,6 @@ namespace SkyWalking.Sample.Frontend ...@@ -19,12 +19,6 @@ namespace SkyWalking.Sample.Frontend
public void ConfigureServices(IServiceCollection services) public void ConfigureServices(IServiceCollection services)
{ {
services.AddMvc(); services.AddMvc();
services.AddSkyWalking(option =>
{
option.DirectServers = "localhost:11800";
option.ApplicationCode = "asp-net-core-frontend";
});
} }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
......
...@@ -11,6 +11,9 @@ ...@@ -11,6 +11,9 @@
"Default": "Warning" "Default": "Warning"
} }
} }
},
"SkyWalking": {
"ApplicationCode": "asp-net-core-frontend"
} }
} }
This diff is collapsed.
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
namespace SkyWalking.Components
{
public class ComponentsDefine
{
public static readonly IComponent HttpClient = new OfficialComponent(2, "HttpClient");
public static readonly IComponent AspNetCore = new OfficialComponent(3001, "AspNetCore");
public static readonly IComponent EntityFrameworkCore = new OfficialComponent(3002, "EntityFrameworkCore");
public static readonly IComponent SqlClient = new OfficialComponent(3003, "SqlClient");
public static readonly IComponent CAP = new OfficialComponent(3004, "CAP");
public static readonly IComponent StackExchange_Redis = new OfficialComponent(3005, "StackExchange.Redis");
public static readonly IComponent SqlServer = new OfficialComponent(3006, "SqlServer");
public static readonly IComponent Npgsql = new OfficialComponent(3007, "Npgsql");
public static readonly IComponent MySqlConnector = new OfficialComponent(3008, "MySqlConnector");
public static readonly IComponent EntityFrameworkCore_InMemory = new OfficialComponent(3009, "EntityFrameworkCore.InMemory");
public static readonly IComponent EntityFrameworkCore_SqlServer = new OfficialComponent(3010, "EntityFrameworkCore.SqlServer");
public static readonly IComponent EntityFrameworkCore_Sqlite = new OfficialComponent(3011, "EntityFrameworkCore.Sqlite");
public static readonly IComponent Pomelo_EntityFrameworkCore_MySql = new OfficialComponent(3012, "Pomelo.EntityFrameworkCore.MySql");
public static readonly IComponent Npgsql_EntityFrameworkCore_PostgreSQL = new OfficialComponent(3013, "Npgsql.EntityFrameworkCore.PostgreSQL");
public static readonly IComponent InMemoryDatabase = new OfficialComponent(3014, "InMemoryDatabase");
public static readonly IComponent AspNet = new OfficialComponent(3015, "AspNet");
}
}
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
* *
*/ */
namespace SkyWalking.NetworkProtocol.Trace namespace SkyWalking.Components
{ {
/// <summary> /// <summary>
/// The <code>Component</code> represents component library , which has been supported by skywalking /// The <code>Component</code> represents component library , which has been supported by skywalking
...@@ -24,6 +24,7 @@ namespace SkyWalking.NetworkProtocol.Trace ...@@ -24,6 +24,7 @@ namespace SkyWalking.NetworkProtocol.Trace
public interface IComponent public interface IComponent
{ {
int Id { get; } int Id { get; }
string Name { get; } string Name { get; }
} }
} }
\ No newline at end of file
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
* *
*/ */
namespace SkyWalking.NetworkProtocol.Trace namespace SkyWalking.Components
{ {
public class OfficialComponent : IComponent 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 * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
...@@ -16,17 +16,17 @@ ...@@ -16,17 +16,17 @@
* *
*/ */
using SkyWalking.Dictionarys; using System;
namespace SkyWalking.Dictionarys namespace SkyWalking.Config
{ {
public class NotFound : PossibleFound public class ConfigAttribute : Attribute
{ {
public NotFound() public string[] Sections { get; }
: base()
public ConfigAttribute(params string[] sections)
{ {
Sections = sections;
} }
public static readonly PossibleFound Instance = new NotFound();
} }
} }
\ No newline at end of file
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
...@@ -18,10 +18,10 @@ ...@@ -18,10 +18,10 @@
namespace SkyWalking.Config namespace SkyWalking.Config
{ {
public static class DictionaryConfig public interface IConfigAccessor
{ {
public static int ApplicationCodeBufferSize { get; set; } = 10 * 10000; T Get<T>() where T : class, new();
public static int OperationNameBufferSize { get; set; } = 1000 * 10000; T Value<T>(string key, params string[] sections);
} }
} }
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace SkyWalking.Config
{
[Config("SkyWalking")]
public class InstrumentationConfig
{
public string Namespace { get; set; }
public string ApplicationCode { get; set; }
public int SpanLimitPerSegment { get; set; } = 300;
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace SkyWalking.Config
{
public class RuntimeConfig
{
public NullableValue ApplicationId { get; set; }
public NullableValue ApplicationInstance { get; set; }
}
}
\ No newline at end of file
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 * The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at * the License. You may obtain a copy of the License at
* *
...@@ -16,15 +16,11 @@ ...@@ -16,15 +16,11 @@
* *
*/ */
using SkyWalking.Dictionarys; namespace SkyWalking.Config
namespace SkyWalking.Dictionarys
{ {
public class Found : PossibleFound [Config("SkyWalking", "Sampling")]
{ public class SamplingConfig
public Found(int value)
: base(value)
{ {
} 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 @@ ...@@ -16,56 +16,33 @@
* *
*/ */
using System;
using System.Collections; using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using SkyWalking.Config;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
public class CarrierItem : IEnumerable<CarrierItem> public class CarrierItem : IEnumerable<CarrierItem>
{ {
private string _headKey; private readonly string _headKey;
private string _headValue; private string _headValue;
private CarrierItem _next; private readonly CarrierItem _next;
public virtual string HeadKey public virtual string HeadKey => _headKey;
{
get
{
return _headKey;
}
}
public virtual string HeadValue public virtual string HeadValue
{ {
get get => _headValue;
{ set => _headValue = value;
return _headValue;
}
set
{
_headValue = value;
}
} }
public CarrierItem(String headKey, String headValue) protected CarrierItem(string headKey, string headValue, string @namespace)
: this(headKey, headValue, null, @namespace)
{ {
_headKey = headKey;
_headValue = headValue;
_next = null;
} }
public CarrierItem(String headKey, String headValue, CarrierItem next) protected CarrierItem(string headKey, string headValue, CarrierItem next, string @namespace)
{ {
if (string.IsNullOrEmpty(AgentConfig.Namespace)) _headKey = string.IsNullOrEmpty(@namespace) ? headKey : $"{@namespace}-{headKey}";
{
_headKey = headKey;
}
else
{
_headKey = $"{AgentConfig.Namespace}-{headKey}";
}
_headValue = headValue; _headValue = headValue;
_next = next; _next = next;
} }
...@@ -82,17 +59,16 @@ namespace SkyWalking.Context ...@@ -82,17 +59,16 @@ namespace SkyWalking.Context
private class Enumerator : IEnumerator<CarrierItem> private class Enumerator : IEnumerator<CarrierItem>
{ {
private CarrierItem _head; private readonly CarrierItem _head;
private CarrierItem _current;
public CarrierItem Current => _current; public CarrierItem Current { get; private set; }
object IEnumerator.Current => _current; object IEnumerator.Current => Current;
public Enumerator(CarrierItem head) public Enumerator(CarrierItem head)
{ {
_head = head; _head = head;
_current = head; Current = head;
} }
public void Dispose() public void Dispose()
...@@ -101,18 +77,19 @@ namespace SkyWalking.Context ...@@ -101,18 +77,19 @@ namespace SkyWalking.Context
public bool MoveNext() public bool MoveNext()
{ {
var next = _current._next; var next = Current._next;
if (next == null) if (next == null)
{ {
return false; return false;
} }
_current = next;
Current = next;
return true; return true;
} }
public void Reset() public void Reset()
{ {
_current = _head; Current = _head;
} }
} }
} }
......
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
...@@ -16,12 +16,10 @@ ...@@ -16,12 +16,10 @@
* *
*/ */
using System.Threading.Tasks; namespace SkyWalking.Context
namespace SkyWalking.Utils
{ {
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 @@ ...@@ -18,11 +18,12 @@
using System; using System;
using SkyWalking.NetworkProtocol; using SkyWalking.Transport;
namespace SkyWalking.Context.Ids namespace SkyWalking.Context.Ids
{ {
/// <inheritdoc />
/// <summary> /// <summary>
/// The <code>DistributedTraceId</code> presents a distributed call chain. /// The <code>DistributedTraceId</code> presents a distributed call chain.
/// This call chain has an unique (service) entrance, /// This call chain has an unique (service) entrance,
...@@ -34,50 +35,35 @@ namespace SkyWalking.Context.Ids ...@@ -34,50 +35,35 @@ namespace SkyWalking.Context.Ids
{ {
private readonly ID _id; private readonly ID _id;
public DistributedTraceId(ID id) protected DistributedTraceId(ID id)
{ {
_id = id; _id = id;
} }
public DistributedTraceId(string id) protected DistributedTraceId(string id)
{ {
_id = new ID(id); _id = new ID(id);
} }
public string Encode public string Encode => _id?.Encode;
{
get
{
return _id?.Encode;
}
}
public UniqueId ToUniqueId() public UniqueIdRequest ToUniqueId() => _id?.Transform();
{
return _id?.Transform();
}
public bool Equals(DistributedTraceId other) public bool Equals(DistributedTraceId other)
{ {
if (other == null) if (other == null)
return false; return false;
return _id != null ? _id.Equals(other._id) : other._id == null; return _id?.Equals(other._id) ?? other._id == null;
} }
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
DistributedTraceId id = obj as DistributedTraceId; var id = obj as DistributedTraceId;
return Equals(id); return Equals(id);
} }
public override int GetHashCode() public override int GetHashCode() => _id != null ? _id.GetHashCode() : 0;
{
return _id != null ? _id.GetHashCode() : 0;
}
public override string ToString() public override string ToString() => _id?.ToString();
{
return _id?.ToString();
}
} }
} }
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
*/ */
using System; using System;
using SkyWalking.NetworkProtocol; using SkyWalking.Transport;
namespace SkyWalking.Context.Ids namespace SkyWalking.Context.Ids
{ {
...@@ -26,35 +26,18 @@ namespace SkyWalking.Context.Ids ...@@ -26,35 +26,18 @@ namespace SkyWalking.Context.Ids
private readonly long _part1; private readonly long _part1;
private readonly long _part2; private readonly long _part2;
private readonly long _part3; private readonly long _part3;
private readonly bool _isValid;
private string _encoding; private string _encoding;
public bool IsValid public bool IsValid { get; }
{
get
{
return _isValid;
}
}
public string Encode public string Encode => _encoding ?? (_encoding = ToString());
{
get
{
if (_encoding == null)
{
_encoding = ToString();
}
return _encoding;
}
}
public ID(long part1, long part2, long part3) public ID(long part1, long part2, long part3)
{ {
_part1 = part1; _part1 = part1;
_part2 = part2; _part2 = part2;
_part3 = part3; _part3 = part3;
_isValid = true; IsValid = true;
} }
public ID(string encodingString) public ID(string encodingString)
...@@ -68,17 +51,17 @@ namespace SkyWalking.Context.Ids ...@@ -68,17 +51,17 @@ namespace SkyWalking.Context.Ids
{ {
if (part == 0) if (part == 0)
{ {
_isValid = long.TryParse(idParts[part], out _part1); IsValid = long.TryParse(idParts[part], out _part1);
} }
else if (part == 1) else if (part == 1)
{ {
_isValid = long.TryParse(idParts[part], out _part2); IsValid = long.TryParse(idParts[part], out _part2);
} }
else else
{ {
_isValid = long.TryParse(idParts[part], out _part3); IsValid = long.TryParse(idParts[part], out _part3);
} }
if (!_isValid) if (!IsValid)
{ {
break; break;
} }
...@@ -92,7 +75,7 @@ namespace SkyWalking.Context.Ids ...@@ -92,7 +75,7 @@ namespace SkyWalking.Context.Ids
public override int GetHashCode() public override int GetHashCode()
{ {
int result = (int)(_part1 ^ (_part1 >> 32)); var result = (int)(_part1 ^ (_part1 >> 32));
result = 31 * result + (int)(_part2 ^ (_part2 >> 32)); result = 31 * result + (int)(_part2 ^ (_part2 >> 32));
result = 31 * result + (int)(_part3 ^ (_part3 >> 32)); result = 31 * result + (int)(_part3 ^ (_part3 >> 32));
return result; return result;
...@@ -100,7 +83,7 @@ namespace SkyWalking.Context.Ids ...@@ -100,7 +83,7 @@ namespace SkyWalking.Context.Ids
public override bool Equals(object obj) public override bool Equals(object obj)
{ {
ID id = obj as ID; var id = obj as ID;
return Equals(id); return Equals(id);
} }
...@@ -117,12 +100,9 @@ namespace SkyWalking.Context.Ids ...@@ -117,12 +100,9 @@ namespace SkyWalking.Context.Ids
return _part3 == other._part3; return _part3 == other._part3;
} }
public UniqueId Transform() public UniqueIdRequest Transform()
{ {
UniqueId uniqueId = new UniqueId(); var uniqueId = new UniqueIdRequest {Part1 = _part1, Part2 = _part2, Part3 = _part3};
uniqueId.IdParts.Add(_part1);
uniqueId.IdParts.Add(_part2);
uniqueId.IdParts.Add(_part3);
return uniqueId; return uniqueId;
} }
} }
......
...@@ -18,11 +18,8 @@ ...@@ -18,11 +18,8 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using SkyWalking.Dictionarys; using SkyWalking.Transport;
using SkyWalking.NetworkProtocol; using SkyWalking.Components;
using SkyWalking.NetworkProtocol.Trace;
using System.Linq;
using SkyWalking.Utils;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -31,8 +28,8 @@ namespace SkyWalking.Context.Trace ...@@ -31,8 +28,8 @@ namespace SkyWalking.Context.Trace
/// </summary> /// </summary>
public abstract class AbstractTracingSpan : ISpan public abstract class AbstractTracingSpan : ISpan
{ {
protected int _spanId; protected readonly int _spanId;
protected int _parnetSpanId; protected readonly int _parnetSpanId;
protected Dictionary<string, string> _tags; protected Dictionary<string, string> _tags;
protected string _operationName; protected string _operationName;
protected int _operationId; protected int _operationId;
...@@ -69,7 +66,6 @@ namespace SkyWalking.Context.Trace ...@@ -69,7 +66,6 @@ namespace SkyWalking.Context.Trace
protected AbstractTracingSpan(int spanId, int parentSpanId, string operationName) protected AbstractTracingSpan(int spanId, int parentSpanId, string operationName)
{ {
_operationName = operationName; _operationName = operationName;
_operationId = DictionaryUtil.NullValue;
_spanId = spanId; _spanId = spanId;
_parnetSpanId = parentSpanId; _parnetSpanId = parentSpanId;
} }
...@@ -90,23 +86,17 @@ namespace SkyWalking.Context.Trace ...@@ -90,23 +86,17 @@ namespace SkyWalking.Context.Trace
public virtual string OperationName public virtual string OperationName
{ {
get get => _operationName;
{
return _operationName;
}
set set
{ {
_operationName = value; _operationName = value;
_operationId = DictionaryUtil.NullValue; _operationId = 0;
} }
} }
public virtual int OperationId public virtual int OperationId
{ {
get get => _operationId;
{
return _operationId;
}
set set
{ {
_operationId = value; _operationId = value;
...@@ -132,6 +122,7 @@ namespace SkyWalking.Context.Trace ...@@ -132,6 +122,7 @@ namespace SkyWalking.Context.Trace
{ {
_tags = new Dictionary<string, string>(); _tags = new Dictionary<string, string>();
} }
_tags.Add(key, value); _tags.Add(key, value);
return this; return this;
} }
...@@ -166,11 +157,12 @@ namespace SkyWalking.Context.Trace ...@@ -166,11 +157,12 @@ namespace SkyWalking.Context.Trace
public virtual ISpan Log(long timestamp, IDictionary<string, object> events) public virtual ISpan Log(long timestamp, IDictionary<string, object> events)
{ {
EnsureLogs(); EnsureLogs();
LogDataEntity.Builder builder = new LogDataEntity.Builder(); var builder = new LogDataEntity.Builder();
foreach (var @event in events) foreach (var @event in events)
{ {
builder.Add(@event.Key, @event.Value.ToString()); builder.Add(@event.Key, @event.Value.ToString());
} }
_logs.Add(builder.Build(timestamp)); _logs.Add(builder.Build(timestamp));
return this; return this;
} }
...@@ -193,6 +185,7 @@ namespace SkyWalking.Context.Trace ...@@ -193,6 +185,7 @@ namespace SkyWalking.Context.Trace
{ {
_refs = new List<ITraceSegmentRef>(); _refs = new List<ITraceSegmentRef>();
} }
if (!_refs.Contains(traceSegmentRef)) if (!_refs.Contains(traceSegmentRef))
{ {
_refs.Add(traceSegmentRef); _refs.Add(traceSegmentRef);
...@@ -211,69 +204,58 @@ namespace SkyWalking.Context.Trace ...@@ -211,69 +204,58 @@ namespace SkyWalking.Context.Trace
return true; return true;
} }
public virtual SpanObject Transform() public virtual SpanRequest Transform()
{ {
SpanObject spanObject = new SpanObject(); var spanRequest = new SpanRequest
spanObject.SpanId = _spanId;
spanObject.ParentSpanId = _parnetSpanId;
spanObject.StartTime = _startTime;
spanObject.EndTime = _endTime;
if (_operationId != DictionaryUtil.NullValue)
{ {
spanObject.OperationNameId = _operationId; SpanId = _spanId,
} ParentSpanId = _parnetSpanId,
else StartTime = _startTime,
{ EndTime = _endTime,
spanObject.OperationName = _operationName; OperationName = new StringOrIntValue(_operationId, _operationName),
} Component = new StringOrIntValue(_componentId, _componentName),
IsError = _errorOccurred
};
if (IsEntry) if (IsEntry)
{ {
spanObject.SpanType = SpanType.Entry; spanRequest.SpanType = 0;
} }
else if (IsExit) else if (IsExit)
{ {
spanObject.SpanType = SpanType.Exit; spanRequest.SpanType = 1;
} }
else else
{ {
spanObject.SpanType = SpanType.Local; spanRequest.SpanType = 2;
} }
if (_layer.HasValue) if (_layer.HasValue)
{ {
spanObject.SpanLayer = (NetworkProtocol.SpanLayer)((int)_layer.Value); spanRequest.SpanLayer = (int) _layer.Value;
}
if (_componentId != DictionaryUtil.NullValue)
{
spanObject.ComponentId = _componentId;
}
else
{
spanObject.Component = _componentName;
} }
spanObject.IsError = _errorOccurred;
if (_tags != null) foreach (var tag in _tags)
{ {
spanObject.Tags.Add(_tags.Select(x => new KeyWithStringValue { Key = x.Key, Value = x.Value })); spanRequest.Tags.Add(new KeyValuePair<string, string>(tag.Key, tag.Value));
} }
if (_logs != null) if (_logs != null)
{ {
spanObject.Logs.Add(_logs.Select(x => x.Transform())); foreach (var logDataEntity in _logs)
{
spanRequest.Logs.Add(logDataEntity.Transform());
}
} }
if (_refs != null) if (_refs == null) return spanRequest;
foreach (var traceSegmentRef in _refs)
{ {
spanObject.Refs.Add(_refs.Select(x => x.Transform())); spanRequest.References.Add(traceSegmentRef.Transform());
} }
return spanObject; return spanRequest;
} }
private void EnsureLogs() private void EnsureLogs()
......
...@@ -18,8 +18,7 @@ ...@@ -18,8 +18,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using SkyWalking.Components;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -36,7 +35,7 @@ namespace SkyWalking.Context.Trace ...@@ -36,7 +35,7 @@ namespace SkyWalking.Context.Trace
ISpan SetComponent(IComponent component); ISpan SetComponent(IComponent component);
/// <summary> /// <summary>
/// Only use this method in explicit instrumentation, like opentracing-skywalking-bridge. It it higher recommend /// Only use this method in explicit skyWalking, like opentracing-skywalking-bridge. It it higher recommend
/// don't use this for performance consideration. /// don't use this for performance consideration.
/// </summary> /// </summary>
/// <param name="componentName"></param> /// <param name="componentName"></param>
......
...@@ -17,8 +17,8 @@ ...@@ -17,8 +17,8 @@
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using SkyWalking.Transport;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -48,6 +48,6 @@ namespace SkyWalking.Context.Trace ...@@ -48,6 +48,6 @@ namespace SkyWalking.Context.Trace
void RelatedGlobalTrace(DistributedTraceId distributedTraceId); void RelatedGlobalTrace(DistributedTraceId distributedTraceId);
UpstreamSegment Transform(); TraceSegmentRequest Transform();
} }
} }
...@@ -17,7 +17,7 @@ ...@@ -17,7 +17,7 @@
*/ */
using System; using System;
using SkyWalking.NetworkProtocol; using SkyWalking.Transport;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -29,6 +29,6 @@ namespace SkyWalking.Context.Trace ...@@ -29,6 +29,6 @@ namespace SkyWalking.Context.Trace
int EntryApplicationInstanceId { get; } int EntryApplicationInstanceId { get; }
TraceSegmentReference Transform(); TraceSegmentReferenceRequest Transform();
} }
} }
\ No newline at end of file
...@@ -18,14 +18,14 @@ ...@@ -18,14 +18,14 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using SkyWalking.NetworkProtocol; using SkyWalking.Transport;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
public class LogDataEntity public class LogDataEntity
{ {
private long _timestamp = 0; private readonly long _timestamp;
private Dictionary<string, string> _logs; private readonly Dictionary<string, string> _logs;
private LogDataEntity(long timestamp, Dictionary<string, string> logs) private LogDataEntity(long timestamp, Dictionary<string, string> logs)
{ {
...@@ -33,14 +33,11 @@ namespace SkyWalking.Context.Trace ...@@ -33,14 +33,11 @@ namespace SkyWalking.Context.Trace
_logs = logs; _logs = logs;
} }
public IReadOnlyDictionary<string, string> Logs public IReadOnlyDictionary<string, string> Logs => new ReadOnlyDictionary<string, string>(_logs);
{
get { return new ReadOnlyDictionary<string, string>(_logs); }
}
public class Builder public class Builder
{ {
private Dictionary<string, string> _logs; private readonly Dictionary<string, string> _logs;
public Builder() public Builder()
{ {
...@@ -66,13 +63,13 @@ namespace SkyWalking.Context.Trace ...@@ -66,13 +63,13 @@ namespace SkyWalking.Context.Trace
} }
} }
public LogMessage Transform() public LogDataRequest Transform()
{ {
LogMessage logMessage = new LogMessage(); var logMessage = new LogDataRequest();
logMessage.Time = _timestamp; logMessage.Timestamp = _timestamp;
foreach (var log in _logs) foreach (var log in _logs)
{ {
logMessage.Data.Add(new KeyWithStringValue {Key = log.Key, Value = log.Value}); logMessage.Data.Add(new KeyValuePair<string, string>(log.Key, log.Value));
} }
return logMessage; return logMessage;
......
...@@ -20,7 +20,7 @@ namespace SkyWalking.Context.Trace ...@@ -20,7 +20,7 @@ namespace SkyWalking.Context.Trace
{ {
public enum SegmentRefType public enum SegmentRefType
{ {
CrossProcess, CrossProcess = 0,
CrossThread CrossThread = 1
} }
} }
\ No newline at end of file
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
...@@ -17,66 +17,65 @@ ...@@ -17,66 +17,65 @@
*/ */
using System; using System;
using System.Reflection; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Web.Configuration;
using SkyWalking.AspNet.Logging;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Logging; using SkyWalking.Logging;
using SkyWalking.Remote;
namespace SkyWalking.AspNet namespace SkyWalking
{ {
public class SkyWalkingStartup : IDisposable public abstract class ExecutionService : IExecutionService, IDisposable
{ {
public void Start() private Timer _timer;
private CancellationTokenSource _cancellationTokenSource;
protected readonly ILogger Logger;
protected readonly IRuntimeEnvironment RuntimeEnvironment;
protected readonly ISkyWalkingClient SkyWalking;
protected ExecutionService(ISkyWalkingClient skyWalking, IRuntimeEnvironment runtimeEnvironment, ILoggerFactory loggerFactory)
{ {
LoadConfigurationSetting(); SkyWalking = skyWalking;
LogManager.SetLoggerFactory(new DebugLoggerFactoryAdapter()); RuntimeEnvironment = runtimeEnvironment;
AsyncContext.Run(async () => await StartAsync()); Logger = loggerFactory.CreateLogger(GetType());
} }
private async Task StartAsync() public Task StartAsync(CancellationToken cancellationToken = default(CancellationToken))
{ {
await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(3)); _cancellationTokenSource = new CancellationTokenSource();
await ServiceManager.Instance.Initialize(); var source = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token, cancellationToken);
_timer = new Timer(Callback, source, DueTime, Period);
Logger.Information($"Loaded instrument service [{GetType().FullName}].");
return Task.CompletedTask;
} }
private void LoadConfigurationSetting() public async Task StopAsync(CancellationToken cancellationToken = default(CancellationToken))
{ {
CollectorConfig.DirectServers = GetAppSetting(nameof(CollectorConfig.DirectServers), true); _cancellationTokenSource?.Cancel();
AgentConfig.ApplicationCode = GetAppSetting(nameof(AgentConfig.ApplicationCode), true); await Stopping(cancellationToken);
AgentConfig.Namespace = GetAppSetting(nameof(AgentConfig.Namespace), false); Logger.Information($"Stopped instrument service {GetType().Name}.");
CollectorConfig.CertificatePath = GetAppSetting(nameof(CollectorConfig.CertificatePath), false);
CollectorConfig.Authentication = GetAppSetting(nameof(CollectorConfig.Authentication), false);
var samplePer3Secs = GetAppSetting(nameof(AgentConfig.SamplePer3Secs), false);
if (int.TryParse(samplePer3Secs, out var v))
{
AgentConfig.SamplePer3Secs = v;
} }
var pendingSegmentsLimit = GetAppSetting(nameof(AgentConfig.PendingSegmentsLimit), false);
if(int.TryParse(pendingSegmentsLimit, out v)) 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 (state is CancellationTokenSource token && !token.IsCancellationRequested && CanExecute())
if (@throw && string.IsNullOrEmpty(value))
{ {
throw new InvalidOperationException($"Cannot read valid '{key}' in AppSettings."); await ExecuteAsync(token.Token);
} }
return value;
} }
public void Dispose() protected virtual bool CanExecute() => RuntimeEnvironment.Initialized;
{
AsyncContext.Run(async () => await GrpcConnectionManager.Instance.ShutdownAsync()); protected virtual Task Stopping(CancellationToken cancellationToke) => Task.CompletedTask;
ServiceManager.Instance.Dispose();
} protected abstract TimeSpan DueTime { get; }
protected abstract TimeSpan Period { get; }
protected abstract Task ExecuteAsync(CancellationToken cancellationToken);
} }
} }
\ No newline at end of file
namespace SkyWalking
{
public interface IEnvironmentProvider
{
string EnvironmentName { get; }
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking
{
public interface IExecutionService
{
Task StartAsync(CancellationToken cancellationToken = default(CancellationToken));
Task StopAsync(CancellationToken cancellationToken = default(CancellationToken));
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using SkyWalking.Config;
namespace SkyWalking
{
public interface IRuntimeEnvironment
{
NullableValue ApplicationId { get; }
NullableValue ApplicationInstanceId { get; }
bool Initialized { get; }
Guid AgentUUID { get; }
IEnvironmentProvider Environment { get; }
}
}
\ No newline at end of file
...@@ -16,13 +16,11 @@ ...@@ -16,13 +16,11 @@
* *
*/ */
using SkyWalking.Boot; namespace SkyWalking
namespace SkyWalking.Sampling
{ {
public interface ISampler : IBootService public interface ISampler
{ {
bool TrySampling(); bool Sampled();
void ForceSampled(); void ForceSampled();
} }
......
using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking
{
public interface ISkyWalkingAgentStartup
{
Task StartAsync(CancellationToken cancellationToken = default(CancellationToken));
Task StopAsync(CancellationToken cancellationToken = default(CancellationToken));
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Transport;
namespace SkyWalking
{
public interface ISkyWalkingClient
{
Task<NullableValue> RegisterApplicationAsync(string applicationCode, CancellationToken cancellationToken = default(CancellationToken));
Task<NullableValue> RegisterApplicationInstanceAsync(int applicationId, Guid agentUUID, long registerTime, AgentOsInfoRequest osInfoRequest,
CancellationToken cancellationToken = default(CancellationToken));
Task HeartbeatAsync(int applicationInstance, long heartbeatTime, CancellationToken cancellationToken = default(CancellationToken));
Task CollectAsync(IEnumerable<TraceSegmentRequest> request, CancellationToken cancellationToken = default(CancellationToken));
}
}
\ No newline at end of file
...@@ -16,7 +16,7 @@ ...@@ -16,7 +16,7 @@
* *
*/ */
namespace SkyWalking.Diagnostics namespace SkyWalking
{ {
public interface ITracingDiagnosticProcessor public interface ITracingDiagnosticProcessor
{ {
......
...@@ -24,7 +24,7 @@ namespace SkyWalking.Logging ...@@ -24,7 +24,7 @@ namespace SkyWalking.Logging
{ {
void Debug(string message); void Debug(string message);
void Info(string message); void Information(string message);
void Warning(string message); void Warning(string message);
......
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace SkyWalking
{
public struct NullableValue
{
public static readonly NullableValue Null = new NullableValue(0);
private const int NULL_VALUE = 0;
public int Value { get; }
public NullableValue(int value)
{
Value = value;
}
public bool HasValue => Value != NULL_VALUE;
}
}
\ No newline at end of file
...@@ -3,16 +3,12 @@ ...@@ -3,16 +3,12 @@
<PropertyGroup> <PropertyGroup>
<Description>SkyWalking Core abstractions and interfaces for apm agent.</Description> <Description>SkyWalking Core abstractions and interfaces for apm agent.</Description>
<AssemblyTitle>SkyWalking.Abstractions</AssemblyTitle> <AssemblyTitle>SkyWalking.Abstractions</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net45;net451</TargetFrameworks>
<AssemblyName>SkyWalking.Abstractions</AssemblyName> <AssemblyName>SkyWalking.Abstractions</AssemblyName>
<PackageId>SkyWalking.Abstractions</PackageId> <PackageId>SkyWalking.Abstractions</PackageId>
<PackageTags>SkyWalking;APM</PackageTags> <PackageTags>SkyWalking;APM</PackageTags>
<PackageReleaseNotes> <PackageReleaseNotes>
</PackageReleaseNotes> </PackageReleaseNotes>
<RootNamespace>SkyWalking</RootNamespace> <RootNamespace>SkyWalking</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.NetworkProtocol.Trace\SkyWalking.NetworkProtocol.Trace.csproj" />
<ProjectReference Include="..\SkyWalking.NetworkProtocol\SkyWalking.NetworkProtocol.csproj" />
</ItemGroup>
</Project> </Project>
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace SkyWalking
{
public struct StringOrIntValue
{
private readonly int _intValue;
private readonly string _stringValue;
public StringOrIntValue(int value)
{
_intValue = value;
_stringValue = null;
}
public bool HasIntValue => _intValue != 0;
public bool HasStringValue => _stringValue != null;
public StringOrIntValue(string value)
{
_intValue = 0;
_stringValue = value;
}
public StringOrIntValue(int intValue, string stringValue)
{
_intValue = intValue;
_stringValue = stringValue;
}
public int GetIntValue() => _intValue;
public string GetStringValue() => _stringValue;
public (string, int) GetValue()
{
return (_stringValue, _intValue);
}
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace SkyWalking.Transport
{
public class AgentOsInfoRequest
{
public string OsName { get; set; }
public string HostName { get; set; }
public int ProcessNo { get; set; }
public string[] IpAddress { get; set; }
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Threading;
using System.Threading.Tasks;
namespace SkyWalking.Transport
{
public interface ITraceDispatcher
{
bool Dispatch(TraceSegmentRequest segment);
Task Flush(CancellationToken token = default(CancellationToken));
void Close();
}
}
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenSkywalking licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
namespace SkyWalking.Transport
{
public class TraceSegmentRequest
{
public IEnumerable<UniqueIdRequest> UniqueIds { get; set; }
public TraceSegmentObjectRequest Segment { get; set; }
}
public class UniqueIdRequest
{
public long Part1 { get; set; }
public long Part2 { get; set; }
public long Part3 { get; set; }
public override string ToString()
{
return $"{Part1}.{Part2}.{Part3}";
}
}
public class TraceSegmentObjectRequest
{
public UniqueIdRequest SegmentId { get; set; }
public int ApplicationId { get; set; }
public int ApplicationInstanceId { get; set; }
public IList<SpanRequest> Spans { get; set; } = new List<SpanRequest>();
}
public class SpanRequest
{
public int SpanId { get; set; }
public int SpanType { get; set; }
public int SpanLayer { get; set; }
public int ParentSpanId { get; set; }
public long StartTime { get; set; }
public long EndTime { get; set; }
public StringOrIntValue Component { get; set; }
public StringOrIntValue OperationName { get; set; }
public StringOrIntValue Peer { get; set; }
public bool IsError { get; set; }
public IList<TraceSegmentReferenceRequest> References { get; } = new List<TraceSegmentReferenceRequest>();
public IList<KeyValuePair<string, string>> Tags { get; } = new List<KeyValuePair<string, string>>();
public IList<LogDataRequest> Logs { get; } = new List<LogDataRequest>();
}
public class TraceSegmentReferenceRequest
{
public UniqueIdRequest ParentTraceSegmentId { get; set; }
public int ParentApplicationInstanceId { get; set; }
public int ParentSpanId { get; set; }
public int EntryApplicationInstanceId { get; set; }
public int RefType { get; set; }
public StringOrIntValue ParentServiceName { get; set; }
public StringOrIntValue EntryServiceName { get; set; }
public StringOrIntValue NetworkAddress { get; set; }
}
public class LogDataRequest
{
public long Timestamp { get; set; }
public IList<KeyValuePair<string, string>> Data { get; } = new List<KeyValuePair<string, string>>();
}
}
\ No newline at end of file
...@@ -22,7 +22,7 @@ using System.Threading.Tasks; ...@@ -22,7 +22,7 @@ using System.Threading.Tasks;
namespace SkyWalking.AspNet namespace SkyWalking.AspNet
{ {
internal class AsyncContext internal static class AsyncContext
{ {
public static void Run(Func<Task> task) public static void Run(Func<Task> task)
{ {
......
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using Microsoft.Extensions.DependencyInjection;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Diagnostics;
using SkyWalking.Logging;
using SkyWalking.Service;
using SkyWalking.Transport;
using SkyWalking.Transport.Grpc;
using SkyWalking.Utilities.Configuration;
using SkyWalking.Utilities.Logging;
namespace SkyWalking.AspNet.Extensions
{
internal static class ServiceCollectionExtensions
{
public static IServiceCollection AddSkyWalkingCore(this IServiceCollection services)
{
services.AddSingleton<SkyWalkingApplicationRequestCallback>();
services.AddSingleton<IContextCarrierFactory, ContextCarrierFactory>();
services.AddSingleton<ITraceDispatcher, AsyncQueueTraceDispatcher>();
services.AddSingleton<IExecutionService, TraceSegmentTransportService>();
services.AddSingleton<IExecutionService, ServiceDiscoveryService>();
services.AddSingleton<IExecutionService, SamplingRefreshService>();
services.AddSingleton<ISkyWalkingAgentStartup, SkyWalkingAgentStartup>();
services.AddSingleton<TracingDiagnosticProcessorObserver>();
services.AddSingleton<IConfigAccessor, ConfigAccessor>();
services.AddSingleton<IEnvironmentProvider, HostingEnvironmentProvider>();
services.AddSingleton<ILoggerFactory, DefaultLoggerFactory>();
services.AddSingleton<ISkyWalkingClient, GrpcClient>();
services.AddSingleton<ConnectionManager>();
services.AddSingleton<IExecutionService, GrpcStateCheckService>();
services.AddSingleton<ISampler>(DefaultSampler.Instance);
services.AddSingleton(RuntimeEnvironment.Instance);
return services;
}
}
}
\ No newline at end of file
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
...@@ -18,15 +18,17 @@ ...@@ -18,15 +18,17 @@
using System; using System;
namespace SkyWalking.Utils namespace SkyWalking.AspNet
{ {
#if NET45 || NET451 internal class HostingEnvironmentProvider : IEnvironmentProvider
public static class DateTimeOffsetExtensions
{ {
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; ...@@ -20,30 +20,38 @@ using System;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using SkyWalking.Components;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Context.Tag; using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.AspNet namespace SkyWalking.AspNet
{ {
public class HttpTracingHandler : DelegatingHandler public class HttpTracingHandler : DelegatingHandler
{ {
private readonly IContextCarrierFactory _contextCarrierFactory;
public HttpTracingHandler() public HttpTracingHandler()
: this(new HttpClientHandler()) : this(new HttpClientHandler())
{ {
} }
public HttpTracingHandler(HttpMessageHandler innerHandler) public HttpTracingHandler(HttpMessageHandler innerHandler)
: this(innerHandler, CommonServiceLocator.ServiceLocator.Current.GetInstance<IContextCarrierFactory>())
{
}
private HttpTracingHandler(HttpMessageHandler innerHandler, IContextCarrierFactory contextCarrierFactory)
{ {
InnerHandler = innerHandler; InnerHandler = innerHandler;
_contextCarrierFactory = contextCarrierFactory;
} }
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken) CancellationToken cancellationToken)
{ {
var peer = $"{request.RequestUri.Host}:{request.RequestUri.Port}"; var peer = $"{request.RequestUri.Host}:{request.RequestUri.Port}";
var contextCarrier = new ContextCarrier(); var contextCarrier = _contextCarrierFactory.Create();
var span = ContextManager.CreateExitSpan(request.RequestUri.ToString(), contextCarrier, peer); var span = ContextManager.CreateExitSpan(request.RequestUri.ToString(), contextCarrier, peer);
try try
{ {
......
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
...@@ -16,30 +16,34 @@ ...@@ -16,30 +16,34 @@
* *
*/ */
using CommonServiceLocator;
using System;
using System.Collections.Generic;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SkyWalking.AspNetCore.Diagnostics; namespace SkyWalking.AspNet
using SkyWalking.AspNetCore.Logging;
using SkyWalking.Diagnostics;
using SkyWalking.Extensions.DependencyInjection;
using SkyWalking.Logging;
namespace SkyWalking.AspNetCore
{ {
internal static class SkyWalkingBuilderExtensions internal class ServiceProviderLocator : IServiceLocator
{
public static SkyWalkingBuilder AddHosting(this SkyWalkingBuilder builder)
{ {
builder.Services.AddSingleton<IHostedService, SkyWalkingHostedService>(); private readonly IServiceProvider _serviceProvider;
builder.Services.AddSingleton<ITracingDiagnosticProcessor, HostingDiagnosticProcessor>();
builder.Services.AddSingleton<ILoggerFactory, LoggerFactoryAdapter>();
return builder;
}
public static SkyWalkingBuilder AddDiagnostics(this SkyWalkingBuilder builder) public ServiceProviderLocator(IServiceProvider serviceProvider)
{ {
builder.Services.AddSingleton<TracingDiagnosticProcessorObserver>(); _serviceProvider = serviceProvider;
return builder;
} }
public object GetService(Type serviceType) => _serviceProvider.GetService(serviceType);
public object GetInstance(Type serviceType) => _serviceProvider.GetService(serviceType);
public object GetInstance(Type serviceType, string key) => GetInstance(serviceType);
public IEnumerable<object> GetAllInstances(Type serviceType) => _serviceProvider.GetServices(serviceType);
public TService GetInstance<TService>() => (TService) GetInstance(typeof(TService));
public TService GetInstance<TService>(string key) => (TService) GetInstance(typeof(TService));
public IEnumerable<TService> GetAllInstances<TService>() => _serviceProvider.GetServices<TService>();
} }
} }
\ No newline at end of file
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" /> <Import Project="..\..\build\common.props" />
<PropertyGroup> <PropertyGroup>
<TargetFrameworks>net45;net451;net452;net46;net461;net462;net47;net471</TargetFrameworks> <TargetFrameworks>net461;net462;net47;net471</TargetFrameworks>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<AssemblyName>SkyWalking.AspNet</AssemblyName> <AssemblyName>SkyWalking.AspNet</AssemblyName>
...@@ -13,13 +13,20 @@ ...@@ -13,13 +13,20 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Transport.Grpc\SkyWalking.Transport.Grpc.csproj" />
<ProjectReference Include="..\SkyWalking.Utilities.Configuration\SkyWalking.Utilities.Configuration.csproj" />
<ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
<ProjectReference Include="..\SkyWalking.Utilities.Logging\SkyWalking.Utilities.Logging.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<Reference Include="System.Configuration" /> <Reference Include="System.Configuration" />
<Reference Include="System.Web" /> <Reference Include="System.Web" />
<Reference Include="System.Net.Http"/> <Reference Include="System.Net.Http" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CommonServiceLocator" Version="2.0.4" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="2.1.0" />
<PackageReference Include="Microsoft.Web.Infrastructure" Version="1.0.0" /> <PackageReference Include="Microsoft.Web.Infrastructure" Version="1.0.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Web;
using SkyWalking.Components;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
namespace SkyWalking.AspNet
{
internal class SkyWalkingApplicationRequestCallback
{
private readonly IContextCarrierFactory _contextCarrierFactory;
private readonly InstrumentationConfig _config;
public SkyWalkingApplicationRequestCallback(IConfigAccessor configAccessor, IContextCarrierFactory carrierFactory)
{
_config = configAccessor.Get<InstrumentationConfig>();
_contextCarrierFactory = carrierFactory;
}
public void ApplicationOnBeginRequest(object sender, EventArgs e)
{
var httpApplication = sender as HttpApplication;
var httpContext = httpApplication.Context;
var carrier = _contextCarrierFactory.Create();
foreach (var item in carrier.Items)
item.HeadValue = httpContext.Request.Headers[item.HeadKey];
var httpRequestSpan = ContextManager.CreateEntrySpan($"{_config.ApplicationCode} {httpContext.Request.Path}", carrier);
httpRequestSpan.AsHttp();
httpRequestSpan.SetComponent(ComponentsDefine.AspNet);
Tags.Url.Set(httpRequestSpan, httpContext.Request.Path);
Tags.HTTP.Method.Set(httpRequestSpan, httpContext.Request.HttpMethod);
httpRequestSpan.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
new Dictionary<string, object>
{
{"event", "AspNet BeginRequest"},
{"message", $"Request starting {httpContext.Request.Url.Scheme} {httpContext.Request.HttpMethod} {httpContext.Request.Url.OriginalString}"}
});
}
public void ApplicationOnEndRequest(object sender, EventArgs e)
{
var httpRequestSpan = ContextManager.ActiveSpan;
if (httpRequestSpan == null)
{
return;
}
var httpApplication = sender as HttpApplication;
var httpContext = httpApplication.Context;
var statusCode = httpContext.Response.StatusCode;
if (statusCode >= 400)
{
httpRequestSpan.ErrorOccurred();
}
Tags.StatusCode.Set(httpRequestSpan, statusCode.ToString());
var exception = httpContext.Error;
if (exception != null)
{
httpRequestSpan.ErrorOccurred().Log(exception);
}
httpRequestSpan.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
new Dictionary<string, object>
{
{"event", "AspNet EndRequest"},
{"message", $"Request finished {httpContext.Response.StatusCode} {httpContext.Response.ContentType}"}
});
ContextManager.StopSpan(httpRequestSpan);
}
}
}
\ No newline at end of file
...@@ -16,87 +16,33 @@ ...@@ -16,87 +16,33 @@
* *
*/ */
using System; using CommonServiceLocator;
using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection;
using System.Web; using System.Web;
using SkyWalking.Boot; using SkyWalking.AspNet.Extensions;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Remote;
using SkyWalking.Utils;
namespace SkyWalking.AspNet namespace SkyWalking.AspNet
{ {
public class SkyWalkingModule : IHttpModule public class SkyWalkingModule : IHttpModule
{ {
private readonly SkyWalkingStartup _skyWalkingStartup = new SkyWalkingStartup(); public SkyWalkingModule()
public void Dispose()
{ {
_skyWalkingStartup.Dispose(); var serviceProvider = new ServiceCollection().AddSkyWalkingCore().BuildServiceProvider();
var serviceLocatorProvider = new ServiceProviderLocator(serviceProvider);
ServiceLocator.SetLocatorProvider(() => serviceLocatorProvider);
} }
public void Init(HttpApplication application) public void Init(HttpApplication application)
{ {
_skyWalkingStartup.Start(); var startup = ServiceLocator.Current.GetInstance<ISkyWalkingAgentStartup>();
application.BeginRequest += ApplicationOnBeginRequest; AsyncContext.Run(() => startup.StartAsync());
application.EndRequest += ApplicationOnEndRequest; var requestCallback = ServiceLocator.Current.GetInstance<SkyWalkingApplicationRequestCallback>();
} application.BeginRequest += requestCallback.ApplicationOnBeginRequest;
application.EndRequest += requestCallback.ApplicationOnEndRequest;
private void ApplicationOnBeginRequest(object sender, EventArgs e)
{
var httpApplication = sender as HttpApplication;
var httpContext = httpApplication.Context;
var carrier = new ContextCarrier();
foreach (var item in carrier.Items)
item.HeadValue = httpContext.Request.Headers[item.HeadKey];
var httpRequestSpan = ContextManager.CreateEntrySpan($"{Config.AgentConfig.ApplicationCode} {httpContext.Request.Path}", carrier);
httpRequestSpan.AsHttp();
httpRequestSpan.SetComponent(ComponentsDefine.AspNet);
Tags.Url.Set(httpRequestSpan, httpContext.Request.Path);
Tags.HTTP.Method.Set(httpRequestSpan, httpContext.Request.HttpMethod);
httpRequestSpan.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
new Dictionary<string, object>
{
{"event", "AspNet BeginRequest"},
{"message", $"Request starting {httpContext.Request.Url.Scheme} {httpContext.Request.HttpMethod} {httpContext.Request.Url.OriginalString}"}
});
}
private void ApplicationOnEndRequest(object sender, EventArgs e)
{
var httpRequestSpan = ContextManager.ActiveSpan;
if (httpRequestSpan == null)
{
return;
} }
var httpApplication = sender as HttpApplication; public void Dispose()
var httpContext = httpApplication.Context;
var statusCode = httpContext.Response.StatusCode;
if (statusCode >= 400)
{
httpRequestSpan.ErrorOccurred();
}
Tags.StatusCode.Set(httpRequestSpan, statusCode.ToString());
var exception = httpContext.Error;
if (exception != null)
{
httpRequestSpan.ErrorOccurred().Log(exception);
}
httpRequestSpan.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
new Dictionary<string, object>
{ {
{"event", "AspNetCore Hosting EndRequest"},
{"message", $"Request finished {httpContext.Response.StatusCode} {httpContext.Response.ContentType}"}
});
ContextManager.StopSpan(httpRequestSpan);
} }
} }
} }
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace SkyWalking.AspNet
{
public class SkyWalkingOptions
{
/// <summary>
/// Application code is showed in sky-walking-ui
/// </summary>
public string ApplicationCode { get; set; }
/// <summary>
/// Collector agent_gRPC/grpc service addresses.
/// By using this, no discovery mechanism provided. The agent only uses these addresses to uplink data.
/// Recommend to use this only when collector cluster IPs are unreachable from agent side. Such as:
/// 1. Agent and collector cluster are in different VPC in Cloud.
/// 2. Agent uplinks data to collector cluster through Internet.
/// Single collector:DirectServers="127.0.0.1:11800"
/// Collector cluster:DirectServers="10.2.45.126:11800,10.2.45.127:11800"
/// </summary>
public string DirectServers { get; set; }
/// <summary>
/// The number of sampled traces per 3 seconds
/// Negative number means sample traces as many as possible, most likely 100% , by default
///
/// </summary>
public int SamplePer3Secs { get; set; } = -1;
/// <summary>
/// Namespace isolates headers in cross propagation. The HEADER name will be 'HeaderName:Namespace'.
/// </summary>
public string Namespace { get; set; }
/// <summary>
/// The max number of segments in the memory queue waiting to be sent to collector.
/// It means that when the number of queued segments reachs this limit,
/// any more segments enqueued into the sending queue, will leads the same number of oldest queued segments dequeued and droped.
/// Zero or minus value means no limit.
/// </summary>
public int PendingSegmentsLimit { get; set; } = 300000;
/// <summary>
/// Set your own token to active auth
/// </summary>
public string Authentication
{
get;
set;
}
/// <summary>
/// Set certificate path to open ssl/tls
/// </summary>
public string CertificatePath
{
get;
set;
}
}
}
\ No newline at end of file
...@@ -17,45 +17,63 @@ ...@@ -17,45 +17,63 @@
*/ */
using System; using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SkyWalking.AspNetCore.Diagnostics;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Diagnostics;
using SkyWalking.Diagnostics.EntityFrameworkCore;
using SkyWalking.Diagnostics.HttpClient; using SkyWalking.Diagnostics.HttpClient;
using SkyWalking.Diagnostics.SqlClient; using SkyWalking.Diagnostics.SqlClient;
using SkyWalking.Extensions.DependencyInjection; using SkyWalking.Utilities.Configuration;
using SkyWalking.Utilities.DependencyInjection;
using SkyWalking.Utilities.Logging;
using SkyWalking.Logging;
using SkyWalking.Service;
using SkyWalking.Transport;
using SkyWalking.Transport.Grpc;
namespace SkyWalking.AspNetCore namespace SkyWalking.AspNetCore
{ {
public static class ServiceCollectionExtensions internal static class ServiceCollectionExtensions
{ {
public static SkyWalkingBuilder AddSkyWalking(this IServiceCollection services, public static IServiceCollection AddSkyWalkingCore(this IServiceCollection services)
Action<SkyWalkingOptions> options)
{ {
if (options == null) if (services == null)
{ {
throw new ArgumentNullException(nameof(options)); throw new ArgumentNullException(nameof(services));
} }
return services.Configure(options).AddSkyWalkingCore(); services.AddSingleton<IContextCarrierFactory, ContextCarrierFactory>();
services.AddSingleton<ITraceDispatcher, AsyncQueueTraceDispatcher>();
services.AddSingleton<IExecutionService, TraceSegmentTransportService>();
services.AddSingleton<IExecutionService, ServiceDiscoveryService>();
services.AddSingleton<IExecutionService, SamplingRefreshService>();
services.AddSingleton<ISkyWalkingAgentStartup, SkyWalkingAgentStartup>();
services.AddSingleton<ISampler>(DefaultSampler.Instance);
services.AddSingleton(RuntimeEnvironment.Instance);
services.AddSingleton<TracingDiagnosticProcessorObserver>();
services.AddSingleton<IConfigAccessor, ConfigAccessor>();
services.AddSingleton<IHostedService, InstrumentationHostedService>();
services.AddSingleton<IEnvironmentProvider, HostingEnvironmentProvider>();
services.AddGrpcTransport().AddLogging();
services.AddSkyWalkingExtensions().AddAspNetCoreHosting().AddHttpClient().AddSqlClient().AddEntityFrameworkCore(c => c.AddSqlite().AddPomeloMysql().AddNpgsql());
return services;
} }
public static SkyWalkingBuilder AddSkyWalking(this IServiceCollection services, private static IServiceCollection AddGrpcTransport(this IServiceCollection services)
IConfiguration configuration)
{ {
return services.Configure<SkyWalkingOptions>(configuration).AddSkyWalkingCore(); services.AddSingleton<ISkyWalkingClient, GrpcClient>();
services.AddSingleton<ConnectionManager>();
services.AddSingleton<IExecutionService, GrpcStateCheckService>();
return services;
} }
private static SkyWalkingBuilder AddSkyWalkingCore(this IServiceCollection services) private static IServiceCollection AddLogging(this IServiceCollection services)
{ {
if (services == null) services.AddSingleton<ILoggerFactory, DefaultLoggerFactory>();
{ return services;
throw new ArgumentNullException(nameof(services));
}
var builder = new SkyWalkingBuilder(services);
builder.AddHosting().AddDiagnostics().AddHttpClient().AddSqlClient();
return builder;
} }
} }
} }
\ No newline at end of file
using Microsoft.AspNetCore.Hosting;
namespace SkyWalking.AspNetCore
{
internal class HostingEnvironmentProvider : IEnvironmentProvider
{
public string EnvironmentName { get; }
public HostingEnvironmentProvider(IHostingEnvironment hostingEnvironment)
{
EnvironmentName = hostingEnvironment.EnvironmentName;
}
}
}
\ No newline at end of file
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
...@@ -16,29 +16,29 @@ ...@@ -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 readonly ISkyWalkingAgentStartup _startup;
private static ILoggerFactory _loggerFactory;
public static ILogger GetLogger(Type type) public InstrumentationHostedService(ISkyWalkingAgentStartup startup)
{ {
var loggerFactory = _loggerFactory ?? defaultLoggerFactory; _startup = startup;
return loggerFactory.CreateLogger(type);
} }
public static ILogger GetLogger<T>() public Task StartAsync(CancellationToken cancellationToken)
{ {
return GetLogger(typeof(T)); return _startup.StartAsync(cancellationToken);
} }
public static void SetLoggerFactory(ILoggerFactory loggerFactory) public Task StopAsync(CancellationToken cancellationToken)
{ {
_loggerFactory = loggerFactory; return _startup.StopAsync(cancellationToken);
} }
} }
} }
\ No newline at end of file
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
<Description>SkyWalking ASP.NET Core Agent.</Description> <Description>SkyWalking ASP.NET Core Agent.</Description>
<AssemblyTitle>SkyWalking.AspNetCore</AssemblyTitle> <AssemblyTitle>SkyWalking.AspNetCore</AssemblyTitle>
<TargetFramework>netstandard2.0</TargetFramework> <TargetFramework>netstandard2.0</TargetFramework>
<AssemblyName>SkyWalking.AspNetCore</AssemblyName> <AssemblyName>SkyWalking_AspNetCore</AssemblyName>
<PackageId>SkyWalking.AspNetCore</PackageId> <PackageId>SkyWalking.AspNetCore</PackageId>
<PackageTags>SkyWalking;APM</PackageTags> <PackageTags>SkyWalking;APM</PackageTags>
<PackageReleaseNotes> <PackageReleaseNotes>
...@@ -12,18 +12,22 @@ ...@@ -12,18 +12,22 @@
<RootNamespace>SkyWalking.AspNetCore</RootNamespace> <RootNamespace>SkyWalking.AspNetCore</RootNamespace>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Hosting.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.0.0" /> <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.0.0" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.0.0" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" /> <ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.AspNetCore\SkyWalking.Diagnostics.AspNetCore.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore.Npgsql\SkyWalking.Diagnostics.EntityFrameworkCore.Npgsql.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore.Pomelo.MySql\SkyWalking.Diagnostics.EntityFrameworkCore.Pomelo.MySql.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore.Sqlite\SkyWalking.Diagnostics.EntityFrameworkCore.Sqlite.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.EntityFrameworkCore\SkyWalking.Diagnostics.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.HttpClient\SkyWalking.Diagnostics.HttpClient.csproj" /> <ProjectReference Include="..\SkyWalking.Diagnostics.HttpClient\SkyWalking.Diagnostics.HttpClient.csproj" />
<ProjectReference Include="..\SkyWalking.Diagnostics.SqlClient\SkyWalking.Diagnostics.SqlClient.csproj" /> <ProjectReference Include="..\SkyWalking.Diagnostics.SqlClient\SkyWalking.Diagnostics.SqlClient.csproj" />
<ProjectReference Include="..\SkyWalking.Extensions.DependencyInjection\SkyWalking.Extensions.DependencyInjection.csproj"> <ProjectReference Include="..\SkyWalking.Utilities.Configuration\SkyWalking.Utilities.Configuration.csproj" />
<Project>{BF5579ED-113C-4EE6-AE03-9A9CA590C924}</Project> <ProjectReference Include="..\SkyWalking.Utilities.DependencyInjection\SkyWalking.Utilities.DependencyInjection.csproj" />
<Name>SkyWalking.Extensions.DependencyInjection</Name> <ProjectReference Include="..\SkyWalking.Utilities.Logging\SkyWalking.Utilities.Logging.csproj" />
</ProjectReference> <ProjectReference Include="..\SkyWalking.Transport.Grpc\SkyWalking.Transport.Grpc.csproj" />
</ItemGroup> </ItemGroup>
</Project> </Project>
\ No newline at end of file
using Microsoft.AspNetCore.Hosting;
using SkyWalking.AspNetCore;
[assembly: HostingStartup(typeof(SkyWalkingHostingStartup))]
namespace SkyWalking.AspNetCore
{
public class SkyWalkingHostingStartup : IHostingStartup
{
public void Configure(IWebHostBuilder builder)
{
builder.ConfigureServices(services => services.AddSkyWalkingCore());
}
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Runtime.CompilerServices;
using Microsoft.Extensions.Options;
namespace SkyWalking.AspNetCore
{
public class SkyWalkingOptions : IOptions<SkyWalkingOptions>
{
public SkyWalkingOptions Value => this;
/// <summary>
/// Application code is showed in sky-walking-ui
/// </summary>
public string ApplicationCode
{
get;
set;
}
/// <summary>
/// Collector agent_gRPC/grpc service addresses.
/// By using this, no discovery mechanism provided. The agent only uses these addresses to uplink data.
/// Recommend to use this only when collector cluster IPs are unreachable from agent side. Such as:
/// 1. Agent and collector cluster are in different VPC in Cloud.
/// 2. Agent uplinks data to collector cluster through Internet.
/// Single collector:DirectServers="127.0.0.1:11800"
/// Collector cluster:DirectServers="10.2.45.126:11800,10.2.45.127:11800"
/// </summary>
public string DirectServers
{
get;
set;
}
/// <summary>
/// The number of sampled traces per 3 seconds
/// Negative number means sample traces as many as possible, most likely 100% , by default
///
/// </summary>
public int SamplePer3Secs
{
get;
set;
} = -1;
/// <summary>
/// The max number of segments in the memory queue waiting to be sent to collector.
/// It means that when the number of queued segments reachs this limit,
/// any more segments enqueued into the sending queue, will leads the same number of oldest queued segments dequeued and droped.
/// Zero or minus value means no limit.
/// </summary>
public int PendingSegmentsLimit
{
get;
set;
} = 300000;
/// <summary>
/// Set your own token to active auth
/// </summary>
public string Authentication
{
get;
set;
}
/// <summary>
/// Set certificate path to open ssl/tls
/// </summary>
public string CertificatePath
{
get;
set;
}
}
}
...@@ -21,7 +21,7 @@ namespace SkyWalking.Context ...@@ -21,7 +21,7 @@ namespace SkyWalking.Context
{ {
public class CarrierItemHead : CarrierItem public class CarrierItemHead : CarrierItem
{ {
public CarrierItemHead(CarrierItem next) : base(string.Empty, string.Empty, next) public CarrierItemHead(CarrierItem next, string @namespace) : base(string.Empty, string.Empty, next, @namespace)
{ {
} }
} }
......
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.Dictionarys;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
...@@ -35,12 +34,12 @@ namespace SkyWalking.Context ...@@ -35,12 +34,12 @@ namespace SkyWalking.Context
/// <summary> /// <summary>
/// id of parent application instance /// id of parent application instance
/// </summary> /// </summary>
private int _parentApplicationInstanceId = DictionaryUtil.NullValue; private int _parentApplicationInstanceId = 0;
/// <summary> /// <summary>
/// id of first application instance in this distributed trace /// id of first application instance in this distributed trace
/// </summary> /// </summary>
private int _entryApplicationInstanceId = DictionaryUtil.NullValue; private int _entryApplicationInstanceId = 0;
/// <summary> /// <summary>
/// peer(ipv4/ipv6/hostname + port) of the server , from client side . /// peer(ipv4/ipv6/hostname + port) of the server , from client side .
...@@ -65,6 +64,12 @@ namespace SkyWalking.Context ...@@ -65,6 +64,12 @@ namespace SkyWalking.Context
private DistributedTraceId _primaryDistributedTraceId; private DistributedTraceId _primaryDistributedTraceId;
private readonly string _namespace;
public ContextCarrier(string @namespace)
{
_namespace = @namespace;
}
public DistributedTraceId DistributedTraceId => _primaryDistributedTraceId; public DistributedTraceId DistributedTraceId => _primaryDistributedTraceId;
...@@ -135,8 +140,8 @@ namespace SkyWalking.Context ...@@ -135,8 +140,8 @@ namespace SkyWalking.Context
return _traceSegmentId != null return _traceSegmentId != null
&& _traceSegmentId.IsValid && _traceSegmentId.IsValid
&& _spanId > -1 && _spanId > -1
&& _parentApplicationInstanceId != DictionaryUtil.NullValue && _parentApplicationInstanceId != 0
&& _entryApplicationInstanceId != DictionaryUtil.NullValue && _entryApplicationInstanceId != 0
&& !string.IsNullOrEmpty(_peerHost) && !string.IsNullOrEmpty(_peerHost)
&& !string.IsNullOrEmpty(_parentOperationName) && !string.IsNullOrEmpty(_parentOperationName)
&& !string.IsNullOrEmpty(_entryOperationName) && !string.IsNullOrEmpty(_entryOperationName)
...@@ -180,17 +185,14 @@ namespace SkyWalking.Context ...@@ -180,17 +185,14 @@ namespace SkyWalking.Context
PrimaryDistributedTraceId.Encode); PrimaryDistributedTraceId.Encode);
} }
public DistributedTraceId PrimaryDistributedTraceId public DistributedTraceId PrimaryDistributedTraceId => _primaryDistributedTraceId;
{
get { return _primaryDistributedTraceId; }
}
public CarrierItem Items public CarrierItem Items
{ {
get get
{ {
SW3CarrierItem carrierItem = new SW3CarrierItem(this, null); var carrierItem = new SW3CarrierItem(this, null, _namespace);
CarrierItemHead head = new CarrierItemHead(carrierItem); var head = new CarrierItemHead(carrierItem, _namespace);
return head; return head;
} }
} }
......
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
...@@ -16,22 +16,22 @@ ...@@ -16,22 +16,22 @@
* *
*/ */
using System; using SkyWalking.Config;
using System.Diagnostics;
using SkyWalking.Logging;
namespace SkyWalking.AspNet.Logging namespace SkyWalking.Context
{ {
internal class DebugLoggerFactoryAdapter : ILoggerFactory public class ContextCarrierFactory : IContextCarrierFactory
{ {
public DebugLoggerFactoryAdapter() private readonly InstrumentationConfig _config;
public ContextCarrierFactory(IConfigAccessor configAccessor)
{ {
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out)); _config = configAccessor.Get<InstrumentationConfig>();
} }
public ILogger CreateLogger(Type type) public IContextCarrier Create()
{ {
return new DebugLoggerAdapter(type); return new ContextCarrier(_config.Namespace);
} }
} }
} }
\ No newline at end of file
...@@ -16,16 +16,9 @@ ...@@ -16,16 +16,9 @@
* *
*/ */
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading; using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.Dictionarys;
using SkyWalking.Sampling;
using SkyWalking.Utils;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
...@@ -34,8 +27,15 @@ namespace SkyWalking.Context ...@@ -34,8 +27,15 @@ namespace SkyWalking.Context
/// We also provide the CONTEXT propagation based on ThreadLocal mechanism. /// We also provide the CONTEXT propagation based on ThreadLocal mechanism.
/// Meaning, each segment also related to singe thread. /// Meaning, each segment also related to singe thread.
/// </summary> /// </summary>
public class ContextManager : ITracingContextListener, IBootService, IIgnoreTracerContextListener public class ContextManager : ITracingContextListener, IIgnoreTracerContextListener
{ {
static ContextManager()
{
var manager = new ContextManager();
TracingContext.ListenerManager.Add(manager);
IgnoredTracerContext.ListenerManager.Add(manager);
}
private static readonly AsyncLocal<ITracerContext> _context = new AsyncLocal<ITracerContext>(); private static readonly AsyncLocal<ITracerContext> _context = new AsyncLocal<ITracerContext>();
private static ITracerContext GetOrCreateContext(string operationName, bool forceSampling) private static ITracerContext GetOrCreateContext(string operationName, bool forceSampling)
...@@ -50,18 +50,17 @@ namespace SkyWalking.Context ...@@ -50,18 +50,17 @@ namespace SkyWalking.Context
} }
else else
{ {
if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && if (RuntimeEnvironment.Instance.Initialized)
!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
{ {
var suffixIdx = operationName.LastIndexOf('.'); // var suffixIdx = operationName.LastIndexOf('.');
if (suffixIdx > -1 && AgentConfig.IgnoreSuffix.Contains(operationName.Substring(suffixIdx))) // if (suffixIdx > -1 && AgentConfig.IgnoreSuffix.Contains(operationName.Substring(suffixIdx)))
{ // {
_context.Value = new IgnoredTracerContext(); // _context.Value = new IgnoredTracerContext();
} // }
else // else
{ // {
var sampler = ServiceManager.Instance.GetService<SamplingService>(); var sampler = DefaultSampler.Instance;
if (forceSampling || sampler.TrySampling()) if (forceSampling || sampler.Sampled())
{ {
_context.Value = new TracingContext(); _context.Value = new TracingContext();
} }
...@@ -69,14 +68,13 @@ namespace SkyWalking.Context ...@@ -69,14 +68,13 @@ namespace SkyWalking.Context
{ {
_context.Value = new IgnoredTracerContext(); _context.Value = new IgnoredTracerContext();
} }
} // }
} }
else else
{ {
_context.Value = new IgnoredTracerContext(); _context.Value = new IgnoredTracerContext();
} }
} }
} }
return _context.Value; return _context.Value;
...@@ -103,7 +101,7 @@ namespace SkyWalking.Context ...@@ -103,7 +101,7 @@ namespace SkyWalking.Context
public static ISpan CreateEntrySpan(string operationName, IContextCarrier carrier) public static ISpan CreateEntrySpan(string operationName, IContextCarrier carrier)
{ {
var samplingService = ServiceManager.Instance.GetService<SamplingService>(); var samplingService = DefaultSampler.Instance;
if (carrier != null && carrier.IsValid) if (carrier != null && carrier.IsValid)
{ {
samplingService.ForceSampled(); samplingService.ForceSampled();
...@@ -179,19 +177,6 @@ namespace SkyWalking.Context ...@@ -179,19 +177,6 @@ namespace SkyWalking.Context
_context.Value = null; _context.Value = null;
} }
public void Dispose()
{
}
public int Order { get; } = 1;
public Task Initialize(CancellationToken token)
{
TracingContext.ListenerManager.Add(this);
IgnoredTracerContext.ListenerManager.Add(this);
return TaskUtils.CompletedTask;
}
public void AfterFinish(ITracerContext tracerContext) public void AfterFinish(ITracerContext tracerContext)
{ {
_context.Value = null; _context.Value = null;
......
...@@ -19,7 +19,6 @@ ...@@ -19,7 +19,6 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.Dictionarys;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
...@@ -39,7 +38,7 @@ namespace SkyWalking.Context ...@@ -39,7 +38,7 @@ namespace SkyWalking.Context
private string _parentOperationName; private string _parentOperationName;
private readonly DistributedTraceId _primaryDistributedTraceId; private readonly DistributedTraceId _primaryDistributedTraceId;
private int _entryApplicationInstanceId = DictionaryUtil.NullValue; private NullableValue _entryApplicationInstanceId = NullableValue.Null;
public ContextSnapshot(ID traceSegmentId, int spanId, IEnumerable<DistributedTraceId> distributedTraceIds) public ContextSnapshot(ID traceSegmentId, int spanId, IEnumerable<DistributedTraceId> distributedTraceIds)
{ {
...@@ -48,7 +47,6 @@ namespace SkyWalking.Context ...@@ -48,7 +47,6 @@ namespace SkyWalking.Context
_primaryDistributedTraceId = distributedTraceIds?.FirstOrDefault(); _primaryDistributedTraceId = distributedTraceIds?.FirstOrDefault();
} }
public string EntryOperationName public string EntryOperationName
{ {
get => _entryOperationName; get => _entryOperationName;
...@@ -65,8 +63,8 @@ namespace SkyWalking.Context ...@@ -65,8 +63,8 @@ namespace SkyWalking.Context
public int EntryApplicationInstanceId public int EntryApplicationInstanceId
{ {
get => _entryApplicationInstanceId; get => _entryApplicationInstanceId.Value;
set => _entryApplicationInstanceId = value; set => _entryApplicationInstanceId = new NullableValue(value);
} }
public int SpanId => _spanId; public int SpanId => _spanId;
...@@ -75,7 +73,7 @@ namespace SkyWalking.Context ...@@ -75,7 +73,7 @@ namespace SkyWalking.Context
public bool IsValid => _traceSegmentId != null public bool IsValid => _traceSegmentId != null
&& _spanId > -1 && _spanId > -1
&& _entryApplicationInstanceId != DictionaryUtil.NullValue && _entryApplicationInstanceId.HasValue
&& _primaryDistributedTraceId != null && _primaryDistributedTraceId != null
&& string.IsNullOrEmpty(_entryOperationName) && string.IsNullOrEmpty(_entryOperationName)
&& string.IsNullOrEmpty(_parentOperationName); && string.IsNullOrEmpty(_parentOperationName);
......
...@@ -18,9 +18,6 @@ ...@@ -18,9 +18,6 @@
using System; using System;
using System.Threading; using System.Threading;
using SkyWalking.Config;
using SkyWalking.Dictionarys;
using SkyWalking.Utils;
namespace SkyWalking.Context.Ids namespace SkyWalking.Context.Ids
{ {
...@@ -30,7 +27,7 @@ namespace SkyWalking.Context.Ids ...@@ -30,7 +27,7 @@ namespace SkyWalking.Context.Ids
public static ID Generate() public static ID Generate()
{ {
if (RemoteDownstreamConfig.Agent.ApplicationId == DictionaryUtil.NullValue) if (!RuntimeEnvironment.Instance.ApplicationInstanceId.HasValue)
{ {
throw new InvalidOperationException(); throw new InvalidOperationException();
} }
...@@ -38,7 +35,7 @@ namespace SkyWalking.Context.Ids ...@@ -38,7 +35,7 @@ namespace SkyWalking.Context.Ids
IDContext context = threadIdSequence.Value; IDContext context = threadIdSequence.Value;
return new ID( return new ID(
RemoteDownstreamConfig.Agent.ApplicationInstanceId, RuntimeEnvironment.Instance.ApplicationInstanceId.Value,
Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ManagedThreadId,
context.NextSeq() context.NextSeq()
); );
......
...@@ -22,15 +22,19 @@ namespace SkyWalking.Context ...@@ -22,15 +22,19 @@ namespace SkyWalking.Context
{ {
public class SW3CarrierItem : CarrierItem public class SW3CarrierItem : CarrierItem
{ {
public const String HEADER_NAME = "sw3"; private const string HEADER_NAME = "sw3";
private readonly IContextCarrier _carrier; private readonly IContextCarrier _carrier;
public SW3CarrierItem(IContextCarrier carrier, CarrierItem next) public SW3CarrierItem(IContextCarrier carrier, CarrierItem next, string @namespace)
: base(HEADER_NAME, carrier.Serialize(), next) : base(HEADER_NAME, carrier.Serialize(), next, @namespace)
{ {
_carrier = carrier; _carrier = carrier;
} }
public override string HeadValue { get => base.HeadValue; set => _carrier.Deserialize(value); } public override string HeadValue
{
get => base.HeadValue;
set => _carrier.Deserialize(value);
}
} }
} }
\ No newline at end of file
...@@ -16,8 +16,7 @@ ...@@ -16,8 +16,7 @@
* *
*/ */
using SkyWalking.Dictionarys; using SkyWalking.Components;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -119,7 +118,7 @@ namespace SkyWalking.Context.Trace ...@@ -119,7 +118,7 @@ namespace SkyWalking.Context.Trace
private void ClearWhenRestart() private void ClearWhenRestart()
{ {
_componentId = DictionaryUtil.NullValue; _componentId = 0;
_componentName = null; _componentName = null;
_layer = null; _layer = null;
_logs = null; _logs = null;
......
...@@ -17,11 +17,8 @@ ...@@ -17,11 +17,8 @@
*/ */
using System; using System;
using System.Collections.Generic; using SkyWalking.Transport;
using System.Text; using SkyWalking.Components;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -34,7 +31,7 @@ namespace SkyWalking.Context.Trace ...@@ -34,7 +31,7 @@ namespace SkyWalking.Context.Trace
: base(spanId, parentSpanId, operationName) : base(spanId, parentSpanId, operationName)
{ {
_peer = peer; _peer = peer;
_peerId = DictionaryUtil.NullValue; _peerId = 0;
} }
public ExitSpan(int spanId, int parentSpanId, int operationId, int peerId) public ExitSpan(int spanId, int parentSpanId, int operationId, int peerId)
...@@ -48,7 +45,7 @@ namespace SkyWalking.Context.Trace ...@@ -48,7 +45,7 @@ namespace SkyWalking.Context.Trace
: base(spanId, parentSpanId, operationId) : base(spanId, parentSpanId, operationId)
{ {
_peer = peer; _peer = peer;
_peerId = DictionaryUtil.NullValue; _peerId = 0;
} }
public ExitSpan(int spanId, int parentSpanId, String operationName, int peerId) public ExitSpan(int spanId, int parentSpanId, String operationName, int peerId)
...@@ -108,17 +105,12 @@ namespace SkyWalking.Context.Trace ...@@ -108,17 +105,12 @@ namespace SkyWalking.Context.Trace
public override ISpan SetComponent(string componentName) public override ISpan SetComponent(string componentName)
{ {
if (_stackDepth == 1) return _stackDepth == 1 ? base.SetComponent(componentName) : this;
{
return base.SetComponent(componentName);
}
return this;
} }
public override string OperationName public override string OperationName
{ {
get { return base.OperationName; } get => base.OperationName;
set set
{ {
if (_stackDepth == 1) if (_stackDepth == 1)
...@@ -130,7 +122,7 @@ namespace SkyWalking.Context.Trace ...@@ -130,7 +122,7 @@ namespace SkyWalking.Context.Trace
public override int OperationId public override int OperationId
{ {
get { return base.OperationId; } get => base.OperationId;
set set
{ {
if (_stackDepth == 1) if (_stackDepth == 1)
...@@ -140,18 +132,11 @@ namespace SkyWalking.Context.Trace ...@@ -140,18 +132,11 @@ namespace SkyWalking.Context.Trace
} }
} }
public override SpanObject Transform() public override SpanRequest Transform()
{ {
var spanObject = base.Transform(); var spanObject = base.Transform();
if (_peerId != DictionaryUtil.NullValue) spanObject.Peer = new StringOrIntValue(_peerId, _peer);
{
spanObject.PeerId = _peerId;
}
else
{
spanObject.Peer = _peer;
}
return spanObject; return spanObject;
} }
......
...@@ -18,8 +18,7 @@ ...@@ -18,8 +18,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using SkyWalking.Components;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
......
...@@ -18,10 +18,8 @@ ...@@ -18,10 +18,8 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using Google.Protobuf; using SkyWalking.Transport;
using SkyWalking.Config;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
...@@ -30,12 +28,11 @@ namespace SkyWalking.Context.Trace ...@@ -30,12 +28,11 @@ namespace SkyWalking.Context.Trace
private readonly IList<ITraceSegmentRef> _refs; private readonly IList<ITraceSegmentRef> _refs;
private readonly IList<AbstractTracingSpan> _spans; private readonly IList<AbstractTracingSpan> _spans;
private readonly DistributedTraceIdCollection _relatedGlobalTraces; private readonly DistributedTraceIdCollection _relatedGlobalTraces;
private bool _isSizeLimited = false; private bool _isSizeLimited;
public int ApplicationId => RuntimeEnvironment.Instance.ApplicationId.Value;
public int ApplicationId => RemoteDownstreamConfig.Agent.ApplicationId; public int ApplicationInstanceId => RuntimeEnvironment.Instance.ApplicationInstanceId.Value;
public int ApplicationInstanceId => RemoteDownstreamConfig.Agent.ApplicationInstanceId;
public IEnumerable<ITraceSegmentRef> Refs => _refs; public IEnumerable<ITraceSegmentRef> Refs => _refs;
...@@ -85,21 +82,21 @@ namespace SkyWalking.Context.Trace ...@@ -85,21 +82,21 @@ namespace SkyWalking.Context.Trace
_relatedGlobalTraces.Append(distributedTraceId); _relatedGlobalTraces.Append(distributedTraceId);
} }
public UpstreamSegment Transform() public TraceSegmentRequest Transform()
{ {
var upstreamSegment = new UpstreamSegment(); var upstreamSegment = new TraceSegmentRequest
upstreamSegment.GlobalTraceIds.AddRange(_relatedGlobalTraces.GetRelatedGlobalTraces() {
.Select(x => x.ToUniqueId())); UniqueIds = _relatedGlobalTraces.GetRelatedGlobalTraces()
.Select(x => x.ToUniqueId()).ToArray()
var traceSegment = new TraceSegmentObject {TraceSegmentId = TraceSegmentId.Transform()}; };
traceSegment.Spans.AddRange(_spans.Select(x => x.Transform()));
traceSegment.ApplicationId = ApplicationId;
traceSegment.ApplicationInstanceId = ApplicationInstanceId;
traceSegment.IsSizeLimited = _isSizeLimited;
upstreamSegment.Segment = traceSegment.ToByteString(); upstreamSegment.Segment = new TraceSegmentObjectRequest
{
SegmentId = TraceSegmentId.Transform(),
Spans = _spans.Select(x => x.Transform()).ToArray(),
ApplicationId = ApplicationId,
ApplicationInstanceId = ApplicationInstanceId
};
return upstreamSegment; return upstreamSegment;
} }
......
...@@ -17,26 +17,25 @@ ...@@ -17,26 +17,25 @@
*/ */
using System.Linq; using System.Linq;
using SkyWalking.Transport;
using SkyWalking.Config; using SkyWalking.Config;
using SkyWalking.Context.Ids; using SkyWalking.Context.Ids;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Context.Trace namespace SkyWalking.Context.Trace
{ {
public class TraceSegmentRef : ITraceSegmentRef public class TraceSegmentRef : ITraceSegmentRef
{ {
private SegmentRefType _type; private readonly SegmentRefType _type;
private ID _traceSegmentId; private readonly ID _traceSegmentId;
private int _spanId = -1; private readonly int _spanId = -1;
private int _peerId = DictionaryUtil.NullValue; private readonly int _peerId = 0;
private string _peerHost; private readonly string _peerHost;
private int _entryApplicationInstanceId = DictionaryUtil.NullValue; private readonly int _entryApplicationInstanceId = 0;
private int _parentApplicationInstanceId = DictionaryUtil.NullValue; private readonly int _parentApplicationInstanceId = 0;
private string _entryOperationName; private readonly string _entryOperationName;
private int _entryOperationId = DictionaryUtil.NullValue; private readonly int _entryOperationId = 0;
private string _parentOperationName; private readonly string _parentOperationName;
private int _parentOperationId = DictionaryUtil.NullValue; private readonly int _parentOperationId = 0;
public TraceSegmentRef(IContextCarrier carrier) public TraceSegmentRef(IContextCarrier carrier)
{ {
...@@ -81,7 +80,7 @@ namespace SkyWalking.Context.Trace ...@@ -81,7 +80,7 @@ namespace SkyWalking.Context.Trace
_type = SegmentRefType.CrossThread; _type = SegmentRefType.CrossThread;
_traceSegmentId = contextSnapshot.TraceSegmentId; _traceSegmentId = contextSnapshot.TraceSegmentId;
_spanId = contextSnapshot.SpanId; _spanId = contextSnapshot.SpanId;
_parentApplicationInstanceId = RemoteDownstreamConfig.Agent.ApplicationInstanceId; _parentApplicationInstanceId = RuntimeEnvironment.Instance.ApplicationInstanceId.Value;
_entryApplicationInstanceId = contextSnapshot.EntryApplicationInstanceId; _entryApplicationInstanceId = contextSnapshot.EntryApplicationInstanceId;
string entryOperationName = contextSnapshot.EntryOperationName; string entryOperationName = contextSnapshot.EntryOperationName;
if (entryOperationName.First() == '#') if (entryOperationName.First() == '#')
...@@ -148,45 +147,29 @@ namespace SkyWalking.Context.Trace ...@@ -148,45 +147,29 @@ namespace SkyWalking.Context.Trace
public int EntryApplicationInstanceId => _entryApplicationInstanceId; public int EntryApplicationInstanceId => _entryApplicationInstanceId;
public TraceSegmentReference Transform() public TraceSegmentReferenceRequest Transform()
{ {
TraceSegmentReference traceSegmentReference = new TraceSegmentReference(); TraceSegmentReferenceRequest traceSegmentReference = new TraceSegmentReferenceRequest();
if (_type == SegmentRefType.CrossProcess) if (_type == SegmentRefType.CrossProcess)
{ {
traceSegmentReference.RefType = RefType.CrossProcess; traceSegmentReference.RefType = (int) SegmentRefType.CrossProcess;
if (_peerId == DictionaryUtil.NullValue) traceSegmentReference.NetworkAddress = new StringOrIntValue(_peerId, _peerHost);
{
traceSegmentReference.NetworkAddress = _peerHost;
}
else
{
traceSegmentReference.NetworkAddressId = _peerId;
}
} }
else else
{ {
traceSegmentReference.RefType = RefType.CrossThread; traceSegmentReference.RefType = (int) SegmentRefType.CrossThread;
traceSegmentReference.NetworkAddress = new StringOrIntValue();
} }
traceSegmentReference.ParentApplicationInstanceId = _parentApplicationInstanceId; traceSegmentReference.ParentApplicationInstanceId = _parentApplicationInstanceId;
traceSegmentReference.EntryApplicationInstanceId = _entryApplicationInstanceId; traceSegmentReference.EntryApplicationInstanceId = _entryApplicationInstanceId;
traceSegmentReference.ParentTraceSegmentId = _traceSegmentId.Transform(); traceSegmentReference.ParentTraceSegmentId = _traceSegmentId.Transform();
traceSegmentReference.ParentSpanId = _spanId; traceSegmentReference.ParentSpanId = _spanId;
if (_entryOperationId == DictionaryUtil.NullValue)
{ traceSegmentReference.EntryServiceName = new StringOrIntValue(_entryOperationId, _entryOperationName);
traceSegmentReference.EntryServiceName = _entryOperationName;
} traceSegmentReference.ParentServiceName = new StringOrIntValue(_parentOperationId, _parentOperationName);
else
{
traceSegmentReference.EntryServiceId = _entryOperationId;
}
if (_parentOperationId == DictionaryUtil.NullValue)
{
traceSegmentReference.ParentServiceName = _parentOperationName;
}
else
{
traceSegmentReference.ParentServiceId = _parentOperationId;
}
return traceSegmentReference; return traceSegmentReference;
} }
} }
......
...@@ -16,16 +16,14 @@ ...@@ -16,16 +16,14 @@
* *
*/ */
using System;
namespace SkyWalking.Context namespace SkyWalking.Context
{ {
public class TraceContextCarrierItem : CarrierItem public class TraceContextCarrierItem : CarrierItem
{ {
private const string HEAD_NAME = "Trace-Context"; private const string HEAD_NAME = "Trace-Context";
public TraceContextCarrierItem(String headValue, CarrierItem next) public TraceContextCarrierItem(string headValue, CarrierItem next, string @namespace)
: base(HEAD_NAME, headValue, next) : base(HEAD_NAME, headValue, next, @namespace)
{ {
} }
} }
......
...@@ -20,10 +20,7 @@ using System; ...@@ -20,10 +20,7 @@ using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using SkyWalking.Boot;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.Dictionarys;
using SkyWalking.Sampling;
using SkyWalking.Utils; using SkyWalking.Utils;
namespace SkyWalking.Context namespace SkyWalking.Context
...@@ -38,7 +35,7 @@ namespace SkyWalking.Context ...@@ -38,7 +35,7 @@ namespace SkyWalking.Context
public TracingContext() public TracingContext()
{ {
_sampler = ServiceManager.Instance.GetService<SamplingService>(); _sampler = DefaultSampler.Instance;
_segment = new TraceSegment(); _segment = new TraceSegment();
_activeSpanStacks = new Stack<ISpan>(); _activeSpanStacks = new Stack<ISpan>();
} }
...@@ -62,7 +59,7 @@ namespace SkyWalking.Context ...@@ -62,7 +59,7 @@ namespace SkyWalking.Context
carrier.SpanId = span.SpanId; carrier.SpanId = span.SpanId;
carrier.ParentApplicationInstanceId = _segment.ApplicationInstanceId; carrier.ParentApplicationInstanceId = _segment.ApplicationInstanceId;
if (DictionaryUtil.IsNull(peerId)) if (peerId == 0)
{ {
carrier.PeerHost = peer; carrier.PeerHost = peer;
} }
...@@ -78,7 +75,7 @@ namespace SkyWalking.Context ...@@ -78,7 +75,7 @@ namespace SkyWalking.Context
carrier.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId; carrier.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId;
if (DictionaryUtil.IsNull(metaValue.operationId)) if (metaValue.operationId == 0)
{ {
carrier.EntryOperationName = metaValue.operationName; carrier.EntryOperationName = metaValue.operationName;
} }
...@@ -88,7 +85,7 @@ namespace SkyWalking.Context ...@@ -88,7 +85,7 @@ namespace SkyWalking.Context
} }
var parentOperationId = firstSpan.OperationId; var parentOperationId = firstSpan.OperationId;
if (DictionaryUtil.IsNull(parentOperationId)) if (parentOperationId == 0)
{ {
carrier.ParentOperationName = firstSpan.OperationName; carrier.ParentOperationName = firstSpan.OperationName;
} }
...@@ -151,24 +148,13 @@ namespace SkyWalking.Context ...@@ -151,24 +148,13 @@ namespace SkyWalking.Context
var parentSpanId = parentSpan?.SpanId ?? -1; var parentSpanId = parentSpan?.SpanId ?? -1;
if (parentSpan != null && parentSpan.IsEntry) if (parentSpan != null && parentSpan.IsEntry)
{
var entrySpan = (ISpan) DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName)
.InCondition(id =>
{
parentSpan.OperationId = id;
return parentSpan;
}, () =>
{ {
parentSpan.OperationName = operationName; parentSpan.OperationName = operationName;
return parentSpan; return parentSpan.Start();
});
return entrySpan.Start();
} }
else else
{ {
var entrySpan = (ISpan) DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName) var entrySpan = new EntrySpan(_spanIdGenerator++, parentSpanId, operationName);
.InCondition(id => new EntrySpan(_spanIdGenerator++, parentSpanId, id),
() => new EntrySpan(_spanIdGenerator++, parentSpanId, operationName));
entrySpan.Start(); entrySpan.Start();
...@@ -192,10 +178,7 @@ namespace SkyWalking.Context ...@@ -192,10 +178,7 @@ namespace SkyWalking.Context
var parentSpanId = parentSpan?.SpanId ?? -1; var parentSpanId = parentSpan?.SpanId ?? -1;
var span = (ISpan) DictionaryManager.OperationName var span = new LocalSpan(_spanIdGenerator++, parentSpanId, operationName);
.FindOrPrepareForRegister(_segment.ApplicationId, operationName, false, false)
.InCondition(id => new LocalSpan(_spanIdGenerator++, parentSpanId, operationName),
() => new LocalSpan(_spanIdGenerator++, parentSpanId, operationName));
span.Start(); span.Start();
_activeSpanStacks.Push(span); _activeSpanStacks.Push(span);
return span; return span;
...@@ -214,30 +197,7 @@ namespace SkyWalking.Context ...@@ -214,30 +197,7 @@ namespace SkyWalking.Context
else else
{ {
var parentSpanId = parentSpan?.SpanId ?? -1; var parentSpanId = parentSpan?.SpanId ?? -1;
var exitSpan = (ISpan) DictionaryManager.NetworkAddress.Find(remotePeer) var exitSpan = IsLimitMechanismWorking() ? (ISpan)new NoopExitSpan(remotePeer) : new ExitSpan(_spanIdGenerator++, parentSpanId, operationName, remotePeer);
.InCondition(peerId =>
{
if (IsLimitMechanismWorking())
{
return new NoopExitSpan(peerId);
}
return DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName)
.InCondition(id => new ExitSpan(_spanIdGenerator++, parentSpanId, id, peerId),
() => new ExitSpan(_spanIdGenerator++, parentSpanId, operationName, peerId));
},
() =>
{
if (IsLimitMechanismWorking())
{
return new NoopExitSpan(remotePeer);
}
return DictionaryManager.OperationName.FindOnly(_segment.ApplicationId, operationName)
.InCondition(id => new ExitSpan(_spanIdGenerator++, parentSpanId, id, remotePeer),
() => new ExitSpan(_spanIdGenerator++, parentSpanId, operationName,
remotePeer));
});
_activeSpanStacks.Push(exitSpan); _activeSpanStacks.Push(exitSpan);
return exitSpan.Start(); return exitSpan.Start();
} }
...@@ -263,7 +223,6 @@ namespace SkyWalking.Context ...@@ -263,7 +223,6 @@ namespace SkyWalking.Context
{ {
_activeSpanStacks.Pop(); _activeSpanStacks.Pop();
} }
} }
else else
{ {
...@@ -283,7 +242,7 @@ namespace SkyWalking.Context ...@@ -283,7 +242,7 @@ namespace SkyWalking.Context
if (!_segment.HasRef && _segment.IsSingleSpanSegment) if (!_segment.HasRef && _segment.IsSingleSpanSegment)
{ {
if (!_sampler.TrySampling()) if (!_sampler.Sampled())
{ {
finishedSegment.IsIgnore = true; finishedSegment.IsIgnore = true;
} }
...@@ -321,7 +280,7 @@ namespace SkyWalking.Context ...@@ -321,7 +280,7 @@ namespace SkyWalking.Context
snapshot.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId; snapshot.EntryApplicationInstanceId = metaValue.entryApplicationInstanceId;
if (DictionaryUtil.IsNull(metaValue.operationId)) if (metaValue.operationId == 0)
{ {
snapshot.EntryOperationName = metaValue.operationName; snapshot.EntryOperationName = metaValue.operationName;
} }
...@@ -332,7 +291,7 @@ namespace SkyWalking.Context ...@@ -332,7 +291,7 @@ namespace SkyWalking.Context
var parentSpan = _activeSpanStacks.Last(); var parentSpan = _activeSpanStacks.Last();
if (DictionaryUtil.IsNull(parentSpan.OperationId)) if (parentSpan.OperationId == 0)
{ {
snapshot.ParentOperationName = parentSpan.OperationName; snapshot.ParentOperationName = parentSpan.OperationName;
} }
...@@ -362,7 +321,7 @@ namespace SkyWalking.Context ...@@ -362,7 +321,7 @@ namespace SkyWalking.Context
private bool IsLimitMechanismWorking() private bool IsLimitMechanismWorking()
{ {
if (_spanIdGenerator < Config.AgentConfig.SpanLimitPerSegment) if (_spanIdGenerator < 300)
{ {
return false; return false;
} }
......
/* /*
* Licensed to the OpenSkywalking under one or more * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. * this work for additional information regarding copyright ownership.
...@@ -16,50 +16,48 @@ ...@@ -16,50 +16,48 @@
* *
*/ */
using System; using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Utils; using SkyWalking.Utils;
namespace SkyWalking.Sampling namespace SkyWalking
{ {
// ReSharper disable once ClassNeverInstantiated.Global public class DefaultSampler : ISampler
public class SamplingService :TimerService, ISampler
{ {
private readonly AtomicInteger _atomicInteger = new AtomicInteger(); public static DefaultSampler Instance { get; } = new DefaultSampler();
private readonly int _sample_N_Per_3_Secs = AgentConfig.SamplePer3Secs;
private readonly bool _sample_on = AgentConfig.SamplePer3Secs > 0;
public bool TrySampling() private readonly AtomicInteger _idx = new AtomicInteger();
private int _samplePer3Secs;
private bool _sample_on;
public bool Sampled()
{ {
if (!_sample_on) if (!_sample_on)
{ {
return true; return true;
} }
return _atomicInteger.Increment() < _sample_N_Per_3_Secs; return _idx.Increment() < _samplePer3Secs;
} }
public void ForceSampled() public void ForceSampled()
{ {
if (_sample_on) if (_sample_on)
{ {
_atomicInteger.Increment(); _idx.Increment();
} }
} }
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(3); [MethodImpl(MethodImplOptions.Synchronized)]
internal void SetSamplePer3Secs(int samplePer3Secs)
protected override Task Execute(CancellationToken token)
{ {
if (_sample_on) _samplePer3Secs = samplePer3Secs;
{ _sample_on = samplePer3Secs > -1;
_atomicInteger.Value = 0;
} }
return TaskUtils.CompletedTask; internal void Reset()
{
_idx.Value = 0;
} }
} }
} }
\ No newline at end of file
...@@ -25,14 +25,14 @@ namespace SkyWalking.Diagnostics ...@@ -25,14 +25,14 @@ namespace SkyWalking.Diagnostics
internal class TracingDiagnosticMethod internal class TracingDiagnosticMethod
{ {
private readonly MethodInfo _method; private readonly MethodInfo _method;
private readonly ITracingDiagnosticProcessor _diagnosticProcessor; private readonly ITracingDiagnosticProcessor _tracingDiagnosticProcessor;
private readonly string _diagnosticName; private readonly string _diagnosticName;
private readonly IParameterResolver[] _parameterResolvers; private readonly IParameterResolver[] _parameterResolvers;
public TracingDiagnosticMethod(ITracingDiagnosticProcessor diagnosticProcessor, MethodInfo method, public TracingDiagnosticMethod(ITracingDiagnosticProcessor tracingDiagnosticProcessor, MethodInfo method,
string diagnosticName) string diagnosticName)
{ {
_diagnosticProcessor = diagnosticProcessor; _tracingDiagnosticProcessor = tracingDiagnosticProcessor;
_method = method; _method = method;
_diagnosticName = diagnosticName; _diagnosticName = diagnosticName;
_parameterResolvers = GetParameterResolvers(method).ToArray(); _parameterResolvers = GetParameterResolvers(method).ToArray();
...@@ -51,7 +51,7 @@ namespace SkyWalking.Diagnostics ...@@ -51,7 +51,7 @@ namespace SkyWalking.Diagnostics
args[i] = _parameterResolvers[i].Resolve(value); args[i] = _parameterResolvers[i].Resolve(value);
} }
_method.Invoke(_diagnosticProcessor, args); _method.Invoke(_tracingDiagnosticProcessor, args);
} }
private static IEnumerable<IParameterResolver> GetParameterResolvers(MethodInfo methodInfo) private static IEnumerable<IParameterResolver> GetParameterResolvers(MethodInfo methodInfo)
......
...@@ -26,15 +26,15 @@ namespace SkyWalking.Diagnostics ...@@ -26,15 +26,15 @@ namespace SkyWalking.Diagnostics
{ {
private readonly List<TracingDiagnosticMethod> _methods; private readonly List<TracingDiagnosticMethod> _methods;
public TracingDiagnosticMethodCollection(ITracingDiagnosticProcessor diagnosticProcessor) public TracingDiagnosticMethodCollection(ITracingDiagnosticProcessor tracingDiagnosticProcessor)
{ {
_methods = new List<TracingDiagnosticMethod>(); _methods = new List<TracingDiagnosticMethod>();
foreach (var method in diagnosticProcessor.GetType().GetMethods()) foreach (var method in tracingDiagnosticProcessor.GetType().GetMethods())
{ {
var diagnosticName = method.GetCustomAttribute<DiagnosticName>(); var diagnosticName = method.GetCustomAttribute<DiagnosticName>();
if(diagnosticName==null) if(diagnosticName==null)
continue; continue;
_methods.Add(new TracingDiagnosticMethod(diagnosticProcessor, method, diagnosticName.Name)); _methods.Add(new TracingDiagnosticMethod(tracingDiagnosticProcessor, method, diagnosticName.Name));
} }
} }
......
...@@ -26,12 +26,12 @@ namespace SkyWalking.Diagnostics ...@@ -26,12 +26,12 @@ namespace SkyWalking.Diagnostics
{ {
public class TracingDiagnosticProcessorObserver : IObserver<DiagnosticListener> public class TracingDiagnosticProcessorObserver : IObserver<DiagnosticListener>
{ {
private static readonly ILogger _logger = LogManager.GetLogger<TracingDiagnosticProcessorObserver>(); private readonly ILogger _logger;
private readonly IEnumerable<ITracingDiagnosticProcessor> _tracingDiagnosticProcessors; private readonly IEnumerable<ITracingDiagnosticProcessor> _tracingDiagnosticProcessors;
public TracingDiagnosticProcessorObserver(IEnumerable<ITracingDiagnosticProcessor> tracingDiagnosticProcessors) public TracingDiagnosticProcessorObserver(IEnumerable<ITracingDiagnosticProcessor> tracingDiagnosticProcessors, ILoggerFactory loggerFactory)
{ {
_logger = loggerFactory.CreateLogger(typeof(TracingDiagnosticProcessorObserver));
_tracingDiagnosticProcessors = tracingDiagnosticProcessors ?? _tracingDiagnosticProcessors = tracingDiagnosticProcessors ??
throw new ArgumentNullException(nameof(tracingDiagnosticProcessors)); throw new ArgumentNullException(nameof(tracingDiagnosticProcessors));
} }
...@@ -51,16 +51,16 @@ namespace SkyWalking.Diagnostics ...@@ -51,16 +51,16 @@ namespace SkyWalking.Diagnostics
if (listener.Name == diagnosticProcessor.ListenerName) if (listener.Name == diagnosticProcessor.ListenerName)
{ {
Subscribe(listener, diagnosticProcessor); Subscribe(listener, diagnosticProcessor);
_logger.Debug( _logger.Information(
$"TracingDiagnosticObserver subscribe diagnosticListener named [{diagnosticProcessor.ListenerName}]."); $"Loaded diagnostic listener [{diagnosticProcessor.ListenerName}].");
} }
} }
} }
protected virtual void Subscribe(DiagnosticListener listener, protected virtual void Subscribe(DiagnosticListener listener,
ITracingDiagnosticProcessor diagnosticProcessor) ITracingDiagnosticProcessor tracingDiagnosticProcessor)
{ {
listener.Subscribe(new TracingDiagnosticObserver(diagnosticProcessor)); listener.Subscribe(new TracingDiagnosticObserver(tracingDiagnosticProcessor));
} }
} }
} }
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace SkyWalking.Dictionarys
{
public class DictionaryManager
{
public static NetworkAddressDictionary NetworkAddress => NetworkAddressDictionary.Instance;
public static OperationNameDictionary OperationName => OperationNameDictionary.Instance;
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.NetworkInformation;
using System.Xml.Schema;
using SkyWalking.Config;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
namespace SkyWalking.Dictionarys
{
public class OperationNameDictionary
{
private static readonly OperationNameDictionary _instance=new OperationNameDictionary();
public static OperationNameDictionary Instance => _instance;
private OperationNameDictionary()
{
}
private readonly ConcurrentDictionary<OperationNameKey,int> _operationNameDic=new ConcurrentDictionary<OperationNameKey, int>();
private readonly ConcurrentDictionary<OperationNameKey,object> _unRegisterOpNames=new ConcurrentDictionary<OperationNameKey, object>();
public PossibleFound FindOrPrepareForRegister(int applicationId, string operationName, bool isEntry,
bool isExit)
{
return internalFind(applicationId, operationName, isEntry, isExit, true);
}
public PossibleFound FindOnly(int applicationId, string operationName)
{
return internalFind(applicationId, operationName, false, false, false);
}
private PossibleFound internalFind(int applicationId, string operationName, bool isEntry, bool isExit,
bool registerWhenNotFound)
{
if (string.IsNullOrEmpty(operationName))
{
return NotFound.Instance;
}
var operationNameKey = new OperationNameKey(applicationId, operationName, isEntry, isExit);
if (_operationNameDic.TryGetValue(operationNameKey, out var id))
{
return new Found(id);
}
else
{
if (registerWhenNotFound && _operationNameDic.Count + _unRegisterOpNames.Count <
DictionaryConfig.OperationNameBufferSize)
{
_unRegisterOpNames.TryAdd(operationNameKey, null);
}
return NotFound.Instance;
}
}
public void SyncRemote(ServiceNameDiscoveryService.ServiceNameDiscoveryServiceClient serviceClient)
{
if (_unRegisterOpNames.Count > 0)
{
var serviceNameCollection = new ServiceNameCollection();
foreach (var opName in _unRegisterOpNames)
{
var serviceName = new ServiceNameElement();
serviceName.ApplicationId = opName.Key.ApplicationId;
serviceName.ServiceName = opName.Key.OperationName;
serviceName.SrcSpanType = opName.Key.SpanType;
serviceNameCollection.Elements.Add(serviceName);
}
var mapping = serviceClient.discovery(serviceNameCollection);
foreach (var item in mapping.Elements)
{
var element = item.Element;
var key = new OperationNameKey(element.ApplicationId, element.ServiceName,
SpanType.Entry == element.SrcSpanType, SpanType.Exit == element.SrcSpanType);
_unRegisterOpNames.TryRemove(key, out _);
_operationNameDic.TryAdd(key, item.ServiceId);
}
}
}
}
public class OperationNameKey : IEquatable<OperationNameKey>
{
private readonly int _applicationId;
private readonly string _operationName;
private readonly bool _isEntry;
private readonly bool _isExit;
public OperationNameKey(int applicationId, string operationName, bool isEntry, bool isExit)
{
_applicationId = applicationId;
_operationName = operationName;
_isEntry = isEntry;
_isExit = isExit;
}
public int ApplicationId => _applicationId;
public string OperationName => _operationName;
public bool Equals(OperationNameKey other)
{
if (other == null)
{
return false;
}
var isMatch = _applicationId == other._applicationId || _operationName == other._operationName;
return isMatch && _isEntry == other._isEntry && _isExit == other._isExit;
}
public override bool Equals(object obj)
{
var other = obj as OperationNameKey;
return Equals(other);
}
public override int GetHashCode()
{
var result = _applicationId;
result = 31 * result + _operationName.GetHashCode();
return result;
}
public SpanType SpanType
{
get
{
if (_isEntry)
{
return SpanType.Entry;
}
else if(_isExit)
{
return SpanType.Exit;
}
else
{
return SpanType.Local;
}
}
}
}
}
\ No newline at end of file
...@@ -26,7 +26,7 @@ namespace SkyWalking.Logging ...@@ -26,7 +26,7 @@ namespace SkyWalking.Logging
{ {
} }
public void Info(string message) public void Information(string message)
{ {
} }
......
...@@ -20,7 +20,7 @@ using System; ...@@ -20,7 +20,7 @@ using System;
namespace SkyWalking.Logging namespace SkyWalking.Logging
{ {
internal class NullLoggerFactory : ILoggerFactory public class NullLoggerFactory : ILoggerFactory
{ {
public ILogger CreateLogger(Type type) public ILogger CreateLogger(Type type)
{ {
......
...@@ -16,31 +16,31 @@ ...@@ -16,31 +16,31 @@
* *
*/ */
using Grpc.Core; //using Grpc.Core;
using SkyWalking.Utils; //using SkyWalking.Utils;
//
namespace SkyWalking.Remote.Authentication //namespace SkyWalking.Remote.Authentication
{ //{
internal static class AuthenticationInterceptors // internal static class AuthenticationInterceptors
{ // {
private const string header = "authentication"; // private const string header = "authentication";
//
public static AsyncAuthInterceptor CreateAuthInterceptor(string token) // public static AsyncAuthInterceptor CreateAuthInterceptor(string token)
{ // {
return (context, metadata) => // return (context, metadata) =>
{ // {
var entry = CreateTokenHeader(token); // var entry = CreateTokenHeader(token);
if (entry != null) // if (entry != null)
{ // {
metadata.Add(entry); // metadata.Add(entry);
} // }
return TaskUtils.CompletedTask; // return TaskUtils.CompletedTask;
}; // };
} // }
//
private static Metadata.Entry CreateTokenHeader(string token) // private static Metadata.Entry CreateTokenHeader(string token)
{ // {
return string.IsNullOrEmpty(token) ? null : new Metadata.Entry(header, token); // return string.IsNullOrEmpty(token) ? null : new Metadata.Entry(header, token);
} // }
} // }
} //}
/* ///*
* Licensed to the OpenSkywalking under one or more // * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with // * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. // * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 // * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with // * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at // * the License. You may obtain a copy of the License at
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using Grpc.Core; //using Grpc.Core;
using SkyWalking.Remote.Authentication; //using SkyWalking.Remote.Authentication;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
internal class GrpcChannelBuilder // internal class GrpcChannelBuilder
{ // {
private string _token; // private string _token;
//
private string _server; // private string _server;
//
private string _rootCertificatePath; // private string _rootCertificatePath;
//
public GrpcChannelBuilder WithAuthenticationToken(string token) // public GrpcChannelBuilder WithAuthenticationToken(string token)
{ // {
_token = token; // _token = token;
return this; // return this;
} // }
//
public GrpcChannelBuilder WithServer(string server) // public GrpcChannelBuilder WithServer(string server)
{ // {
_server = server; // _server = server;
return this; // return this;
} // }
//
public GrpcChannelBuilder WithCredential(string rootCertificatePath) // public GrpcChannelBuilder WithCredential(string rootCertificatePath)
{ // {
_rootCertificatePath = rootCertificatePath; // _rootCertificatePath = rootCertificatePath;
return this; // return this;
} // }
//
public Channel Build() // public Channel Build()
{ // {
return new Channel(_server, GetCredentials()); // return new Channel(_server, GetCredentials());
} // }
//
private ChannelCredentials GetCredentials() // private ChannelCredentials GetCredentials()
{ // {
if (_rootCertificatePath != null) // if (_rootCertificatePath != null)
{ // {
var authInterceptor = AuthenticationInterceptors.CreateAuthInterceptor(_token); // var authInterceptor = AuthenticationInterceptors.CreateAuthInterceptor(_token);
return ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor(authInterceptor)); // return ChannelCredentials.Create(new SslCredentials(), CallCredentials.FromInterceptor(authInterceptor));
} // }
return ChannelCredentials.Insecure; //
} // return ChannelCredentials.Insecure;
} // }
} // }
//}
/* ///*
* Licensed to the OpenSkywalking under one or more // * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with // * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. // * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 // * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with // * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at // * the License. You may obtain a copy of the License at
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Threading.Tasks; //using System.Threading.Tasks;
using Grpc.Core; //using Grpc.Core;
using SkyWalking.Logging; //using SkyWalking.Logging;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcConnection // public class GrpcConnection
{ // {
private static readonly ILogger _logger = LogManager.GetLogger<GrpcConnection>(); // private static readonly ILogger Logger = LogManager.GetLogger<GrpcConnection>();
//
public Channel GrpcChannel { get; } // public Channel GrpcChannel { get; }
//
public GrpcConnectionState State { get; private set; } = GrpcConnectionState.Idle; // public GrpcConnectionState State { get; private set; } = GrpcConnectionState.Idle;
//
public string Server { get; } // public string Server { get; }
//
public GrpcConnection(string server, string rootCertificatePath = null, string token = null) // public GrpcConnection(string server, string rootCertificatePath = null, string token = null)
{ // {
Server = server; // Server = server;
GrpcChannel = new GrpcChannelBuilder() // GrpcChannel = new GrpcChannelBuilder()
.WithServer(server) // .WithServer(server)
.WithCredential(rootCertificatePath) // .WithCredential(rootCertificatePath)
.WithAuthenticationToken(token) // .WithAuthenticationToken(token)
.Build(); // .Build();
} // }
//
public async Task<bool> ConnectAsync(TimeSpan timeout) // public async Task<bool> ConnectAsync(TimeSpan timeout)
{ // {
if (State == GrpcConnectionState.Ready) // if (State == GrpcConnectionState.Ready)
{ // {
return true; // return true;
} // }
State = GrpcConnectionState.Connecting; // State = GrpcConnectionState.Connecting;
try // try
{ // {
var deadLine = DateTime.UtcNow.AddSeconds(timeout.TotalSeconds); // var deadLine = DateTime.UtcNow.AddSeconds(timeout.TotalSeconds);
await GrpcChannel.ConnectAsync(deadLine); // await GrpcChannel.ConnectAsync(deadLine);
State = GrpcConnectionState.Ready; // State = GrpcConnectionState.Ready;
_logger.Info($"Grpc channel connect success. [Server] = {GrpcChannel.Target}"); // Logger.Information($"Grpc channel connect success. [Server] = {GrpcChannel.Target}");
} // }
catch (TaskCanceledException ex) // catch (TaskCanceledException ex)
{ // {
State = GrpcConnectionState.Failure; // State = GrpcConnectionState.Failure;
_logger.Warning($"Grpc channel connect timeout. {ex.Message}"); // Logger.Warning($"Grpc channel connect timeout. {ex.Message}");
} // }
catch (Exception ex) // catch (Exception ex)
{ // {
State = GrpcConnectionState.Failure; // State = GrpcConnectionState.Failure;
_logger.Warning($"Grpc channel connect fail. {ex.Message}"); // Logger.Warning($"Grpc channel connect fail. {ex.Message}");
} // }
//
return State == GrpcConnectionState.Ready; // return State == GrpcConnectionState.Ready;
} // }
//
public async Task ShutdowmAsync() // public async Task ShutdowmAsync()
{ // {
try // try
{ // {
await GrpcChannel.ShutdownAsync(); // await GrpcChannel.ShutdownAsync();
} // }
catch (Exception e) // catch (Exception e)
{ // {
_logger.Debug($"Grpc channel shutdown fail. {e.Message}"); // Logger.Debug($"Grpc channel shutdown fail. {e.Message}");
} // }
finally // finally
{ // {
State = GrpcConnectionState.Shutdown; // State = GrpcConnectionState.Shutdown;
} // }
} // }
//
public bool CheckState() // public bool CheckState()
{ // {
return State == GrpcConnectionState.Ready && GrpcChannel.State == ChannelState.Ready; // return State == GrpcConnectionState.Ready && GrpcChannel.State == ChannelState.Ready;
} // }
//
public void Failure() // public void Failure()
{ // {
var currentState = State; // var currentState = State;
//
if (GrpcConnectionState.Ready == currentState) // if (GrpcConnectionState.Ready == currentState)
{ // {
_logger.Debug($"Grpc channel state changed. {State} -> {GrpcChannel.State}"); // Logger.Debug($"Grpc channel state changed. {State} -> {GrpcChannel.State}");
} // }
//
State = GrpcConnectionState.Failure; // State = GrpcConnectionState.Failure;
} // }
} // }
} //}
\ No newline at end of file \ No newline at end of file
/* ///*
* Licensed to the OpenSkywalking under one or more // * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with // * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. // * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 // * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with // * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at // * the License. You may obtain a copy of the License at
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Linq; //using System.Linq;
using System.Threading.Tasks; //using System.Threading.Tasks;
using SkyWalking.Config; //using SkyWalking.Config;
using SkyWalking.Logging; //using SkyWalking.Logging;
using SkyWalking.Utils; //using SkyWalking.Utils;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcConnectionManager // public class GrpcConnectionManager
{ // {
private static readonly ILogger _logger = LogManager.GetLogger<GrpcConnectionManager>(); // private static readonly ILogger Logger = LogManager.GetLogger<GrpcConnectionManager>();
//
public const string NotFoundErrorMessage = "Not found available connection."; // public const string NotFoundErrorMessage = "Not found available connection.";
//
public static GrpcConnectionManager Instance { get; } = new GrpcConnectionManager(); // public static GrpcConnectionManager Instance { get; } = new GrpcConnectionManager();
//
private readonly Random _random = new Random(); // private readonly Random _random = new Random();
private readonly AsyncLock _lock = new AsyncLock(); // private readonly AsyncLock _lock = new AsyncLock();
private GrpcConnection _connection; // private GrpcConnection _connection;
//
public bool Available => _connection != null && _connection.CheckState(); // public bool Available => _connection != null && _connection.CheckState();
//
private GrpcConnectionManager() // private GrpcConnectionManager()
{ // {
} // }
//
public async Task ConnectAsync(TimeSpan timeout) // public async Task ConnectAsync(TimeSpan timeout)
{ // {
// using async lock // // using async lock
using (await _lock.LockAsync()) // using (await _lock.LockAsync())
{ // {
if (_connection != null && _connection.CheckState()) // if (_connection != null && _connection.CheckState())
{ // {
return; // return;
} // }
//
if (_connection != null && !_connection.CheckState()) // if (_connection != null && !_connection.CheckState())
{ // {
await _connection.ShutdowmAsync(); // await _connection.ShutdowmAsync();
} // }
//
var metadata = GetServerMetadata(_connection?.Server); // var metadata = GetServerMetadata(_connection?.Server);
_connection = new GrpcConnection(metadata.Address, metadata.CertificatePath, metadata.Token); // _connection = new GrpcConnection(metadata.Address, metadata.CertificatePath, metadata.Token);
await _connection.ConnectAsync(timeout); // await _connection.ConnectAsync(timeout);
} // }
} // }
//
public async Task ShutdownAsync() // public async Task ShutdownAsync()
{ // {
await _connection?.ShutdowmAsync(); // await _connection?.ShutdowmAsync();
} // }
//
public GrpcConnection GetAvailableConnection() // public GrpcConnection GetAvailableConnection()
{ // {
var connection = _connection; // var connection = _connection;
if (connection == null || connection.State != GrpcConnectionState.Ready) // if (connection == null || connection.State != GrpcConnectionState.Ready)
{ // {
_logger.Debug(NotFoundErrorMessage); // Logger.Debug(NotFoundErrorMessage);
return null; // return null;
} // }
//
return connection; // return connection;
} // }
//
private ServerMetadata GetServerMetadata(string currentServer) // private ServerMetadata GetServerMetadata(string currentServer)
{ // {
return new ServerMetadata(GetServerAddress(currentServer), // return new ServerMetadata(GetServerAddress(currentServer),
CollectorConfig.CertificatePath, CollectorConfig.Authentication); // CollectorConfig.CertificatePath, CollectorConfig.Authentication);
} // }
//
private string GetServerAddress(string currentServer) // private string GetServerAddress(string currentServer)
{ // {
var servers = RemoteDownstreamConfig.Collector.gRPCServers.Distinct().ToArray(); // var servers = RemoteDownstreamConfig.Collector.gRPCServers.Distinct().ToArray();
if (servers.Length == 1) // if (servers.Length == 1)
{ // {
return servers[0]; // return servers[0];
} // }
//
if (currentServer != null) // if (currentServer != null)
{ // {
servers = servers.Where(x => x != currentServer).ToArray(); // servers = servers.Where(x => x != currentServer).ToArray();
} // }
//
var index = _random.Next() % servers.Length; // var index = _random.Next() % servers.Length;
return servers[index]; // return servers[index];
} // }
//
public struct ServerMetadata // public struct ServerMetadata
{ // {
public string Address { get; } // public string Address { get; }
//
public string Token { get; } // public string Token { get; }
//
public string CertificatePath { get; } // public string CertificatePath { get; }
//
public ServerMetadata(string address, string certificate, string token) // public ServerMetadata(string address, string certificate, string token)
{ // {
Address = address; // Address = address;
CertificatePath = certificate; // CertificatePath = certificate;
Token = token; // Token = token;
} // }
} // }
} // }
} //}
\ No newline at end of file \ No newline at end of file
/* ///*
* Licensed to the OpenSkywalking under one or more // * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with // * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. // * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 // * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with // * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at // * the License. You may obtain a copy of the License at
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Threading; //using System.Threading;
using System.Threading.Tasks; //using System.Threading.Tasks;
using SkyWalking.Boot; //using SkyWalking.Boot;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcConnectionService : TimerService // public class GrpcConnectionService : TimerService
{ // {
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15); // protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(15);
//
protected override async Task Execute(CancellationToken token) // protected override async Task Execute(CancellationToken token)
{ // {
if (!GrpcConnectionManager.Instance.Available) // if (!GrpcConnectionManager.Instance.Available)
{ // {
// default timeout = 5s // // default timeout = 5s
await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(5)); // await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(5));
} // }
} // }
} // }
} //}
\ No newline at end of file \ No newline at end of file
/* ///*
* Licensed to the OpenSkywalking under one or more // * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with // * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. // * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 // * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with // * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at // * the License. You may obtain a copy of the License at
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public enum GrpcConnectionState // public enum GrpcConnectionState
{ // {
Idle, // Idle,
Connecting, // Connecting,
Ready, // Ready,
Failure, // Failure,
Shutdown // Shutdown
} // }
} //}
/* ///*
* Licensed to the OpenSkywalking under one or more // * Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with // * contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. // * this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0 // * The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with // * (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at // * the License. You may obtain a copy of the License at
* // *
* http://www.apache.org/licenses/LICENSE-2.0 // * http://www.apache.org/licenses/LICENSE-2.0
* // *
* Unless required by applicable law or agreed to in writing, software // * Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, // * distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and // * See the License for the specific language governing permissions and
* limitations under the License. // * limitations under the License.
* // *
*/ // */
//
using System; //using System;
using System.Threading; //using System.Threading;
using System.Threading.Tasks; //using System.Threading.Tasks;
using SkyWalking.Boot; //using SkyWalking.Boot;
using SkyWalking.Utils; //using SkyWalking.Utils;
//
namespace SkyWalking.Remote //namespace SkyWalking.Remote
{ //{
public class GrpcRuntimeService : TimerService // public class GrpcRuntimeService : TimerService
{ // {
protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(120); // protected override TimeSpan Interval { get; } = TimeSpan.FromSeconds(120);
//
protected override Task Execute(CancellationToken token) // protected override Task Execute(CancellationToken token)
{ // {
// todo // // todo
return TaskUtils.CompletedTask; // return TaskUtils.CompletedTask;
} // }
} // }
} //}
\ No newline at end of file \ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* 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
This diff is collapsed.
...@@ -3,22 +3,19 @@ ...@@ -3,22 +3,19 @@
<PropertyGroup> <PropertyGroup>
<Description>SkyWalking core components.</Description> <Description>SkyWalking core components.</Description>
<AssemblyTitle>SkyWalking.Core</AssemblyTitle> <AssemblyTitle>SkyWalking.Core</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net45;net451</TargetFrameworks>
<AssemblyName>SkyWalking.Core</AssemblyName> <AssemblyName>SkyWalking.Core</AssemblyName>
<PackageId>SkyWalking.Core</PackageId> <PackageId>SkyWalking.Core</PackageId>
<PackageTags>SkyWalking;APM</PackageTags> <PackageTags>SkyWalking;APM</PackageTags>
<PackageReleaseNotes> <PackageReleaseNotes>
</PackageReleaseNotes> </PackageReleaseNotes>
<RootNamespace>SkyWalking</RootNamespace> <RootNamespace>SkyWalking</RootNamespace>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" /> <ProjectReference Include="..\SkyWalking.Abstractions\SkyWalking.Abstractions.csproj" />
<ProjectReference Include="..\SkyWalking.NetworkProtocol.Trace\SkyWalking.NetworkProtocol.Trace.csproj" />
<ProjectReference Include="..\SkyWalking.NetworkProtocol\SkyWalking.NetworkProtocol.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.4.1" /> <PackageReference Include="System.Diagnostics.DiagnosticSource" Version="4.5.0" />
<PackageReference Include="System.Runtime.InteropServices.RuntimeInformation" Version="4.3.0" />
<PackageReference Include="System.ValueTuple" Version="4.5.0" /> <PackageReference Include="System.ValueTuple" Version="4.5.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
\ No newline at end of file
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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