Salmon/Salmon.Service/Program.cs
2024-04-25 22:02:17 +02:00

124 lines
2.8 KiB
C#

using Salmon.Core;
using Salmon.Service;
using System.Diagnostics;
using System.Text.Json;
const string ENV_PERIOD = "SALMON_PERIOD";
const string ENV_URI = "SALMON_URI";
Console.WriteLine($"Salmon.Service initializing...");
int? period = null;
Uri? uri = null;
bool? monitor_hardware = null;
bool? monitor_localsoftware = null;
// 1: use environment variable
var period_env = Environment.GetEnvironmentVariable(ENV_PERIOD);
if (period_env != null)
{
if (int.TryParse(period_env, out int p))
period = p;
else
Console.WriteLine($"Cannot use env variable {ENV_PERIOD}, should be an int in milliseconds.");
}
var uri_env = Environment.GetEnvironmentVariable(ENV_URI);
if(uri_env != null)
{
if (Uri.TryCreate(uri_env, UriKind.Absolute, out var u))
uri = u;
else
Console.WriteLine($"Cannot use env variable {ENV_URI}, url is malformated.");
}
// 2: override with configuration file
string configpath = "config.json";
if (File.Exists(configpath))
{
Console.WriteLine("Found a configuration file, parsing...");
string content = File.ReadAllText(configpath);
Configuration? conf = null;
try
{
conf = JsonSerializer.Deserialize<Configuration>(content);
}
catch(Exception e)
{
Console.WriteLine($"Cannot parse config file \"{configpath}\", {e}.");
return 1;
}
if(conf == null)
{
Console.WriteLine($"Cannot parse config file \"{configpath}\".");
return 1;
}
if(conf.Url != null)
uri = conf.Url;
if(conf.Period != null)
period = conf.Period;
if(conf.MonitorHardware != null)
monitor_hardware = conf.MonitorHardware;
if(conf.MonitorLocalSoftware != null)
monitor_localsoftware = conf.MonitorLocalSoftware;
}
//todo: override with parameter
// 3 : override with argument
// 4 : override with default
period ??= 60000;
monitor_hardware ??= true;
monitor_localsoftware ??= true;
// 5 : Check if valid
if(uri == null)
{
Console.WriteLine($"Cannot start: not any URI defined.");
return 1;
}
// Initialisation
Transmitter transmitter = new();
Console.WriteLine($"Salmon.Service started at {DateTime.Now}.");
while ( true )
{
var software = Salmon.Model.Monitor.Software.FromLocal();
List<Element> tosend = new();
tosend.Add(software);
if(monitor_hardware == true)
{
var hardwares = Salmon.Model.Monitor.Hardware.FromAllHardware();
tosend.AddRange(hardwares);
}
try
{
await transmitter.SendAsync(uri, tosend);
}
catch(HttpRequestException e)
{
Console.WriteLine($"[{e.StatusCode}] Sending data failed: {e.Message}.");
}
catch(Exception e)
{
Console.WriteLine($"Sending data failed: {e}");
}
await Task.Delay(period.Value);
}