Пример #1
0
        public void ReleaseLock(Guid sessionId)
        {
            if (sessionId == default)
            {
                throw new ArgumentException("Invalid sessionId");
            }

            var request = new LockRequest
            {
                SessionId = sessionId,
                Unlock    = true,
            };

            var response = Channel.SendRequest(request);

            if (response is LockResponse)
            {
                return;
            }

            if (response is ExceptionResponse exResponse)
            {
                throw new CacheException("Error while writing an object to the cache", exResponse.Message,
                                         exResponse.CallStack);
            }

            throw new CacheException("Unexpected response type for AcquireLock");
        }
Пример #2
0
        public LockResponse Lock(LockRequest request)
        {
            var req = request.ToProto();
            var rsp = client.Lock(req);

            return(rsp.FromProto());
        }
Пример #3
0
        internal bool TryAcquireLock(Guid sessionId, bool writeAccess, params string[] collections)
        {
            if (collections.Length == 0)
            {
                throw new ArgumentException("Value cannot be an empty collection.", nameof(collections));
            }


            var request = new LockRequest
            {
                SessionId = sessionId,
                WaitDelayInMilliseconds = 20,
                WriteMode         = writeAccess,
                CollectionsToLock = new List <string>(collections)
            };

            var response = Channel.SendRequest(request);


            if (response is LockResponse lockResponse)
            {
                return(lockResponse.Success);
            }

            if (response is ExceptionResponse exResponse)
            {
                throw new CacheException("Error while trying to acquire lock", exResponse.Message,
                                         exResponse.CallStack);
            }

            throw new CacheException("Unexpected response type for AcquireLock");
        }
Пример #4
0
        public override async Task <WopiResponse> Lock(LockRequest lockRequest)
        {
            var userId = WopiSecurity.GetIdentityNameFromToken(lockRequest.AccessToken);

            var wopiFileRepository = new WopiFileRepository();
            var response           = await wopiFileRepository.LockFile(lockRequest.ResourceId, userId, lockRequest.Lock, null);

            if (response.Item1 == HttpStatusCode.BadRequest)
            {
                return(lockRequest.ResponseBadRequest());
            }
            // Check for file not found or no permissions
            else if (response.Item1 == HttpStatusCode.NotFound)
            {
                return(lockRequest.ResponseNotFound());
            }
            // Ensure the file isn't already locked
            else if (response.Item1 == HttpStatusCode.Conflict)
            {
                return(lockRequest.ResponseLockConflict(response.Item2));
            }
            // File successfully locked
            else if (response.Item1 == HttpStatusCode.OK)
            {
                return(lockRequest.ResponseOK(response.Item3));
            }
            else
            {
                return(lockRequest.ResponseServerError(string.Format("Unknown HTTPStatusCode from WopiFileRepository.LockFile: {0}", response.Item1)));
            }
        }
Пример #5
0
        private void ProcessLockRequest(LockRequest lockRequest, IClient client)
        {
            var lockManager = _serviceContainer.LockManager;

            try
            {
                if (lockRequest.Unlock)
                {
                    lockManager.CloseSession(lockRequest.SessionId);
                    client.SendResponse(new LockResponse {
                        Success = true
                    });
                }
                else
                {
                    bool lockAcquired = lockManager.TryAcquireReadLock(lockRequest.SessionId, Constants.DelayForLockInMilliseconds,
                                                                       lockRequest.CollectionsToLock.ToArray());

                    client.SendResponse(new LockResponse {
                        Success = lockAcquired
                    });
                }
            }
            catch (Exception e)
            {
                client.SendResponse(new ExceptionResponse(e));
            }
        }
