Commit 886300ad authored by Liuhaoyang's avatar Liuhaoyang

Fix some bug .

parent af15d97d
...@@ -22,6 +22,7 @@ using Microsoft.Extensions.DiagnosticAdapter; ...@@ -22,6 +22,7 @@ using Microsoft.Extensions.DiagnosticAdapter;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Context.Tag; using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace; using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.AspNetCore.Diagnostics namespace SkyWalking.AspNetCore.Diagnostics
{ {
...@@ -48,7 +49,7 @@ namespace SkyWalking.AspNetCore.Diagnostics ...@@ -48,7 +49,7 @@ namespace SkyWalking.AspNetCore.Diagnostics
var httpRequestSpan = ContextManager.CreateEntrySpan(httpContext.Request.Path, carrier); var httpRequestSpan = ContextManager.CreateEntrySpan(httpContext.Request.Path, carrier);
httpRequestSpan.AsHttp(); httpRequestSpan.AsHttp();
httpRequestSpan.SetComponent("Asp.Net Core"); httpRequestSpan.SetComponent(ComponentsDefine.AspNetCore);
Tags.Url.Set(httpRequestSpan, httpContext.Request.Path); Tags.Url.Set(httpRequestSpan, httpContext.Request.Path);
Tags.HTTP.Method.Set(httpRequestSpan, httpContext.Request.Method); Tags.HTTP.Method.Set(httpRequestSpan, httpContext.Request.Method);
} }
...@@ -57,6 +58,10 @@ namespace SkyWalking.AspNetCore.Diagnostics ...@@ -57,6 +58,10 @@ namespace SkyWalking.AspNetCore.Diagnostics
public void HttpRequestInStop(HttpContext httpContext) public void HttpRequestInStop(HttpContext httpContext)
{ {
var httpRequestSpan = ContextManager.ActiveSpan; var httpRequestSpan = ContextManager.ActiveSpan;
if (httpRequestSpan == null)
{
return;
}
var statusCode = httpContext.Response.StatusCode; var statusCode = httpContext.Response.StatusCode;
if (statusCode >= 400) if (statusCode >= 400)
{ {
......
...@@ -19,7 +19,9 @@ ...@@ -19,7 +19,9 @@
using System; using System;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Http;
using SkyWalking.AspNetCore.Diagnostics; using SkyWalking.AspNetCore.Diagnostics;
namespace SkyWalking.AspNetCore namespace SkyWalking.AspNetCore
...@@ -50,9 +52,12 @@ namespace SkyWalking.AspNetCore ...@@ -50,9 +52,12 @@ namespace SkyWalking.AspNetCore
throw new ArgumentNullException(nameof(services)); throw new ArgumentNullException(nameof(services));
} }
services.AddSingleton<IHostedService, SkyWalkingHostedService>(); services.AddHttpClient<TracingHttpClient>("sw-tracing");
services.AddSingleton<ITracingDiagnosticListener, HostingDiagnosticListener>();
services.AddSingleton<IHostedService, SkyWalkingHostedService>();
services.TryAddSingleton<ITracingDiagnosticListener, HostingDiagnosticListener>();
services.AddTransient<HttpMessageHandlerBuilder, TracingHttpMessageHandlerBuilder>();
return services; return services;
} }
} }
......
...@@ -7,6 +7,7 @@ ...@@ -7,6 +7,7 @@
<PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.0-preview2-final" /> <PackageReference Include="Microsoft.AspNetCore.Http.Abstractions" Version="2.1.0-preview2-final" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.1.0-preview2-final" /> <PackageReference Include="Microsoft.AspNetCore.Mvc.Abstractions" Version="2.1.0-preview2-final" />
<PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="2.1.0-preview2-final" /> <PackageReference Include="Microsoft.Extensions.DiagnosticAdapter" Version="2.1.0-preview2-final" />
<PackageReference Include="Microsoft.Extensions.Http" Version="2.1.0-preview2-final" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="2.1.0-preview2-final" /> <PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="2.1.0-preview2-final" />
<PackageReference Include="Microsoft.Extensions.Options" Version="2.1.0-preview2-final" /> <PackageReference Include="Microsoft.Extensions.Options" Version="2.1.0-preview2-final" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0-preview2-final" /> <PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="2.1.0-preview2-final" />
......
...@@ -32,6 +32,9 @@ namespace SkyWalking.AspNetCore ...@@ -32,6 +32,9 @@ namespace SkyWalking.AspNetCore
{ {
public class SkyWalkingHostedService : IHostedService public class SkyWalkingHostedService : IHostedService
{ {
private readonly IEnumerable<ITracingDiagnosticListener> _tracingDiagnosticListeners;
private readonly DiagnosticListener _diagnosticListener;
public SkyWalkingHostedService(IOptions<SkyWalkingOptions> options, IHostingEnvironment hostingEnvironment, public SkyWalkingHostedService(IOptions<SkyWalkingOptions> options, IHostingEnvironment hostingEnvironment,
IEnumerable<ITracingDiagnosticListener> tracingDiagnosticListeners, DiagnosticListener diagnosticListener) IEnumerable<ITracingDiagnosticListener> tracingDiagnosticListeners, DiagnosticListener diagnosticListener)
{ {
...@@ -48,19 +51,21 @@ namespace SkyWalking.AspNetCore ...@@ -48,19 +51,21 @@ namespace SkyWalking.AspNetCore
AgentConfig.ApplicationCode = options.Value.ApplicationCode; AgentConfig.ApplicationCode = options.Value.ApplicationCode;
CollectorConfig.DirectServers = options.Value.DirectServers; CollectorConfig.DirectServers = options.Value.DirectServers;
foreach (var tracingDiagnosticListener in tracingDiagnosticListeners) _tracingDiagnosticListeners = tracingDiagnosticListeners;
diagnosticListener.SubscribeWithAdapter(tracingDiagnosticListener); _diagnosticListener = diagnosticListener;
} }
public async Task StartAsync(CancellationToken cancellationToken) public async Task StartAsync(CancellationToken cancellationToken)
{ {
await GrpcChannelManager.Instance.ConnectAsync(); await GrpcChannelManager.Instance.ConnectAsync();
await ServiceManager.Instance.Initialize(); await ServiceManager.Instance.Initialize();
foreach (var tracingDiagnosticListener in _tracingDiagnosticListeners)
_diagnosticListener.SubscribeWithAdapter(tracingDiagnosticListener);
} }
public async Task StopAsync(CancellationToken cancellationToken) public async Task StopAsync(CancellationToken cancellationToken)
{ {
GrpcChannelManager.Instance.ShutdownAsync(); await GrpcChannelManager.Instance.ShutdownAsync();
ServiceManager.Instance.Dispose(); ServiceManager.Instance.Dispose();
} }
} }
......
using System.Net.Http;
namespace SkyWalking.AspNetCore
{
public class TracingHttpClient
{
public HttpClient HttpClient { get; }
public TracingHttpClient(HttpClient httpClient)
{
HttpClient = httpClient;
}
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) 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.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
namespace SkyWalking.AspNetCore
{
public class TracingHttpHandler : DelegatingHandler
{
public TracingHttpHandler()
{
InnerHandler = new HttpClientHandler();
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var contextCarrier = new ContextCarrier();
var peer = $"{request.RequestUri.Host}:{request.RequestUri.Port}";
var span = ContextManager.CreateExitSpan(request.RequestUri.ToString(), contextCarrier, peer);
Tags.Url.Set(span, request.RequestUri.ToString());
span.AsHttp();
span.SetComponent(ComponentsDefine.HttpClient);
Tags.HTTP.Method.Set(span, request.Method.ToString());
foreach (var item in contextCarrier.Items)
request.Headers.Add(item.HeadKey, item.HeadValue);
var response = await base.SendAsync(request, cancellationToken);
Tags.StatusCode.Set(span, response.StatusCode.ToString());
ContextManager.StopSpan(span);
return response;
}
}
}
\ No newline at end of file
/*
* Licensed to the Apache Software Foundation (ASF) 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.Net.Http;
using Microsoft.Extensions.Http;
namespace SkyWalking.AspNetCore
{
internal class TracingHttpMessageHandlerBuilder : HttpMessageHandlerBuilder
{
private readonly TracingHttpHandler _primaryHandler = new TracingHttpHandler();
private string _name;
public override string Name
{
get => _name;
set
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
_name = value;
}
}
public override IList<DelegatingHandler> AdditionalHandlers { get; } = new List<DelegatingHandler>();
public override HttpMessageHandler Build()
{
if (PrimaryHandler == null)
{
throw new InvalidOperationException();
}
return CreateHandlerPipeline(PrimaryHandler, AdditionalHandlers);
}
public override HttpMessageHandler PrimaryHandler
{
get => _primaryHandler;
set
{
if (value != null)
{
_primaryHandler.InnerHandler = value;
}
}
}
}
}
\ No newline at end of file
...@@ -107,7 +107,7 @@ namespace SkyWalking.Context ...@@ -107,7 +107,7 @@ namespace SkyWalking.Context
public string PeerHost public string PeerHost
{ {
get => _peerHost; get => _peerHost;
set => _peerHost = value; set => _peerHost = "#" + value;
} }
public int PeerId public int PeerId
...@@ -137,8 +137,9 @@ namespace SkyWalking.Context ...@@ -137,8 +137,9 @@ namespace SkyWalking.Context
&& _spanId > -1 && _spanId > -1
&& _parentApplicationInstanceId != DictionaryUtil.NullValue && _parentApplicationInstanceId != DictionaryUtil.NullValue
&& _entryApplicationInstanceId != DictionaryUtil.NullValue && _entryApplicationInstanceId != DictionaryUtil.NullValue
&& string.IsNullOrEmpty(_parentOperationName) && !string.IsNullOrEmpty(_peerHost)
&& string.IsNullOrEmpty(_entryOperationName) && !string.IsNullOrEmpty(_parentOperationName)
&& !string.IsNullOrEmpty(_entryOperationName)
&& _primaryDistributedTraceId != null; && _primaryDistributedTraceId != null;
} }
} }
......
...@@ -34,9 +34,9 @@ namespace SkyWalking.Context ...@@ -34,9 +34,9 @@ namespace SkyWalking.Context
/// </summary> /// </summary>
public class ContextManager : ITracingContextListener, IBootService, IIgnoreTracerContextListener public class ContextManager : ITracingContextListener, IBootService, IIgnoreTracerContextListener
{ {
private static readonly ThreadLocal<ITracerContext> _context = new ThreadLocal<ITracerContext>(); private static readonly AsyncLocal<ITracerContext> _context = new AsyncLocal<ITracerContext>();
private static ITracerContext GetOrCreateContext(String operationName, bool forceSampling) private static ITracerContext GetOrCreateContext(string operationName, bool forceSampling)
{ {
var context = _context.Value; var context = _context.Value;
if (context == null) if (context == null)
...@@ -49,7 +49,7 @@ namespace SkyWalking.Context ...@@ -49,7 +49,7 @@ namespace SkyWalking.Context
else else
{ {
if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) && if (!DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationId) &&
DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId)) !DictionaryUtil.IsNull(RemoteDownstreamConfig.Agent.ApplicationInstanceId))
{ {
var suffixIdx = operationName.LastIndexOf('.'); var suffixIdx = operationName.LastIndexOf('.');
if (suffixIdx > -1 && AgentConfig.IgnoreSuffix.Contains(operationName.Substring(suffixIdx))) if (suffixIdx > -1 && AgentConfig.IgnoreSuffix.Contains(operationName.Substring(suffixIdx)))
......
...@@ -39,7 +39,7 @@ namespace SkyWalking.Context.Trace ...@@ -39,7 +39,7 @@ namespace SkyWalking.Context.Trace
public IEnumerable<ITraceSegmentRef> Refs => _refs; public IEnumerable<ITraceSegmentRef> Refs => _refs;
public IEnumerable<DistributedTraceId> RelatedGlobalTraces { get; } public IEnumerable<DistributedTraceId> RelatedGlobalTraces => _relatedGlobalTraces.GetRelatedGlobalTraces();
public ID TraceSegmentId { get; } public ID TraceSegmentId { get; }
......
...@@ -72,7 +72,7 @@ namespace SkyWalking.Context ...@@ -72,7 +72,7 @@ namespace SkyWalking.Context
} }
var refs = _segment.Refs; var refs = _segment.Refs;
var firstSpan = _activeSpanStacks.First(); var firstSpan = _activeSpanStacks.Last();
var metaValue = GetMetaValue(refs); var metaValue = GetMetaValue(refs);
...@@ -132,7 +132,7 @@ namespace SkyWalking.Context ...@@ -132,7 +132,7 @@ namespace SkyWalking.Context
public string GetReadableGlobalTraceId() public string GetReadableGlobalTraceId()
{ {
return _segment.RelatedGlobalTraces.First()?.ToString(); return _segment.RelatedGlobalTraces.FirstOrDefault()?.ToString();
} }
/// <summary> /// <summary>
...@@ -320,7 +320,7 @@ namespace SkyWalking.Context ...@@ -320,7 +320,7 @@ namespace SkyWalking.Context
snapshot.EntryOperationId = metaValue.operationId; snapshot.EntryOperationId = metaValue.operationId;
} }
var parentSpan = _activeSpanStacks.First(); var parentSpan = _activeSpanStacks.Last();
if (DictionaryUtil.IsNull(parentSpan.OperationId)) if (DictionaryUtil.IsNull(parentSpan.OperationId))
{ {
...@@ -345,7 +345,7 @@ namespace SkyWalking.Context ...@@ -345,7 +345,7 @@ namespace SkyWalking.Context
} }
else else
{ {
var span = _activeSpanStacks.First(); var span = _activeSpanStacks.Last();
return (span.OperationName, span.OperationId, _segment.ApplicationInstanceId); return (span.OperationName, span.OperationId, _segment.ApplicationInstanceId);
} }
} }
......
...@@ -24,6 +24,7 @@ using System.Threading.Tasks; ...@@ -24,6 +24,7 @@ using System.Threading.Tasks;
using SkyWalking.Boot; using SkyWalking.Boot;
using SkyWalking.Config; using SkyWalking.Config;
using SkyWalking.Context; using SkyWalking.Context;
using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol; using SkyWalking.NetworkProtocol;
namespace SkyWalking.Remote namespace SkyWalking.Remote
...@@ -37,9 +38,16 @@ namespace SkyWalking.Remote ...@@ -37,9 +38,16 @@ namespace SkyWalking.Remote
var application = new Application {ApplicationCode = AgentConfig.ApplicationCode}; var application = new Application {ApplicationCode = AgentConfig.ApplicationCode};
var applicationRegisterService = var applicationRegisterService =
new ApplicationRegisterService.ApplicationRegisterServiceClient(GrpcChannelManager.Instance.Channel); new ApplicationRegisterService.ApplicationRegisterServiceClient(GrpcChannelManager.Instance.Channel);
var applicationMapping = await applicationRegisterService.applicationCodeRegisterAsync(application);
RemoteDownstreamConfig.Agent.ApplicationId = applicationMapping.Application.Value; var applicationId = default(int?);
while (!applicationId.HasValue || DictionaryUtil.IsNull(applicationId.Value))
{
var applicationMapping = await applicationRegisterService.applicationCodeRegisterAsync(application);
applicationId = applicationMapping?.Application?.Value;
}
RemoteDownstreamConfig.Agent.ApplicationId = applicationId.Value;
var instanceDiscoveryService = var instanceDiscoveryService =
new InstanceDiscoveryService.InstanceDiscoveryServiceClient(GrpcChannelManager.Instance.Channel); new InstanceDiscoveryService.InstanceDiscoveryServiceClient(GrpcChannelManager.Instance.Channel);
...@@ -63,14 +71,21 @@ namespace SkyWalking.Remote ...@@ -63,14 +71,21 @@ namespace SkyWalking.Remote
var applicationInstance = new ApplicationInstance var applicationInstance = new ApplicationInstance
{ {
ApplicationId = applicationMapping.Application.Value, ApplicationId = applicationId.Value,
AgentUUID = agentUUID, AgentUUID = agentUUID,
RegisterTime = registerTime, RegisterTime = registerTime,
Osinfo = osInfo Osinfo = osInfo
}; };
var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance); var applicationInstanceId = 0;
RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceMapping.ApplicationInstanceId;
while (DictionaryUtil.IsNull(applicationInstanceId))
{
var applicationInstanceMapping = await instanceDiscoveryService.registerInstanceAsync(applicationInstance);
applicationInstanceId = applicationInstanceMapping.ApplicationInstanceId;
}
RemoteDownstreamConfig.Agent.ApplicationInstanceId = applicationInstanceId;
} }
......
...@@ -29,7 +29,7 @@ namespace SkyWalking.Remote ...@@ -29,7 +29,7 @@ namespace SkyWalking.Remote
new TraceSegmentService.TraceSegmentServiceClient(GrpcChannelManager.Instance.Channel); new TraceSegmentService.TraceSegmentServiceClient(GrpcChannelManager.Instance.Channel);
using (var asyncClientStreamingCall = traceSegmentService.collect()) using (var asyncClientStreamingCall = traceSegmentService.collect())
{ {
asyncClientStreamingCall.RequestStream.WriteAsync(segment); await asyncClientStreamingCall.RequestStream.WriteAsync(segment);
await asyncClientStreamingCall.RequestStream.CompleteAsync(); await asyncClientStreamingCall.RequestStream.CompleteAsync();
} }
} }
......
...@@ -17,12 +17,17 @@ ...@@ -17,12 +17,17 @@
*/ */
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
namespace SkyWalking.NetworkProtocol.Trace namespace SkyWalking.NetworkProtocol.Trace
{ {
public class ComponentsDefine public class ComponentsDefine
{ {
public static readonly OfficialComponent AspNetCore = new OfficialComponent(1, "AspNetCore"); public static readonly OfficialComponent HttpClient = new OfficialComponent(2, "HttpClient");
public static readonly OfficialComponent AspNetCore = new OfficialComponent(30, "AspNetCore");
public static readonly OfficialComponent EntityFrameworkCore = new OfficialComponent(31, "EntityFrameworkCore");
private static readonly ComponentsDefine _instance = new ComponentsDefine(); private static readonly ComponentsDefine _instance = new ComponentsDefine();
...@@ -39,6 +44,8 @@ namespace SkyWalking.NetworkProtocol.Trace ...@@ -39,6 +44,8 @@ namespace SkyWalking.NetworkProtocol.Trace
private ComponentsDefine() private ComponentsDefine()
{ {
_components = new Dictionary<int, string>(); _components = new Dictionary<int, string>();
AddComponent(AspNetCore);
AddComponent(EntityFrameworkCore);
} }
private void AddComponent(OfficialComponent component) private void AddComponent(OfficialComponent component)
......
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