Exemple #1
0
 /// <summary>
 /// Informs that a frontend has connected
 /// </summary>
 /// <param name="instance">indicating the frontend instance</param>
 public void FrontendConnected(object instance, object frontend)
 {
     BrokerTracing.TraceInfo("[BrokerClient] Client {0}: Frontend connected: {1} ({2}).", this.clientId, instance.ToString(), instance.GetHashCode());
     lock (this.connectedInstance)
     {
         this.connectedInstance.Add(instance, frontend);
     }
 }
 /// <summary>
 /// Initializes a new instance of the BrokerStateManager class
 /// </summary>
 /// <param name="sharedData">indicating the shared data</param>
 /// <param name="clientAvaliable">indicating whether there is client avaliable when starting up</param>
 public BrokerStateManager(SharedData sharedData, bool clientAvaliable)
 {
     this.sharedData     = sharedData;
     this.timeoutManager = new TimeoutManager("BrokerStateManager");
     this.state          = BrokerState.Started;
     this.timeoutManager.RegisterTimeout(this.sharedData.Config.Monitor.ClientConnectionTimeout, clientAvaliable ? new WaitCallback(this.TimeoutToSuspended) : new WaitCallback(this.TimeoutToFinish), null);
     BrokerTracing.TraceInfo("[BrokerStateManager] Successfully initialized BrokerStateManager: State = {0}", this.state);
 }
        /// <summary>
        /// Dispose the instance
        /// </summary>
        protected override void DisposeInternal()
        {
            BrokerTracing.TraceVerbose("[AzureServiceClient]. DisposeInternal: Dispose client {0}.", this);

            base.DisposeInternal();

            this.AsyncClose();
        }
        /// <summary>
        /// Invoke the cached callback for specified request queue, which is
        /// deleted when session is running.
        /// </summary>
        /// <param name="requestQueueName">
        /// request queue name
        /// </param>
        /// <param name="e">
        /// exception occurred when access the request queue
        /// </param>
        private void TriggerCallbackForInvalidRequestQueue(string requestQueueName, StorageException e)
        {
            BrokerTracing.TraceWarning(
                "[AzureQueueManager].TriggerCallbackForInvalidRequestQueue: Handle the invalid request queue {0}",
                requestQueueName);

            this.TriggerCallback(this.requestsMappingToRequestQueue, requestQueueName, e);
        }
