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

Homework #3

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
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
6 changes: 6 additions & 0 deletions Observability.Homework.Tracing.Client/Models/Client.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
namespace Observability.Homework.Models;

public class Client
{
public required string Id { get; set; }
}
23 changes: 23 additions & 0 deletions Observability.Homework.Tracing.Client/Models/Order.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace Observability.Homework.Models;

public class Order
{
public required Client Client { get; set; }

public required Product Product { get; set; }

public static Order Create(ProductType type)
{
return new Order
{
Client = new()
{
Id = Guid.NewGuid().ToString()
},
Product = new Product
{
Type = type
}
};
}
}
15 changes: 15 additions & 0 deletions Observability.Homework.Tracing.Client/Models/Product.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
namespace Observability.Homework.Models;

public class Product
{
public Guid Id { get; } = Guid.NewGuid();

public required ProductType Type { get; set; }
}

public enum ProductType
{
Pizza = 0,
Desert = 1,
Beverage = 2
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="OpenTelemetry" Version="1.10.0-beta.1" />
<PackageReference Include="OpenTelemetry.Exporter.Jaeger" Version="1.6.0-rc.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.9.0" />
</ItemGroup>

</Project>
32 changes: 32 additions & 0 deletions Observability.Homework.Tracing.Client/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// See https://aka.ms/new-console-template for more information

using System.Net.Http.Json;
using Observability.Homework.Models;
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var serviceName = "Observability.Homework.Tracing.Client";

using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource(serviceName)
.AddHttpClientInstrumentation()
.SetResourceBuilder(
ResourceBuilder.CreateDefault()
.AddService(serviceName: serviceName))
.AddJaegerExporter()
.Build();
Random random = new Random();
while (true)
{
Parallel.For(0, 30, _ =>
{
using var httpClient = new HttpClient();
var order = Order.Create((ProductType)random.Next(0, 3));
var response = httpClient.PostAsync("http://localhost:5216/order/", JsonContent.Create(order)).Result;
response.EnsureSuccessStatusCode();
Console.WriteLine("Response received successfully.{0}", order.Product.Type);
});

}

6 changes: 6 additions & 0 deletions Observability.Homework.sln
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Observability.Homework", "Observability.Homework\Observability.Homework.csproj", "{FA51BFEE-F62F-4D80-A43A-3C384C62D1AB}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Observability.Homework.Tracing.Client", "Observability.Homework.Tracing.Client\Observability.Homework.Tracing.Client.csproj", "{ED0F7FFB-2DD2-429F-B389-76680F8825C8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -12,5 +14,9 @@ Global
{FA51BFEE-F62F-4D80-A43A-3C384C62D1AB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FA51BFEE-F62F-4D80-A43A-3C384C62D1AB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FA51BFEE-F62F-4D80-A43A-3C384C62D1AB}.Release|Any CPU.Build.0 = Release|Any CPU
{ED0F7FFB-2DD2-429F-B389-76680F8825C8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ED0F7FFB-2DD2-429F-B389-76680F8825C8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ED0F7FFB-2DD2-429F-B389-76680F8825C8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ED0F7FFB-2DD2-429F-B389-76680F8825C8}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
41 changes: 41 additions & 0 deletions Observability.Homework/Extensions/LoggingConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System.Globalization;
using Serilog;
using Serilog.Events;
using Serilog.Formatting.Elasticsearch;

namespace Observability.Homework.Extensions;

public static class LoggingConfig
{
public static void AppLogging(this WebApplicationBuilder builder)
{
ArgumentNullException.ThrowIfNull(builder);

builder.Host.UseSerilog(
(context, configuration) =>
{
configuration
.ReadFrom.Configuration(context.Configuration);


if (builder.Environment.EnvironmentName == "Development")
configuration
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.WriteTo.Console(formatProvider: CultureInfo.DefaultThreadCurrentCulture,
outputTemplate:
"[{Level:u3} {Timestamp:HH:mm:ss} {ScopePath}] {ClientId} {Message:lj}{NewLine}{Exception}");

else
configuration
.MinimumLevel.Warning()
.WriteTo.Async(
to => to.Console(
new ExceptionAsObjectJsonFormatter(
renderMessage: true,
inlineFields: true),
standardErrorFromLevel: LogEventLevel.Warning));
}
);
}
}
8 changes: 8 additions & 0 deletions Observability.Homework/Homework.http
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
@HomeWorkToDoList_HostAddress = http://localhost:5216

POST {{HomeWorkToDoList_HostAddress}}/order/
Accept: application/json
Content-Type: application/json

{"product":{"type":0},"client":{"id":"rgerg"}}
###
19 changes: 19 additions & 0 deletions Observability.Homework/Observability.Homework.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,23 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="OpenTelemetry" Version="1.10.0-beta.1" />
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.10.0-beta.1" />
<PackageReference Include="OpenTelemetry.Exporter.Jaeger" Version="1.6.0-rc.1" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.10.0-beta.1" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus" Version="1.3.0-rc.2" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" Version="1.9.0-beta.2" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.10.0-beta.1" />
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.9.0" />
<PackageReference Include="Serilog" Version="4.1.0" />
<PackageReference Include="Serilog.Extensions.Hosting" Version="8.0.0" />
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.1-dev-10398" />
<PackageReference Include="Serilog.Formatting.Compact" Version="3.0.0" />
<PackageReference Include="Serilog.Formatting.Elasticsearch" Version="10.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="8.0.4" />
<PackageReference Include="Serilog.Sinks.Async" Version="2.1.0-dev-00096" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
</ItemGroup>

</Project>
49 changes: 43 additions & 6 deletions Observability.Homework/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,57 @@
*/

using Microsoft.AspNetCore.Mvc;
using Observability.Homework.Extensions;
using Observability.Homework.Models;
using Observability.Homework.Services;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var serviceName = "Observability.Homework";
var builder = WebApplication.CreateBuilder(args);

//builder.AppLogging();
//Trace don,t work with logging=(
builder.Logging.ClearProviders();
builder.Services
.AddOpenTelemetry()
.WithTracing(tcb =>
{
tcb
.AddSource(serviceName)
.SetResourceBuilder(
ResourceBuilder.CreateDefault()
.AddService(serviceName: serviceName))
.AddAspNetCoreInstrumentation()
.AddJaegerExporter();
})
.WithMetrics(mpb => mpb
.AddAspNetCoreInstrumentation()
//.AddRuntimeInstrumentation()
//.AddProcessInstrumentation()
.AddPrometheusExporter()
.AddMeter(PizzeriaMetricsService.MeterName)
);
builder.Services.AddSingleton(TracerProvider.Default.GetTracer(serviceName));
builder.Services.AddSingleton<IPizzaBakeryService, PizzaBakeryService>();
builder.Services.AddSingleton<PizzeriaMetricsService>();

var app = builder.Build();

app.MapPost("/order", async ([FromBody] Order order, IPizzaBakeryService pizzaBakeryService, CancellationToken cancellationToken) =>
app.MapPrometheusScrapingEndpoint();
app.MapPost("/order", async ([FromServices] Tracer tracer,PizzeriaMetricsService metric, [FromBody] Order order, IPizzaBakeryService pizzaBakeryService, CancellationToken cancellationToken) =>
{
if (order.Product.Type is ProductType.Pizza)
await pizzaBakeryService.DoPizza(order.Product, cancellationToken);

using var span = tracer.StartActiveSpan("Request DoPizza");
span.SetAttribute("userId", order.Client.Id);
span.SetAttribute("productId", order.Product.Id.ToString());
metric.ProductType(order.Product);
DateTime start = DateTime.Now;
using (app.Logger.BeginScope(new Dictionary<string, object> { { "ClientId", order.Client.Id } }))
{
app.Logger.LogInformation("request");
if (order.Product.Type is ProductType.Pizza)
await pizzaBakeryService.DoPizza(order.Product, cancellationToken);
}
metric.RecordProductCooking((DateTime.Now-start).Microseconds);
return Results.Ok(order.Product);
});

Expand Down
2 changes: 1 addition & 1 deletion Observability.Homework/Properties/launchSettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7205;http://localhost:5216",
"applicationUrl": "https://localhost:7242;http://localhost:5216",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
Expand Down
39 changes: 36 additions & 3 deletions Observability.Homework/Services/PizzaBakeryService.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using System.Collections.Concurrent;
using Observability.Homework.Exceptions;
using Observability.Homework.Models;
using OpenTelemetry.Trace;


namespace Observability.Homework.Services;

Expand All @@ -9,32 +11,48 @@ public interface IPizzaBakeryService
Task<Product> DoPizza(Product product, CancellationToken cancellationToken = default);
}

public class PizzaBakeryService : IPizzaBakeryService
public class PizzaBakeryService(Tracer tracer, ILogger<PizzaBakeryService> logger, PizzeriaMetricsService pizzeriaMetricsService) : IPizzaBakeryService
{
private readonly PizzeriaMetricsService _metrics = pizzeriaMetricsService;
private readonly Tracer _tracer = tracer;
private readonly ConcurrentDictionary<Guid, Product> _bake = new();

public async Task<Product> DoPizza(Product product, CancellationToken cancellationToken = default)
{
logger.LogInformation("DoPizza id:{productId} type:{productType}",product.Id, product.Type);
_metrics.ProductBakingCount(_bake.Count);
using var span = tracer.StartActiveSpan("DoPizza");
try
{
await MakePizza(product, cancellationToken);
await BakePizza(product, cancellationToken);
await PackPizza(product, cancellationToken);
return product;
}
catch (OperationCanceledException)
catch (OperationCanceledException ex)
{
_metrics.ProductCancel();
logger.LogError("PizzaBakeryService cancel do pizza");
span.SetStatus(Status.Error.WithDescription("PizzaBakeryService cancel do pizza"));
span.RecordException(ex);
DropPizza(product);
throw;
}
catch (BurntPizzaException)
catch (BurntPizzaException ex)
{
_metrics.ProductBurnt();
logger.LogError("PizzaBakeryService burnt pizza");
span.SetStatus(Status.Error.WithDescription("PizzaBakeryService burnt pizza"));
span.RecordException(ex);
return await DoPizza(product, cancellationToken);
}
}

private async Task<Product> BakePizza(Product product, CancellationToken cancellationToken = default)
{
using var span = tracer.StartActiveSpan("BakePizza");
logger.LogInformation("BakePizza id:{productId} type:{productType}",product.Id, product.Type);

PushToBake(product);
var bakeForSeconds = new Random().Next(3, 9);
await Task.Delay(TimeSpan.FromSeconds(bakeForSeconds), cancellationToken);
Expand All @@ -48,29 +66,44 @@ private async Task<Product> BakePizza(Product product, CancellationToken cancell

private async Task<Product> MakePizza(Product product, CancellationToken cancellationToken = default)
{
using var span = tracer.StartActiveSpan("MakePizza");
logger.LogInformation("MakePizza id:{productId} type:{productType}",product.Id, product.Type);

await Task.Delay(new Random().Next(1, 3) * 1000, cancellationToken);
return product;
}

private async Task<Product> PackPizza(Product product, CancellationToken cancellationToken = default)
{
using var span = tracer.StartActiveSpan("PackPizza");
logger.LogInformation("PackPizza id:{productId} type:{productType}",product.Id, product.Type);

await Task.Delay(new Random().Next(1, 2) * 1000, cancellationToken);
return product;
}

private void PushToBake(Product product)
{
using var span = tracer.StartActiveSpan("PushToBake");
logger.LogInformation("PushToBake id:{productId} type:{productType}",product.Id, product.Type);

_bake[product.Id] = product;
}

private Product PopFromBake(Product product)
{
using var span = tracer.StartActiveSpan("PopFromBake");
logger.LogInformation("PopFromBake id:{productId} type:{productType}",product.Id, product.Type);

_bake.Remove(product.Id, out var pizza);
return pizza!; //пусть у нас всегда есть пицца
}

private void DropPizza(Product product)
{
using var span = tracer.StartActiveSpan("DropPizza");
logger.LogInformation("DropPizza id:{productId} type:{productType}",product.Id, product.Type);

_bake.Remove(product.Id, out _);
}
}
Loading