Пример #6
0
        public virtual string Describe()
        {
            lock (this)
            {
                StringBuilder sb = new StringBuilder(this.ToString());
                sb.Append(" Total lock count: readCount=").Append(_totalReadCount).Append(" writeCount=").Append(_totalWriteCount).Append(" for ").Append(_resource).Append("\n").Append("Waiting list:" + "\n");
                IEnumerator <LockRequest> wElements = _waitingThreadList.GetEnumerator();
                while (wElements.MoveNext())
                {
                    LockRequest lockRequest = wElements.Current;
                    sb.Append("[").Append(lockRequest.WaitingThread).Append("(").Append(lockRequest.Element.readCount).Append("r,").Append(lockRequest.Element.writeCount).Append("w),").Append(lockRequest.LockType).Append("]\n");
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                    if (wElements.hasNext())
                    {
                        sb.Append(",");
                    }
                }

                sb.Append("Locking transactions:\n");
                foreach (TxLockElement tle in _txLockElementMap.Values)
                {
                    sb.Append(tle.Tx).Append("(").Append(tle.ReadCount).Append("r,").Append(tle.WriteCount).Append("w)\n");
                }
                return(sb.ToString());
            }
        }
Пример #7
0
        public virtual bool LogTo(Logger logger)
        {
            lock (this)
            {
                logger.Log("Total lock count: readCount=" + _totalReadCount + " writeCount=" + _totalWriteCount + " for " + _resource);

                logger.Log("Waiting list:");
                IEnumerator <LockRequest> wElements = _waitingThreadList.GetEnumerator();
                while (wElements.MoveNext())
                {
                    LockRequest lockRequest = wElements.Current;
                    logger.Log("[" + lockRequest.WaitingThread + "(" + lockRequest.Element.readCount + "r," + lockRequest.Element.writeCount + "w)," + lockRequest.LockType + "]");
//JAVA TO C# CONVERTER TODO TASK: Java iterators are only converted within the context of 'while' and 'for' loops:
                    if (wElements.hasNext())
                    {
                        logger.Log(",");
                    }
                    else
                    {
                        logger.Log("");
                    }
                }

                logger.Log("Locking transactions:");
                foreach (TxLockElement tle in _txLockElementMap.Values)
                {
                    logger.Log("" + tle.Tx + "(" + tle.ReadCount + "r," + tle.WriteCount + "w)");
                }
                return(true);
            }
        }
        public static bool Prefix(DockedVehicleHandTarget __instance, GUIHand hand)
        {
            Vehicle vehicle = __instance.dockingBay.GetDockedVehicle();

            if (skipPrefix || vehicle == null)
            {
                return(true);
            }

            SimulationOwnership simulationOwnership = NitroxServiceLocator.LocateService <SimulationOwnership>();

            NitroxId id = NitroxEntity.GetId(vehicle.gameObject);

            if (simulationOwnership.HasExclusiveLock(id))
            {
                Log.Debug($"Already have an exclusive lock on this vehicle: {id}");
                return(true);
            }

            HandInteraction <DockedVehicleHandTarget> context = new HandInteraction <DockedVehicleHandTarget>(__instance, hand);
            LockRequest <HandInteraction <DockedVehicleHandTarget> > lockRequest = new LockRequest <HandInteraction <DockedVehicleHandTarget> >(id, SimulationLockType.EXCLUSIVE, ReceivedSimulationLockResponse, context);

            simulationOwnership.RequestSimulationLock(lockRequest);

            return(false);
        }
Пример #9
0
        /// <summary>
        /// LockAsync acquires a distributed shared lock on a given named lock.
        /// On success, it will return a unique key that exists so long as the
        /// lock is held by the caller. This key can be used in conjunction with
        /// transactions to safely ensure updates to etcd only occur while holding
        /// lock ownership. The lock is held until Unlock is called on the key or the
        /// lease associate with the owner expires.
        /// </summary>
        /// <param name="request">The request to send to the server</param>
        /// <returns></returns>
        public async Task <LockResponse> LockAsync(LockRequest request, Metadata headers = null)
        {
            LockResponse response   = new LockResponse();
            bool         success    = false;
            int          retryCount = 0;

            while (!success)
            {
                try
                {
                    response = await _balancer.GetConnection().lockClient.LockAsync(request, headers);

                    success = true;
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable)
                {
                    retryCount++;
                    if (retryCount >= _balancer._numNodes)
                    {
                        throw ex;
                    }
                }
            }
            return(response);
        }
