Example #1
0
        public async Task ExecuteInSemaphore(SemaphoreOptions opts, Action a, CancellationToken ct = default(CancellationToken))
        {
            if (opts == null)
            {
                throw new ArgumentNullException(nameof(opts));
            }
            if (a == null)
            {
                throw new ArgumentNullException(nameof(a));
            }

            var semaphore = await AcquireSemaphore(opts, ct).ConfigureAwait(false);

            try
            {
                if (!semaphore.IsHeld)
                {
                    throw new LockNotHeldException("Could not obtain the lock");
                }
                a();
            }
            finally
            {
                await semaphore.Release(ct).ConfigureAwait(false);
            }
        }
Example #2
0
 public IDisposableSemaphore AcquireSemaphore(SemaphoreOptions opts)
 {
     if (opts == null)
     {
         throw new ArgumentNullException("opts");
     }
     return(new AutoSemaphore(this, opts));
 }
Example #3
0
 public AutoSemaphore AcquireSemaphore(SemaphoreOptions opts)
 {
     if (opts == null)
     {
         throw new ArgumentNullException("opts");
     }
     return new AutoSemaphore(this, opts);
 }
Example #4
0
 /// <summary>
 /// SemaphoreOpts is used to create a Semaphore with the given options.
 /// The prefix must have write privileges, and the limit must be agreed upon by all contenders.
 /// If a Session is not provided, one will be created.
 /// </summary>
 /// <param name="opts">The semaphore options</param>
 /// <returns>An unlocked semaphore</returns>
 public IDistributedSemaphore Semaphore(SemaphoreOptions opts)
 {
     if (opts == null)
     {
         throw new ArgumentNullException(nameof(opts));
     }
     return(new Semaphore(this)
     {
         Opts = opts
     });
 }
Example #5
0
        public async Task <IDistributedSemaphore> AcquireSemaphore(SemaphoreOptions opts, CancellationToken ct = default(CancellationToken))
        {
            if (opts == null)
            {
                throw new ArgumentNullException(nameof(opts));
            }

            var semaphore = Semaphore(opts);
            await semaphore.Acquire(ct).ConfigureAwait(false);

            return(semaphore);
        }
Example #6
0
 public void ExecuteInSemaphore(SemaphoreOptions opts, Action a)
 {
     if (opts == null)
     {
         throw new ArgumentNullException("opts");
     }
     if (a == null)
     {
         throw new ArgumentNullException("a");
     }
     using (var l = new AutoSemaphore(this, opts))
     {
         if (l.IsHeld)
         {
             a();
         }
     }
 }
Example #7
0
 internal AutoSemaphore(Client c, SemaphoreOptions opts)
     : base(c)
 {
     Opts = opts;
     CancellationToken = Acquire();
 }
Example #8
0
 /// <summary>
 /// SemaphoreOpts is used to create a Semaphore with the given options.
 /// The prefix must have write privileges, and the limit must be agreed upon by all contenders.
 /// If a Session is not provided, one will be created.
 /// </summary>
 /// <param name="opts">The semaphore options</param>
 /// <returns>An unlocked semaphore</returns>
 public Semaphore Semaphore(SemaphoreOptions opts)
 {
     if (opts == null)
     {
         throw new ArgumentNullException("opts");
     }
     return new Semaphore(this) { Opts = opts };
 }
Example #9
0
 public void ExecuteInSemaphore(SemaphoreOptions opts, Action a)
 {
     if (opts == null)
     {
         throw new ArgumentNullException("opts");
     }
     if (a == null)
     {
         throw new ArgumentNullException("a");
     }
     using (var l = new AutoSemaphore(this, opts))
     {
         if (l.IsHeld)
         {
             a();
         }
     }
 }
Example #10
0
 internal AutoSemaphore(ConsulClient c, SemaphoreOptions opts)
     : base(c)
 {
     Opts = opts;
     CancellationToken = Acquire();
 }
