Example #1
0
        public bool Acquire(TimeSpan?timeout = null)
        {
            /*
             * Note on concurrency: a given lockData instance
             * can be only acted on by a single thread so locking isn't necessary
             */
            var hasLock = false;

            var lockData = SafeGetLockData();

            if (null != lockData)
            {
                // Re-entering
                lockData.Inc();
                hasLock = true;
            }
            else
            {
                var lockPath = _internals.AttemptLock(timeout, null);
                if (null != lockPath)
                {
                    var newLockData = new LockData(Thread.CurrentThread, lockPath);
                    SetLockData(newLockData);
                    hasLock = true;
                }
            }

            if (!hasLock && !timeout.HasValue)
            {
                throw new IOException("Lost connection while trying to acquire lock: " + _basePath);
            }

            return(hasLock);
        }
Example #2
0
    public void SetLockSettings(LockType lockType, int lockTimer)
    {
        if (lockType != lockData.lockType)
        {
            SetLockStateMachine(lockType);
        }

        if (lockData.lockTimer <= 0)
        {
            if (Application.isPlaying) // Preventing errors in editor
            {
                ActivateLock();
            }
        }

        if (lockData == null)
        {
            lockData = new LockData(lockType, lockTimer);
        }
        else
        {
            lockData.lockType  = lockType;
            lockData.lockTimer = lockTimer;
        }

        textAnim.SetTextValue(lockData.lockTimer);
    }
Example #3
0
        protected override IEnumerable <LockData> FindCandidateSubsumptionLockData(long apTranId
                                                                                   , string tableName)
        {
            List <LockData> ret = new List <LockData>();

            try {
                //Readerロックを取得する
                _memLockData.AcquireReaderLock(_timeout);

                LockData aLockData = null;
                for (int i = 0; i <= _memLockData.Count - 1; i++)
                {
                    aLockData = (LockData)_memLockData.Item(i);
                    if (aLockData.ApTranId != apTranId && aLockData.TableName == tableName)
                    {
                        ret.Add(aLockData);
                    }
                }
            } finally {
                //Readerロックを開放する
                _memLockData.ReleaseReaderLock();
            }

            return(ret);
        }
Example #4
0
        private async Task WaitForCallAsync(LockData @lock, IPageRequestSettings settings)
        {
            await @lock.Semaphore.WaitAsync()
            .ConfigureAwait(false);

            try
            {
                var currentSpan = DateTime.UtcNow - @lock.LastCall;
                if (currentSpan >= settings.DelayBetweenCalls)
                {
                    logger.LogDebug("Waiting for a next call having host {Host} is not needed. Current span is {Span}", settings.Host, currentSpan);
                }
                else
                {
                    var toWait = settings.DelayBetweenCalls - currentSpan;
                    logger.LogDebug("Waiting {Delay} for a next call having host {Host}", toWait, settings.Host);
                    await Task.Delay(toWait)
                    .ConfigureAwait(false);
                }
                @lock.LastCall = DateTime.UtcNow;
            }
            finally
            {
                @lock.Semaphore.Release();
            }
        }
        public async Task <IActionResult> LockUser([FromBody] LockData data)
        {
            CheckUserManager();
            if (!User.IsInRole("Administrator"))
            {
                return(Forbid());
            }
            if (data == null || string.IsNullOrEmpty(data.secs) || string.IsNullOrEmpty(data.uid))
            {
                return(BadRequest());
            }
            double dSecs = default(double);

            if (!double.TryParse(data.secs, out dSecs))
            {
                return(BadRequest());
            }
            var user = await _userManager.FindByIdAsync(data.uid);

            if (await _userManager.GetLockoutEnabledAsync(user))
            {
                await _userManager.SetLockoutEndDateAsync(user, DateTimeOffset.Now.AddSeconds(dSecs));

                user.IsLocked = true;
                var updateUserResult = await _userManager.UpdateAsync(user);

                if (updateUserResult.Succeeded)
                {
                    return(Ok());
                }
            }
            return(BadRequest());
        }
