Exemplo n.º 1
0
        /// <summary>
        /// Try Aquire the lock. If success it will return a successful <see cref="LockLeaseResult"/>.
        /// If the lockmanger throws a <seealso cref="LockManagerLockException"/> it will catch that and return a failed <see cref="LockLeaseResult"/>.
        /// In case of failure it will retry sometimes before calling it a day.
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="name"></param>
        /// <param name="retryCount"></param>
        /// <param name="retryAfter"></param>
        /// <returns></returns>
        public static async Task <LockLeaseResult> TryAquireLockWithRetryPolicy(this ILockManager manager, string name, int retryCount = 3, int retryAfter = 3)
        {
            var policy = Policy.HandleResult <LockLeaseResult>(lockLeaseResult => !lockLeaseResult.Ok)
                         .WaitAndRetryAsync(retryCount, retryAttempt => TimeSpan.FromSeconds(retryAfter));

            return(await policy.ExecuteAsync(async() => await manager.TryAquireLock(name)));
        }
        /// <summary>
        /// Adds a lock to be tracked by this cleanup task.
        /// </summary>
        /// <param name="lockManager">The lock manager that created this active lock.</param>
        /// <param name="activeLock">The active lock to track</param>
        public void Add(ILockManager lockManager, IActiveLock activeLock)
        {
            if (_logger.IsEnabled(LogLevel.Trace))
            {
                _logger.LogTrace($"Adding lock {activeLock}");
            }

            // Don't track locks with infinite timeout
            if (activeLock.Timeout == TimeoutHeader.Infinite)
            {
                return;
            }

            lock (_syncRoot)
            {
                var newLockItem = new ActiveLockItem(lockManager, activeLock);
                _activeLocks.Add(activeLock.Expiration, newLockItem);
                if (_mostRecentExpirationLockItem != null &&
                    newLockItem.Expiration >= _mostRecentExpirationLockItem.Expiration)
                {
                    // New item is not the most recent to expire
                    if (_logger.IsEnabled(LogLevel.Debug))
                    {
                        _logger.LogDebug($"New lock {activeLock.StateToken} item is not the most recent item");
                    }
                    return;
                }

                _mostRecentExpirationLockItem = newLockItem;
                ConfigureTimer(newLockItem);
            }
        }
        private async Task TestSingleLockAsync(ISet <string> releasedLocks, ILockManager lockManager, CancellationToken ct)
        {
            var l = new Lock(
                "/",
                "/",
                false,
                new XElement("test"),
                LockAccessType.Write,
                LockShareMode.Exclusive,
                TimeSpan.FromMilliseconds(100));
            var sem = new SemaphoreSlim(0, 1);
            var evt = new EventHandler <LockEventArgs>((s, e) =>
            {
                Assert.True(releasedLocks.Add(e.Lock.StateToken));
                sem.Release();
            });

            lockManager.LockReleased += evt;
            try
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                await lockManager.LockAsync(l, ct);

                Assert.True(await sem.WaitAsync(5000, ct));
                stopwatch.Stop();
                Assert.True(
                    stopwatch.ElapsedMilliseconds >= 90,
                    $"Duration should be at least 100ms, but was {stopwatch.ElapsedMilliseconds}");
            }
            finally
            {
                lockManager.LockReleased -= evt;
            }
        }
Exemplo n.º 4
0
 private JobberSupervisor()
 {
     if (JobberConfiguration.ProducerMode == ProducerMode.ActivePassive)
     {
         _lockManager = RedisLockManager.Instance.Initialize(JobberConfiguration.RedisEndPoints.ToArray(), JobberConfiguration.RedisPassword);
     }
 }
