Beispiel #1
0
        public CloudLock(string lockName)
        {
            IKernel kernel = ServiceLocator.Current.GetInstance <IKernel>();

            BlobRepository = kernel.Get <IBlobRepository <CloudLockBlobData> >();
            Blob           = EnsureBlobExists(lockName);

            try
            {
                leaseId            = Blob.AcquireLease(TimeSpan.FromSeconds(30), Guid.NewGuid().ToString());
                LeaseRenewalThread = new Thread(() =>
                {
                    try
                    {
                        while (true)
                        {
                            Thread.Sleep(TimeSpan.FromSeconds(30));
                            Blob.ReleaseLease(new AccessCondition()
                            {
                                LeaseId = leaseId
                            });
                        }
                    }
                    catch (ThreadAbortException)
                    {
                    }
                });
                LeaseRenewalThread.Start();
            }
            catch (StorageException)
            {
                leaseId = null;
            }
        }
        private void AcquireBlobLease(LeaseTakingPolicy policy)
        {
            string ProposedLeaseId = Guid.NewGuid().ToString();
            bool   isDone          = false;

            // if policy == LeaseTakingPolicy.TryUntilSuccessful then loop indefinitely
            while (!isDone)
            {
                try
                {
                    LeaseId  = blob.AcquireLease(null, ProposedLeaseId);
                    HasLease = true;
                    isDone   = true;
                }
                catch (StorageException ex)
                {
                    HasLease = false;
                    if (StorageExceptionCode.Conflict(ex)) //Conflict
                    {
                        if (policy == LeaseTakingPolicy.TryOnce)
                        {
                            isDone = true;
                        }
                    }
                    else
                    {
                        ReleaseBlobLease();
                        throw;
                    }
                }
            }
        }