Exemple #5
0
        /// <summary>
        /// Triggered when a client is disconnected
        /// </summary>
        /// <param name="sender">indicating the client</param>
        /// <param name="e">indicating the event args</param>
        private void Client_ClientDisconnected(object sender, EventArgs e)
        {
            BrokerClient client = sender as BrokerClient;

            Debug.Assert(client != null, "[BrokerClientManager] ClientDisconnected Event: Sender should be the BrokerClient type.");
            BrokerTracing.TraceVerbose("[BrokerClientManager] Remove client {0}", client.ClientId);
            this.RemoveClient(client, false);
        }
        public static async Task RestoreRequest(
            CloudQueue requestQueue,
            CloudQueue pendingQueue,
            CloudTable responseTable,
            CloudBlobContainer container)
        {
            try
            {
                while (true)
                {
                    var message = await pendingQueue.PeekMessageAsync();

                    if (message == null)
                    {
                        break;
                    }

                    var messageId =
                        ((BrokerQueueItem)formatter.Deserialize(await GetMsgBody(container, message.AsBytes))).Message
                        .Headers.MessageId.ToString();
                    BrokerTracing.TraceVerbose(
                        "[AzureStorageTool] .CheckRequestQueue: queueName = {0}, cloudMessageId = {1}, messageId = {2}",
                        pendingQueue.Name,
                        message.Id,
                        messageId);
                    var query = new TableQuery <TableEntity>().Where("MessageId eq '" + messageId + "'");
                    var list  = responseTable.ExecuteQuery(query).ToList();
                    if (list.Count > 0)
                    {
                        await pendingQueue.DeleteMessageAsync(await pendingQueue.GetMessageAsync());
                    }
                    else
                    {
                        // Add msg to request queue & delete it from pending queue.
                        message = await pendingQueue.GetMessageAsync();

                        await requestQueue.AddMessageAsync(new CloudQueueMessage(message.AsBytes));

                        await pendingQueue.DeleteMessageAsync(message);

                        BrokerTracing.TraceVerbose(
                            "[AzureStorageTool] .CheckRequestQueue: messageId = {0} is restored into request queue.",
                            messageId);
                    }
                }
            }
            catch (Exception e)
            {
                BrokerTracing.TraceError(
                    "[AzureStorageTool] .CheckRequestQueue: queueName={0}, responseTable={1}, the exception, {2}",
                    pendingQueue.Name,
                    responseTable.Name,
                    e);
                throw;
            }

            await requestQueue.FetchAttributesAsync();
        }
        /// <summary>
        /// Mark the dispatchers being preempted to stop
        /// </summary>
        /// <param name="coresToRelease">the cores to release</param>
        /// <param name="plannedToShutdownTaskIds">the task ids planned to be shutdown</param>
        private void MarkStoppingFlags(IEnumerable <string> plannedToShutdownTaskIds, IEnumerable <string> exitingTaskIds)
        {
            BrokerTracing.TraceVerbose(
                "[GracefulPreemptionHandler].MarkStoppingFlags: stop the ExitIfPossible dispatchers, total count = {0}",
                exitingTaskIds.Count());

            // Occupied too much resource, stop the prefetch to release.
            this.dispatcherManager.StopDispatchers(exitingTaskIds.Union(plannedToShutdownTaskIds), null);
        }
        /// <summary>
        /// Dispose this MSMQMessageFetcher instance.
        /// </summary>
        public void SafeDispose()
        {
            BrokerTracing.TraceVerbose("[MSMQMessageFetcher] .SafeDispose.");

            //
            // SafeDispose:
            // 1. mark this instance as disposed
            // 2. wait for all outstanding BeginPeek operations back, and then dispose the cursor.
            //
            if (!this.isDisposedField)
            {
                this.isDisposedField = true;
                // dispose prefetched messages
                this.lockPrefetchCache.EnterWriteLock();
                try
                {
                    if (this.prefetchCache != null)
                    {
                        // below line of code is put inside of prefetchCache lock scope just to ensure it's executed only once
                        this.msmqQueueField.Disposed -= this.OnQueueDisposed;

                        if (!this.prefetchCache.IsEmpty)
                        {
                            BrokerTracing.TraceWarning("[MSMQMessageFetcher] .SafeDispose: PrefetchCache is not empty when disposing.");
                        }

                        foreach (MessageResult result in this.prefetchCache)
                        {
                            if (result.Message != null)
                            {
                                result.Message.Dispose();
                            }
                        }

                        this.prefetchCache = null;
                    }
                }
                finally
                {
                    this.lockPrefetchCache.ExitWriteLock();
                }

                this.rwlockMessagePeekCursorField.EnterWriteLock();
                try
                {
                    if (this.messagePeekCursorField != null)
                    {
                        this.messagePeekCursorField.Release();
                        this.messagePeekCursorField = null;
                    }
                }
                finally
                {
                    this.rwlockMessagePeekCursorField.ExitWriteLock();
                }
            }
        }
        /// <summary>
        /// Gets the instance of scheduler adapter client
        /// </summary>
        /// <returns>returns the instance of the scheduler adapter client</returns>
        public async Task <ISchedulerAdapter> GetSchedulerAdapterClientAsync()
        {
            // this.CheckClient();
            bool newClientCreated       = false;
            ICommunicationObject client = this.schedulerAdapterClient as ICommunicationObject;

            if (this.schedulerAdapterClient == null || client == null || client.State == CommunicationState.Faulted)
            {
                await this.createClientSS.WaitAsync();

                try
                {
                    if (this.schedulerAdapterClient == null)
                    {
                        await this.CreateClient();

                        if (!SoaCommonConfig.WithoutSessionLayer)
                        {
                            newClientCreated = true;
                        }
                    }
                    else
                    {
                        client = this.schedulerAdapterClient as ICommunicationObject;
                        if (client == null || client.State == CommunicationState.Faulted)
                        {
                            try
                            {
                                Utility.AsyncCloseICommunicationObject(client);
                                await this.CreateClient();

                                if (!SoaCommonConfig.WithoutSessionLayer)
                                {
                                    newClientCreated = true;
                                }
                            }
                            catch (Exception e)
                            {
                                // Swallow exception when creating client
                                BrokerTracing.TraceError("[SchedulerAdapterClientFactory] Exception thrown when creating client: {0}", e);
                            }
                        }
                    }
                }
                finally
                {
                    this.createClientSS.Release();
                }

                if (newClientCreated)
                {
                    await this.monitor.RegisterJob();
                }
            }

            return(this.schedulerAdapterClient);
        }
        /// <summary>
        /// Async Pattern
        /// Begin method for ProcessMessage
        /// </summary>
        /// <param name="request">request message</param>
        /// <param name="callback">async callback</param>
        /// <param name="asyncState">async state</param>
        /// <returns>async result</returns>
        public IAsyncResult BeginProcessMessage(Message request, AsyncCallback callback, object asyncState)
        {
            //
            // if the connection is not ready (waitone timeout), let following BeginProcessMessage method throw exception.
            //

            BrokerTracing.TraceVerbose("[AzureServiceClient]. BeginProcessMessage: Send message at client {0}.", this);
            return(this.ServiceClient.BeginProcessMessage(request, callback, asyncState));
        }
        /// <summary>
        /// Invoke the cached callback for specified target queue name.
        /// </summary>
        /// <param name="messageIdMapping">
        /// mapping from message Id to request/response name
        /// </param>
        /// <param name="queueName">
        /// target request/response queue name
        /// </param>
        /// <param name="e">
        /// exception occurred when access the queue
        /// </param>
        private void TriggerCallback(ConcurrentDictionary <UniqueId, string> messageIdMapping, string queueName, StorageException e)
        {
            BrokerTracing.TraceVerbose(
                "[AzureQueueManager].TriggerCallback: Handle the invalid queue {0}",
                queueName);

            while (messageIdMapping.Values.Contains <string>(queueName, StringComparer.InvariantCultureIgnoreCase))
            {
                List <UniqueId> messageIds = new List <UniqueId>();

                string tmpQueueName;

                foreach (UniqueId id in messageIdMapping.Keys)
                {
                    if (messageIdMapping.TryGetValue(id, out tmpQueueName))
                    {
                        if (string.Equals(queueName, tmpQueueName, StringComparison.InvariantCultureIgnoreCase))
                        {
                            messageIds.Add(id);
                        }
                    }
                }

                BrokerTracing.TraceVerbose(
                    "[AzureQueueManager].TriggerCallback: Invoke callback for {0} messages.",
                    messageIds.Count);

                foreach (UniqueId messageId in messageIds)
                {
                    QueueAsyncResult result;

                    if (this.callbacks.TryGetValue(messageId, out result))
                    {
                        BrokerTracing.TraceVerbose(
                            "[AzureQueueManager].TriggerCallback: Get callback for message {0} from callbacks.",
                            messageId);

                        // following method deletes callback and deletes message from mapping
                        this.CompleteCallback(result, null, e);
                    }
                    else
                    {
                        BrokerTracing.TraceWarning(
                            "[AzureQueueManager].TriggerCallback: Can not get callback for message {0} from callbacks.",
                            messageId);
                    }

                    if (!messageIdMapping.TryRemove(messageId, out tmpQueueName))
                    {
                        BrokerTracing.TraceWarning(
                            "[AzureQueueManager].TriggerCallback: Can not remove message {0} from mapping.",
                            messageId);
                    }
                }
            }
        }