Exemplo n.º 5
0
        public ContextManagerNested(
            ILockManager lockManager,
            ContextControllerFactoryServiceContext factoryServiceContext)
        {
            _iLock                     = lockManager.CreateLock(GetType());
            _contextName               = factoryServiceContext.ContextName;
            _servicesContext           = factoryServiceContext.ServicesContext;
            _contextPartitionIdManager = factoryServiceContext.AgentInstanceContextCreate.StatementContext.ContextControllerFactoryService.AllocatePartitionIdMgr(
                _contextName, factoryServiceContext.AgentInstanceContextCreate.StatementContext.StatementId);
            _nestedContextFactories = factoryServiceContext.AgentInstanceContextCreate.StatementContext.ContextControllerFactoryService.GetFactory(
                factoryServiceContext);

            StatementAIResourceRegistryFactory resourceRegistryFactory =
                () => new StatementAIResourceRegistry(new AIRegistryAggregationMap(), new AIRegistryExprMap());

            var contextProps = ContextPropertyEventType.GetNestedTypeBase();

            foreach (var factory in _nestedContextFactories)
            {
                contextProps.Put(factory.FactoryContext.ContextName, factory.ContextBuiltinProps);
            }
            var contextPropsType = _servicesContext.EventAdapterService.CreateAnonymousMapType(
                _contextName, contextProps, true);
            var registry = new ContextPropertyRegistryImpl(
                Collections.GetEmptyList <ContextDetailPartitionItem>(), contextPropsType);

            _contextDescriptor = new ContextDescriptor(
                _contextName, false, registry, resourceRegistryFactory, this, factoryServiceContext.Detail);
        }
Exemplo n.º 6
0
 /// <summary>Ctor. </summary>
 public ValueAddEventServiceImpl(ILockManager lockManager)
 {
     _lockManager = lockManager;
     SpecificationsByRevisionName = new Dictionary <String, RevisionSpec>().WithNullSupport();
     ProcessorsByNamedWindow      = new Dictionary <String, ValueAddEventProcessor>().WithNullSupport();
     VariantProcessors            = new Dictionary <String, ValueAddEventProcessor>().WithNullSupport();
 }
Exemplo n.º 7
0
 public EventBusSource(
     ILockManager lockManager,
     IThreadLocalManager threadLocalManager)
 {
     _iLock           = lockManager.CreateLock(GetType());
     _collectorDataTL = threadLocalManager.Create <EPDataFlowEventBeanCollectorContext>(() => null);
 }
Exemplo n.º 8
0
 public EPDeploymentAdminImpl(
     EPAdministratorSPI epService,
     ILockManager lockManager,
     IReaderWriterLock eventProcessingRWLock,
     IResourceManager resourceManager,
     DeploymentStateService deploymentStateService,
     StatementEventTypeRef statementEventTypeRef,
     EventAdapterService eventAdapterService,
     StatementIsolationService statementIsolationService,
     FilterService filterService,
     TimeZoneInfo timeZone,
     ConfigurationEngineDefaults.UndeployRethrowPolicy undeployRethrowPolicy)
 {
     _iLock                     = lockManager.CreateDefaultLock();
     _epService                 = epService;
     _resourceManager           = resourceManager;
     _eventProcessingRwLock     = eventProcessingRWLock;
     _deploymentStateService    = deploymentStateService;
     _statementEventTypeRef     = statementEventTypeRef;
     _eventAdapterService       = eventAdapterService;
     _statementIsolationService = statementIsolationService;
     _filterService             = filterService;
     _timeZone                  = timeZone;
     _undeployRethrowPolicy     = undeployRethrowPolicy;
 }
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="lockManager">The lock manager.</param>
 /// <param name="knownTypes">types known at cache construction type, may be an empty list for the ANY type variance.</param>
 public VariantPropertyGetterCache(ILockManager lockManager, EventType[] knownTypes)
 {
     _iLock      = lockManager.CreateLock(GetType());
     _knownTypes = knownTypes;
     _allGetters = new Dictionary <EventType, VariantPropertyGetterRow>();
     _properties = new List <String>();
 }