Beispiel #3
0
        public void RemoveBlobWithLease()
        {
            string             containerName = Utility.GenNameString("container");
            string             blobName      = Utility.GenNameString("blob");
            CloudBlobContainer container     = blobUtil.CreateContainer(containerName);

            try
            {
                ICloudBlob blob = blobUtil.CreatePageBlob(container, blobName);
                blob.AcquireLease(null, string.Empty);

                List <IListBlobItem> blobLists = container.ListBlobs(string.Empty, true, BlobListingDetails.All).ToList();
                Test.Assert(blobLists.Count == 1, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", containerName, 1, blobLists.Count));
                Test.Assert(!agent.RemoveAzureStorageBlob(blobName, containerName), Utility.GenComparisonData("Remove-AzureStorageBlob with lease", false));
                Test.Assert(agent.ErrorMessages[0].StartsWith("The remote server returned an error: (412)"), "The remove azure storage blob with lease should be failed");
                blobLists = container.ListBlobs(string.Empty, true, BlobListingDetails.All).ToList();
                Test.Assert(blobLists.Count == 1, string.Format("container {0} should contain {1} blobs, and actually it contain {2} blobs", containerName, 1, blobLists.Count));
                ICloudBlob remainBlob = blobLists[0] as ICloudBlob;
                Test.Assert(blob.Name == remainBlob.Name, string.Format("Blob name should be {0}, and actually it's {1}", blob.Name, remainBlob.Name));
                Test.Assert(remainBlob.Properties.LeaseStatus == LeaseStatus.Locked, "blob should be locked by lease");
            }
            finally
            {
                blobUtil.RemoveContainer(containerName);
            }
        }
        public async Task TestGetInstanceIdsOnEmptyBlob()
        {
            ICloudBlob blob = await CreateEmptyBlob();

            blob.AcquireLease(null, null);
            UpdateBlobWrapper updateBlobWrapper = await UpdateBlobWrapper.Create(blob);

            Assert.AreEqual(0, updateBlobWrapper.GetInstanceIds().Count);
        }
        public async Task TestGetUpdateDomainOnEmptyBlob()
        {
            ICloudBlob blob = await CreateEmptyBlob();

            blob.AcquireLease(null, null);
            UpdateBlobWrapper updateBlobWrapper = await UpdateBlobWrapper.Create(blob);

            Assert.AreEqual(0, updateBlobWrapper.GetUpdateDomain().Length);
        }
        public async Task TestThatSetDataFailsIfWrongLeaseIdIsGiven()
        {
            ICloudBlob blob = await CreateEmptyBlob();

            blob.AcquireLease(null, null);
            UpdateBlobWrapper updateBlobWrapper = await UpdateBlobWrapper.Create(blob);

            var instanceIds = new HashSet <string>(new[] { "instanceId1" });
            await updateBlobWrapper.SetData("wrongLeaseId", "1", instanceIds);
        }
        public async Task TestSetDataWithMultipleInstanceIds()
        {
            ICloudBlob blob = await CreateEmptyBlob();

            string            leaseId           = blob.AcquireLease(null, null);
            UpdateBlobWrapper updateBlobWrapper = await UpdateBlobWrapper.Create(blob);

            var instanceIds = new HashSet <string>(new[] { "instanceId1" });
            await updateBlobWrapper.SetData(leaseId, "1", instanceIds);

            Assert.AreEqual("1", updateBlobWrapper.GetUpdateDomain());
            Assert.IsTrue(instanceIds.SetEquals(updateBlobWrapper.GetInstanceIds()));
        }
        public async Task TestThatSetDataOverwritesExistingContent()
        {
            ICloudBlob blob = await CreateEmptyBlob();

            string            leaseId           = blob.AcquireLease(null, null);
            UpdateBlobWrapper updateBlobWrapper = await UpdateBlobWrapper.Create(blob);

            await updateBlobWrapper.SetData(leaseId, "1", new[] { "instanceId1" });

            await updateBlobWrapper.SetData(leaseId, "2", new[] { "instanceId2" });

            Assert.AreEqual("2", updateBlobWrapper.GetUpdateDomain());
            Assert.IsTrue(new HashSet <string>(new[] { "instanceId2" }).SetEquals(updateBlobWrapper.GetInstanceIds()));
        }
        public async Task TestSetDataWhenBlobIsEmpty()
        {
            ICloudBlob blob = await CreateEmptyBlob();

            string            leaseId           = blob.AcquireLease(null, null);
            UpdateBlobWrapper updateBlobWrapper = await UpdateBlobWrapper.Create(blob);

            const string instanceId   = "instanceId";
            const string updateDomain = "1";
            await updateBlobWrapper.SetData(leaseId, updateDomain, new[] { instanceId });

            Assert.AreEqual(updateDomain, updateBlobWrapper.GetUpdateDomain());
            Assert.IsTrue(new HashSet <string>(new[] { instanceId }).SetEquals(updateBlobWrapper.GetInstanceIds()));
        }
Beispiel #10
0
        /// <summary>
        /// Lease configuration container responsible for this blob along with blobs in the containers
        /// </summary>
        /// <param name="blobName">Particular blobs we would like to lease</param>
        /// <param name="containerElementSet">list of containers</param>
        /// <param name="putOptimization">perform put optimization. I.e., for put operations, it is not required to take lease if there is only one primary.</param>
        public PrimaryCloudBlobLease(string blobName, ReplicaConfiguration configuration, bool putOptimization = false)
        {
            if ((putOptimization) && configuration.PrimaryServers.Count == 1)
            {
                //There is only one primary. No need to
                HasLease = true;
                return;
            }

            leasedBlobs = new Dictionary <ICloudBlob, string>();
            //Reconfiguration is not going to happen in near future.
            //We can safely take leases of primary blobs.
            this.ProposedLeaseId = Guid.NewGuid().ToString();

            foreach (string serverName in configuration.PrimaryServers)
            {
                try
                {
                    ICloudBlob blob = ClientRegistry.GetCloudBlob(serverName, configuration.Name, blobName);
                    if (!blob.Exists())
                    {
                        //we cannot take lease on a non-existing blob.
                        //Hence, we create it first.
                        byte[] dummy = new byte[1];
                        dummy[0] = (byte)0;
                        var ms = new MemoryStream(dummy);
                        blob.UploadFromStream(ms, null, null, null);
                    }
                    string leaseID = blob.AcquireLease(null, ProposedLeaseId);
                    leasedBlobs.Add(blob, leaseID);
                }
                catch (StorageException ex)
                {
                    releaseContainers();
                    leasedBlobs.Clear();
                    HasLease = false;
                    if (ex.GetBaseException().Message.Contains("409")) //Conflict
                    {
                        return;
                    }
                    else
                    {
                        throw ex;
                    }
                }
            }
            HasLease = true;
        }
Beispiel #11
0
        public bool IsLocked(string _lockFile)
        {
            ICloudBlob blob     = this.blobContainer.GetBlobReferenceFromServer(_lockFile);
            string     _leaseid = null;

            if (this.leases.ContainsKey(_lockFile))
            {
                _leaseid = this.leases[_lockFile];
            }
            try {
                Debug.Print("IsLocked() : {0}", _leaseid);
                if (string.IsNullOrEmpty(_leaseid))
                {
                    string tempLease = blob.AcquireLease(TimeSpan.FromSeconds(60), _leaseid);
                    if (string.IsNullOrEmpty(tempLease))
                    {
                        Debug.Print("IsLocked() : TRUE");
                        return(true);
                    }
                    blob.ReleaseLease(new AccessCondition()
                    {
                        LeaseId = tempLease
                    });
                }
                Debug.Print("IsLocked() : {0}", _leaseid);
                return(string.IsNullOrEmpty(_leaseid));
            } catch (StorageException webErr) {
                if (this._handleWebException(blob, webErr, _lockFile))
                {
                    return(this.IsLocked(_lockFile));
                }
            }

            /*catch (StorageClientException err) {
             *      if (_handleStorageClientException(blob, err)) {
             *              return IsLocked(_lockFile);
             *      }
             * }*/
            _leaseid = null;
            return(false);
        }
 /// <summary>
 /// Puts the lease on the given blob in a leased state.
 /// </summary>
 /// <param name="blob">The blob with the lease.</param>
 /// <param name="leaseTime">The amount of time on the new lease.</param>
 /// <returns>The lease ID of the current lease.</returns>
 internal static string SetLeasedState(ICloudBlob blob, TimeSpan? leaseTime)
 {
     string leaseId = Guid.NewGuid().ToString();
     SetAvailableState(blob);
     return blob.AcquireLease(leaseTime, leaseId);
 }