mirror of
https://github.com/ckaczor/HomeMonitor.git
synced 2026-01-13 17:22:54 -05:00
Power service updates
- Upgrade to .NET 8 - Remove ApplicationInsights - Add OpenTelemetry
This commit is contained in:
@@ -1,9 +1,8 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.28705.295
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Service", "Service\Service.csproj", "{914B9DB9-3BCD-4B55-8289-2E59D6CA96BA}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Service", "Service\Service.csproj", "{914B9DB9-3BCD-4B55-8289-2E59D6CA96BA}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
|
||||
@@ -6,29 +6,21 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Controllers
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Controllers;
|
||||
|
||||
[Route("[controller]")]
|
||||
[ApiController]
|
||||
public class StatusController(Database database) : ControllerBase
|
||||
{
|
||||
[Route("[controller]")]
|
||||
[ApiController]
|
||||
public class StatusController : ControllerBase
|
||||
{
|
||||
private readonly Database _database;
|
||||
|
||||
public StatusController(Database database)
|
||||
{
|
||||
_database = database;
|
||||
}
|
||||
|
||||
[HttpGet("recent")]
|
||||
public async Task<ActionResult<PowerStatus>> GetRecent()
|
||||
{
|
||||
return await _database.GetRecentStatus();
|
||||
return await database.GetRecentStatus();
|
||||
}
|
||||
|
||||
[HttpGet("history-grouped")]
|
||||
public async Task<ActionResult<List<PowerStatusGrouped>>> GetHistoryGrouped(DateTimeOffset start, DateTimeOffset end, int bucketMinutes = 2)
|
||||
{
|
||||
return (await _database.GetStatusHistoryGrouped(start, end, bucketMinutes)).ToList();
|
||||
}
|
||||
return (await database.GetStatusHistoryGrouped(start, end, bucketMinutes)).ToList();
|
||||
}
|
||||
}
|
||||
@@ -6,25 +6,19 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Data
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Data;
|
||||
|
||||
public class Database(IConfiguration configuration)
|
||||
{
|
||||
public class Database
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
public Database(IConfiguration configuration)
|
||||
{
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public void EnsureDatabase()
|
||||
{
|
||||
var connectionStringBuilder = new SqlConnectionStringBuilder
|
||||
{
|
||||
DataSource = $"{_configuration["Power:Database:Host"]},{_configuration["Power:Database:Port"]}",
|
||||
UserID = _configuration["Power:Database:User"],
|
||||
Password = _configuration["Power:Database:Password"],
|
||||
InitialCatalog = "master"
|
||||
DataSource = $"{configuration["Power:Database:Host"]},{configuration["Power:Database:Port"]}",
|
||||
UserID = configuration["Power:Database:User"],
|
||||
Password = configuration["Power:Database:Password"],
|
||||
InitialCatalog = "master",
|
||||
TrustServerCertificate = bool.Parse(configuration["Power:Database:TrustServerCertificate"] ?? "false")
|
||||
};
|
||||
|
||||
using var connection = new SqlConnection(connectionStringBuilder.ConnectionString);
|
||||
@@ -34,22 +28,22 @@ namespace ChrisKaczor.HomeMonitor.Power.Service.Data
|
||||
connection.Open();
|
||||
|
||||
// Check to see if the database exists
|
||||
command.CommandText = $"SELECT CAST(1 as bit) from sys.databases WHERE name='{_configuration["Power:Database:Name"]}'";
|
||||
command.CommandText = $"SELECT CAST(1 as bit) from sys.databases WHERE name='{configuration["Power:Database:Name"]}'";
|
||||
var databaseExists = (bool?)command.ExecuteScalar();
|
||||
|
||||
// Create database if needed
|
||||
if (!(databaseExists ?? false))
|
||||
{
|
||||
command.CommandText = $"CREATE DATABASE {_configuration["Power:Database:Name"]}";
|
||||
command.CommandText = $"CREATE DATABASE {configuration["Power:Database:Name"]}";
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
|
||||
// Switch to the database now that we're sure it exists
|
||||
connection.ChangeDatabase(_configuration["Power:Database:Name"]);
|
||||
connection.ChangeDatabase(configuration["Power:Database:Name"]!);
|
||||
|
||||
var schema = ResourceReader.GetString("ChrisKaczor.HomeMonitor.Power.Service.Data.Resources.Schema.sql");
|
||||
|
||||
// Make sure the database is up to date
|
||||
// Make sure the database is up-to-date
|
||||
command.CommandText = schema;
|
||||
command.ExecuteNonQuery();
|
||||
}
|
||||
@@ -58,10 +52,11 @@ namespace ChrisKaczor.HomeMonitor.Power.Service.Data
|
||||
{
|
||||
var connectionStringBuilder = new SqlConnectionStringBuilder
|
||||
{
|
||||
DataSource = $"{_configuration["Power:Database:Host"]},{_configuration["Power:Database:Port"]}",
|
||||
UserID = _configuration["Power:Database:User"],
|
||||
Password = _configuration["Power:Database:Password"],
|
||||
InitialCatalog = _configuration["Power:Database:Name"]
|
||||
DataSource = $"{configuration["Power:Database:Host"]},{configuration["Power:Database:Port"]}",
|
||||
UserID = configuration["Power:Database:User"],
|
||||
Password = configuration["Power:Database:Password"],
|
||||
InitialCatalog = configuration["Power:Database:Name"],
|
||||
TrustServerCertificate = bool.Parse(configuration["Power:Database:TrustServerCertificate"] ?? "false")
|
||||
};
|
||||
|
||||
var connection = new SqlConnection(connectionStringBuilder.ConnectionString);
|
||||
@@ -96,5 +91,4 @@ namespace ChrisKaczor.HomeMonitor.Power.Service.Data
|
||||
|
||||
return await connection.QueryAsync<PowerStatusGrouped>(query, new { Start = start, End = end, BucketMinutes = bucketMinutes });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:5.0-alpine AS base
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:8.0-alpine AS base
|
||||
WORKDIR /app
|
||||
EXPOSE 80
|
||||
|
||||
FROM mcr.microsoft.com/dotnet/sdk:5.0-alpine AS build
|
||||
FROM mcr.microsoft.com/dotnet/sdk:8.0-alpine AS build
|
||||
WORKDIR /src
|
||||
COPY ["./Service.csproj", "./"]
|
||||
RUN dotnet restore "Service.csproj"
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
using JetBrains.Annotations;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Models
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Models;
|
||||
|
||||
[PublicAPI]
|
||||
public class PowerChannel
|
||||
{
|
||||
[PublicAPI]
|
||||
public class PowerChannel
|
||||
{
|
||||
[JsonPropertyName("type")]
|
||||
public string Type { get; set; }
|
||||
|
||||
@@ -26,5 +26,4 @@ namespace ChrisKaczor.HomeMonitor.Power.Service.Models
|
||||
|
||||
[JsonPropertyName("v_V")]
|
||||
public double Voltage { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,11 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Models
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Models;
|
||||
|
||||
[PublicAPI]
|
||||
public class PowerSample
|
||||
{
|
||||
[PublicAPI]
|
||||
public class PowerSample
|
||||
{
|
||||
[JsonPropertyName("sensorId")]
|
||||
public string SensorId { get; set; }
|
||||
|
||||
@@ -19,5 +19,4 @@ namespace ChrisKaczor.HomeMonitor.Power.Service.Models
|
||||
|
||||
[JsonPropertyName("cts")]
|
||||
public Dictionary<string, double>[] CurrentTransformers { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
using JetBrains.Annotations;
|
||||
using System;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Models
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Models;
|
||||
|
||||
[PublicAPI]
|
||||
public class PowerStatus
|
||||
{
|
||||
[PublicAPI]
|
||||
public class PowerStatus
|
||||
{
|
||||
public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.UtcNow;
|
||||
public long Generation { get; set; }
|
||||
public long Consumption { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
using JetBrains.Annotations;
|
||||
using System;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Models
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service.Models;
|
||||
|
||||
[PublicAPI]
|
||||
public class PowerStatusGrouped
|
||||
{
|
||||
[PublicAPI]
|
||||
public class PowerStatusGrouped
|
||||
{
|
||||
public DateTimeOffset Bucket { get; set; }
|
||||
public long AverageGeneration { get; set; }
|
||||
public long AverageConsumption { get; set; }
|
||||
}
|
||||
}
|
||||
@@ -1,59 +1,57 @@
|
||||
using ChrisKaczor.HomeMonitor.Power.Service.Data;
|
||||
using ChrisKaczor.HomeMonitor.Power.Service.Models;
|
||||
using JetBrains.Annotations;
|
||||
using Microsoft.ApplicationInsights;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using RestSharp;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service;
|
||||
|
||||
[UsedImplicitly]
|
||||
public class PowerReader(IConfiguration configuration, Database database, ILogger<PowerReader> logger) : IHostedService
|
||||
{
|
||||
[UsedImplicitly]
|
||||
public class PowerReader : IHostedService
|
||||
{
|
||||
private readonly IConfiguration _configuration;
|
||||
private readonly Database _database;
|
||||
private readonly TelemetryClient _telemetryClient;
|
||||
private readonly ActivitySource _activitySource = new(nameof(PowerReader));
|
||||
|
||||
private HubConnection _hubConnection;
|
||||
private Timer _readTimer;
|
||||
|
||||
public PowerReader(IConfiguration configuration, Database database, TelemetryClient telemetryClient)
|
||||
{
|
||||
_configuration = configuration;
|
||||
_database = database;
|
||||
_telemetryClient = telemetryClient;
|
||||
}
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_telemetryClient.TrackTrace($"{nameof(PowerReader)} - Start");
|
||||
logger.LogInformation($"{nameof(PowerReader)} - Start");
|
||||
|
||||
_readTimer = new Timer(OnTimer, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
|
||||
_readTimer = new Timer(GetCurrentSample, null, TimeSpan.Zero, TimeSpan.FromSeconds(1));
|
||||
|
||||
if (!string.IsNullOrEmpty(_configuration["Hub:Power"]))
|
||||
_hubConnection = new HubConnectionBuilder().WithUrl(_configuration["Hub:Power"]).Build();
|
||||
if (!string.IsNullOrEmpty(configuration["Hub:Power"]))
|
||||
_hubConnection = new HubConnectionBuilder().WithUrl(configuration["Hub:Power"]).Build();
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void OnTimer(object state)
|
||||
private void GetCurrentSample(object state)
|
||||
{
|
||||
using var activity = _activitySource.StartActivity();
|
||||
|
||||
try
|
||||
{
|
||||
var client = new RestClient(_configuration["Power:Host"]);
|
||||
var client = new RestClient(configuration["Power:Host"]!);
|
||||
|
||||
var request = new RestRequest("current-sample", Method.GET);
|
||||
request.AddHeader("Authorization", _configuration["Power:AuthorizationHeader"]);
|
||||
var request = new RestRequest("current-sample");
|
||||
request.AddHeader("Authorization", configuration["Power:AuthorizationHeader"]!);
|
||||
|
||||
var response = client.Execute(request);
|
||||
|
||||
var sample = JsonSerializer.Deserialize<PowerSample>(response.Content);
|
||||
var content = response.Content!;
|
||||
|
||||
logger.LogInformation("API response: {content}", content);
|
||||
|
||||
var sample = JsonSerializer.Deserialize<PowerSample>(content);
|
||||
|
||||
var generation = Array.Find(sample.Channels, c => c.Type == "GENERATION");
|
||||
var consumption = Array.Find(sample.Channels, c => c.Type == "CONSUMPTION");
|
||||
@@ -63,11 +61,11 @@ namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
|
||||
var status = new PowerStatus { Generation = generation.RealPower, Consumption = consumption.RealPower };
|
||||
|
||||
_database.StorePowerData(status);
|
||||
database.StorePowerData(status);
|
||||
|
||||
var json = JsonSerializer.Serialize(status);
|
||||
|
||||
Console.WriteLine(json);
|
||||
logger.LogInformation("Output message: {json}", json);
|
||||
|
||||
if (_hubConnection == null)
|
||||
return;
|
||||
@@ -79,13 +77,13 @@ namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
WriteLog($"Exception: {exception}");
|
||||
logger.LogError(exception, "Exception");
|
||||
}
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_telemetryClient.TrackTrace($"{nameof(PowerReader)} - Stop");
|
||||
logger.LogInformation($"{nameof(PowerReader)} - Stop");
|
||||
|
||||
_readTimer.Dispose();
|
||||
|
||||
@@ -93,10 +91,4 @@ namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private static void WriteLog(string message)
|
||||
{
|
||||
Console.WriteLine(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,19 +1,127 @@
|
||||
using Microsoft.AspNetCore;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using ChrisKaczor.HomeMonitor.Power.Service.Data;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.ResponseCompression;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenTelemetry.Exporter;
|
||||
using OpenTelemetry.Logs;
|
||||
using OpenTelemetry.Metrics;
|
||||
using OpenTelemetry.Resources;
|
||||
using OpenTelemetry.Trace;
|
||||
using System;
|
||||
using System.IO.Compression;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
public static class Program
|
||||
{
|
||||
public static void Main(string[] args)
|
||||
{
|
||||
CreateWebHostBuilder(args).Build().Run();
|
||||
}
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
private static IWebHostBuilder CreateWebHostBuilder(string[] args)
|
||||
builder.Configuration.AddEnvironmentVariables();
|
||||
|
||||
builder.Services.AddControllers();
|
||||
|
||||
// ---
|
||||
|
||||
var openTelemetry = builder.Services.AddOpenTelemetry();
|
||||
|
||||
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
|
||||
|
||||
var name = Assembly.GetExecutingAssembly().GetName().Name;
|
||||
|
||||
openTelemetry.ConfigureResource(resource => resource.AddService(name!));
|
||||
|
||||
openTelemetry.WithMetrics(meterProviderBuilder => meterProviderBuilder
|
||||
.AddAspNetCoreInstrumentation()
|
||||
.AddHttpClientInstrumentation()
|
||||
.AddProcessInstrumentation()
|
||||
.AddMeter("Microsoft.AspNetCore.Hosting")
|
||||
.AddMeter("Microsoft.AspNetCore.Server.Kestrel"));
|
||||
|
||||
openTelemetry.WithTracing(tracerProviderBuilder =>
|
||||
{
|
||||
return WebHost.CreateDefaultBuilder(args).ConfigureAppConfiguration((_, config) => config.AddEnvironmentVariables()).UseStartup<Startup>();
|
||||
tracerProviderBuilder.AddAspNetCoreInstrumentation(instrumentationOptions => instrumentationOptions.RecordException = true);
|
||||
|
||||
tracerProviderBuilder.AddHttpClientInstrumentation(instrumentationOptions => instrumentationOptions.RecordException = true);
|
||||
|
||||
tracerProviderBuilder.AddSqlClientInstrumentation(o =>
|
||||
{
|
||||
o.RecordException = true;
|
||||
o.SetDbStatementForText = true;
|
||||
});
|
||||
|
||||
tracerProviderBuilder.AddSource(nameof(PowerReader));
|
||||
|
||||
if (builder.Environment.IsDevelopment())
|
||||
tracerProviderBuilder.AddConsoleExporter();
|
||||
|
||||
tracerProviderBuilder.SetErrorStatusOnException();
|
||||
|
||||
tracerProviderBuilder.AddOtlpExporter(exporterOptions =>
|
||||
{
|
||||
exporterOptions.Endpoint = new Uri(builder.Configuration["Telemetry:Endpoint"]!);
|
||||
exporterOptions.Protocol = OtlpExportProtocol.Grpc;
|
||||
});
|
||||
});
|
||||
|
||||
builder.Services.AddLogging((loggingBuilder) =>
|
||||
{
|
||||
loggingBuilder.SetMinimumLevel(LogLevel.Information);
|
||||
loggingBuilder.AddOpenTelemetry(options =>
|
||||
{
|
||||
if (builder.Environment.IsDevelopment())
|
||||
options.AddConsoleExporter();
|
||||
|
||||
options.AddOtlpExporter(exporterOptions =>
|
||||
{
|
||||
exporterOptions.Endpoint = new Uri(builder.Configuration["Telemetry:Endpoint"]!);
|
||||
exporterOptions.Protocol = OtlpExportProtocol.Grpc;
|
||||
});
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
builder.Services.AddTransient<Database>();
|
||||
|
||||
builder.Services.AddHostedService<PowerReader>();
|
||||
|
||||
builder.Services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal);
|
||||
|
||||
builder.Services.AddResponseCompression(options =>
|
||||
{
|
||||
options.Providers.Add<GzipCompressionProvider>();
|
||||
options.EnableForHttps = true;
|
||||
});
|
||||
|
||||
builder.Services.AddCors(o => o.AddPolicy("CorsPolicy", corsPolicyBuilder => corsPolicyBuilder.AllowAnyMethod().AllowAnyHeader().AllowCredentials().WithOrigins("http://localhost:4200")));
|
||||
|
||||
builder.Services.AddMvc();
|
||||
|
||||
// ---
|
||||
|
||||
var app = builder.Build();
|
||||
|
||||
if (builder.Environment.IsDevelopment())
|
||||
app.UseDeveloperExceptionPage();
|
||||
|
||||
var database = app.Services.GetRequiredService<Database>();
|
||||
database.EnsureDatabase();
|
||||
|
||||
app.UseCors("CorsPolicy");
|
||||
|
||||
app.UseResponseCompression();
|
||||
|
||||
app.UseRouting();
|
||||
|
||||
app.UseAuthorization();
|
||||
|
||||
app.MapControllers();
|
||||
|
||||
app.Run();
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,10 @@
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service;
|
||||
|
||||
public static class ResourceReader
|
||||
{
|
||||
public static class ResourceReader
|
||||
{
|
||||
public static string GetString(string resourceName)
|
||||
{
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
@@ -18,5 +18,4 @@ namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
|
||||
return reader.ReadToEnd();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,36 +1,35 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net5.0</TargetFramework>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
|
||||
<AssemblyName>ChrisKaczor.HomeMonitor.Power.Service</AssemblyName>
|
||||
<RootNamespace>ChrisKaczor.HomeMonitor.Power.Service</RootNamespace>
|
||||
<CodeAnalysisRuleSet>../../ChrisKaczor.ruleset</CodeAnalysisRuleSet>
|
||||
<GenerateTargetFrameworkAttribute>false</GenerateTargetFrameworkAttribute>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Remove="C:\Users\chris\.nuget\packages\opentelemetry.autoinstrumentation\1.3.0\contentFiles\any\any\instrument.cmd" />
|
||||
<None Remove="C:\Users\chris\.nuget\packages\opentelemetry.autoinstrumentation\1.3.0\contentFiles\any\any\instrument.sh" />
|
||||
<None Remove="Data\Resources\CreateStatus.sql" />
|
||||
<None Remove="Data\Resources\GetStatusHistoryGrouped.sql" />
|
||||
<None Remove="Data\Resources\Schema.sql" />
|
||||
<None Remove="Data\Resources\GetRecentStatus.sql" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Include="Data\Resources\CreateStatus.sql" />
|
||||
<EmbeddedResource Include="Data\Resources\GetStatusHistoryGrouped.sql" />
|
||||
<EmbeddedResource Include="Data\Resources\Schema.sql" />
|
||||
<EmbeddedResource Include="Data\Resources\GetRecentStatus.sql" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Dapper" Version="2.0.90" />
|
||||
<PackageReference Include="JetBrains.Annotations" Version="2021.1.0" />
|
||||
<PackageReference Include="Microsoft.ApplicationInsights" Version="2.17.0" />
|
||||
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.17.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="5.0.6" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="2.1.3" />
|
||||
<PackageReference Include="RestSharp" Version="106.11.7" />
|
||||
<PackageReference Include="Dapper" Version="2.1.28" />
|
||||
<PackageReference Include="JetBrains.Annotations" Version="2023.3.0" />
|
||||
<PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.4" />
|
||||
<PackageReference Include="OpenTelemetry.AutoInstrumentation" Version="1.3.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.Console" Version="1.7.0" />
|
||||
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.7.0" />
|
||||
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.7.0" />
|
||||
<PackageReference Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.7.0" />
|
||||
<PackageReference Include="RestSharp" Version="110.2.0" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -1,69 +0,0 @@
|
||||
using ChrisKaczor.HomeMonitor.Power.Service.Data;
|
||||
using Microsoft.ApplicationInsights;
|
||||
using Microsoft.ApplicationInsights.Extensibility;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.ResponseCompression;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using System.IO.Compression;
|
||||
using System.Threading;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
{
|
||||
public class Startup
|
||||
{
|
||||
public void ConfigureServices(IServiceCollection services)
|
||||
{
|
||||
services.AddSingleton<ITelemetryInitializer, TelemetryInitializer>();
|
||||
|
||||
services.AddApplicationInsightsTelemetry(options =>
|
||||
{
|
||||
options.EnableDependencyTrackingTelemetryModule = false;
|
||||
});
|
||||
|
||||
services.AddTransient<Database>();
|
||||
|
||||
services.AddHostedService<PowerReader>();
|
||||
|
||||
services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Optimal);
|
||||
|
||||
services.AddResponseCompression(options =>
|
||||
{
|
||||
options.Providers.Add<GzipCompressionProvider>();
|
||||
options.EnableForHttps = true;
|
||||
});
|
||||
|
||||
services.AddCors(o => o.AddPolicy("CorsPolicy", builder => builder.AllowAnyMethod().AllowAnyHeader().AllowCredentials().WithOrigins("http://localhost:4200")));
|
||||
|
||||
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
|
||||
}
|
||||
|
||||
public void Configure(IApplicationBuilder applicationBuilder, IWebHostEnvironment environment, IHostApplicationLifetime hostApplicationLifetime)
|
||||
{
|
||||
if (environment.IsDevelopment())
|
||||
applicationBuilder.UseDeveloperExceptionPage();
|
||||
|
||||
hostApplicationLifetime.ApplicationStopping.Register(() =>
|
||||
{
|
||||
var telemetryClient = applicationBuilder.ApplicationServices.GetRequiredService<TelemetryClient>();
|
||||
|
||||
telemetryClient.Flush();
|
||||
|
||||
Thread.Sleep(5000);
|
||||
});
|
||||
|
||||
var database = applicationBuilder.ApplicationServices.GetRequiredService<Database>();
|
||||
database.EnsureDatabase();
|
||||
|
||||
applicationBuilder.UseCors("CorsPolicy");
|
||||
|
||||
applicationBuilder.UseResponseCompression();
|
||||
|
||||
applicationBuilder.UseRouting();
|
||||
|
||||
applicationBuilder.UseEndpoints(endpoints => endpoints.MapDefaultControllerRoute());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
using Microsoft.ApplicationInsights.Channel;
|
||||
using Microsoft.ApplicationInsights.Extensibility;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ChrisKaczor.HomeMonitor.Power.Service
|
||||
{
|
||||
public class TelemetryInitializer : ITelemetryInitializer
|
||||
{
|
||||
public void Initialize(ITelemetry telemetry)
|
||||
{
|
||||
telemetry.Context.Cloud.RoleName = Assembly.GetEntryAssembly()?.GetName().Name;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +1,20 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Warning"
|
||||
"Default": "Information"
|
||||
}
|
||||
},
|
||||
"Power": {
|
||||
"Database": {
|
||||
"Name": "Power",
|
||||
"Port": 1434
|
||||
"Port": 1434,
|
||||
"TrustServerCertificate": true
|
||||
}
|
||||
},
|
||||
"Hub": {
|
||||
"Power": "http://hub-server/power"
|
||||
"Power": ""
|
||||
},
|
||||
"Telemetry": {
|
||||
"Endpoint": "http://signoz-otel-collector.platform:4317/"
|
||||
}
|
||||
}
|
||||
@@ -94,11 +94,6 @@ spec:
|
||||
securityContext:
|
||||
privileged: true
|
||||
env:
|
||||
- name: ApplicationInsights__ConnectionString
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: telemetry
|
||||
key: key
|
||||
- name: Power__Database__Host
|
||||
value: power-database
|
||||
- name: Power__Database__User
|
||||
|
||||
Reference in New Issue
Block a user