Exemplo n.º 10
0
 /// <summary>
 /// Ctor.
 /// </summary>
 /// <param name="timeZone">The time zone.</param>
 /// <param name="hasYear">if set to <c>true</c> [has year].</param>
 /// <param name="hasMonth">if set to <c>true</c> [has month].</param>
 /// <param name="hasWeek">if set to <c>true</c> [has week].</param>
 /// <param name="hasDay">true if the expression has that part, false if not</param>
 /// <param name="hasHour">true if the expression has that part, false if not</param>
 /// <param name="hasMinute">true if the expression has that part, false if not</param>
 /// <param name="hasSecond">true if the expression has that part, false if not</param>
 /// <param name="hasMillisecond">true if the expression has that part, false if not</param>
 /// <param name="hasMicrosecond">if set to <c>true</c> [has microsecond].</param>
 /// <param name="timeAbacus">The time abacus.</param>
 /// <param name="lockManager">The lock manager.</param>
 public ExprTimePeriodImpl(
     TimeZoneInfo timeZone,
     bool hasYear,
     bool hasMonth,
     bool hasWeek,
     bool hasDay,
     bool hasHour,
     bool hasMinute,
     bool hasSecond,
     bool hasMillisecond,
     bool hasMicrosecond,
     TimeAbacus timeAbacus,
     ILockManager lockManager)
 {
     _lockManager    = lockManager;
     _timeZone       = timeZone;
     _hasYear        = hasYear;
     _hasMonth       = hasMonth;
     _hasWeek        = hasWeek;
     _hasDay         = hasDay;
     _hasHour        = hasHour;
     _hasMinute      = hasMinute;
     _hasSecond      = hasSecond;
     _hasMillisecond = hasMillisecond;
     _hasMicrosecond = hasMicrosecond;
     _timeAbacus     = timeAbacus;
 }
Exemplo n.º 11
0
        /// <summary>
        /// Tries to acquire the lock indefinitely until the action succeeds.
        /// </summary>
        /// <param name="manager">The instance of <see cref="ILockManager"/>.</param>
        /// <param name="name">Topic or name.</param>
        /// <param name="retryAfter">Specifies the duration in seconds to wait for a particular retry attempt.</param>
        /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
        /// <returns>The task that represents the asynchronous operation result for acquiring the lock.</returns>
        public static async Task <LockLeaseResult> TryAcquireLockForeverPolicy(this ILockManager manager, string name, int retryAfter = 3, CancellationToken cancellationToken = default)
        {
            var policy = Policy.HandleResult <LockLeaseResult>(lockLeaseResult => !lockLeaseResult.Ok)
                         .WaitAndRetryForeverAsync(retryAttempt => TimeSpan.FromSeconds(retryAfter));

            return(await policy.ExecuteAsync(token => manager.TryAcquireLock(name), cancellationToken));
        }
Exemplo n.º 12
0
        static async void A2(ILockManager manager)
        {
            // wait one second
            await Task.Delay(1000);

            // check if it's locked
            LockToken existingLock = await manager.QueryAsync("tandem://devices/Wow");

            if (existingLock.IsValid)
            {
                Console.WriteLine($"It's locked by '{existingLock.Owner}'");
            }

            // now try and obtain a lock
            await Task.Delay(2000);

            using (var h = await manager.LockAsync("tandem://devices/wow")) {
                if (h == null)
                {
                    Console.WriteLine("Couldn't get a lock!");
                }
                else
                {
                    Console.WriteLine("Got a lock!");
                    ProceedSemaphore.Release();
                }
            }
        }
Exemplo n.º 13
0
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            if (_lockManager == null)
            {
                //http://www.strathweb.com/2012/11/asp-net-web-api-and-dependencies-in-request-scope/
                _lockManager = request.GetDependencyScope().GetService(typeof(ILockManager)) as ILockManager;
            }
            // Preconditions
            HttpResponseMessage error;
            if (!TryNoLockTokenMatchesRequestUri(request, out error))
            {
                return base.SendAsync(request, cancellationToken)
                    .ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { return error; });
            }

            if (!TryNoLockTokenSubmitted(request, out error))
            {
                return base.SendAsync(request, cancellationToken)
                    .ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { return error; });
            }

            if (!TryNoConflictingLock(request, out error))
            {
                return base.SendAsync(request, cancellationToken)
                    .ContinueWith<HttpResponseMessage>((responseToCompleteTask) => { return error; });
            }
            return base.SendAsync(request, cancellationToken);
        }