Example #6
0
        public void LockData_FromBody_Parsing()
        {
            // Verify simple vanilla parsing
            LockData lockDataBefore = new LockData(1, true, true, "git status --serialize=D:\\Sources\\tqoscy2l.ud0_status.tmp --ignored=matching --untracked-files=complete");
            LockData lockDataAfter  = LockData.FromBody(lockDataBefore.ToMessage());

            lockDataAfter.PID.ShouldEqual(1);
            lockDataAfter.IsElevated.ShouldEqual(true);
            lockDataAfter.CheckAvailabilityOnly.ShouldEqual(true);
            lockDataAfter.ParsedCommand.ShouldEqual("git status --serialize=D:\\Sources\\tqoscy2l.ud0_status.tmp --ignored=matching --untracked-files=complete");

            // Verify strings with "|" will work
            LockData lockDataWithPipeBefore = new LockData(1, true, true, "git commit -m 'message with a | and another |'");
            LockData lockDataWithPipeAfter  = LockData.FromBody(lockDataWithPipeBefore.ToMessage());

            lockDataWithPipeAfter.PID.ShouldEqual(1);
            lockDataWithPipeAfter.IsElevated.ShouldEqual(true);
            lockDataWithPipeAfter.CheckAvailabilityOnly.ShouldEqual(true);
            lockDataWithPipeAfter.ParsedCommand.ShouldEqual("git commit -m 'message with a | and another |'");

            // Verify exception cases and messages
            this.ValidateError("1|true|true", "Invalid lock message. Expected at least 5 parts, got: 3 from message: '1|true|true'");
            this.ValidateError("blah|true|true|10|git status", "Invalid lock message. Expected PID, got: blah from message: 'blah|true|true|10|git status'");
            this.ValidateError("1|true|1|10|git status", "Invalid lock message. Expected bool for checkAvailabilityOnly, got: 1 from message: '1|true|1|10|git status'");
            this.ValidateError("1|1|true|10|git status", "Invalid lock message. Expected bool for isElevated, got: 1 from message: '1|1|true|10|git status'");
            this.ValidateError("1|true|true|true|git status", "Invalid lock message. Expected command length, got: true from message: '1|true|true|true|git status'");
            this.ValidateError("1|true|true|5|git status", "Invalid lock message. The parsedCommand is an unexpected length, got: 5 from message: '1|true|true|5|git status'");
        }
Example #7
0
        public bool TryReleaseLock()
        {
            if (this.DisposeStream())
            {
                return(true);
            }

            LockData lockData = this.GetLockDataFromDisk();

            if (lockData == null || lockData.Signature != this.Signature)
            {
                if (lockData == null)
                {
                    throw new LockFileDoesNotExistException(this.lockPath);
                }

                throw new LockSignatureDoesNotMatchException(this.lockPath, this.Signature, lockData.Signature);
            }

            try
            {
                this.fileSystem.DeleteFile(this.lockPath);
            }
            catch (IOException e)
            {
                EventMetadata metadata = this.CreateLockMetadata(e);
                this.tracer.RelatedWarning(metadata, "TryReleaseLock: IOException caught while trying to release lock");

                return(false);
            }

            return(true);
        }
Example #8
0
    protected override void Initialize(DoorRecord record, ReferenceData referenceData)
    {
        base.Initialize(record, referenceData);

        doorData = referenceData.DoorExitData;
        loadCell = referenceData.LoadCell;
        lockData = new LockData(referenceData.LockLevel, referenceData.Trap, referenceData.Key);
    }
Example #9
0
            public static LockData New()
            {
                var data = new LockData();

                data.LockId      = Guid.NewGuid().ToByteArray();
                data.LockUtcTime = DateTime.UtcNow;
                return(data);
            }