Example #11
0
        void AllInOne(ManagedService svc)
        {
            MyLogger.Trace("Entering {0} for service: {1}", MethodBase.GetCurrentMethod().Name, svc.ConsulServiceName);

            // Wait if service is ready to manage
            if (!svc.CanRun) MyLogger.Info("Wait for service {0} to get in a ready state", svc.ConsulServiceName);
            while (!_shouldStop && !svc.CanRun && svc.ShouldRun)
            {
                Thread.Sleep(1000);
            }
            MyLogger.Debug("Service {0} is ready, wait for lock", svc.ConsulServiceName);
            while (!_shouldStop && svc.ShouldRun)
            {
                var semaphoreOptions = new SemaphoreOptions(Config.KvPrefix + Config.SemaPrefix + svc.ConsulServiceName,
                    svc.Limit) { SessionName = svc.ConsulServiceName + "_Session", SessionTTL = TimeSpan.FromSeconds(10) };
                var semaphore = ConsulClient.Semaphore(semaphoreOptions);
                // Try to get a lock until it is aqcuired or the program should stop
                while (!_shouldStop && !semaphore.IsHeld && svc.ShouldRun)
                {
                    MyLogger.Info("Acquiring lock on semaphore for {0}", svc.ConsulServiceName);
                    try
                    {
                        semaphore.Acquire();
                    }
                    catch
                    {
                        Thread.Sleep(1000);

                    }
                }
                // if the program should not stop and the semaphore is aqcuired, start the service
                if (!_shouldStop && svc.ShouldRun && semaphore.IsHeld && (ServiceHelper.GetServiceStatus(svc.WindowsServiceName) != "Running"))
                {
                    bool svcstarted = StartService(svc);
                    MyLogger.Info("Service {0} send start command with success: {1}", svc.WindowsServiceName, svcstarted);
                }
                // Make sure the service runs while the lock is held or the program should stop, otherwise stop the service and releade the lock
                while (!_shouldStop && svc.ShouldRun && semaphore.IsHeld)
                {
                    ServiceController sc = new ServiceController(svc.WindowsServiceName);
                    if (sc.Status != ServiceControllerStatus.Running)
                    {
                        MyLogger.Debug("Service not running, releasing lock");
                        if (semaphore.IsHeld) semaphore.Release();
                    }
                    sc.Close();
                }
                if (_shouldStop || !svc.ShouldRun)
                {
                    if (ServiceHelper.GetServiceStatus(svc.WindowsServiceName) == "Running")
                    {
                        bool svcstopped = StopService(svc);
                        MyLogger.Info("Service {0} send stop command with success: {1}", svc.WindowsServiceName, svcstopped);
                    }
                    if (semaphore.IsHeld) semaphore.Release();
                    try
                    {
                        semaphore.Destroy();
                    }
                    catch (Exception ex)
                    {
                        MyLogger.Error("some error: {0}",ex.Message);
                        MyLogger.Debug(ex);
                    }
                }
                else
                {
                    MyLogger.Info("Lock no longer held for {0}",svc.WindowsServiceName);
                    //Release lock because it could be the lock isheld was set to false due to consistency timeout
                    try
                    {
                        semaphore.Release();
                    }
                    catch (SemaphoreNotHeldException)
                    {
                    }
                    catch (Exception ex1) {
                        MyLogger.Error("Some error: {0}",ex1.Message);
                        MyLogger.Debug(ex1);
                    }
                    if (ServiceHelper.GetServiceStatus(svc.WindowsServiceName) == "Running")
                    {
                        bool svcstopped = StopService(svc);
                        MyLogger.Info("Service {0} send stop command with success: {1}", svc.WindowsServiceName, svcstopped);
                    }
                }
            }
        }
 private void GetLock()
 {
     Console.WriteLine("Trying to acquire lock");
     if (_semaphore != null) try { _semaphore.Destroy(); }
         catch (SemaphoreInUseException) { }
     _semaphoreOptions = new SemaphoreOptions(Prefix, Limit) { SessionName = Name + "_Session", SessionTTL = TimeSpan.FromSeconds(10) };
     _semaphore = _parent.ConsulClient.Semaphore(_semaphoreOptions);
     _semaphore.Acquire(_getLockCancellationTokenSource.Token);
     if (_getLockCancellationTokenSource.IsCancellationRequested)
     {
         Console.WriteLine("Cancelling Lock aqcuisition");
     }
     else
     {
         Console.WriteLine("Lock acquired, becoming active");
         _actionThread = ActionThread();
         _actionThread.Start();
     }
 }