Exemplo n.º 14
0
        /// <summary>
        /// This is for internal use only.
        /// Removes the lock context
        /// </summary>
        /// <param name="lockManager">Lock manager object which contains the lock to be removed</param>
        /// <param name="lockOrKey">name of the lock</param>
        /// <returns>LockContext object if found. null otherwise</returns>
        public LockContext RemoveLockContext(ILockManager lockManager, object lockOrKey)
        {
            if (lockManager == null)
            {
                throw new ArgumentNullException(
                          string.Format(CultureInfo.CurrentCulture, SR.Error_NullArgument_Formatted, "lockManager"));
            }

            if (lockOrKey == null)
            {
                throw new ArgumentNullException(
                          string.Format(CultureInfo.CurrentCulture, SR.Error_NullArgument_Formatted, "lockOrKey"));
            }

            LockContext removedLockContext = null;

            for (var i = 0; i < this.LockContexts.Count; i++)
            {
                var lockContext = this.LockContexts[i];
                if (lockContext.IsEqual(lockManager, lockOrKey) == true)
                {
                    this.LockContexts.RemoveAt(i);
                    removedLockContext = lockContext;
                    break;
                }
            }

            return(removedLockContext);
        }
Exemplo n.º 15
0
 public ScheduledJob(TaskHandlerActivator taskHandlerActivator, IScheduledTaskStore <TState> scheduledTaskStore, ILogger <ScheduledJob <TTaskHandler, TState> > logger, IConfiguration configuration, ILockManager lockManager)
 {
     _taskHandlerActivator = taskHandlerActivator ?? throw new ArgumentNullException(nameof(taskHandlerActivator));
     _scheduledTaskStore   = scheduledTaskStore ?? throw new ArgumentNullException(nameof(scheduledTaskStore));
     _logger        = logger ?? throw new ArgumentNullException(nameof(logger));
     _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
     _lockManager   = lockManager ?? throw new ArgumentNullException(nameof(lockManager));
 }
Exemplo n.º 16
0
 public EPStatementSource(
     ILockManager lockManager,
     IThreadLocalManager threadLocalManager)
 {
     _iLock                 = lockManager.CreateLock(MethodBase.GetCurrentMethod().DeclaringType);
     _collectorDataTL       = threadLocalManager.Create <EPDataFlowIRStreamCollectorContext>(() => null);
     _lifeCycleEventHandler = Observe;
 }
Exemplo n.º 17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LockHandler"/> class.
 /// </summary>
 /// <param name="context">The WebDAV request context</param>
 /// <param name="rootFileSystem">The root file system</param>
 /// <param name="lockManager">The lock manager</param>
 /// <param name="timeoutPolicy">The timeout policy for the selection of the <see cref="TimeoutHeader"/> value</param>
 public LockHandler(IWebDavContext context, IFileSystem rootFileSystem, ILockManager lockManager = null, ITimeoutPolicy timeoutPolicy = null)
 {
     _context        = context;
     _rootFileSystem = rootFileSystem;
     _lockManager    = lockManager;
     _timeoutPolicy  = timeoutPolicy;
     HttpMethods     = _lockManager == null ? new string[0] : new[] { "LOCK" };
 }
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="timeSourceService">time source provider</param>
 /// <param name="lockManager">The lock manager.</param>
 public SchedulingServiceImpl(TimeSourceService timeSourceService, ILockManager lockManager)
 {
     _uLock         = lockManager.CreateLock(GetType());
     _timeHandleMap = new SortedList <long, IDictionary <long, ScheduleHandle> >();
     _handleSetMap  = new Dictionary <ScheduleHandle, IDictionary <long, ScheduleHandle> >();
     // initialize time to just before now as there is a check for duplicate external time events
     _currentTime = timeSourceService.GetTimeMillis() - 1;
 }
Exemplo n.º 19
0
 public SharedDataController(ISharedDataManager sharedDataManager, IAuditManager auditManager,
                             ILockManager lockManager, ITiersManager tiersManager)
 {
     _sharedDataManager = sharedDataManager;
     _auditManager      = auditManager;
     _lockManager       = lockManager;
     _tiersManager      = tiersManager;
 }