Example #10
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        public void Lock(object key)
        {
            Log.Debug("acquiring cache lock: regionName='{0}', key='{1}'", RegionName, key);

            LockData lockData = null;

            try
            {
                var lockKey     = CacheNamespace.GetLockKey(key);
                var shouldRetry = _options.AcquireLockRetryStrategy.GetShouldRetry();

                var wasLockAcquired      = false;
                var shouldTryAcquireLock = true;
                while (shouldTryAcquireLock)
                {
                    lockData = new LockData(
                        key: Convert.ToString(key),
                        lockKey: lockKey,
                        // Recalculated each attempt to ensure a unique value.
                        lockValue: _options.LockValueFactory.GetLockValue()
                        );

                    if (TryAcquireLock(lockData))
                    {
                        wasLockAcquired      = true;
                        shouldTryAcquireLock = false;
                    }
                    else
                    {
                        var shouldRetryArgs = new ShouldRetryAcquireLockArgs(
                            RegionName, lockData.Key, lockData.LockKey,
                            lockData.LockValue, _lockTimeout, _acquireLockTimeout
                            );
                        shouldTryAcquireLock = shouldRetry(shouldRetryArgs);
                    }
                }

                if (!wasLockAcquired)
                {
                    var lockFailedArgs = new LockFailedEventArgs(
                        RegionName, key, lockKey,
                        _lockTimeout, _acquireLockTimeout
                        );
                    _options.OnLockFailed(this, lockFailedArgs);
                }
            }
            catch (Exception e)
            {
                Log.Error("could not acquire cache lock: regionName='{0}', key='{1}'", RegionName, key);

                var evtArg = new ExceptionEventArgs(RegionName, RedisCacheMethod.Lock, e);
                _options.OnException(this, evtArg);
                if (evtArg.Throw)
                {
                    throw new RedisCacheException(RegionName, "Failed to lock item in cache. See inner exception.", e);
                }
            }
        }
Example #11
0
 //post to locks
 public void Test(LockData value)
 {
     using (var conn = new SqlConnection(this.connString))
     {
         string sQuery = "INSERT INTO Locks (Name, LockTypeID)"
                         + " VALUES(@Name, @LockTypeID)";
         conn.Open();
         conn.Execute(sQuery, value);
     }
 }
Example #12
0
 //edit locks
 public void Edit(LockData value)
 {
     using (var conn = new SqlConnection(this.connString))
     {
         string sQuery = "UPDATE Locks SET Name = @Name, LockTypeID = @LockTypeID"
                         + " WHERE LockID = @LockID";
         conn.Open();
         conn.Query(sQuery, value);
     }
 }
Example #13
0
 void LockDefine()
 {
     GameInformation.ObjectLocks = new List <LockData>();
     for (int i = 0; i < data.numOfLocks; i++)
     {
         LockData newLock = new LockData();
         newLock.locked = data.lockLocked[i];
         newLock.index  = data.lockIndex[i];
         GameInformation.ObjectLocks.Insert(i, newLock);
     }
 }
Example #14
0
        public void LockData_FromBody_WithDelimiters()
        {
            // Verify strings with "|" will work
            LockData lockDataWithPipeBefore = new LockData(1, true, true, "git commit -m 'message with a | and another |'", "123|321");
            LockData lockDataWithPipeAfter  = LockData.FromBody(lockDataWithPipeBefore.ToMessage());

            lockDataWithPipeAfter.PID.ShouldEqual(1);
            lockDataWithPipeAfter.IsElevated.ShouldEqual(true);
            lockDataWithPipeAfter.CheckAvailabilityOnly.ShouldEqual(true);
            lockDataWithPipeAfter.ParsedCommand.ShouldEqual("git commit -m 'message with a | and another |'");
            lockDataWithPipeAfter.GitCommandSessionId.ShouldEqual("123|321");
        }
