Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initial commit dotnetcore service #82

Merged
merged 6 commits into from
Jan 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/reusable-build-container-images.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ jobs:
name: services-java
- context: ./src/services/nodejs
name: services-nodejs
- context: ./src/services/dotnetcore
name: services-dotnetcore
- context: ./src/databases/mysql
name: databases-mysql
steps:
Expand Down
2 changes: 1 addition & 1 deletion scripts/generators/k8s/.gitignore
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
deployments/*
templates/*
!deployments/.gitkeep
config.yaml
config*.yaml
!/templates/databases
!/templates/loaders
!/templates/services
26 changes: 26 additions & 0 deletions src/services/dotnetcore/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 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 mcr.microsoft.com/dotnet/core/aspnet:3.1

LABEL org.opencontainers.image.source=https://github.com/cisco-open/app-simulator
LABEL org.opencontainers.image.description="dotnetcore service for app-simulator"
LABEL org.opencontainers.image.licenses=BSD-3-Clause

RUN apt-get update && apt-get install -y \
unzip \
&& rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY --from=build-env /app/out .
COPY entrypoint.sh /app
CMD ["/app/entrypoint.sh"]
35 changes: 35 additions & 0 deletions src/services/dotnetcore/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

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

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging(logging =>
{
logging.ClearProviders();
logging.AddConsole();
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
webBuilder.ConfigureKestrel(serverOptions =>
{
serverOptions.ListenAnyIP(8080); // Specify the port number here
});
});
}
}
27 changes: 27 additions & 0 deletions src/services/dotnetcore/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:35517",
"sslPort": 44381
}
},
"profiles": {
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"dotnetcore": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:8443;http://localhost:8080",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
55 changes: 55 additions & 0 deletions src/services/dotnetcore/RequestLoggingMiddleware.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace dotnetcore
{
public class RequestLoggingMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger _logger;

public RequestLoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
_logger = loggerFactory.CreateLogger<RequestLoggingMiddleware>();
}

public async Task Invoke(HttpContext context)
{
var watch = Stopwatch.StartNew();
try
{
await _next(context);
}
finally
{
watch.Stop();
string logLevelString = "INFO";
LogLevel ll = LogLevel.Information;

if(context.Response?.StatusCode > 399) {
logLevelString = "ERROR";
ll = LogLevel.Error;
}

Console.WriteLine(context.Request?.Headers);

_logger.Log(ll,
"{dateTime} [{processId}] [] {level} default - {remoteAddr} - \"{method} {url}\" {statusCode} {length} \"{userAgent}\" - {time} ms",
DateTime.Now.ToString("yyyyy-MM-dd HH:mm:ss,fff"),
Process.GetCurrentProcess().Id,
logLevelString,
context.Connection.RemoteIpAddress,
context.Request?.Method,
context.Request?.Path.Value,
context.Response?.StatusCode,
context.Response?.ContentLength,
context.Request?.Headers["User-Agent"].ToString(),
watch.ElapsedMilliseconds);
}
}
}
}
153 changes: 153 additions & 0 deletions src/services/dotnetcore/Startup.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;

namespace dotnetcore
{
namespace Controllers
{
public class HomeController : Controller
{
private async Task<string> processCall(JToken token)
{
string call = "";
if (token is JObject)
{
call = token["call"].ToString();
Random rnd = new Random();
if (token["probability"] != null && Double.Parse(token["probability"].ToString()) <= rnd.NextDouble())
{
return call + " was not probable";
}
}
if (token is JValue)
{
call = token.ToString();
}

// Walk over all potential commands
if (call.StartsWith("sleep"))
{
string[] r = call.Split(",");
Thread.Sleep(Int32.Parse(r[1]));
return call;
}
else if (call.StartsWith("http://"))
{
HttpClient c = new HttpClient();
c.BaseAddress = new Uri(call);
c.DefaultRequestHeaders.Add("User-Agent", "app-simulator/0.0.2");
return await c.GetStringAsync("");
}
else if (call.StartsWith("slow"))
{
string[] r = call.Split(",");
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
string response = "";
while (stopWatch.ElapsedMilliseconds < Int64.Parse(r[1]))
{
response += " ";
}
return response.Length + " slow response";
}
else if (call.StartsWith("error"))
{
string[] r = call.Split(",");
throw new WebException(r.Length > 2 ? r[2] : "", Int32.Parse(r[1]));
}

return call + " is not supported";
}

public async Task<IActionResult> Index()
{
JToken value = (JToken)RouteData.DataTokens["Value"];

int code = 200;

if(value is JArray)
{
JArray calls = (JArray)value;
List<string> result = new List<String>();
foreach (JToken token in calls)
{
try {
result.Add(await processCall(token));
} catch (WebException e) {
code = e.Code;
result.Add(e.Message);
}
}
string finalResponse = JsonConvert.SerializeObject(result);
//await context.Response.WriteAsync(finalResponse);
//context.Response.Headers.ContentLength = finalResponse.Length;
return StatusCode(code, finalResponse);
}
return Ok("200");
}
}
}

public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseMiddleware<RequestLoggingMiddleware>();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}

string appConfig = Environment.GetEnvironmentVariable("APP_CONFIG");

if (String.IsNullOrEmpty(appConfig))
{
appConfig = "{ endpoints: {}}";
}

Console.WriteLine(appConfig);

JObject config = JsonConvert.DeserializeObject<JObject>(appConfig);

app.UseRouting();

app.UseEndpoints(appEndpoints =>
{
if (config["endpoints"] is JObject && config["endpoints"]["http"] is JObject)
{
foreach (KeyValuePair<string, JToken> endpoint in (JObject)config["endpoints"]["http"])
{
appEndpoints.MapControllerRoute(
name: "Default",
pattern: endpoint.Key,
defaults: new { controller = "Home", action = "Index"},
dataTokens: new { Value = endpoint.Value }
);
}
}
});
}
}
}
12 changes: 12 additions & 0 deletions src/services/dotnetcore/WebException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
using System;

namespace dotnetcore
{
public class WebException : Exception
{
public int Code { get; }
public WebException(string message, int code) : base(message) {
Code = code;
}
}
}
9 changes: 9 additions & 0 deletions src/services/dotnetcore/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
}
}
11 changes: 11 additions & 0 deletions src/services/dotnetcore/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information",
"dotnetcore": "Information"
}
},
"AllowedHosts": "*"
}
11 changes: 11 additions & 0 deletions src/services/dotnetcore/dotnetcore.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
</ItemGroup>

</Project>
2 changes: 2 additions & 0 deletions src/services/dotnetcore/entrypoint.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
#!/bin/bash
APP_CONFIG="$(</config.json)" dotnet dotnetcore.dll
Loading