Exemple #12
0
        /// <summary>
        /// Close the instance, primarily the underlying communictaion object.
        /// </summary>
        public void AsyncClose()
        {
            BrokerTracing.TraceEvent(
                TraceEventType.Verbose,
                0,
                "[ServiceClient].AsyncClose: Will close the client, client id {0}",
                this.guid);

            Utility.AsyncCloseICommunicationObject(this);
        }
        protected override void CloseClient()
        {
            if (this.Client == null)
            {
                BrokerTracing.TraceWarning("[AzureHttpsRequestSender] .CloseClient: Client is null.");
                return;
            }

            this.Client.Close();
        }
        /// <summary>
        /// Invoke the cached callback for specified response queue, which is
        /// deleted when session is running.
        /// </summary>
        /// <param name="e">
        /// exception occurred when access the queue
        /// </param>
        public void TriggerCallbackForInvalidResponseQueue(ResponseStorageException e)
        {
            BrokerTracing.TraceWarning(
                "[AzureQueueManager].TriggerCallbackForInvalidResponseQueue: Handle the invalid response queue {0}",
                e.ResponseStorageName);

            this.responseQueueNotFound.TryAdd(e.ResponseStorageName, e);

            this.TriggerCallback(this.requestsMappingToResponseQueue, e.ResponseStorageName, e);
        }
        /// <summary>
        /// Initializes a new instance of the AzureServiceClient class.
        /// </summary>
        /// <param name="binding">binding information</param>
        /// <param name="remoteAddress">remote address</param>
        public AzureServiceClient(Binding binding, EndpointAddress remoteAddress)
        {
            this.binding       = binding;
            this.remoteAddress = remoteAddress;

            this.serviceClient = new ServiceClient(this.binding, this.remoteAddress);
            BrokerTracing.TraceVerbose("[AzureServiceClient]. AzureServiceClient: Create a new client {0}", this.serviceClient.ToString());
            this.serviceClient.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            Utility.SetAzureClientCertificate(this.serviceClient.ChannelFactory.Credentials);
        }
