Renaming only when necessary and rebooting after renaming

This commit is contained in:
Kim 2023-05-11 17:02:13 +02:00
parent be099118c1
commit 3453b05a94
2 changed files with 64 additions and 49 deletions

View File

@ -28,62 +28,47 @@ public class InstallationDetails
public static partial class Db public static partial class Db
{ {
internal const String DbPath = "./db.sqlite";
public static Dictionary<Lib.Victron.VictronVRM.Installation, InstallationDetails> InstallationsAndDetails; public static Dictionary<Lib.Victron.VictronVRM.Installation, InstallationDetails> InstallationsAndDetails;
private static SQLiteConnection Connection { get; } = new SQLiteConnection(DbPath); public static async Task UpdateDetailsAndInstallations()
public static TableQuery<Installation> Installations => Connection.Table<Installation>();
public static void Init()
{ {
// used to force static constructor
}
static Db()
{
// on startup create/migrate tables
Connection.RunInTransaction(() =>
{
// Connection.CreateTable<Installation>();
});// on startup create/migrate tables
InstallationsAndDetails = new Dictionary<Lib.Victron.VictronVRM.Installation, InstallationDetails>(); InstallationsAndDetails = new Dictionary<Lib.Victron.VictronVRM.Installation, InstallationDetails>();
while (true)
Observable.Interval(TimeSpan.FromMinutes(5)) //Repeat(0) {
.ObserveOn(TaskPoolScheduler.Default) await UpdateInstallationsAndDetailsFromVrm(0);
.SubscribeOn(TaskPoolScheduler.Default) }
.StartWith(0) // Do it right away (on startup)
.Select(UpdateInstallationsAndDetailsFromVrm)
// .Select(t => t.ToObservable())
// .Concat()
.Subscribe(d => InstallationsAndDetails = d, exception => exception.WriteLine());
} }
[UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "<Pending>")] [UnconditionalSuppressMessage("Trimming", "IL2026:Members annotated with 'RequiresUnreferencedCodeAttribute' require dynamic access otherwise can break functionality when trimming application code", Justification = "<Pending>")]
private static Dictionary<Lib.Victron.VictronVRM.Installation, InstallationDetails> UpdateInstallationsAndDetailsFromVrm(Int64 _) private static async Task<Dictionary<Lib.Victron.VictronVRM.Installation, InstallationDetails>> UpdateInstallationsAndDetailsFromVrm(Int32 _)
{ {
var fileContent = File.ReadAllTextAsync("./token.json").Result; var fileContent = await File.ReadAllTextAsync("./token.json");
var acc = Deserialize<AccToken>(fileContent); var acc = Deserialize<AccToken>(fileContent);
var user = VrmAccount.Token(acc.idUser, acc.token); var user = VrmAccount.Token(acc!.idUser, acc.token);
var installations = user.GetInstallations().Result; var installations = await user.GetInstallations();
return installations.Take(30) var returnDictionary = new Dictionary<Lib.Victron.VictronVRM.Installation, InstallationDetails>();
.Do(i=>i.Name.WriteLine()) foreach (var installation in installations)
.ToDictionary(i => i, GetInstallationDetails); {
Console.WriteLine(installation.Name);
var details = await GetInstallationDetails(installation);
returnDictionary.Add(installation, details);
}
return returnDictionary;
} }
private static InstallationDetails GetInstallationDetails(Lib.Victron.VictronVRM.Installation i) private static async Task<InstallationDetails> GetInstallationDetails(Lib.Victron.VictronVRM.Installation i)
{ {
// Thread.Sleep(3000); await Task.Delay(1000);
IReadOnlyList<Detail> details;
try try
{ {
details = i.GetDetails().Result; var details = await i.GetDetails();
var ip = VpnInfo.LookUpIp(i.Identifier, details.MachineSerial()).Result ?? "Unknown"; var ip = await VpnInfo.LookUpIp(i.Identifier, details.MachineSerial()) ?? "Unknown";
if(ip != "Unknown") if(ip != "Unknown")
UpdateInstallationName(i, ip); await UpdateInstallationName(i, ip);
return new InstallationDetails(ip,details); return new InstallationDetails(ip,details);
} }
@ -92,21 +77,50 @@ public static partial class Db
Console.WriteLine(e); Console.WriteLine(e);
} }
return new InstallationDetails("Unkown", Array.Empty<Detail>()); return new InstallationDetails("Unknown", Array.Empty<Detail>());
} }
private static async Task UpdateInstallationName(Lib.Victron.VictronVRM.Installation installation, String ip) private static async Task UpdateInstallationName(Lib.Victron.VictronVRM.Installation installation, String ip)
{ {
var command = Cli.Wrap("ssh") var oldNameInFileRequest = await Cli.Wrap("ssh")
.WithArguments($@"root@{ip}") .WithArguments($@"root@{ip}")
.AppendArgument("-o StrictHostKeyChecking=accept-new") .AppendArgument("-o StrictHostKeyChecking=accept-new")
.AppendArgument($"echo '{installation.Name}' > /data/innovenergy/openvpn/installation-name"); .AppendArgument("cat /data/innovenergy/openvpn/installation-name")
Console.WriteLine(command.ToString());
var x = await command
.WithValidation(CommandResultValidation.None).ExecuteBufferedAsync(); .WithValidation(CommandResultValidation.None).ExecuteBufferedAsync();
if (x.ExitCode != 0)
{ Console.WriteLine(x.StandardError); var oldNameInFileWithoutNewLine = oldNameInFileRequest.StandardOutput.TrimEnd();
Console.WriteLine("Renaming did not work");
if (oldNameInFileRequest.ExitCode == 0 && oldNameInFileWithoutNewLine != installation.Name)
{
var overwriteNameCommand = Cli.Wrap("ssh")
.WithArguments($@"root@{ip}")
.AppendArgument($"echo '{installation.Name}' > /data/innovenergy/openvpn/installation-name");
var overwriteNameResponse = await overwriteNameCommand
.WithValidation(CommandResultValidation.None).ExecuteBufferedAsync();
if (overwriteNameResponse.ExitCode != 0)
{
Console.WriteLine(overwriteNameResponse.StandardError);
Console.WriteLine("Renaming did not work");
}
else
{
var rebootAfterRename = await Cli.Wrap("ssh")
.WithArguments($@"root@{ip}")
.AppendArgument("reboot")
.WithValidation(CommandResultValidation.None).ExecuteBufferedAsync();
if (rebootAfterRename.ExitCode != 0)
{
Console.WriteLine(overwriteNameResponse.StandardError);
Console.WriteLine("Rebooting did not work");
}
else
{
Console.WriteLine($"Renamed and rebooted {installation.Name}");
}
}
} }
} }
} }

View File

@ -5,9 +5,9 @@ namespace InnovEnergy.App.VrmGrabber;
public static class Program public static class Program
{ {
public static void Main(String[] args) public static async Task Main(String[] args)
{ {
var updateTask =Db.UpdateDetailsAndInstallations();
var builder = WebApplication.CreateBuilder(args); var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(); builder.Services.AddControllers();
@ -24,7 +24,8 @@ public static class Program
app.UseHttpsRedirection(); app.UseHttpsRedirection();
app.MapControllers(); app.MapControllers();
// app.MapGet("/", () => Controller.Index()); // app.MapGet("/", () => Controller.Index());
app.Run(); var webTask = app.RunAsync();
await Task.WhenAll(webTask, updateTask);
} }
private static OpenApiInfo OpenApiInfo { get; } = new OpenApiInfo private static OpenApiInfo OpenApiInfo { get; } = new OpenApiInfo