Example #15
0
        public void LockData_FromBody_Simple()
        {
            // Verify simple vanilla parsing
            LockData lockDataBefore = new LockData(1, true, true, "git status --serialize=D:\\Sources\\tqoscy2l.ud0_status.tmp --ignored=matching --untracked-files=complete", "123");
            LockData lockDataAfter  = LockData.FromBody(lockDataBefore.ToMessage());

            lockDataAfter.PID.ShouldEqual(1);
            lockDataAfter.IsElevated.ShouldEqual(true);
            lockDataAfter.CheckAvailabilityOnly.ShouldEqual(true);
            lockDataAfter.ParsedCommand.ShouldEqual("git status --serialize=D:\\Sources\\tqoscy2l.ud0_status.tmp --ignored=matching --untracked-files=complete");
            lockDataAfter.GitCommandSessionId.ShouldEqual("123");
        }
Example #16
0
        private static string CompareImageResult(Bitmap bmp, string file, string type)
        {
            var exist = File.Exists(file);

            if (bmp == null)
            {
                if (exist)
                {
                    return(string.Format("{0} not found", type));
                }
                else
                {
                    return("");
                }
            }

            if (!exist)
            {
                return(string.Format("unexpectedly found {0}", type));
            }

            var expected = new Bitmap(file);

            if (expected.Width != bmp.Width ||
                expected.Height != bmp.Height)
            {
                return(string.Format(
                           "{0} dimension does not match, expected {1}/{2}, got {3}/{4}",
                           type, expected.Width, expected.Height, bmp.Width, bmp.Height));
            }

            unsafe
            {
                var rect  = new Rectangle(0, 0, bmp.Width, bmp.Height);
                var bytes = bmp.BytesPerPixel();

                using (var expectedData = new LockData(expected, rect))
                    using (var resultData = new LockData(bmp, rect))
                    {
                        for (var y = 0; y < resultData.Data.Height; y++)
                        {
                            if (memcmp(resultData.Row(y), expectedData.Row(y),
                                       resultData.Width * bytes) != 0)
                            {
                                return(string.Format("{0} bitmap data did not match", type));
                            }
                        }
                    }
            }

            return("");
        }
Example #17
0
        public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
        {
            var      redis         = GetRedisConnection();
            var      getLock       = redis.Hashes.Get(0, lockHashKey, id);
            var      lockIdAsBytes = (byte[])lockId;
            LockData lockData;

            if (getLock.Result != null && LockData.TryParse(getLock.Result, out lockData) && Enumerable.SequenceEqual(lockData.LockId, lockIdAsBytes))
            {
                redis.Keys.Remove(0, GetKeyForSessionId(id));
                redis.Hashes.Remove(0, lockHashKey, id);
            }
        }
                public Response(Message message)
                {
                    this.Result = message.Header;

                    if (this.Result == DenyGSDResult)
                    {
                        this.DenyGSDMessage = message.Body;
                    }
                    else
                    {
                        this.ResponseData = LockData.FromBody(message.Body);
                    }
                }
Example #19
0
 public static bool TryParse(byte[] raw, out LockData data)
 {
     if (raw != null && raw.Length > 1)
     {
         var lockId    = raw.Take(16).ToArray();
         var lockTicks = BitConverter.ToInt64(raw, 17);
         data = new LockData {
             LockId      = lockId,
             LockUtcTime = new DateTime(lockTicks)
         };
         return(true);
     }
     data = new LockData();
     return(false);
 }
Example #20
0
    public BoardData(Transform gameBoardParent, Vector2Int boardSize)
    {
        this.boardSize = boardSize;

        shapes       = new List <ShapeData>();
        locks        = new List <LockData>();
        transformers = new List <TransformerData>();

        // Looping through the game board, get all the shapes and store them in the board list
        GameSlot         slot;
        GameShape        shape;
        SlotLock         slotLock;
        ShapeTransformer transformer;

        for (int i = 0; i < gameBoardParent.childCount; i++)
        {
            slot = gameBoardParent.GetChild(i).GetComponent <GameSlot>();
            if (slot != null)
            {
                transformers.Add(new TransformerData(ShapeTransformer.TransformerType.None, 0));
                shape    = slot.GetSlotShape();
                slotLock = slot.GetSlotLock();

                ShapeData newShape = shape != null ? new ShapeData(shape.GetShapeColor(), shape.GetShapeType()) : new ShapeData(GameShape.ColorType.None, GameShape.ShapeType.None);
                shapes.Add(newShape);

                LockData newLock = slotLock != null ? new LockData(slotLock.GetLockType(), slotLock.GetLockCounter()) : new LockData(SlotLock.LockType.None, 0);
                locks.Add(newLock);
            }
            else
            {
                shapes.Add(null);
                locks.Add(null);

                transformer = gameBoardParent.GetChild(i).GetComponent <ShapeTransformer>();
                TransformerData transformerData = transformer?.GetTransformerData();
                if (transformerData != null)
                {
                    transformers.Add(new TransformerData(transformerData));
                }
                else
                {
                    transformers.Add(new TransformerData(ShapeTransformer.TransformerType.None, 0));
                }
            }
        }
    }