Exemple #16
0
 /// <summary>
 /// Create a new instance of the ServiceClient class.
 /// </summary>
 /// <param name="binding">binding information</param>
 /// <param name="remoteAddress">remote address</param>
 public ServiceClient(Binding binding, EndpointAddress remoteAddress)
     : base(binding, remoteAddress)
 {
     BrokerTracing.TraceEvent(
         TraceEventType.Verbose,
         0,
         "[ServiceClient] In constructor, client id {0}, IsHA = {1}",
         this.guid,
         BrokerIdentity.IsHAMode);
 }
        protected override void CloseClient()
        {
            if (this.Client == null)
            {
                BrokerTracing.TraceWarning("[OnPremiseRequestSender] .CloseClient: Client is null.");
                return;
            }

            this.Client.AsyncClose();
        }
Exemple #18
0
        /// <summary>
        /// Send out request to the target proxy or host.
        /// </summary>
        /// <param name="data">dispatch data</param>
        /// <param name="dispatchId">dispatch Id</param>
        /// <param name="clientIndex">client index</param>
        public virtual void SendRequest(DispatchData data, Guid dispatchId, int clientIndex)
        {
            Message requestMessage = data.BrokerQueueItem.Message;

            Guid messageId = Utility.GetMessageIdFromMessage(requestMessage);

            // Bug 12045: Convert message before preparing it as some headers
            // might be added during preparation.
            // Check version
            if (requestMessage.Headers.MessageVersion != this.BackendBinding.MessageVersion)
            {
                BrokerTracing.TraceVerbose("[RequestSender].SendRequest: Convert message version from {0} to {1}", requestMessage.Headers.MessageVersion, this.BackendBinding.MessageVersion);

                requestMessage = Utility.ConvertMessage(requestMessage, this.BackendBinding.MessageVersion);
            }

            this.PrepareMessage(requestMessage, dispatchId, this.Dispatcher.PassBindingFlags[clientIndex]);

            data.Client = this.IServiceClient;

            // Bug #16197: reserve request message action in case it gets dropped when wcf processes the message
            data.RequestAction = requestMessage.Headers.Action;

            data.DispatchTime = DateTime.Now;

            this.IServiceClient.BeginProcessMessage(
                requestMessage,
                this.ProcessMessageCallback,
                data);

            this.lastSentTime = DateTime.UtcNow;

            // Notice: the request may complete fast, and it is disposed when response comes back before following code executes.
            // So don't access item.Message in following code.

            // Bug #13430:
            // (1) Define "try" as request sent by broker, so any request sent by broker successfully should
            //     have "current try count + 1" and not retried any more if retrylimit=0.
            // (2) Don't increase the try count if EndpointNotFoundException occurs.
            // (3) In "Burst to Azure" mode, connections are shared by dispatchers. The connection is possible to
            //     be killed because of failure in one dispatcher. Don't increase the try count in such case.

            // Increase the try count when BeginProcessMessage succeeds.
            data.BrokerQueueItem.TryCount++;

            BrokerTracing.TraceVerbose(
                BrokerTracing.GenerateTraceString(
                    "RequestSender",
                    "SendRequest",
                    this.TaskId,
                    clientIndex,
                    this.IServiceClient.ToString(),
                    messageId,
                    string.Format("Sent out message and increase the try count to {0}", data.BrokerQueueItem.TryCount)));
        }
