Skip to content

Commit

Permalink
Start implementing update for docker distribution.
Browse files Browse the repository at this point in the history
  • Loading branch information
Bounz committed Oct 27, 2018
1 parent 0f4fb22 commit 613d857
Show file tree
Hide file tree
Showing 7 changed files with 72 additions and 154 deletions.
6 changes: 6 additions & 0 deletions HomeGenie/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,12 @@ internal static void Quit(bool restartService, bool saveData = true)
IsRunning = false;
}

internal static void QuitAndUpdateDockerImage()
{
Log.Info("...RESTARTING WITH DOCKER IMAGE UPDATE!");
Environment.Exit(5);
}

private static void ShutDown(bool restart, bool saveData = true)
{
Log.Info("HomeGenie is now exiting...");
Expand Down
40 changes: 25 additions & 15 deletions HomeGenie/Service/Handlers/Config.cs
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,9 @@ private void HandleSystemConfigure(MigInterfaceCommand migCommand, MigClientRequ
var installPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "_update", "files");
Utility.FolderCleanUp(installPath);
Directory.Move(Path.Combine(_tempFolderPath, "homegenie"), Path.Combine(installPath, "HomeGenie"));
var installStatus = _homegenie.UpdateInstaller.InstallFiles();

// TODO: this will not work for docker distribution
var installStatus = _homegenie.UpdateInstaller.InstallUpdate();
if (installStatus != InstallStatus.Error)
{
success = true;
Expand Down Expand Up @@ -241,27 +243,35 @@ private void HandleSystemConfigure(MigInterfaceCommand migCommand, MigClientRequ
{
var resultMessage = "OK";
_homegenie.SaveData();
var installStatus = _homegenie.UpdateInstaller.InstallFiles();
if (installStatus == InstallStatus.Error)
{
resultMessage = "ERROR";
}
else
var installStatus = _homegenie.UpdateInstaller.InstallUpdate();

switch (installStatus)
{
if (installStatus == InstallStatus.RestartRequired)
{
case InstallStatus.Success:
_homegenie.LoadConfiguration();
_homegenie.UpdateChecker.Check();
break;
case InstallStatus.RestartRequired:
resultMessage = "RESTART";
Utility.RunAsyncTask(() =>
{
Thread.Sleep(2000);
Program.Quit(true);
});
}
else
{
_homegenie.LoadConfiguration();
_homegenie.UpdateChecker.Check();
}
break;
case InstallStatus.Error:
resultMessage = "ERROR";
break;
case InstallStatus.DockerUpdateRequired:
resultMessage = "RESTART";
Utility.RunAsyncTask(() =>
{
Thread.Sleep(2000);
Program.QuitAndUpdateDockerImage();
});
break;
default:
throw new ArgumentOutOfRangeException();
}
request.ResponseData = new ResponseText(resultMessage);
break;
Expand Down
9 changes: 0 additions & 9 deletions HomeGenie/Service/HomeGenieService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -199,15 +199,6 @@ private void ConfigureUpdater()
);
};

// TODO remove as the lagacy code
// this is a fix for upgrading from r522 to any new release as the SchedulerItem object has changed in r523
// de-serializing new object will only work after HomeGenie.exe update and restart
if (File.Exists("scheduler_update.xml"))
{
updateInstaller.UpdateScheduler("scheduler_update.xml");
File.Delete("scheduler_update.xml");
}

_updateManager.Start();
}

Expand Down
3 changes: 2 additions & 1 deletion HomeGenie/Service/Updates/InstallStatus.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ public enum InstallStatus
{
Success,
RestartRequired,
Error
Error,
DockerUpdateRequired
}
}
3 changes: 0 additions & 3 deletions HomeGenie/Service/Updates/ReleaseInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,10 @@ namespace HomeGenie.Service.Updates
[Serializable]
public class ReleaseInfo
{
//public string Name { get; set; }
public string Version { get; set; }
public string Description { get; set; }
public string ReleaseNote { get; set; }
public DateTime ReleaseDate { get; set; }
public string DownloadUrl;
public bool RequireRestart;
public bool UpdateBreak;
}
}
113 changes: 9 additions & 104 deletions HomeGenie/Service/Updates/UpdateChecker.cs
Original file line number Diff line number Diff line change
@@ -1,16 +1,11 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Security;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using System.Timers;
using System.Xml.Serialization;
using HomeGenie.Service.Updates.GitHub;
using Newtonsoft.Json;

Expand All @@ -22,70 +17,23 @@ public class UpdateChecker
public UpdateProgressEvent UpdateProgress;

private readonly string _githubReleases = "https://api.github.com/repos/Bounz/HomeGenie-BE/releases";
private readonly string _dockerHubReleases = "https://registry.hub.docker.com/v2/repositories/bounz/homegenie/tags";

private ReleaseInfo _currentRelease;
private List<ReleaseInfo> _newReleases;
private readonly Timer _checkForUpdatesTimer;

private static readonly HttpClient HttpClient = new HttpClient();