Example #21
0
 public static void SaveLock(ObjectLock oLock)
 {
     if (GameInformation.ObjectLocks.Count <= oLock.lockIndex)
     {
         LockData newLock = new LockData();
         for (int i = 0; i < oLock.lockIndex + 1; i++)
         {
             if (i <= GameInformation.ObjectLocks.Count)
             {
                 GameInformation.ObjectLocks.Insert(i, newLock);
             }
         }
         //GameInformation.NPCData.Insert(npc.NPCIndex, newNPC);
     }
     GameInformation.ObjectLocks[oLock.lockIndex].locked = oLock.IsLocked();
     GameInformation.ObjectLocks[oLock.lockIndex].index  = oLock.lockIndex;
 }
        private async Task <bool> TryAcquireLockAsync(LockData lockData)
        {
            var db = GetDatabase();

            // Don't use IDatabase.LockTake() because we don't use the matching
            // LockRelease(). So, avoid any confusion. Besides, LockTake() just
            // calls this anyways.
            var wasLockAcquired = await db.StringSetAsync(lockData.LockKey, lockData.LockValue, lockTimeout, When.NotExists);

            if (wasLockAcquired)
            {
                // It's ok to use Set() instead of Add() because the lock in
                // Redis will cause other clients to wait.
                acquiredLocks.Set(lockData.Key, lockData, absoluteExpiration: DateTime.UtcNow.Add(lockTimeout));
            }

            return(wasLockAcquired);
        }
Example #23
0
        protected override void DeleteLockData(long apTranId)
        {
            //LockDataへのアクセスによるLockDataのアクセスを排除する
            //(LockDataに対するアクセスの場合、APトランザクションIDは-1である(暫定設計))
            if (apTranId == -1)
            {
                return;
            }

            //削除対象レコードの抽出条件を作成する
            LockData criteria = new LockData();

            criteria.ApTranId = apTranId;

            using (Tran aTran = _aDb.CreateTranWithoutLock()) {
                aTran.Delete <LockData>(criteria);
            }
        }
Example #24
0
        public static unsafe int GetBrightness(Texture tex, int xStart, int yStart, int xStep, int yStep, int count)
        {
            LockData lockData = tex.Lock(LockFlags.ReadOnly);
            short *  numPtr1  = (short *)lockData.pvSrc;
            int      num1     = lockData.Pitch >> 1;
            short *  numPtr2  = numPtr1 + yStart * num1 + xStart;
            int      num2     = num1 * yStep + xStep;
            int      num3     = 0;

            for (int index = 0; index < count; ++index)
            {
                short num4 = *numPtr2;
                num3     = num3 + ((int)num4 & 31) * 114 + ((int)num4 >> 5 & 31) * 587 + ((int)num4 >> 10 & 31) * 299;
                numPtr2 += num2;
            }
            tex.Unlock();
            return((num3 << 3) / count / 1000);
        }