Exemple #19
0
        /// <summary>
        /// Build the frontend
        /// </summary>
        /// <param name="sharedData">indicating the shared data</param>
        /// <param name="observer">indicating the broker observer</param>
        /// <param name="clientManager">indicating the client manager</param>
        /// <param name="brokerAuth">indicating the broker authorization</param>
        /// <param name="bindings">indicating the bindings</param>
        /// <param name="azureQueueProxy">indicating the Azure storage proxy</param>
        /// <returns>frontend result</returns>
        public static FrontendResult BuildFrontEnd(SharedData sharedData, BrokerObserver observer, BrokerClientManager clientManager, BrokerAuthorization brokerAuth, BindingsSection bindings, AzureQueueProxy azureQueueProxy)
        {
            FrontendResult result = new FrontendResult();

            // Bug 9514: Do not open frontend for inprocess broker
            if (sharedData.StartInfo.UseInprocessBroker)
            {
                return(result);
            }

            bool flag = false;

            // Open frontend for different scheme

            // TODO: Separate HTTP frontend and Queue frontend
            if (azureQueueProxy != null)
            {
                flag = true;
                result.SetFrontendInfo(BuildHttpFrontend(sharedData, observer, clientManager, brokerAuth, bindings, azureQueueProxy), TransportScheme.Http);
            }
            else
            {
                if ((sharedData.StartInfo.TransportScheme & TransportScheme.Custom) == TransportScheme.Custom)
                {
                    flag = true;
                    result.SetFrontendInfo(BuildCustomFrontend(sharedData, observer, clientManager, brokerAuth, bindings), TransportScheme.Custom);
                }

                if ((sharedData.StartInfo.TransportScheme & TransportScheme.Http) == TransportScheme.Http)
                {
                    flag = true;
                    result.SetFrontendInfo(BuildHttpFrontend(sharedData, observer, clientManager, brokerAuth, bindings, azureQueueProxy), TransportScheme.Http);
                }

                if ((sharedData.StartInfo.TransportScheme & TransportScheme.NetTcp) == TransportScheme.NetTcp)
                {
                    flag = true;
                    result.SetFrontendInfo(BuildNetTcpFrontend(sharedData, observer, clientManager, brokerAuth, bindings), TransportScheme.NetTcp);
                }

                if ((sharedData.StartInfo.TransportScheme & TransportScheme.NetHttp) == TransportScheme.NetHttp)
                {
                    flag = true;
                    result.SetFrontendInfo(BuildNetHttpFrontend(sharedData, observer, clientManager, brokerAuth, bindings), TransportScheme.NetHttp);
                }
            }

            if (!flag)
            {
                BrokerTracing.TraceEvent(TraceEventType.Critical, 0, "[FrontEndBuilder] Invalid transport scheme: {0}", sharedData.StartInfo.TransportScheme);
                ThrowHelper.ThrowSessionFault(SOAFaultCode.Broker_NotSupportedTransportScheme, SR.NotSupportedTransportScheme, sharedData.StartInfo.TransportScheme.ToString());
            }

            return(result);
        }
