Skip to content

Commit

Permalink
Use timer for cert renewal (#419)
Browse files Browse the repository at this point in the history
* Use timer for cert renewal

* Create cts once
  • Loading branch information
myagley authored Oct 12, 2018
1 parent 6d63054 commit c92aa9d
Showing 1 changed file with 13 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ namespace Microsoft.Azure.Devices.Edge.Hub.Service
public class CertificateRenewal : IDisposable
{
readonly static TimeSpan TimeBuffer = TimeSpan.FromMinutes(5);
readonly ILogger logger;
readonly Timer timer;
readonly CancellationTokenSource cts;

/// <summary>
Expand All @@ -20,20 +22,20 @@ public class CertificateRenewal : IDisposable
public CertificateRenewal(EdgeHubCertificates certificates, ILogger logger)
{
Preconditions.CheckNotNull(certificates, nameof(certificates));
Preconditions.CheckNotNull(logger, nameof(logger));
this.logger = Preconditions.CheckNotNull(logger, nameof(logger));
this.cts = new CancellationTokenSource();

TimeSpan timeToExpire = certificates.ServerCertificate.NotAfter - DateTime.UtcNow;
if (timeToExpire > TimeBuffer)
{
var renewAfter = timeToExpire - TimeBuffer;
logger.LogInformation("Scheduling server certificate renewal for {0}.", DateTime.UtcNow.Add(renewAfter).ToString("o"));
this.cts = new CancellationTokenSource(renewAfter);
this.cts.Token.Register(l => ((ILogger)l).LogInformation("Restarting process to perform server certificate renewal."), logger);
this.timer = new Timer(this.Callback, null, renewAfter, Timeout.InfiniteTimeSpan);
}
else
{
this.cts = new CancellationTokenSource();
logger.LogWarning("Server certificate is expired ({0}). Not scheduling renewal.", timeToExpire.ToString("c"));
this.timer = new Timer(this.Callback, null, Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
}

Expand All @@ -43,12 +45,19 @@ public void Dispose()
GC.SuppressFinalize(this);
}

void Callback(object _state)
{
this.logger.LogInformation("Restarting process to perform server certificate renewal.");
this.cts.Cancel();
}

protected virtual void Dispose(bool disposing)
{
if (disposing)
{
try
{
this.timer.Dispose();
this.cts.Dispose();
}
catch (OperationCanceledException)
Expand Down

0 comments on commit c92aa9d

Please sign in to comment.