Example #25
0
    public override GameObject CreateGameObject(ReferenceData referenceData, Transform parent = null)
    {
        var gameObject = base.CreateGameObject(referenceData, parent);

        var childGameObjects = gameObject.GetComponentsInChildren <MeshFilter>();
        var length           = childGameObjects.Length;

        for (var i = 0; i < length; i++)
        {
            childGameObjects[i].gameObject.isStatic = true;
            CellManager.StaticBatching.Add(childGameObjects[i].gameObject);
        }

        var lockData = new LockData(referenceData.LockLevel, referenceData.Trap, referenceData.Key);

        Container.Create(gameObject, this, referenceData);

        return(gameObject);
    }
Example #26
0
        /// <summary>
        /// 指定したロックデータが既にロックされているデータか判定する
        /// </summary>
        /// <param name="aLockData">判定対象のロックデータ</param>
        /// <returns>ロックされている:True、されていない:False</returns>
        /// <remarks></remarks>
        private bool IsLocked(LockData aLockData)
        {
            //包摂候補(異なるApTranIDかつ同一テーブル)となるLockDataの述語を抽出する
            List <CNFofEquation> predicates = new List <CNFofEquation>();

            foreach (LockData candidateLockData in this.FindCandidateSubsumptionLockData(aLockData.ApTranId
                                                                                         , aLockData.TableName))
            {
                predicates.Add(candidateLockData.Predicate);
            }

            //述語同士の包摂判定
            if (this.IsSubsumption(aLockData.Predicate, predicates.ToArray()))
            {
                return(true);
            }

            return(false);
        }
        public virtual void Lock(object key)
        {
            log.DebugFormat("acquiring cache lock : {0}", key);

            try
            {
                var lockKey = CacheNamespace.GetLockKey(key);

                Retry.UntilTrue(() =>
                {
                    var lockData = new LockData(
                        key: Convert.ToString(key),
                        lockKey: lockKey,
                        lockValue: GetLockValue()
                        );

                    var db           = GetDatabase();
                    var wasLockTaken = db.LockTake(lockData.LockKey, lockData.LockValue, lockTimeout);

                    if (wasLockTaken)
                    {
                        // It's ok to use Set() instead of Add() because the
                        // lock in Redis will cause other clients to wait.
                        acquiredLocks.Set(lockData.Key, lockData, absoluteExpiration: DateTime.UtcNow.Add(lockTimeout));
                    }

                    return(wasLockTaken);
                }, lockTimeout);
            }
            catch (Exception e)
            {
                log.ErrorFormat("could not acquire cache lock : {0}", key);

                var evtArg = new RedisCacheExceptionEventArgs(e);
                OnException(evtArg);
                if (evtArg.Throw)
                {
                    throw;
                }
            }
        }
Example #28
0
        /// <summary>
        /// SQL文の抽出条件からロックを作成する
        /// </summary>
        /// <typeparam name="TRecord"></typeparam>
        /// <param name="apTranId">APトランザクションID</param>
        /// <param name="sql">SQL文</param>
        /// <returns>作成したロックデータ</returns>
        /// <remarks></remarks>
        private List <LockData> CreateLockData <TRecord>(long apTranId
                                                         , SqlBuilder sql)
            where TRecord : class, IRecord, new()
        {
            List <LockData> ret = new List <LockData>();

            //TRecord型レコードとテーブルのマッピング情報を取得する
            RecordViewTableMap <TRecord> aRecordViewTableMap = _aRecordViewTableMapFactory.CreateRecordViewTableMap <TRecord>();
            //TRecord型レコードのメタ情報を取得する
            RecordInfo <TRecord> aRecordInfo = aRecordViewTableMap.GetRecordInfo();

            //テーブル列リストを作成する
            Dictionary <string, IEnumerable <string> > tableColumns = new Dictionary <string, IEnumerable <string> >();

            foreach (string srcTableName in sql.GetSrcTableNames())
            {
                //相関テーブルの主キーリストを作成する
                List <string> allColumnNames = new List <string>();
                foreach (ColumnInfo column in aRecordViewTableMap.GetTableInfo(srcTableName).GetAllColumns())
                {
                    allColumnNames.Add(column.ColumnName);
                }
                tableColumns.Add(srcTableName, allColumnNames);
            }

            //SQL文の抽出条件からロック情報を作成する
            foreach (KeyValuePair <SqlTable, Dictionary <string, string> > tableNameCnfPair in sql.GetCNF(tableColumns))
            {
                string srcTableName             = tableNameCnfPair.Key.Name;
                Dictionary <string, string> cnf = tableNameCnfPair.Value;
                LockData aLockData = this.CreateLockDataSub(aRecordViewTableMap
                                                            , apTranId
                                                            , aRecordInfo.Name
                                                            , srcTableName
                                                            , cnf);
                ret.Add(aLockData);
            }

            return(ret);
        }