Exemplo n.º 20
0
 public FilterServiceLockCoarse(
     ILockManager lockManager,
     IReaderWriterLockManager rwLockManager,
     bool allowIsolation)
     : base(lockManager, FilterServiceGranularLockFactoryNone.Instance, allowIsolation)
 {
     _iLock = rwLockManager.CreateLock(GetType());
 }
Exemplo n.º 21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="HealthWorker"/> class.
 /// </summary>
 /// <param name="processor">The parent processor.</param>
 /// <param name="name">The name of the worker.</param>
 public HealthWorker(IMessageProcessor processor, string name)
     : base(processor, name)
 {
     // create throttle lock to only allow one run per schedule
     var lockCollection = Configuration.LockCollection ?? "ServiceLock";
     var collection = Repository.Collection.Database.GetCollection<LockData>(lockCollection);
     _lockManager = new ThrottleLock(collection, Configuration.HealthCheck);
 }
Exemplo n.º 22
0
 public FilterServiceLockFine(
     ILockManager lockManager,
     IReaderWriterLockManager rwLockManager,
     bool allowIsolation)
     : base(lockManager, new FilterServiceGranularLockFactoryReentrant(rwLockManager), allowIsolation)
 {
     _iLock = rwLockManager.CreateLock(GetType());
 }
Exemplo n.º 23
0
 /// <summary>
 /// Constructor - takes the event type index to manipulate as its parameter.
 /// </summary>
 /// <param name="lockManager">The lock manager.</param>
 /// <param name="eventTypeIndex">index to manipulate</param>
 /// <param name="allowIsolation">if set to <c>true</c> [allow isolation].</param>
 public EventTypeIndexBuilder(
     ILockManager lockManager,
     EventTypeIndex eventTypeIndex,
     bool allowIsolation)
 {
     _eventTypeIndex      = eventTypeIndex;
     _callbacksLock       = lockManager.CreateLock(GetType());
     _isolatableCallbacks = allowIsolation ? new Dictionary <FilterHandle, EventTypeIndexBuilderValueIndexesPair>() : null;
 }
