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
{
internal const String DbPath = "./db.sqlite";
public static Dictionary<Lib.Victron.VictronVRM.Installation, InstallationDetails> InstallationsAndDetails;
private static SQLiteConnection Connection { get; } = new SQLiteConnection(DbPath);
public static TableQuery<Installation> Installations => Connection.Table<Installation>();
public static void Init()
public static async Task UpdateDetailsAndInstallations()
{
// 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>();
Observable.Interval(TimeSpan.FromMinutes(5)) //Repeat(0)
.ObserveOn(TaskPoolScheduler.Default)
.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());
while (true)
{
await UpdateInstallationsAndDetailsFromVrm(0);
}
}
[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 user = VrmAccount.Token(acc.idUser, acc.token);
var installations = user.GetInstallations().Result;
return installations.Take(30)
.Do(i=>i.Name.WriteLine())
.ToDictionary(i => i, GetInstallationDetails);
var user = VrmAccount.Token(acc!.idUser, acc.token);
var installations = await user.GetInstallations();
var returnDictionary = new Dictionary<Lib.Victron.VictronVRM.Installation, InstallationDetails>();
foreach (var installation in installations)
{
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);
IReadOnlyList<Detail> details;
await Task.Delay(1000);
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")
UpdateInstallationName(i, ip);
await UpdateInstallationName(i, ip);
return new InstallationDetails(ip,details);
}
@ -92,21 +77,50 @@ public static partial class Db
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)
{
var command = Cli.Wrap("ssh")
var oldNameInFileRequest = await Cli.Wrap("ssh")
.WithArguments($@"root@{ip}")
.AppendArgument("-o StrictHostKeyChecking=accept-new")
.AppendArgument($"echo '{installation.Name}' > /data/innovenergy/openvpn/installation-name");
Console.WriteLine(command.ToString());
var x = await command
.AppendArgument("cat /data/innovenergy/openvpn/installation-name")
.WithValidation(CommandResultValidation.None).ExecuteBufferedAsync();
if (x.ExitCode != 0)
{ Console.WriteLine(x.StandardError);
Console.WriteLine("Renaming did not work");
var oldNameInFileWithoutNewLine = oldNameInFileRequest.StandardOutput.TrimEnd();
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 void Main(String[] args)
public static async Task Main(String[] args)
{
var updateTask =Db.UpdateDetailsAndInstallations();
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
@ -24,7 +24,8 @@ public static class Program
app.UseHttpsRedirection();
app.MapControllers();
// app.MapGet("/", () => Controller.Index());
app.Run();
var webTask = app.RunAsync();
await Task.WhenAll(webTask, updateTask);
}
private static OpenApiInfo OpenApiInfo { get; } = new OpenApiInfo