Unverified Commit b366155f authored by Lemon's avatar Lemon Committed by GitHub

Support Asp.Net Framework (#61)

* Add SkyWalking.AspNet project

* Support .NET 4.5

* Support Asp.Net Framework

* Add Sample.AspNet project

* Fix CI

* Close grpc connection when application pool recycles
parent 62067838
using System.Web.Mvc;
using System.Web.Routing;
namespace SkyWalking.Sample.AspNet
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new {controller = "Home", action = "Index", id = UrlParameter.Optional}
);
}
}
}
\ No newline at end of file
using System.Web.Http;
namespace SkyWalking.Sample.AspNet
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
"DefaultApi",
"api/{controller}/{id}",
new {id = RouteParameter.Optional}
);
}
}
}
\ No newline at end of file
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using SkyWalking.AspNet;
namespace SkyWalking.Sample.AspNet.Controllers
{
public class ValuesController : ApiController
{
public async Task<IHttpActionResult> Get()
{
var httpClient = new HttpClient(new HttpTracingHandler());
var values = await httpClient.GetStringAsync("http://localhost:5002/api/values");
return Json(values);
}
}
}
\ No newline at end of file
<%@ Application Inherits="SkyWalking.Sample.AspNet.Global" %>
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Http;
namespace SkyWalking.Sample.AspNet
{
public class Global : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
}
\ No newline at end of file
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SkyWalking.Sample.AspNet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SkyWalking.Sample.AspNet")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("C3649845-E458-448D-B97D-C7E231E1D040")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{C3649845-E458-448D-B97D-C7E231E1D040}</ProjectGuid>
<ProjectTypeGuids>{349C5851-65DF-11DA-9384-00065B846F21};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SkyWalking.Sample.AspNet</RootNamespace>
<AssemblyName>SkyWalking.Sample.AspNet</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed">
<HintPath>../..\packages\Newtonsoft.Json.6.0.4\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Net.Http.Formatting, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll</HintPath>
</Reference>
<Reference Include="System.Web" />
<Reference Include="System.Web.Http, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll</HintPath>
</Reference>
<Reference Include="System.Web.Http.WebHost, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.AspNet.WebApi.WebHost.5.2.3\lib\net45\System.Web.Http.WebHost.dll</HintPath>
</Reference>
<Reference Include="System.Web.Services" />
<Reference Include="System.Web.Routing" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Web.Abstractions" />
<Reference Include="System.Web.DynamicData" />
<Reference Include="System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.Helpers.dll</HintPath>
</Reference>
<Reference Include="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.AspNet.Mvc.5.2.3\lib\net45\System.Web.Mvc.dll</HintPath>
</Reference>
<Reference Include="System.Web.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.AspNet.Razor.3.2.3\lib\net45\System.Web.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages.Deployment, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Deployment.dll</HintPath>
</Reference>
<Reference Include="System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
<HintPath>../..\packages\Microsoft.AspNet.WebPages.3.2.3\lib\net45\System.Web.WebPages.Razor.dll</HintPath>
</Reference>
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="App_Start\RouteConfig.cs" />
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="Controllers\ValuesController.cs" />
<Compile Include="Global.asax.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="favicon.ico" />
<Content Include="Global.asax" />
<Content Include="packages.config" />
<Content Include="Web.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\SkyWalking.AspNet\SkyWalking.AspNet.csproj">
<Project>{3a454a8a-a1b7-4c6d-be08-52d956f95cc1}</Project>
<Name>SkyWalking.AspNet</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<!--
Web.config file for SkyWalking.Sample.AspNet.
The settings that can be used in this file are documented at
http://www.mono-project.com/Config_system.web and
http://msdn2.microsoft.com/en-us/library/b5ysx397.aspx
-->
<configuration>
<appSettings>
<add key="ApplicationCode" value="aspnet-sample"/>
<add key="DirectServers" value="localhost:11800"/>
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5">
<assemblies />
</compilation>
<httpRuntime targetFramework="4.5" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="bootstrap" version="3.3.7" targetFramework="net45" />
<package id="jQuery" version="1.9.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net45" />
<package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net45" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="6.0.4" targetFramework="net45" />
</packages>
\ No newline at end of file
......@@ -58,6 +58,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Diagnostics.Enti
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Diagnostics.EntityFrameworkCore.Npgsql", "src\SkyWalking.Diagnostics.EntityFrameworkCore.Npgsql\SkyWalking.Diagnostics.EntityFrameworkCore.Npgsql.csproj", "{F8D96C30-369C-4FCB-B5B2-02EAA74199C9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.AspNet", "src\SkyWalking.AspNet\SkyWalking.AspNet.csproj", "{3A454A8A-A1B7-4C6D-BE08-52D956F95CC1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SkyWalking.Sample.AspNet", "sample\SkyWalking.Sample.AspNet\SkyWalking.Sample.AspNet.csproj", "{C3649845-E458-448D-B97D-C7E231E1D040}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -136,6 +140,14 @@ Global
{F8D96C30-369C-4FCB-B5B2-02EAA74199C9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F8D96C30-369C-4FCB-B5B2-02EAA74199C9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F8D96C30-369C-4FCB-B5B2-02EAA74199C9}.Release|Any CPU.Build.0 = Release|Any CPU
{3A454A8A-A1B7-4C6D-BE08-52D956F95CC1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3A454A8A-A1B7-4C6D-BE08-52D956F95CC1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3A454A8A-A1B7-4C6D-BE08-52D956F95CC1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3A454A8A-A1B7-4C6D-BE08-52D956F95CC1}.Release|Any CPU.Build.0 = Release|Any CPU
{C3649845-E458-448D-B97D-C7E231E1D040}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C3649845-E458-448D-B97D-C7E231E1D040}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C3649845-E458-448D-B97D-C7E231E1D040}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C3649845-E458-448D-B97D-C7E231E1D040}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......@@ -162,6 +174,8 @@ Global
{F5C529C9-23C4-46B7-84FF-E86C6D17EB3E} = {A4E67E09-3156-4D30-B451-F24F706E96C4}
{7BD880F3-2886-4EE6-9569-114613AFFCBC} = {A4E67E09-3156-4D30-B451-F24F706E96C4}
{F8D96C30-369C-4FCB-B5B2-02EAA74199C9} = {A4E67E09-3156-4D30-B451-F24F706E96C4}
{3A454A8A-A1B7-4C6D-BE08-52D956F95CC1} = {79ED86A5-E9B9-49B2-9354-C911C079D03E}
{C3649845-E458-448D-B97D-C7E231E1D040} = {844CEACD-4C85-4B15-9E2B-892B01FDA4BB}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {94C0DA2C-CCCB-4314-93A2-9809B5DD0583}
......
......@@ -35,7 +35,7 @@ namespace SkyWalking.Config
/// Negative number means sample traces as many as possible, most likely 100% , by default
///
/// </summary>
public static int Sample_N_Per_3_Secs = -1;
public static int SamplePer3Secs = -1;
/// <summary>
/// If the operation name of the first span is included in this set, this segment should be ignored.
......
......@@ -22,6 +22,7 @@ using SkyWalking.Dictionarys;
using SkyWalking.NetworkProtocol;
using SkyWalking.NetworkProtocol.Trace;
using System.Linq;
using SkyWalking.Utils;
namespace SkyWalking.Context.Trace
{
......
......@@ -3,7 +3,7 @@
<PropertyGroup>
<Description>SkyWalking Core abstractions and interfaces for apm agent.</Description>
<AssemblyTitle>SkyWalking.Abstractions</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
<TargetFrameworks>netstandard2.0;net45;net451</TargetFrameworks>
<AssemblyName>SkyWalking.Abstractions</AssemblyName>
<PackageId>SkyWalking.Abstractions</PackageId>
<PackageTags>SkyWalking;APM</PackageTags>
......
/*
* 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.Utils
{
#if NET45 || NET451
public static class DateTimeOffsetExtensions
{
public static long ToUnixTimeMilliseconds(this DateTimeOffset dateTimeOffset)
{
return dateTimeOffset.UtcDateTime.Ticks / 10000L - 62135596800000L;
}
}
#endif
}
/*
* 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;
namespace SkyWalking.AspNet
{
internal class AsyncContext
{
public static void Run(Func<Task> task)
{
using (new ContextScope())
{
Task.Run(async () => await task()).GetAwaiter().GetResult();
}
}
private class ContextScope : IDisposable
{
private readonly SynchronizationContext _current;
public ContextScope()
{
_current = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(null);
}
public void Dispose()
{
SynchronizationContext.SetSynchronizationContext(_current);
}
}
}
}
/*
* 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.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.AspNet
{
public class HttpTracingHandler : DelegatingHandler
{
public HttpTracingHandler()
: this(new HttpClientHandler())
{
}
public HttpTracingHandler(HttpMessageHandler innerHandler)
{
InnerHandler = innerHandler;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
var peer = $"{request.RequestUri.Host}:{request.RequestUri.Port}";
var contextCarrier = new ContextCarrier();
var span = ContextManager.CreateExitSpan(request.RequestUri.ToString(), contextCarrier, peer);
try
{
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());
return response;
}
catch (Exception e)
{
span.ErrorOccurred().Log(e);
throw;
}
finally
{
ContextManager.StopSpan(span);
}
}
}
}
/*
* 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 SkyWalking.Logging;
namespace SkyWalking.AspNet.Logging
{
internal class DebugLoggerAdapter : ILogger
{
private readonly Type type;
public DebugLoggerAdapter(Type type)
{
this.type = type;
}
public void Debug(string message)
{
WriteLine("debug", message);
}
public void Info(string message)
{
WriteLine("info", message);
}
public void Warning(string message)
{
WriteLine("warn", message);
}
public void Error(string message, Exception exception)
{
WriteLine("error", message + Environment.NewLine + exception);
}
public void Trace(string message)
{
WriteLine("trace", message);
}
private void WriteLine(string level, string message)
{
System.Diagnostics.Debug.WriteLine($"{DateTime.Now} : [{level}] [{type.Name}] {message}");
}
}
}
\ No newline at end of file
/*
* Licensed to the OpenSkywalking under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Diagnostics;
using SkyWalking.Logging;
namespace SkyWalking.AspNet.Logging
{
internal class DebugLoggerFactoryAdapter : ILoggerFactory
{
public DebugLoggerFactoryAdapter()
{
Debug.Listeners.Add(new TextWriterTraceListener(Console.Out));
}
public ILogger CreateLogger(Type type)
{
return new DebugLoggerAdapter(type);
}
}
}
<Project Sdk="Microsoft.NET.Sdk">
<Import Project="..\..\build\common.props" />
<PropertyGroup>
<TargetFrameworks>net45;net451;net452;net46;net461;net462;net47;net471</TargetFrameworks>
</PropertyGroup>
<PropertyGroup>
<AssemblyName>SkyWalking.AspNet</AssemblyName>
<AssemblyTitle>SkyWalking.AspNet</AssemblyTitle>
<PackageId>SkyWalking.AspNet</PackageId>
<PackageTags>SkyWalking;APM;Tracing</PackageTags>
<Description>SkyWalking ASP.NET Agent.</Description>
<RootNamespace>SkyWalking.AspNet</RootNamespace>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SkyWalking.Core\SkyWalking.Core.csproj" />
</ItemGroup>
<ItemGroup>
<Reference Include="System.Configuration" />
<Reference Include="System.Web" />
<Reference Include="System.Net.Http"/>
</ItemGroup>
<ItemGroup>
<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.Boot;
using SkyWalking.Context;
using SkyWalking.Context.Tag;
using SkyWalking.Context.Trace;
using SkyWalking.NetworkProtocol.Trace;
using SkyWalking.Remote;
using SkyWalking.Utils;
namespace SkyWalking.AspNet
{
public class SkyWalkingModule : IHttpModule
{
private readonly SkyWalkingStartup _skyWalkingStartup = new SkyWalkingStartup();
public void Dispose()
{
_skyWalkingStartup.Dispose();
}
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 httpApplication = sender as HttpApplication;
var httpContext = httpApplication.Context;
var statusCode = httpContext.Response.StatusCode;
if (statusCode >= 400)
{
httpRequestSpan.ErrorOccurred();
}
Tags.StatusCode.Set(httpRequestSpan, statusCode.ToString());
var exception = httpContext.Error;
if (exception != null)
{
httpRequestSpan.ErrorOccurred().Log(exception);
}
httpRequestSpan.Log(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(),
new Dictionary<string, object>
{
{"event", "AspNetCore Hosting EndRequest"},
{"message", $"Request finished {httpContext.Response.StatusCode} {httpContext.Response.ContentType}"}
});
ContextManager.StopSpan(httpRequestSpan);
}
}
}
/*
* 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.Web.Infrastructure.DynamicModuleHelper;
using System.Web;
using SkyWalking.AspNet;
[assembly:PreApplicationStartMethod(typeof(SkyWalkingModuleRegister), "Register")]
namespace SkyWalking.AspNet
{
public class SkyWalkingModuleRegister
{
public static void Register()
{
DynamicModuleUtility.RegisterModule(typeof(SkyWalkingModule));
}
}
}
\ 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; }
}
}
\ 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.Reflection;
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
{
public class SkyWalkingStartup : IDisposable
{
public void Start()
{
LoadConfigurationSetting();
LogManager.SetLoggerFactory(new DebugLoggerFactoryAdapter());
AsyncContext.Run(async () => await StartAsync());
}
private async Task StartAsync()
{
await GrpcConnectionManager.Instance.ConnectAsync(TimeSpan.FromSeconds(3));
await ServiceManager.Instance.Initialize();
}
private void LoadConfigurationSetting()
{
CollectorConfig.DirectServers = GetAppSetting(nameof(CollectorConfig.DirectServers), true);
AgentConfig.ApplicationCode = GetAppSetting(nameof(AgentConfig.ApplicationCode), true);
AgentConfig.Namespace = GetAppSetting(nameof(AgentConfig.Namespace), false);
var samplePer3Secs = GetAppSetting(nameof(AgentConfig.SamplePer3Secs), false);
if (int.TryParse(samplePer3Secs, out var v))
{
AgentConfig.SamplePer3Secs = v;
}
}
private string GetAppSetting(string key, bool @throw)
{
var value = WebConfigurationManager.AppSettings[key];
if (@throw && string.IsNullOrEmpty(value))
{
throw new InvalidOperationException($"Cannot read valid '{key}' in AppSettings.");
}
return value;
}
public void Dispose()
{
AsyncContext.Run(async () => await GrpcConnectionManager.Instance.ShutdownAsync());
ServiceManager.Instance.Dispose();
}
}
}
......@@ -53,7 +53,7 @@ namespace SkyWalking.AspNetCore
LogManager.SetLoggerFactory(loggerFactory);
AgentConfig.ApplicationCode = options.Value.ApplicationCode;
CollectorConfig.DirectServers = options.Value.DirectServers;
AgentConfig.Sample_N_Per_3_Secs = options.Value.SamplePer3Secs;
AgentConfig.SamplePer3Secs = options.Value.SamplePer3Secs;
_logger = LogManager.GetLogger<SkyWalkingHostedService>();
_diagnosticObserver = diagnosticObserver;
}
......
......@@ -20,6 +20,7 @@ using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Logging;
using SkyWalking.Utils;
namespace SkyWalking.Boot
{
......@@ -59,12 +60,12 @@ namespace SkyWalking.Boot
protected virtual Task Initializing(CancellationToken token)
{
return Task.CompletedTask;
return TaskUtils.CompletedTask;
}
protected virtual Task Starting(CancellationToken token)
{
return Task.CompletedTask;
return TaskUtils.CompletedTask;
}
protected abstract Task Execute(CancellationToken token);
......
......@@ -24,6 +24,7 @@ using SkyWalking.Config;
using SkyWalking.Context.Trace;
using SkyWalking.Dictionarys;
using SkyWalking.Sampling;
using SkyWalking.Utils;
namespace SkyWalking.Context
{
......@@ -185,7 +186,7 @@ namespace SkyWalking.Context
{
TracingContext.ListenerManager.Add(this);
IgnoredTracerContext.ListenerManager.Add(this);
return Task.CompletedTask;
return TaskUtils.CompletedTask;
}
public void AfterFinish(ITracerContext tracerContext)
......
......@@ -20,6 +20,7 @@ using System;
using System.Threading;
using SkyWalking.Config;
using SkyWalking.Dictionarys;
using SkyWalking.Utils;
namespace SkyWalking.Context.Ids
{
......@@ -77,6 +78,7 @@ namespace SkyWalking.Context.Ids
_lastRandomValue = _random.Next();
_runRandomTimestamp = currentTimeMillis;
}
return _lastRandomValue;
}
else
......@@ -92,6 +94,7 @@ namespace SkyWalking.Context.Ids
{
_threadSeq = 0;
}
return _threadSeq++;
}
}
......
......@@ -49,6 +49,11 @@ namespace SkyWalking.Remote
return;
}
if (string.IsNullOrEmpty(AgentConfig.ApplicationCode))
{
return;
}
if (!GrpcConnectionManager.Instance.Available)
{
return;
......
......@@ -21,10 +21,10 @@ using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Config;
using SkyWalking.Context;
using SkyWalking.Dictionarys;
using SkyWalking.Logging;
using SkyWalking.NetworkProtocol;
using SkyWalking.Utils;
namespace SkyWalking.Remote
{
......
......@@ -20,6 +20,7 @@ using System;
using System.Threading;
using System.Threading.Tasks;
using SkyWalking.Boot;
using SkyWalking.Utils;
namespace SkyWalking.Remote
{
......@@ -30,7 +31,7 @@ namespace SkyWalking.Remote
protected override Task Execute(CancellationToken token)
{
// todo
return Task.CompletedTask;
return TaskUtils.CompletedTask;
}
}
}
\ No newline at end of file
......@@ -25,6 +25,7 @@ using SkyWalking.Context;
using SkyWalking.Context.Trace;
using SkyWalking.Logging;
using SkyWalking.NetworkProtocol;
using SkyWalking.Utils;
namespace SkyWalking.Remote
{
......@@ -42,7 +43,7 @@ namespace SkyWalking.Remote
public Task Initialize(CancellationToken token)
{
TracingContext.ListenerManager.Add(this);
return Task.CompletedTask;
return TaskUtils.CompletedTask;
}
public async void AfterFinished(ITraceSegment traceSegment)
......
......@@ -29,8 +29,8 @@ namespace SkyWalking.Sampling
public class SamplingService :TimerService, ISampler
{
private readonly AtomicInteger _atomicInteger = new AtomicInteger();
private readonly int _sample_N_Per_3_Secs = AgentConfig.Sample_N_Per_3_Secs;
private readonly bool _sample_on = AgentConfig.Sample_N_Per_3_Secs > 0;
private readonly int _sample_N_Per_3_Secs = AgentConfig.SamplePer3Secs;
private readonly bool _sample_on = AgentConfig.SamplePer3Secs > 0;
public bool TrySampling()
{
......@@ -59,7 +59,7 @@ namespace SkyWalking.Sampling
_atomicInteger.Value = 0;
}
return Task.CompletedTask;
return TaskUtils.CompletedTask;
}
}
}
\ No newline at end of file
......@@ -3,7 +3,7 @@
<PropertyGroup>
<Description>SkyWalking core components.</Description>
<AssemblyTitle>SkyWalking.Core</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
<TargetFrameworks>netstandard2.0;net45;net451</TargetFrameworks>
<AssemblyName>SkyWalking.Core</AssemblyName>
<PackageId>SkyWalking.Core</PackageId>
<PackageTags>SkyWalking;APM</PackageTags>
......
/*
* 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.
*
*/
#if NET45 || NET451
using System.Runtime.Remoting.Messaging;
namespace SkyWalking.Utils
{
internal class AsyncLocal<T>
{
private static readonly string key = "sw-" + typeof(T).FullName;
public T Value
{
get => (T) CallContext.LogicalGetData(key);
set => CallContext.LogicalSetData(key, value);
}
}
}
#endif
/*
* 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.Threading.Tasks;
namespace SkyWalking.Utils
{
internal static class TaskUtils
{
public static readonly Task CompletedTask = Task.FromResult(0);
}
}
\ No newline at end of file
......@@ -53,6 +53,8 @@ namespace SkyWalking.NetworkProtocol.Trace
public static readonly OfficialComponent InMemoryDatabase = new OfficialComponent(3014, "InMemoryDatabase");
public static readonly OfficialComponent AspNet = new OfficialComponent(3015, "AspNet");
private static readonly ComponentsDefine _instance = new ComponentsDefine();
public ComponentsDefine Instance => _instance;
......@@ -76,6 +78,7 @@ namespace SkyWalking.NetworkProtocol.Trace
AddComponent(Pomelo_EntityFrameworkCore_MySql);
AddComponent(Npgsql_EntityFrameworkCore_PostgreSQL);
AddComponent(InMemoryDatabase);
AddComponent(AspNet);
}
private void AddComponent(OfficialComponent component)
......
......@@ -3,7 +3,7 @@
<PropertyGroup>
<Description>SkyWalking trace protocol.</Description>
<AssemblyTitle>SkyWalking.NetworkProtocol.Trace</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
<AssemblyName>SkyWalking.NetworkProtocol.Trace</AssemblyName>
<PackageId>SkyWalking.NetworkProtocol.Trace</PackageId>
<PackageTags>SkyWalking</PackageTags>
......
......@@ -3,7 +3,7 @@
<PropertyGroup>
<Description>SkyWalking gRPC protocol and generated codes.</Description>
<AssemblyTitle>SkyWalking.NetworkProtocol</AssemblyTitle>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
<TargetFrameworks>netstandard2.0;net45</TargetFrameworks>
<AssemblyName>SkyWalking.NetworkProtocol</AssemblyName>
<PackageId>SkyWalking.NetworkProtocol</PackageId>
<PackageTags>SkyWalking</PackageTags>
......
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