Exemplo n.º 24
0
        /// <summary>
        /// Gets a value that indicates whether the current lock manager instance is the same as the other lock manager.
        /// </summary>
        internal bool IsEqual(ILockManager inputLockManager, object stateOrKey)
        {
            if (this.lockManager == inputLockManager)
            {
                return(this.IsEqual(stateOrKey));
            }

            return(false);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="HealthWorker"/> class.
        /// </summary>
        /// <param name="processor">The parent processor.</param>
        /// <param name="name">The name of the worker.</param>
        public HealthWorker(IMessageProcessor processor, string name)
            : base(processor, name)
        {
            // create throttle lock to only allow one run per schedule
            var lockCollection = Configuration.LockCollection ?? "ServiceLock";
            var collection     = Repository.Collection.Database.GetCollection <LockData>(lockCollection);

            _lockManager = new ThrottleLock(collection, Configuration.HealthCheck);
        }
 internal LockToken(byte lockLevel, T lockedObject, ILockManager <T> holder, LockRuleset matrix, int sharedLockCount)
 {
     LockLevel       = lockLevel;
     LockedObject    = lockedObject;
     _holder         = holder;
     _matrix         = matrix;
     _isReleased     = 0;
     SharedLockCount = sharedLockCount;
 }
Exemplo n.º 27
0
 public LotManager(LMG_FABContext context, ILockManager lockManager, ReflmgContext refContext,
                   IDateFormater dateFormater, ILogger <LotManager> logger)
 {
     _fabContext   = context;
     _lockManager  = lockManager;
     _refContext   = refContext;
     _dateFormater = dateFormater;
     _logger       = logger;
 }
Exemplo n.º 28
0
        public NamedWindowProcessor AddProcessor(
            string name,
            string contextName,
            EventType eventType,
            StatementResultService statementResultService,
            ValueAddEventProcessor revisionProcessor,
            string eplExpression,
            string statementName,
            bool isPrioritized,
            bool isEnableSubqueryIndexShare,
            bool isBatchingDataWindow,
            bool isVirtualDataWindow,
            ICollection <string> optionalUniqueKeyProps,
            string eventTypeAsName,
            StatementContext statementContextCreateWindow,
            NamedWindowDispatchService namedWindowDispatchService,
            ILockManager lockManager)
        {
            if (_processors.ContainsKey(name))
            {
                throw new ViewProcessingException("A named window by name '" + name + "' has already been created");
            }

            var processor = namedWindowDispatchService.CreateProcessor(
                name, this,
                namedWindowDispatchService,
                contextName,
                eventType,
                statementResultService,
                revisionProcessor,
                eplExpression,
                statementName,
                isPrioritized,
                isEnableSubqueryIndexShare,
                _enableQueryPlanLog,
                _metricReportingService,
                isBatchingDataWindow,
                isVirtualDataWindow,
                optionalUniqueKeyProps,
                eventTypeAsName,
                statementContextCreateWindow,
                lockManager);

            _processors.Put(name, processor);

            if (!_observers.IsEmpty())
            {
                var theEvent = new NamedWindowLifecycleEvent(name, processor, NamedWindowLifecycleEvent.LifecycleEventType.CREATE);
                foreach (var observer in _observers)
                {
                    observer.Observe(theEvent);
                }
            }

            return(processor);
        }
Exemplo n.º 29
0
 public ReadWriteRecordReader(IRecordReaderImp <TRecord> aRecordReaderImp
                              , ILockManager aLockManager
                              , long apTranId
                              , Dictionary <SqlTable, string> tableAndAliasNames)
 {
     _aRecordReaderImp   = aRecordReaderImp;
     _aLockManager       = aLockManager;
     _apTranId           = apTranId;
     _tableAndAliasNames = tableAndAliasNames;
 }
Exemplo n.º 30
0
 public MyVirtualRootFileSystemFactory(
     [NotNull] IServiceProvider serviceProvider,
     [NotNull] IPathTraversalEngine pathTraversalEngine,
     [NotNull] ISystemClock systemClock,
     ILockManager lockManager = null,
     IPropertyStoreFactory propertyStoreFactory = null)
     : base(pathTraversalEngine, systemClock, lockManager, propertyStoreFactory)
 {
     _serviceProvider = serviceProvider;
 }
Exemplo n.º 31
0
        /// <summary>
        /// Try aquire the lock. If success it will return a successful <see cref="LockLeaseResult"/>.
        /// If the <see cref="ILockManager"/> throws a <seealso cref="LockManagerException"/> it will catch that and return a failed <see cref="LockLeaseResult"/>.
        /// </summary>
        /// <param name="manager">The instance of <see cref="ILockManager"/>.</param>
        /// <param name="name">Topic or name.</param>
        /// <param name="duration">The duration the lease will be active. Defaults 30 seconds.</param>
        /// <param name="cancellationToken">Propagates notification that operations should be canceled.</param>
        /// <returns>The task the represent the asynchronous operation result for acquiring the lock.</returns>
        public static async Task <LockLeaseResult> TryAcquireLock(this ILockManager manager, string name, TimeSpan?duration = null, CancellationToken cancellationToken = default)
        {
            try {
                var @lock = await manager.AcquireLock(name, duration, cancellationToken);

                return(LockLeaseResult.Success(@lock));
            } catch (LockManagerException) {
                return(LockLeaseResult.Fail());
            }
        }
Exemplo n.º 32
0
        /// <summary>
        /// Try Aquire the lock. If success it will return a successful <see cref="LockLeaseResult"/>.
        /// If the lockmanger throws a <seealso cref="LockManagerLockException"/> it will catch that and return a failed <see cref="LockLeaseResult"/>
        /// </summary>
        /// <param name="manager"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static async Task <LockLeaseResult> TryAquireLock(this ILockManager manager, string name)
        {
            try {
                var @lock = await manager.AcquireLock(name);

                return(LockLeaseResult.Success(@lock));
            } catch (LockManagerLockException) {
                return(LockLeaseResult.Fail());
            }
        }
Exemplo n.º 33
0
 public LockController(ILockManager lockManager)
 {
     _lockManager = lockManager;
 }
Exemplo n.º 34
0
 public LockDelegatingHandler(ILockManager lockManager)
 {
     _lockManager = lockManager;
 }