From f0fadee7c21ce862395835162af7983333f64e90 Mon Sep 17 00:00:00 2001 From: James Ross Date: Sat, 20 Jan 2024 15:58:05 +0000 Subject: [PATCH] feat: Add system data collection API endpoint --- .gitignore | 1 + API/Collect.cs | 40 ++++++++++++++++++++++++++++++++++++ Program.cs | 2 ++ appsettings.Development.json | 3 ++- appsettings.json | 3 ++- 5 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 API/Collect.cs diff --git a/.gitignore b/.gitignore index 4c7473d..4abc45e 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,3 @@ /bin +/data /obj diff --git a/API/Collect.cs b/API/Collect.cs new file mode 100644 index 0000000..b64f419 --- /dev/null +++ b/API/Collect.cs @@ -0,0 +1,40 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Mvc; + +namespace Open_Rails_Telemetry.API +{ + [Route("api/[controller]")] + [ApiController] + public class Collect : ControllerBase + { + readonly IConfiguration Configuration; + readonly string DataPathCollectSystem; + + public Collect(IConfiguration configuration) + { + Configuration = configuration; + DataPathCollectSystem = Path.Combine(Configuration["DataPath"], "collect", "system"); + if (!Directory.Exists(DataPathCollectSystem)) Directory.CreateDirectory(DataPathCollectSystem); + } + + [HttpPost("System")] + [Consumes("application/json")] + public async Task PostSystem([FromBody] JsonElement data) + { + // File's name has the date for analysis, and a random key to prevent collisions + var date = DateTime.UtcNow.Date; + var randomKey = Guid.NewGuid().ToString(); + var file = new FileInfo(Path.Combine(DataPathCollectSystem, $"{date:yyyy-MM-dd}_{randomKey}.json")); + // Write the JSON into the file + await using (var stream = file.Create()) + { + await JsonSerializer.SerializeAsync(stream, data); + } + // Wipe out the file's timestamps so we cannot correlate them with e.g. access logs + file.CreationTimeUtc = date; + file.LastWriteTimeUtc = date; + file.LastAccessTimeUtc = date; + return Ok(); + } + } +} diff --git a/Program.cs b/Program.cs index bc275e4..647e622 100644 --- a/Program.cs +++ b/Program.cs @@ -1,6 +1,7 @@ var builder = WebApplication.CreateBuilder(args); // Add services to the container. +builder.Services.AddControllers(); builder.Services.AddRazorPages(); var app = builder.Build(); @@ -20,6 +21,7 @@ app.UseAuthorization(); +app.MapControllers(); app.MapRazorPages(); app.Run(); diff --git a/appsettings.Development.json b/appsettings.Development.json index 770d3e9..a960d71 100644 --- a/appsettings.Development.json +++ b/appsettings.Development.json @@ -5,5 +5,6 @@ "Default": "Information", "Microsoft.AspNetCore": "Warning" } - } + }, + "DataPath": "data" } diff --git a/appsettings.json b/appsettings.json index 10f68b8..48d4b02 100644 --- a/appsettings.json +++ b/appsettings.json @@ -5,5 +5,6 @@ "Microsoft.AspNetCore": "Warning" } }, - "AllowedHosts": "*" + "AllowedHosts": "*", + "DataPath": "/var/local/dotnet/telemetry.openrails.org" }