Exemple #20
0
        private bool HandleResponseWithoutAsyncToken(BrokerQueue queue, BrokerQueueItem requestItem)
        {
            bool   isHandled        = false;
            Guid   persistId        = requestItem.PersistId;
            object asyncToken       = requestItem.PersistAsyncToken.AsyncToken;
            int    dispatcherNumber = requestItem.DispatchNumber;

            if (asyncToken != null && this.responsesWithoutAsyncTokenTable.Count > 0)
            {
                bool needPutResponse = false;
                DispatcherAsyncTokenItem asyncTokenItem = null;
                try
                {
                    lock (this.responsesWithoutAsyncTokenTable)
                    {
                        this.responsesWithoutAsyncTokenTable.TryGetValue(persistId, out asyncTokenItem);
                    }

                    if (asyncTokenItem != null)
                    {
                        lock (this.responsesWithoutAsyncTokenTable)
                        {
                            this.responsesWithoutAsyncTokenTable.Remove(persistId);
                        }

                        needPutResponse = true;

                        lock (this.requestsAsyncTokenTable)
                        {
                            this.requestsAsyncTokenTable.Remove(persistId);
                        }
                    }
                }
                catch (Exception e)
                {
                    if (needPutResponse)
                    {
                        BrokerTracing.TraceInfo("[BrokerQueueDispatcher] .PrefetchRequestCallback: fail to remove the async token from the table, Exception: {0}", e);
                    }
                    else
                    {
                        BrokerTracing.TraceInfo("[BrokerQueueDispatcher] .PrefetchRequestCallback: can not get the response async token, Exception: {0}", e);
                    }
                }

                if (needPutResponse && dispatcherNumber == 0)
                {
                    asyncTokenItem.PersistAsyncToken.AsyncToken = asyncToken;
                    queue.PutResponseAsync(asyncTokenItem.Message, requestItem);
                    isHandled = true;
                }
            }
            return(isHandled);
        }
Exemple #21
0
 /// <summary>
 /// Triggers for queue events
 /// </summary>
 /// <param name="sender">indicating the sender</param>
 /// <param name="e">indicating the event args</param>
 private void Queue_OnPutResponsesSuccessEvent(object sender, PutResponsesSuccessEventArgs e)
 {
     // For both durable session, enable ClientIdleTimeout when all flushed requests are processed
     if (this.sharedData.BrokerInfo.Durable)
     {
         if (this.queue.FlushedRequestsCount == this.queue.ProcessedRequestsCount)
         {
             BrokerTracing.TraceInfo(
                 "[BrokerClient] Client {0}: Queue_OnPutResponsesSuccessEvent FlushedRequestsCount {1} ProcessedRequestsCount {2}.",
                 this.clientId, this.queue.FlushedRequestsCount, this.queue.ProcessedRequestsCount);
             lock (this.lockState)
             {
                 if (this.state == BrokerClientState.AllRequestDone ||
                     this.state == BrokerClientState.ClientConnected ||
                     this.state == BrokerClientState.GetResponse)
                 {
                     if (this.queue.FlushedRequestsCount == this.queue.ProcessedRequestsCount)
                     {
                         BrokerTracing.TraceInfo(
                             "[BrokerClient] Client {0}: Restart counting ClientIdleTimeout because all flushed requests are processed.",
                             this.clientId);
                         this.timeoutManager.RegisterTimeout(this.sharedData.Config.Monitor.ClientIdleTimeout,
                                                             this.TimeoutToDisconnected, this.state);
                     }
                 }
             }
         }
     }
     else // For interactive session, enable ClientIdleTimeout when all requests are processed
     {
         if (this.queue.AllRequestsCount == this.queue.ProcessedRequestsCount)
         {
             BrokerTracing.TraceInfo(
                 "[BrokerClient] Client {0}: Queue_OnPutResponsesSuccessEvent AllRequestsCount {1} ProcessedRequestsCount {2}.",
                 this.clientId, this.queue.AllRequestsCount, this.queue.ProcessedRequestsCount);
             lock (this.lockState)
             {
                 if (this.state == BrokerClientState.AllRequestDone ||
                     this.state == BrokerClientState.ClientConnected ||
                     this.state == BrokerClientState.GetResponse)
                 {
                     if (this.queue.AllRequestsCount == this.queue.ProcessedRequestsCount)
                     {
                         BrokerTracing.TraceInfo(
                             "[BrokerClient] Client {0}: Restart counting ClientIdleTimeout because all requests are processed.",
                             this.clientId);
                         this.timeoutManager.RegisterTimeout(this.sharedData.Config.Monitor.ClientIdleTimeout,
                                                             this.TimeoutToDisconnected, this.state);
                     }
                 }
             }
         }
     }
 }