Пример #10
0
        public LockResponse Lock(LockRequest request)
        {
            LockResponse response = new LockResponse();

            response.Errors = new List <BusinessRule>();

            User user = _repository
                        .FindBy(request.UserId);

            if (user != null)
            {
                try
                {
                    user.Status = 0;
                    _repository.Save(user);
                    _uow.Commit();

                    response.Result = true;
                }
                catch (Exception ex)
                {
                    response.Errors.Add(new BusinessRule("Error", ex.Message));
                    response.Result = false;
                }
            }
            else
            {
                response.Result = false;
            }

            return(response);
        }
Пример #11
0
        private static void ParseLockScope(LockRequest lockRequest, XContainer element)
        {
            if (element == null)
            {
                throw new ArgumentNullException("element");
            }
            if (null == lockRequest)
            {
                throw new ArgumentNullException("lockRequest");
            }
            var lockScope = GetElement(element, XmlNamespace + "lockscope");

            if (null == lockScope)
            {
                return;
            }
            var type = lockScope.Elements().ElementAt(0).ToString();

            switch (type)
            {
            case "exclusive":
                lockRequest.SetLockScope(LockScope.Exclusive);
                break;

            case "shared":
                lockRequest.SetLockScope(LockScope.Shared);
                break;

            default:
                lockRequest.SetLockScope(LockScope.Exclusive);
                break;
            }
        }
Пример #12
0
        /// <summary>
        /// Lock acquires a distributed shared lock on a given named lock.
        /// On success, it will return a unique key that exists so long as the
        /// lock is held by the caller. This key can be used in conjunction with
        /// transactions to safely ensure updates to etcd only occur while holding
        /// lock ownership. The lock is held until Unlock is called on the key or the
        /// lease associate with the owner expires.
        /// </summary>
        /// <param name="request">The request to send to the server</param>
        /// <param name="headers">The initial metadata to send with the call. This parameter is optional.</param>
        /// <param name="deadline">An optional deadline for the call. The call will be cancelled if deadline is hit.</param>
        /// <param name="cancellationToken">An optional token for canceling the call.</param>
        /// <returns>The response received from the server.</returns>
        public LockResponse Lock(LockRequest request, Grpc.Core.Metadata headers = null, DateTime?deadline = null,
                                 CancellationToken cancellationToken             = default)
        {
            LockResponse response   = new LockResponse();
            bool         success    = false;
            int          retryCount = 0;

            while (!success)
            {
                try
                {
                    response = _balancer.GetConnection().lockClient.Lock(request, headers, deadline, cancellationToken);
                    success  = true;
                }
                catch (RpcException ex) when(ex.StatusCode == StatusCode.Unavailable)
                {
                    retryCount++;
                    if (retryCount >= _balancer._numNodes)
                    {
                        throw;
                    }
                }
            }

            return(response);
        }
Пример #13
0
 public LockResponse Lock(LockRequest lockRequest)
 {
     return(apiService.SendAndConvert <LockResponse, LockRequest>(
                HttpMethod.Post,
                new Uri("api/lockable/lock"),
                lockRequest));
 }
Пример #14
0
        public override async Task <LockResponse> Lock(LockRequest request, ServerCallContext context)
        {
            await dispatcher.OnLock(ParseLockRequest(request));

            return(new LockResponse {
            });
        }
        public static bool Prefix(PilotingChair __instance, GUIHand hand)
        {
            if (skipPrefix)
            {
                return(true);
            }

            SimulationOwnership simulationOwnership = NitroxServiceLocator.LocateService <SimulationOwnership>();

            SubRoot subRoot = __instance.GetComponentInParent <SubRoot>();

            Validate.NotNull(subRoot, "PilotingChair cannot find it's corresponding SubRoot!");
            NitroxId id = NitroxEntity.GetId(subRoot.gameObject);

            if (simulationOwnership.HasExclusiveLock(id))
            {
                Log.Debug($"Already have an exclusive lock on the piloting chair: {id}");
                return(true);
            }

            HandInteraction <PilotingChair> context = new HandInteraction <PilotingChair>(__instance, hand);
            LockRequest <HandInteraction <PilotingChair> > lockRequest = new LockRequest <HandInteraction <PilotingChair> >(id, SimulationLockType.EXCLUSIVE, ReceivedSimulationLockResponse, context);

            simulationOwnership.RequestSimulationLock(lockRequest);

            return(false);
        }
