/// <inheritdoc/> public void Dispose() { if (leaderElector == null) { return; } tcs.Cancel(); leaderElector.Dispose(); leaderElector = null; GC.SuppressFinalize(this); }
/// <summary> /// Constructor. /// </summary> /// <param name="config">Specifies the elector configuration.</param> /// <param name="onStartedLeading"> /// Optionally specifies the action to be called when the instance assumes /// leadership. /// </param> /// <param name="onNewLeader"> /// Optionally specifies the action to be called when leadership changes. /// The identity of the new leader will be passed. /// </param> /// <param name="onStoppedLeading"> /// Optionally specifies the action to be called when the instance is demoted. /// </param> public LeaderElector( LeaderElectionConfig config, Action onStartedLeading = null, Action <string> onNewLeader = null, Action onStoppedLeading = null) { Covenant.Requires <ArgumentNullException>(config != null, nameof(config)); tcs = new CancellationTokenSource(); leaderElector = new StockLeaderElector( new StockLeaderElectionConfig(new StockLeaseLock(config.K8s, config.Namespace, config.LeaseName, config.Identity)) { LeaseDuration = config.LeaseDuration, RenewDeadline = config.RenewDeadline, RetryPeriod = config.RetryPeriod }); var hasCounterLabels = config.CounterLabels != null && config.CounterLabels.Length > 0; leaderElector.OnStartedLeading += () => { if (hasCounterLabels) { config.PromotionCounter?.WithLabels(config.CounterLabels).Inc(); } else { config.PromotionCounter?.Inc(); } onStartedLeading?.Invoke(); }; leaderElector.OnStoppedLeading += () => { if (hasCounterLabels) { config.NewLeaderCounter?.WithLabels(config.CounterLabels).Inc(); } else { config.NewLeaderCounter?.Inc(); } onStoppedLeading?.Invoke(); }; leaderElector.OnNewLeader += identity => { if (hasCounterLabels) { config.NewLeaderCounter?.WithLabels(config.CounterLabels).Inc(); } else { config.NewLeaderCounter?.Inc(); } onNewLeader?.Invoke(identity); }; }