Example #29
0
        public override void SetAndReleaseItemExclusive(HttpContext context,
                                                        string id,
                                                        SessionStateStoreData item,
                                                        object lockId,
                                                        bool newItem)
        {
            var redis         = GetRedisConnection();
            var getLock       = redis.Hashes.Get(0, lockHashKey, id);
            var lockIdAsBytes = (byte[])lockId;
            var ms            = new MemoryStream();
            var writer        = new BinaryWriter(ms);

            if (item.Items as SessionStateItemCollection != null)
            {
                ((SessionStateItemCollection)item.Items).Serialize(writer);
            }

            writer.Close();

            byte[] sessionData     = ms.ToArray();
            var    sessionItemHash = new Dictionary <string, byte[]>();

            sessionItemHash.Add("initialize", new byte[] { 0 });
            sessionItemHash.Add("data", sessionData);
            sessionItemHash.Add("timeoutMinutes", BitConverter.GetBytes(item.Timeout));

            LockData lockData;

            getLock.Wait();
            if (getLock.Result == null)
            {
                redis.Hashes.Set(0, GetKeyForSessionId(id), sessionItemHash, false);
            }
            else if (LockData.TryParse(getLock.Result, out lockData) && Enumerable.SequenceEqual(lockData.LockId, lockIdAsBytes))
            {
                redis.Hashes.Set(0, GetKeyForSessionId(id), sessionItemHash, false);
                redis.Hashes.Remove(0, lockHashKey, id);
            }
        }