Пример #16
0
 private LockArguments ParseLockRequest(LockRequest request)
 {
     return(new LockArguments {
         PartitionId = request.PartitionId,
         ObjectId = request.ObjectId
     });
 }
Пример #17
0
        public override Task <LockResponse> lockServer(LockRequest request, ServerCallContext context)
        {
            Console.WriteLine("Locking the server to write" +
                              request.ObjectId + " in partition " +
                              request.PartitionId
                              );

            try {
                var partitionId = request.PartitionId;
                var objectId    = request.ObjectId;
                var partition   = _storage.Partitions[partitionId];

                BaseServerObjectInfo objectInfo;
                lock (partition.Objects) {
                    if (!partition.Objects.TryGetValue(objectId, out objectInfo))
                    {
                        partition.Objects.Add(objectId, objectInfo = new BaseServerObjectInfo("NA"));
                    }
                }

                objectInfo._lock.Set(); //unlock is called inside partition write slave
            }
            catch (Exception e) {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return(Task.FromResult(new LockResponse {
                    Acknowledge = "NOK"
                }));
            }

            return(Task.FromResult(new LockResponse {
                Acknowledge = "Ok"
            }));
        }
        public bool LockUser(Guid userId)
        {
            LockRequest request = new LockRequest();

            request.UserId = userId;
            return(_membershipService.Lock(request).Result);
        }
Пример #19
0
        // in case of spurious wake up, deadlock during spurious wake up, termination
        // when we already have request in a queue we need to clean it up
        private void CleanupWaitingListRequests(LockRequest lockRequest, TxLockElement lockElement, bool addLockRequest)
        {
            if (lockRequest != null && (lockElement.Terminated || !addLockRequest))
            {
//JAVA TO C# CONVERTER TODO TASK: There is no .NET LinkedList equivalent to the Java 'remove' method:
                _waitingThreadList.remove(lockRequest);
            }
        }
Пример #20
0
 public override Task <LockReply> LockServers(LockRequest request, ServerCallContext context)
 {
     WaitUnfreeze();
     _gigaStorage.Lock(request.PartitionId, request.ObjectId);
     return(Task.FromResult(new LockReply
     {
         // Empty message as ack
     }));
 }
Пример #21
0
        private async Task CheckLockStatus(LockRequest request)
        {
            var currentLock = await _expiringDataStore.Get <Lock>(request.ResourceId);

            if (currentLock.IsNotNullOrDefault() && !currentLock.Equals(new Lock()) && !currentLock.IsInactive())
            {
                var errorMessage = $"Resource is already locked by {currentLock.LockHolderId} until: {currentLock.Expiry}";
                throw new RpcException(new Status(StatusCode.AlreadyExists, errorMessage), errorMessage);
            }
        }
        /// <summary>
        /// Sets the sites.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public LockResponse SetLock(LockRequest request)
        {
            var response = new LockResponse();

            if (request.LoadOptions.Contains("ExcuteLock"))
            {
                response.Message = LockDao.ExcuteUnLock(request.Lock);
            }

            return(response);
        }
Пример #23
0
        private async Task <LockToken> TakeLock(LockRequest lockRequest)
        {
            var lockToken = await _lockProvider.TakeLock(lockRequest.ResourceId, lockRequest.HoldSeconds * 1000);

            if (!lockToken.GotLock)
            {
                throw new RpcException(new Status(StatusCode.AlreadyExists, "Resource is already locked."), "Resource is already locked.");
            }

            return(lockToken);
        }
