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

Provide automatic-agent (#85)

* Feature/hostingstartup (#80)

* Update TargetFrameworkVersion

* Update appveyor.yml

* Feature/hostingstartup (#81)

* Update TargetFrameworkVersion

* Update appveyor.yml

* Update appveyor.yml

* Update version.props

* Add ISkyWalkingClient interface

* Refactor

* Fix ProjectReference

* Fix PackageReference

* Fix  System.Threading.ThreadPool

* Refactor IComponents

* Update appveyor.yml

* Update version.cake

* Fix namespace

* Remove SkyWalking.Dictionarys

* Refactor

* Refactor ServiceDiscoveryService

* Refactor

* Refactor

* Add TraceSegmentTransportService

* Blocking dispatcher strategy

* Add gRPC Transport

* Add InstrumentationHostedService

* Refactor skywalking logger

* Agent function test.

* Add debug log

* Fix trace segment queue

* Refactor AsyncQueueTraceDispatcher

* re-naming

* Rename gRPCClient

* Refactor SkyWalking.Utilities

* Trace data sent to collector

* Add SkyWalkingHostingStartup

* Fix peer transform

* Refactor ContextCarrier

* Refactor SkyWalking.AspNet

* Update appveyor.yml

* Fix CI

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