Example #30
0
        private List <LockData> CreateLockDataFromRecord_new <TRecord>(long apTranId
                                                                       , TRecord aRecord
                                                                       , IEnumerable <SqlTable> usedTableNames)
            where TRecord : class, IRecord, new()
        {
            List <LockData> ret = new List <LockData>();

            //TRecord型レコードとテーブルのマッピング情報を取得する
            RecordViewTableMap <TRecord> aRecordViewTableMap = _aRecordViewTableMapFactory.CreateRecordViewTableMap <TRecord>();
            //TRecord型レコードのメタ情報を取得する
            RecordInfo <TRecord> aRecordInfo = aRecordViewTableMap.GetRecordInfo();

            foreach (KeyValuePair <SqlTable, Dictionary <string, SqlExpr> > kv in aRecordViewTableMap.GetCNFExpression(aRecord
                                                                                                                       , usedTableNames))
            {
                string tableName = kv.Key.Name;
                //CNFを作成する
                Dictionary <string, string> cnf = new Dictionary <string, string>();
                foreach (KeyValuePair <string, SqlExpr> eq in kv.Value)
                {
                    //CNFの素論理式はリテラル値への一致条件のみとする
                    if (eq.Value.IsLiteral)
                    {
                        cnf.Add(eq.Key, eq.Value.ToString());
                    }
                }

                //ロック情報を作成する
                LockData aLockData = this.CreateLockDataSub(aRecordViewTableMap
                                                            , apTranId
                                                            , aRecordInfo.Name
                                                            , tableName
                                                            , cnf);
                ret.Add(aLockData);
            }

            return(ret);
        }
        private bool TryAcquireLock(LockData lockData)
        {
            var db = GetDatabase();

            // Don't use IDatabase.LockTake() because we don't use the matching
            // LockRelease(). So, avoid any confusion. Besides, LockTake() just
            // calls this anyways.
            var wasLockAcquired = db.StringSet(lockData.LockKey, lockData.LockValue, lockTimeout, When.NotExists);

            if (wasLockAcquired)
            {
                // It's ok to use Set() instead of Add() because the lock in 
                // Redis will cause other clients to wait.
                acquiredLocks.Set(lockData.Key, lockData, absoluteExpiration: DateTime.UtcNow.Add(lockTimeout));
            }

            return wasLockAcquired;
        }
        public virtual void Lock(object key)
        {
            log.DebugFormat("acquiring cache lock: regionName='{0}', key='{1}'", RegionName, key);

            try
            {
                var lockKey = CacheNamespace.GetLockKey(key);
                var shouldRetry = options.AcquireLockRetryStrategy.GetShouldRetry();

                var wasLockAcquired = false;
                var shouldTryAcquireLock = true;
                
                while (shouldTryAcquireLock)
                {
                    var lockData = new LockData(
                        key: Convert.ToString(key),
                        lockKey: lockKey,
                        // Recalculated each attempt to ensure a unique value.
                        lockValue: options.LockValueFactory.GetLockValue()
                    );

                    if (TryAcquireLock(lockData))
                    {
                        wasLockAcquired = true;
                        shouldTryAcquireLock = false;
                    }
                    else
                    {
                        var shouldRetryArgs = new ShouldRetryAcquireLockArgs(
                            RegionName, lockData.Key, lockData.LockKey,
                            lockData.LockValue, lockTimeout, acquireLockTimeout
                        );
                        shouldTryAcquireLock = shouldRetry(shouldRetryArgs);
                    }
                }

                if (!wasLockAcquired)
                {
                    var lockFailedArgs = new LockFailedEventArgs(
                        RegionName, key, lockKey,
                        lockTimeout, acquireLockTimeout
                    );
                    options.OnLockFailed(this, lockFailedArgs);
                }
            }
            catch (Exception e)
            {
                log.ErrorFormat("could not acquire cache lock: regionName='{0}', key='{1}'", RegionName, key);

                var evtArg = new ExceptionEventArgs(RegionName, RedisCacheMethod.Lock, e);
                options.OnException(this, evtArg);
                if (evtArg.Throw)
                {
                    throw new RedisCacheException(RegionName, "Failed to lock item in cache. See inner exception.", e);
                }
            }
        }
 public static LockData New()
 {
     var data = new LockData();
     data.LockId = Guid.NewGuid().ToByteArray();
     data.LockUtcTime = DateTime.UtcNow;
     return data;
 }
 public static bool TryParse(byte[] raw, out LockData data)
 {
     if (raw != null && raw.Length > 1) {
         var lockId = raw.Take(16).ToArray();
         var lockTicks = BitConverter.ToInt64(raw, 17);
         data = new LockData {
             LockId = lockId,
             LockUtcTime = new DateTime(lockTicks)
         };
         return true;
     }
     data = new LockData();
     return false;
 }
        public virtual void Lock(object key)
        {
            log.DebugFormat("acquiring cache lock : {0}", key);

            try
            {
                var lockKey = CacheNamespace.GetLockKey(key);

                Retry.UntilTrue(() =>
                {
                    var lockData = new LockData(
                        key: Convert.ToString(key),
                        lockKey: lockKey,
                        lockValue: GetLockValue()
                    );

                    var db = GetDatabase();
                    var wasLockTaken = db.LockTake(lockData.LockKey, lockData.LockValue, lockTimeout);

                    if (wasLockTaken)
                    {
                        // It's ok to use Set() instead of Add() because the 
                        // lock in Redis will cause other clients to wait.
                        acquiredLocks.Set(lockData.Key, lockData, absoluteExpiration: DateTime.UtcNow.Add(lockTimeout));
                    }

                    return wasLockTaken;
                }, lockTimeout);
            }
            catch (Exception e)
            {
                log.ErrorFormat("could not acquire cache lock : {0}", key);

                var evtArg = new RedisCacheExceptionEventArgs(e);
                OnException(evtArg);
                if (evtArg.Throw) throw;
            }
        }