Пример #24
0
        private LockReply ExecuteLock(LockRequest request)
        {
            Console.WriteLine($"Lock request -> PartitionId: {request.ObjectIdentifier.PartitionId} ObjectId: {request.ObjectIdentifier.ObjectId}");
            GStoreObjectIdentifier gStoreObjectIdentifier = new GStoreObjectIdentifier(request.ObjectIdentifier.PartitionId, request.ObjectIdentifier.ObjectId);
            int lockId = gStore.Lock(gStoreObjectIdentifier);

            return(new LockReply
            {
                LockId = lockId
            });
        }
Пример #25
0
 /// <summary>
 /// Lock acquires a distributed shared lock on a given named lock.
 /// On success, it will return a unique key that exists so long as the
 /// lock is held by the caller. This key can be used in conjunction with
 /// transactions to safely ensure updates to etcd only occur while holding
 /// lock ownership. The lock is held until Unlock is called on the key or the
 /// lease associate with the owner expires.
 /// </summary>
 /// <param name="request">The request to send to the server</param>
 /// <returns></returns>
 public LockResponse Lock(LockRequest request)
 {
     try
     {
         return(_lockClient.Lock(request, _headers));
     }
     catch (RpcException)
     {
         ResetConnection();
         throw;
     }
 }
Пример #26
0
 /// <summary>
 /// LockAsync acquires a distributed shared lock on a given named lock.
 /// On success, it will return a unique key that exists so long as the
 /// lock is held by the caller. This key can be used in conjunction with
 /// transactions to safely ensure updates to etcd only occur while holding
 /// lock ownership. The lock is held until Unlock is called on the key or the
 /// lease associate with the owner expires.
 /// </summary>
 /// <param name="request">The request to send to the server</param>
 /// <returns></returns>
 public async Task <LockResponse> LockAsync(LockRequest request)
 {
     try
     {
         return(await _lockClient.LockAsync(request, _headers));
     }
     catch (RpcException)
     {
         ResetConnection();
         throw;
     }
 }
Пример #27
0
        public override Task <LockReply> Lock(LockRequest req, ServerCallContext _)
        {
            man.CheckFreeze();
            try {
                store.Lock(req.IdPart, req.IdObj);
            } catch (DomainException e) {
                throw new GRPCException(StatusCode.NotFound, e.Message);
            }

            Lib.Sleep(new Random().Next(minDelay, maxDelay));
            return(Task.FromResult(new LockReply()));
        }
Пример #28
0
 public ActionResult LockItem([FromBody] LockRequest lockRequest)
 {
     try
     {
         _lockService.Lock(lockRequest.ItemId, lockRequest.UserId);
         return(Ok());
     }
     catch (Exception e)
     {
         return(BadRequest(e.GetBaseException().Message));
     }
 }
 public IActionResult Lock([Required, StateNameValidator] string name, [FromBody, Required] LockRequest lockRequest)
 {
     try
     {
         database.TransactionalLock(name, lockRequest);
         return(Ok());
     }
     catch (StateLockedException ex)
     {
         Response.StatusCode = 409;
         return(Content(ex.LockData, "application/json"));
     }
 }
Пример #30
0
 // Method to facilitate Lock Requests to other servers with threads
 public async Task ThreadLockAsync(int t, string server, LockRequest lockRequest)
 {
     try
     {
         await _clients[server].LockServersAsync(lockRequest);
     }
     catch
     {
         // If fails then the server is down
         DeadServerReport(server);
     }
     _handles[t].Set();
 }