Exemple #22
0
        private async Task DeleteFromHostAsnyc(string epr)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(this.prefix + epr + ":" + this.port + "/" + this.serverName + "/api/");
                //HTTP DELETE
                var result = await client.DeleteAsync(this.endPoint);

                BrokerTracing.TraceVerbose("[CloseSvcHost].result{0}:", result);
            }
        }
Exemple #23
0
        /// <summary>
        /// Increase the count
        /// </summary>
        /// <returns>Return false means the count is already 0 and needs to return immediately</returns>
        public bool IncreaseCount()
        {
            if (this.refCount <= 0)
            {
                BrokerTracing.TraceVerbose("[ReferenceObject] Ref count is 0 when increasing, return false.");
                return(false);
            }

            Interlocked.Increment(ref this.refCount);
            return(true);
        }
Exemple #24
0
        /// <summary>
        /// Gets the counters
        /// </summary>
        /// <param name="totalCalls">output the total calls</param>
        /// <param name="totalFaulted">output the total faulted</param>
        /// <param name="callDuration">output call duration</param>
        /// <param name="outstands">output the outstands</param>
        /// <param name="incomingRate">output incoming rate</param>
        /// <param name="processed">output the processed count</param>
        /// <param name="processing">output the processing count</param>
        /// <param name="purgedProcessed">output the purged processed count</param>
        /// <param name="reemitted">the reemitted request count</param>
        public void GetCounters(out long totalCalls, out long totalFaulted, out long callDuration, out long outstands, out long incomingRate, out long processed, out long processing, out long purgedProcessed, out long reemitted)
        {
            //
            // Math of counters:
            //  totalCalls = processed + outstands,
            //  outstands = processing + incoming
            // So:
            //  totalCalls = processed + processing + incoming
            //
            // Update logic for a group of counters: processed, processing, directlyReplied
            // - on dispatching a request, processing++
            // - on receiving a response, processing--, processed++, and
            // - if the response is sent to client directly instead of put into broker queue, directlyReplied++
            //
            // [Bug 9731] update above group of counters without using a lock
            // To acheive this, below operation sequences should be followed:
            // 1. on receiving a resonse, first decrease "processing", and then increase "processed".  This ensures "processed + processing <= totalCalls"
            // 2. when to increase "directlyReplied", first increase "processed", and then increase "directlyReplied".
            // 3. when to read "directlyReplied", first read "directlyReplied", and then read "processed".  2 & 3 ensures that "directlyReplied <= processed".
            //

            // read "directlyReplied" before "processed"
            long tmpDirectlyReplied = Interlocked.Read(ref this.directlyReplied);

            totalCalls   = Interlocked.Read(ref this.total);
            processing   = Interlocked.Read(ref this.processing);
            processed    = Interlocked.Read(ref this.processed);
            reemitted    = Interlocked.Read(ref this.reemitted);
            totalFaulted = this.faultedCallsObserver.Total;
            incomingRate = this.callsObserver.Changed;
            callDuration = this.callDurationObserver.Average;

            long tmpPurgedTotal     = 0;
            long tmpPurgedProcessed = 0;

            lock (this.lockPurgedCounters)
            {
                tmpPurgedTotal     = Interlocked.Read(ref this.purgedTotal);
                tmpPurgedProcessed = Interlocked.Read(ref this.purgedProcessed);
            }

            purgedProcessed = tmpPurgedProcessed + tmpDirectlyReplied;
            outstands       = totalCalls - processed - tmpPurgedTotal + tmpPurgedProcessed;

            BrokerTracing.TraceVerbose(
                "[BrokerObserver] GetCounters: totalCalls = {0}, processed = {1}, processing = {2}, purgedTotal = {3}, tmpPurgedProcessed = {4}, purgedProcessed = {5}, reemitted = {6}",
                totalCalls,
                processed,
                processing,
                this.purgedTotal,
                tmpPurgedProcessed,
                purgedProcessed,
                reemitted);
        }