public List<ReleaseInfo> NewReleases => _newReleases;
public ReleaseInfo NewestRelease => _newReleases?.FirstOrDefault();
public static Version CurrentVersion => Assembly.GetExecutingAssembly().GetName().Version;

static UpdateChecker()
{
HttpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("HomeGenieUpdater", "1.1"));
}

// TODO: this is just a temporary hack not meant to be used in production enviroment
private static bool Validator(
object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors
)
{
if (sslPolicyErrors == SslPolicyErrors.None)
{
return true;
}
// Work-around missing certificates
var remoteCertificateHash = certificate.GetCertHashString();
var acceptedCertificates = new List<string>
{
// Amazon AWS github files hosting
"89E471D8A4977D0D9C6E67E557BF36A74A5A01DB",
// github.com
"D79F076110B39293E349AC89845B0380C19E2F8B",
// api.github.com
"CF059889CAFF8ED85E5CE0C2E4F7E6C3C750DD5C",
"358574EF6735A7CE406950F3C0F680CF803B2E19"
};
// try to load acceptedCertificates from file "certaccept.xml"
try
{
var xmlSerializer = new XmlSerializer(typeof(List<string>));
using (var stringReader = new StringReader(File.ReadAllText("certaccept.xml")))
{
var cert = (List<string>)xmlSerializer.Deserialize(stringReader);
acceptedCertificates.Clear();
acceptedCertificates.AddRange(cert);
}
} catch { }

// verify against accepted certificate hash strings
if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateChainErrors
&& acceptedCertificates.Contains(remoteCertificateHash))
{
Console.WriteLine("Applied 'SSL certificates issue' work-around.");
return true;
}
else
{
Console.WriteLine("SSL validation error! Remote hash is: {0}", remoteCertificateHash);
return false;
}
}


// TODO: add automatic interval check and "UpdateAvailable", "UpdateChecking" events

public UpdateChecker()
Expand All @@ -94,15 +42,11 @@ public UpdateChecker()
_checkForUpdatesTimer.Elapsed += CheckForUpdates_Elapsed;

_newReleases = new List<ReleaseInfo>();
}

// TODO: SSL connection certificate validation:
// TODO: this is just an hack to fix certificate issues happening sometimes on api.github.com site,
// TODO: not meant to be used in production enviroment
if (Environment.OSVersion.Platform == PlatformID.Unix)
{
// TODO: this is just an hack to fix certificate issues on mono < 4.0,
ServicePointManager.ServerCertificateValidationCallback = Validator;
}
private void CheckForUpdates_Elapsed(object sender, ElapsedEventArgs e)
{
Check();
}

public bool Check()
Expand Down Expand Up @@ -139,10 +83,6 @@ public ReleaseInfo GetCurrentRelease()
return _currentRelease = UpdatesHelper.GetReleaseInfoFromFile(UpdatesHelper.ReleaseFile);
}

public List<ReleaseInfo> NewReleases => _newReleases;

public ReleaseInfo NewestRelease => _newReleases?.FirstOrDefault();

private async Task<List<ReleaseInfo>> GetNewReleasesAsync()
{
var releases = new List<ReleaseInfo>();
Expand All @@ -159,8 +99,6 @@ private async Task<List<ReleaseInfo>> GetNewReleasesAsync()
Version = gitHubRelease.TagName,
Description = gitHubRelease.Name,
ReleaseNote = gitHubRelease.Description,
RequireRestart = false,
UpdateBreak = true,
DownloadUrl = relFile.BrowserDownloadUrl,
ReleaseDate = gitHubRelease.CreatedAt
};
Expand All @@ -170,32 +108,6 @@ private async Task<List<ReleaseInfo>> GetNewReleasesAsync()
return releases;
}

private async Task<List<GitHubRelease>> GetLatestGitHubReleaseAsync(DateTime filterDate, bool checkForPrereleases = false)
{
#if DEBUG
checkForPrereleases = true;
#endif
var releasesString = await HttpClient.GetStringAsync(_githubReleases);
try
{
var gitHubReleases = JsonConvert.DeserializeObject<List<GitHubRelease>>(releasesString);
var orderedReleases = gitHubReleases
.OrderByDescending(x => x.CreatedAt)
.Where(x => x.CreatedAt >= filterDate);
var latestReleases = checkForPrereleases
? orderedReleases
: orderedReleases.Where(x => x.Prerelease = false);

return latestReleases.ToList();
}
catch (Exception e)
{
// TODO: write log
Console.WriteLine(e.Message);
return new List<GitHubRelease>();
}
}

private async Task<List<GitHubRelease>> GetLatestGitHubReleaseAsync(Version currentVersion, bool checkForPrereleases = false)
{
#if DEBUG
Expand Down Expand Up @@ -242,13 +154,6 @@ public bool IsUpdateAvailable
}
}

private void CheckForUpdates_Elapsed(object sender, ElapsedEventArgs e)
{
Check();
if (IsUpdateAvailable)
{
// TODO: ...
}
}

}
}
Loading

0 comments on commit 613d857

Please sign in to comment.