Пример #31
0
        /// <summary>
        /// Lock an envelope. Locks the specified envelope, and sets the time until the lock expires, to prevent other users or recipients from accessing and changing the envelope.\n\nNote: Users must have envelope locking capability enabled to use this function (userSetting `canLockEnvelopes` must be  set to true for the user).
        /// </summary>
	    ///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="envelopeId">The envelopeId Guid of the envelope being accessed.</param> <param name="lockRequest">TBD Description</param>
		/// <returns>8Task of ApiResponse (LockInformation)</returns>
        public async System.Threading.Tasks.Task<ApiResponse<LockInformation>> CreateLockAsyncWithHttpInfo (string accountId, string envelopeId, LockRequest lockRequest)
        {
            // verify the required parameter 'accountId' is set
            if (accountId == null) throw new ApiException(400, "Missing required parameter 'accountId' when calling CreateLock");
            // verify the required parameter 'envelopeId' is set
            if (envelopeId == null) throw new ApiException(400, "Missing required parameter 'envelopeId' when calling CreateLock");
            
    
            var path_ = "/v2/accounts/{accountId}/envelopes/{envelopeId}/lock";
    
            var pathParams = new Dictionary<String, String>();
            var queryParams = new Dictionary<String, String>();
            var headerParams = new Dictionary<String, String>(Configuration.DefaultHeader);
            var formParams = new Dictionary<String, String>();
            var fileParams = new Dictionary<String, FileParameter>();
            String postBody = null;

            // to determine the Accept header
            String[] http_header_accepts = new String[] {
                "application/json"
            };
            String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts);
            if (http_header_accept != null)
                headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts));

            // set "format" to json by default
            // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json
            pathParams.Add("format", "json");
            if (accountId != null) pathParams.Add("accountId", Configuration.ApiClient.ParameterToString(accountId)); // path parameter
            if (envelopeId != null) pathParams.Add("envelopeId", Configuration.ApiClient.ParameterToString(envelopeId)); // path parameter
            

						
			
			

            
            
            postBody = Configuration.ApiClient.Serialize(lockRequest); // http body (model) parameter
            

            

            // make the HTTP request
            IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams);

            int statusCode = (int) response.StatusCode;
 
            if (statusCode >= 400)
                throw new ApiException (statusCode, "Error calling CreateLock: " + response.Content, response.Content);
            else if (statusCode == 0)
                throw new ApiException (statusCode, "Error calling CreateLock: " + response.ErrorMessage, response.ErrorMessage);

            return new ApiResponse<LockInformation>(statusCode,
                response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
                (LockInformation) Configuration.ApiClient.Deserialize(response, typeof(LockInformation)));
            
        }
Пример #32
0
        /// <summary>
        /// Lock an envelope. Locks the specified envelope, and sets the time until the lock expires, to prevent other users or recipients from accessing and changing the envelope.\n\nNote: Users must have envelope locking capability enabled to use this function (userSetting `canLockEnvelopes` must be  set to true for the user).
        /// </summary>
 	    ///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="envelopeId">The envelopeId Guid of the envelope being accessed.</param> <param name="lockRequest">TBD Description</param>
		/// <returns>7Task of LockInformation</returns>
        public async System.Threading.Tasks.Task<LockInformation> CreateLockAsync (string accountId, string envelopeId, LockRequest lockRequest)
        {
             ApiResponse<LockInformation> response = await CreateLockAsyncWithHttpInfo(accountId, envelopeId, lockRequest);
             return response.Data;

        }
Пример #33
0
        /// <summary>
        /// Lock an envelope. Locks the specified envelope, and sets the time until the lock expires, to prevent other users or recipients from accessing and changing the envelope.\n\nNote: Users must have envelope locking capability enabled to use this function (userSetting `canLockEnvelopes` must be  set to true for the user).
        /// </summary>
 	    ///<param name="accountId">The external account number (int) or account ID Guid.</param><param name="envelopeId">The envelopeId Guid of the envelope being accessed.</param> <param name="lockRequest">TBD Description</param>
		/// <returns>5LockInformation</returns>
        public LockInformation CreateLock (string accountId, string envelopeId, LockRequest lockRequest)
        {
             ApiResponse<LockInformation> response = CreateLockWithHttpInfo(accountId, envelopeId, lockRequest);
             return response.Data;
        }