Exemple #25
0
 /// <summary>
 /// remove the broker queue from the cached list.
 /// </summary>
 /// <param name="clientId">the client id.</param>
 internal void RemovePersistQueueByClient(string clientId)
 {
     ParamCheckUtility.ThrowIfNull(clientId, "clientId");
     BrokerTracing.TraceInfo("[BrokerQueueFactory] .RemovePersistQueueByClient: ClientId:{0}", clientId);
     lock (this.clientBrokerQueueDic)
     {
         if (this.clientBrokerQueueDic.ContainsKey(clientId))
         {
             this.clientBrokerQueueDic.Remove(clientId);
         }
     }
 }
Exemple #26
0
 /// <summary>
 /// Callback method of the message retriever.
 /// </summary>
 /// <param name="messages">a collection of messages</param>
 private void HandleMessages(IEnumerable <CloudQueueMessage> messages)
 {
     try
     {
         this.requestCache.Enqueue(messages);
         this.semaphoreForRequest.Release();
     }
     catch (Exception e)
     {
         BrokerTracing.TraceError(SoaHelper.CreateTraceMessage("Proxy", "HandleMessages", string.Format("Error occurs, {0}", e)));
     }
 }
Exemple #27
0
        public void SendResponse(Message response)
        {
            BrokerTracing.TraceInfo("[AzureQueueProxy] Response is inqueued {0}", response.Version.ToString());

            // for azure queue need to copy a new message
            MessageBuffer messageBuffer = null;

            messageBuffer = response.CreateBufferedCopy(int.MaxValue);
            Message m = messageBuffer.CreateMessage();

            this.responseMessageQueue.Enqueue(m);
        }
Exemple #28
0
        public void SendResponse(Message response, string clientData)
        {
            BrokerTracing.TraceInfo("[AzureQueueProxy] Response is inqueued with clientData {0}", response.Version.ToString());

            // for azure queue need to copy a new message
            MessageBuffer messageBuffer = null;

            messageBuffer = response.CreateBufferedCopy(int.MaxValue);
            Message m = messageBuffer.CreateMessage();

            this.responseMessageClients[this.sessionClientData[clientData]].Item1.Enqueue(m);
        }
 /// <summary>
 /// Gets the broker controller instance
 /// </summary>
 /// <returns>returns the broker controller instance</returns>
 private BrokerController GetInstance()
 {
     if (this.singletonInstance == null)
     {
         BrokerTracing.TraceInfo("[ControllerFrontendProvider] GetInstance.");
         return(new BrokerController(false, this.clientManager, this.brokerAuth, this.observer, this.azureQueueProxy));
     }
     else
     {
         return(this.singletonInstance);
     }
 }
Exemple #30
0
        /// <summary>
        /// Create OnPremiseRequestSender.
        /// </summary>
        /// <returns>OnPremiseRequestSender instance</returns>
        protected override RequestSender CreateRequestSender()
        {
            BrokerTracing.TraceVerbose("[WssDispatcher]. Create WssRequestSender for {0}.", this.Epr);

            return(new WssRequestSender(
                       this.Epr,
                       this.BackendBinding,
                       this.ServiceOperationTimeout,
                       this,
                       this.ServiceInitializationTimeout,
                       InitEndpointNotFoundWaitPeriod));
        }