Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/develop'
Browse files Browse the repository at this point in the history
  • Loading branch information
xiaomi7732 committed Aug 11, 2018
2 parents d2d2184 + 5d7c812 commit 8e47365
Show file tree
Hide file tree
Showing 82 changed files with 24,929 additions and 55 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ Microsoft Application Insights for Kubernetes
==
This repository has code for Application Insights for Kubernetes, which works on .NET Core applications within the containers, managed by Kubernetes, on Azure Container Service.

**Note:** This library enhanced the [Microsoft Application Insights](https://github.com/Microsoft/ApplicationInsights-aspnetcore) but is **not required** to run applicaiton insights in Kubernetes. When you choose to use Microsoft Application Insights for Kubernetes, you will see Kubernetes related properties like *Pod-Name, Deployment ...* on all your telemetry entries. Rich features like Appliation Map to show the multiple micro service on your application map will also be provided.
**Note:** `Microsoft Application Insights for Kubernetes` (this library) is an enhancement to the [Microsoft Application Insights](https://github.com/Microsoft/ApplicationInsights-aspnetcore). You can choose to run **Application Insights** without this library in Kubernetes cluster too. However, when using `Microsoft Application Insights for Kubernetes`, you will see Kubernetes related properties like *Pod-Name, Deployment ...* on all your telemetry entries. Proper values will also be set to make use of the rich features like enabling the Application Map to show the multiple micro services on the same map.

### Continous Integration Status
|Rolling Build | Nightly Build |
Expand All @@ -22,11 +22,16 @@ We support **ASP.NET Core** application as well as **.NET Core** application.

* For **.NET Core** Application: Refer [Getting Started](https://github.com/Microsoft/ApplicationInsights-Kubernetes/wiki/Getting-Started-for-.NET-Core-Applications) for a simple walkthrough.

* Follow [this example](examples/BasicUsage_clr21_RBAC) for Role-based access control (RBAC) enabled Kubernetes clusters.

### Learn more
* To build a container for Kubernetes that have Application Insights baked in for the existing applications, please refer the example of [Zero Code light up](https://github.com/Microsoft/ApplicationInsights-Kubernetes/tree/develop/examples/ZeroUserCodeLightup).
* To enable Application Insights for Kubernetes by environement variable instead of code, please refer [Hosting startup for ApplicationInsights.Kubernetes](https://github.com/Microsoft/ApplicationInsights-Kubernetes/wiki/Hosting-startup-for-ApplicationInsights.Kubernetes).
* Still want more? Read the [Wikis](https://github.com/Microsoft/ApplicationInsights-Kubernetes/wiki).

### Next step
Profile your application for performance improvement using [Application Insights Profiler for Linux](https://github.com/Microsoft/ApplicationInsights-Profiler-AspNetCore).

## Contributing
### Report issues
Please file bug, discussion or any other interesting topics in [issues](https://github.com/Microsoft/ApplicationInsights-Kubernetes/issues) on github.
Expand Down
2 changes: 2 additions & 0 deletions examples/BasicUsage_clr21_RBAC/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
obj/
bin/
92 changes: 92 additions & 0 deletions examples/BasicUsage_clr21_RBAC/README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Walkthrough
This example walks through the steps to deploy an ASP.NET Core 2.1 MVC application to a Kubernets cluster with `Application Insights for Kubernetes` on.

A simple cluster role sample yaml is also included to describe how to make it work in a Role-based access control(RBAC) enabled clusters.

_Tip: [Read this for more information about RBAC](https://kubernetes.io/docs/reference/access-authn-authz/rbac/)._

_Note: This is an example that does not follow all best practices, including security-related best practices. E.g. Application Insights instrumentation key is not adequately protected (it should be deployed as a secret)._

## Prerequisite
* .NETCore SDK 2.1.300 or above

* .NET Core SDK is required in this example. Go to [https://dot.net](https://dot.net) to download the latest SDK. Make sure you have `2.1.300` or `above`:
```bash
dotnet --version
2.1.301
```
* A Kubernetes Cluster that you can manage with kubectl.
* If you don't have any, an easy way is to go to [Azure AKS](https://docs.microsoft.com/en-us/azure/aks/) to get a managed cluster. Verify that the credential is properly set for kubctl to work:
```bash
user@user-pc:~$ kubectl get nodes
NAME STATUS ROLES AGE VERSION
aks-nodepool1-10984277-0 Ready agent 17d v1.9.9
aks-nodepool1-10984277-1 Ready agent 17d v1.9.9
aks-nodepool1-10984277-2 Ready agent 17d v1.9.9
user@user-pc:~$
```
* A container image repository
* The image built will be pushed into an image repository. Dockerhub is used in this example.
## Create the project
* Let's start by creating an ASP.NET Core MVC applicaiton:
```
dotnet new mvc
```
* Add the NuGet Packages:
```
dotnet add package Microsoft.ApplicationInsights.AspNetCore
dotnet add package Microsoft.ApplicationInsights.Kubernetes --version 1.0.0-beta8
```
* Enable Application Insights in Program.cs by calling UseApplicaitonInsights() on WebHostBuilder:
```csharp
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseApplicationInsights() // Add this line of code
.UseStartup<Startup>()
.Build();
```
* Enable Application Insights for Kubernetes in Startup.cs:
```csharp
public void ConfigureServices(IServiceCollection services)
{
services.EnableKubernetes(); // Add this line of code
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
```

## Prepare the container
* It is always recommended to update the base images:
```
docker pull microsoft/dotnet:2.1-sdk
docker pull microsoft/dotnet:2.1-aspnetcore-runtime
```
* Add [Dockerfile](app/Dockerfile) to the project folder. Build the docker container (dockeraccount/aik8sbasic_rbac, for example) using [Dockerfile](app/Dockerfile) and upload it to an image registry.
```
docker build . -t dockeraccount/aik8sbasic_rbac:latest
docker push dockeraccount/aik8sbasic_rbac:latest
```
## Setup the default Service Account for RBAC enabled cluster
* If the cluster is RBAC enabled, the service account used will need to bind to proper cluster role so that the application can fetch Kubernetes related properties.
In [saRole.yaml](k8s/saRole.yaml), a cluster role named `metrics-reader` is created and then bind to the default service account. Permissions needed are listed in the resources property. To deploy it, update the value for the `namespace` and then:
```
kubectl create -f k8s/saRole.yaml
```

## Deploy the application
* Create the Kubernetes spec for the deployment and the service. Referencing [k8s.yaml](k8s/k8s.yaml). Please update the variable of `APPINSIGHTS_INSTRUMENTATIONKEY` to your own application insights instrumentation key.
Deploy it:
```
kubectl create -f k8s/k8s.yaml
```

## Verification
Once properly set up, your telemetry data will all be decorated with Kubernetes properties on it:

<img src="media/Result.png" width="779px" />

## Next step
* [Troubleshoot Application Insights for Kubernetes](https://github.com/Microsoft/ApplicationInsights-Kubernetes/wiki/%5BAdvanced%5D-How-to-enable-self-diagnostics-for-ApplicationInsights.Kubernetes)

* [Enable Application Insights Profiler](https://github.com/Microsoft/ApplicationInsights-Profiler-AspNetCore) to optimize the performance for your application.
43 changes: 43 additions & 0 deletions examples/BasicUsage_clr21_RBAC/app/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using app.Models;

namespace app.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}

public IActionResult About()
{
ViewData["Message"] = "Your application description page.";

return View();
}

public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";

return View();
}

public IActionResult Privacy()
{
return View();
}

[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
16 changes: 16 additions & 0 deletions examples/BasicUsage_clr21_RBAC/app/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
FROM microsoft/dotnet:2.1-sdk AS build-env
WORKDIR /app

# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out

# Build runtime image
FROM microsoft/dotnet:2.1-aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "app.dll"]
11 changes: 11 additions & 0 deletions examples/BasicUsage_clr21_RBAC/app/Models/ErrorViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System;

namespace app.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }

public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
25 changes: 25 additions & 0 deletions examples/BasicUsage_clr21_RBAC/app/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;

namespace app
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseApplicationInsights()
.UseStartup<Startup>();
}
}
27 changes: 27 additions & 0 deletions examples/BasicUsage_clr21_RBAC/app/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:12997",
"sslPort": 44301
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"app": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
64 changes: 64 additions & 0 deletions examples/BasicUsage_clr21_RBAC/app/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace app
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}

public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});


services.EnableKubernetes();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
7 changes: 7 additions & 0 deletions examples/BasicUsage_clr21_RBAC/app/Views/Home/About.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
@{
ViewData["Title"] = "About";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<p>Use this area to provide additional information.</p>
17 changes: 17 additions & 0 deletions examples/BasicUsage_clr21_RBAC/app/Views/Home/Contact.cshtml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
@{
ViewData["Title"] = "Contact";
}
<h2>@ViewData["Title"]</h2>
<h3>@ViewData["Message"]</h3>

<address>
One Microsoft Way<br />
Redmond, WA 98052-6399<br />
<abbr title="Phone">P:</abbr>
425.555.0100
</address>

<address>
<strong>Support:</strong> <a href="mailto:[email protected]">Support@example.com</a><br />
<strong>Marketing:</strong> <a href="mailto:[email protected]">Marketing@example.com</a>
</address>
Loading

0 comments on commit 8e47365

Please sign in to comment.