예제 #1
0
        /// <summary>
        /// Close a session
        /// </summary>
        /// <param name="sessionId">session id</param>
        public void Close(string sessionId)
        {
            try
            {
                bool?isAadOrLocalUser = this.BrokerManager.IfSeesionCreatedByAadOrLocalUser(sessionId);
                if (!isAadOrLocalUser.HasValue)
                {
                    TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Warning, "[BrokerLauncher] Info not found: SessionId = {0}", sessionId);
                    return;
                }
                this.CheckAccess(sessionId);
                TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Information, "[BrokerLauncher] Close: SessionId = {0}", sessionId);
                this.brokerManager.CloseBrokerDomain(sessionId).GetAwaiter().GetResult();

                #region Debug Failure Test
                SimulateFailure.FailOperation(1);
                #endregion

                TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Information, "[BrokerLauncher] Close Broker {0} Succeeded.", sessionId);
            }
            catch (Exception e)
            {
                // Bug 14019: Swallow the exception for close as the broker node is already taken offline
                if (!this.AllowNewSession)
                {
                    return;
                }

                TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Error, "[BrokerLauncher] Close Broker {0} failed: {1}", sessionId, e);
                throw ExceptionHelper.ConvertExceptionToFaultException(e);
            }
        }
예제 #2
0
        /// <summary>
        /// For Java to pull the responses
        /// </summary>
        /// <param name="action">indicating the action</param>
        /// <param name="position">indicating the position</param>
        /// <param name="count">indicating the count</param>
        /// <param name="clientId">indicating the client id</param>
        /// <returns>returns the responses messages</returns>
        public BrokerResponseMessages PullResponses(string action, GetResponsePosition position, int count, string clientId)
        {
            try
            {
                ParamCheckUtility.ThrowIfOutofRange(count <= 0, "count");
                ParamCheckUtility.ThrowIfNull(clientId, "clientId");
                ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong);
                ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId);

                BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "[BrokerController] PullResponses: Action = {0}, Position = {1}, Count = {2}", action, position, count);
                this.ThrowIfDisposed();
                this.CheckAuth();

                #region Debug Failure Test
                SimulateFailure.FailOperation(1);
                #endregion

                return(this.GetClient(clientId).PullResponses(action, position, count, GetMessageVersion()));
            }
            catch (Exception e)
            {
                BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[BrokerController] PullResponses Failed: {0}", e);
                throw TranslateException(e);
            }
        }
예제 #3
0
        /// <summary>
        /// Attach to a session
        /// </summary>
        /// <param name="sessionId">session id</param>
        /// <returns>returns broker initialization result</returns>
        public BrokerInitializationResult Attach(string sessionId)
        {
            if (!this.AllowNewSession)
            {
                ThrowHelper.ThrowSessionFault(SOAFaultCode.Broker_BrokerIsOffline, SR.BrokerIsOffline);
            }

            try
            {
                this.CheckAccess(sessionId);

                TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Information, "[BrokerLauncher] Attach: SessionId = {0}", sessionId);
                BrokerInitializationResult returnValue = this.brokerManager.AttachBroker(sessionId).GetAwaiter().GetResult();

                #region Debug Failure Test
                SimulateFailure.FailOperation(1);
                #endregion

                TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Information, "[BrokerLauncher] Attach Broker {0} Succeeded.", sessionId);
                return(returnValue);
            }
            catch (Exception e)
            {
                // Bug 10614: Throw a proper exception when the broker node is being taken offline
                if (!this.AllowNewSession)
                {
                    ThrowHelper.ThrowSessionFault(SOAFaultCode.Broker_BrokerIsOffline, SR.BrokerIsOffline);
                }

                TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Error, "[BrokerLauncher] Attach Broker {0} failed: {1}", sessionId, e);
                throw ExceptionHelper.ConvertExceptionToFaultException(e);
            }
        }
        /// <summary>
        /// Handle retry limit exceeded
        /// </summary>
        /// <param name="data"></param>
        public void HandleRetryLimitExceeded(DispatchData data)
        {
            // handle retry limit only when we get exception or fault message
            Contract.Requires(data.Exception != null ||
                              (data.ReplyMessage != null && data.ReplyMessage.IsFault == true),
                              "Retry Limit Exceeded when there is exception or fault message");

            int retryLimit = this.sharedData.Config.LoadBalancing.MessageResendLimit;

            BrokerTracing.EtwTrace.LogBackendResponseReceivedRetryLimitExceed(data.SessionId, data.TaskId, data.MessageId, retryLimit);

            // Initialize retry error and fault reason
            RetryOperationError retryError;
            FaultReason         faultReason;

            if (data.Exception != null)
            {
                // generate fault exception from original exception
                retryError = new RetryOperationError(data.Exception.Message);

                string exceptionFaultReason = String.Format(SR.RetryLimitExceeded, retryLimit + 1, data.Exception.Message);
                faultReason = new FaultReason(exceptionFaultReason);
            }
            else
            {
                #region Debug Failure Test
                SimulateFailure.FailOperation(1);
                #endregion

                // generate fault exception from original reply
                MessageFault messageFault = MessageFault.CreateFault(data.ReplyMessage, Constant.MaxBufferSize);
                retryError  = messageFault.GetDetail <RetryOperationError>();
                faultReason = messageFault.Reason;

                // close original reply message
                data.ReplyMessage.Close();
            }

            retryError.RetryCount          = retryLimit + 1;
            retryError.LastFailedServiceId = data.TaskId;

            // Construct the new exception
            FaultException <RetryOperationError> faultException = new FaultException <RetryOperationError>(retryError, faultReason, Constant.RetryLimitExceedFaultCode, RetryOperationError.Action);

            data.Exception = faultException;
            this.responseQueueAdapter.PutResponseBack(data);
        }
예제 #5
0
        /// <summary>
        /// Create a session
        /// </summary>
        /// <param name="info">session start info</param>
        /// <param name="sessionId">session id</param>
        /// <returns>returns broker initialization result</returns>
        public BrokerInitializationResult Create(SessionStartInfoContract info, string sessionId)
        {
            if ((!this.AllowNewSession) || (!this.IsOnline && String.IsNullOrEmpty(info.DiagnosticBrokerNode)))
            {
                ThrowHelper.ThrowSessionFault(SOAFaultCode.Broker_BrokerIsOffline, SR.BrokerIsOffline);
            }

            // Handle invalid input parameters
            try
            {
                ParamCheckUtility.ThrowIfNull(info, "info");
                if (!BrokerLauncherEnvironment.Standalone)
                {
                    this.CheckAccess(sessionId);
                }

                TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Information, "[BrokerLauncher] Create: SessionId = {0}", sessionId);
                //TODO: make it async
                BrokerInitializationResult returnValue = this.brokerManager.CreateNewBrokerDomain(info, sessionId, false).GetAwaiter().GetResult();

                #region Debug Failure Test
                SimulateFailure.FailOperation(1);
                #endregion

                TraceHelper.RuntimeTrace.LogSessionCreated(sessionId);
                TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Information, "[BrokerLauncher] Create Broker {0} Succeeded.", sessionId);
                return(returnValue);
            }
            catch (Exception e)
            {
                TraceHelper.RuntimeTrace.LogFailedToCreateSession(sessionId);

                // Bug 10614: Throw a proper exception when the broker node is being taken offline
                if ((!this.AllowNewSession) || (!this.IsOnline && String.IsNullOrEmpty(info.DiagnosticBrokerNode)))
                {
                    ThrowHelper.ThrowSessionFault(SOAFaultCode.Broker_BrokerIsOffline, SR.BrokerIsOffline);
                }

                TraceHelper.TraceEvent(sessionId, System.Diagnostics.TraceEventType.Error, "[BrokerLauncher] Create Broker {0} failed: {1}", sessionId, e.ToString());
                throw ExceptionHelper.ConvertExceptionToFaultException(e);
            }
        }
예제 #6
0
        /// <summary>
        /// Get responses from client
        /// </summary>
        /// <param name="action">indicating the action</param>
        /// <param name="clientData">indicating the client data</param>
        /// <param name="resetToBegin">indicating the position</param>
        /// <param name="count">indicating the count</param>
        /// <param name="clientId">indicating the client id</param>
        public void GetResponses(string action, string clientData, GetResponsePosition resetToBegin, int count, string clientId)
        {
            try
            {
                BrokerTracing.TraceVerbose("[BrokerController] GetResponses is called for Client {0}.", clientId);

                ParamCheckUtility.ThrowIfOutofRange(count <= 0 && count != -1, "count");
                ParamCheckUtility.ThrowIfNull(clientId, "clientId");
                ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong);
                ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId);

                BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "[BrokerController] GetResponses for Client {2}, Count = {0}, Position = {1}", count, resetToBegin, clientId);

                this.ThrowIfDisposed();
                this.CheckAuth();

                // Try to get callback instance for inprocess broker
                IResponseServiceCallback callbackInstance = this.callbackInstance;

                // If callback instance is null, get callback instance from operation context
                if (callbackInstance == null)
                {
                    callbackInstance = OperationContext.Current.GetCallbackChannel <IResponseServiceCallback>();
                }

                this.GetClient(clientId).GetResponses(action, clientData, resetToBegin, count, callbackInstance, GetMessageVersion());

                #region Debug Failure Test
                SimulateFailure.FailOperation(1);
                #endregion

                BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "[BrokerController] GetResponses for Client {0} Succeeded.", clientId);
            }
            catch (Exception e)
            {
                BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[BrokerController] GetResponses for Client {1} Failed: {0}", e, clientId);
                throw TranslateException(e);
            }
        }
예제 #7
0
        /// <summary>
        /// Indicate the end of requeusts
        /// </summary>
        /// <param name="count">indicating the number of the messages</param>
        /// <param name="timeoutMs">indicating the timeout in MS</param>
        /// <param name="clientId">indicating the client id</param>
        public void EndRequests(int count, string clientId, int batchId, int timeoutThrottlingMs, int timeoutEOMMs)
        {
            ParamCheckUtility.ThrowIfOutofRange(count < 0, "count");
            ParamCheckUtility.ThrowIfOutofRange(timeoutThrottlingMs <= 0 && timeoutThrottlingMs != Timeout.Infinite, "timeoutThrottlingMs");
            ParamCheckUtility.ThrowIfOutofRange(timeoutEOMMs <= 0 && timeoutEOMMs != Timeout.Infinite, "timeoutEOMMs");
            ParamCheckUtility.ThrowIfNull(clientId, "clientId");
            ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong);
            ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId);

            this.ThrowIfDisposed();
            this.CheckAuth();

            BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "[BrokerController] Receive EOM for Client {0}, Count = {1}", clientId, count);
            try
            {
                #region Debug Failure Test
                SimulateFailure.FailOperation(1);
                #endregion

                BrokerClient brokerClient = this.GetClient(clientId);
                FrontEndBase frontendBase = brokerClient.GetDuplexFrontEnd();

                WaitOnThrottling(frontendBase, timeoutThrottlingMs);

                // Then handle the EOM which waits until all requests are stored. Use user specified EndRequests timeout for this
                brokerClient.EndOfMessage(count, batchId, timeoutEOMMs);

                #region Debug Failure Test
                SimulateFailure.FailOperation(2);
                #endregion
            }
            catch (Exception e)
            {
                BrokerTracing.TraceError("[BrokerController] EOM failed for client {0}: {1}", clientId, e);
                throw TranslateException(e);
            }
        }
예제 #8
0
        /// <summary>
        /// AsyncCallback for ReceiveRequest
        /// </summary>
        /// <param name="ar">async result</param>
        private void ReceiveRequest(IAsyncResult ar)
        {
            ChannelClientState state = (ChannelClientState)ar.AsyncState;
            T              channel   = (T)state.Channel;
            BrokerClient   client    = state.Client;
            RequestContext request;

            try
            {
                request = channel.EndReceiveRequest(ar);
            }
            catch (TimeoutException)
            {
                BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[RequestReplyFrontEnd] Receive Request timed out");
                if (!ar.CompletedSynchronously)
                {
                    this.TryToBeginReceiveMessagesWithThrottling(state);
                }

                return;
            }
            catch (CommunicationException ce)
            {
                BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[RequestReplyFrontEnd] Exception while receiving requests: {0}", ce.Message);

                // Retry receiving requests
                if (!ar.CompletedSynchronously)
                {
                    this.TryToBeginReceiveMessagesWithThrottling(state);
                }

                return;
            }

            #region Debug Failure Test
            SimulateFailure.FailOperation(1);
            #endregion

            // After channel timed out, the request will be null if you call channel.ReceiveRequest()
            // Need to end the channel at this time
            if (request == null)
            {
                // Indicate that the channel should be closed
                // Close the channel
                lock (channel)
                {
                    if (channel.State == CommunicationState.Opened)
                    {
                        try
                        {
                            channel.Close();
                        }
                        catch (CommunicationException ce)
                        {
                            BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[RequestReplyFrontEnd] Exception throwed while close the channel: {0}", ce);
                            channel.Abort();
                        }
                    }
                }

                return;
            }

            // Try to get the client id and the user name
            string callerSID;
            string userName = this.GetUserName(request.RequestMessage, out callerSID);
            string clientId = GetClientId(request.RequestMessage, callerSID);

            try
            {
                ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong);
                ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId);
            }
            catch (ArgumentException)
            {
                BrokerTracing.EtwTrace.LogFrontEndRequestRejectedClientIdInvalid(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request.RequestMessage));
                RequestContextBase requestContextToReject = new RequestReplyRequestContext(request, this.Observer);
                requestContextToReject.BeginReply(FrontEndFaultMessage.GenerateFaultMessage(request.RequestMessage, request.RequestMessage.Headers.MessageVersion, SOAFaultCode.Broker_InvalidClientIdOrTooLong, SR.InvalidClientIdOrTooLong), this.ReplySentCallback, requestContextToReject);
                return;
            }

            if (client == null || client.State == BrokerClientState.Disconnected || String.Compare(clientId, client.ClientId, StringComparison.OrdinalIgnoreCase) != 0)
            {
                try
                {
                    client = this.ClientManager.GetClient(clientId, userName);
                    client.SingletonInstanceConnected();
                }
                catch (FaultException <SessionFault> e)
                {
                    if (e.Detail.Code == (int)SOAFaultCode.AccessDenied_BrokerQueue)
                    {
                        BrokerTracing.EtwTrace.LogFrontEndRequestRejectedAuthenticationError(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request.RequestMessage), userName);
                        RequestContextBase requestContextToReject = new RequestReplyRequestContext(request, this.Observer);
                        requestContextToReject.BeginReply(FrontEndFaultMessage.GenerateFaultMessage(request.RequestMessage, request.RequestMessage.Headers.MessageVersion, SOAFaultCode.Broker_UserNameNotMatch, SR.UserNameNotMatch, userName, clientId), this.ReplySentCallback, requestContextToReject);
                        return;
                    }
                    else
                    {
                        BrokerTracing.EtwTrace.LogFrontEndRequestRejectedGeneralError(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request.RequestMessage), e.ToString());
                        throw;
                    }
                }
                catch (BrokerQueueException e)
                {
                    BrokerTracing.EtwTrace.LogFrontEndRequestRejectedGeneralError(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request.RequestMessage), e.ToString());
                    RequestContextBase requestContextToReject = new RequestReplyRequestContext(request, this.Observer);
                    requestContextToReject.BeginReply(FrontEndFaultMessage.TranslateBrokerQueueExceptionToFaultMessage(e, request.RequestMessage), this.ReplySentCallback, requestContextToReject);
                    return;
                }
                catch (Exception e)
                {
                    BrokerTracing.EtwTrace.LogFrontEndRequestRejectedGeneralError(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request.RequestMessage), e.ToString());
                    throw;
                }

                state.Client = client;
            }

            // Receive new requests
            if (!ar.CompletedSynchronously)
            {
                this.TryToBeginReceiveMessagesWithThrottling(state);
            }

            // Try to get the user info header
            bool userDataFlag = GetUserInfoHeader(request.RequestMessage);

            // Create request context
            RequestContextBase requestContext;
            if (userDataFlag)
            {
                // Message that needs not to reply
                requestContext = DummyRequestContext.GetInstance(request.RequestMessage.Version);

                // Reply the message to the client immediately if user data is found for request/reply MEP (basic http binding)
                try
                {
                    request.BeginReply(Message.CreateMessage(request.RequestMessage.Headers.MessageVersion, request.RequestMessage.Headers.Action + "Response"), this.ReplySent, request);
                }
                catch (Exception e)
                {
                    BrokerTracing.TraceEvent(TraceEventType.Error, 0, "[RequestReplyFrontEnd] Exception throwed while trying to reply dummy message to client: {0}", e);
                }
            }
            else
            {
                requestContext = new RequestReplyRequestContext(request, this.Observer, client);
            }

            // Check auth
            if (!this.CheckAuth(requestContext, request.RequestMessage))
            {
                return;
            }

            // Bug 15195: Remove security header for https
            TryRemoveSecurityHeaderForHttps(request.RequestMessage);

            // Send request to the broker client
            client.RequestReceived(requestContext, request.RequestMessage, null);
        }
예제 #9
0
        /// <summary>
        /// Receive response message from host.
        /// </summary>
        /// <param name="data">DispatchData instance</param>
        public void ReceiveResponse(DispatchData data)
        {
            Contract.Requires(data.AsyncResult != null, string.Format(ContractMessageFormat, "DispatchData.AsyncResult"));

            Contract.Requires(data.Client != null, string.Format(ContractMessageFormat, "DispatchData.Client"));

            Contract.Requires(data.BrokerQueueItem != null, string.Format(ContractMessageFormat, "DispatchData.BrokerQueueItem"));

            Contract.Ensures(
                data.ReplyMessage != null || data.Exception != null,
                "DispatchData should have either a reply message either an exception.");

            Message reply = null;

            string taskId = data.TaskId;

            DateTime dispatchTime = data.DispatchTime;

            int clientIndex = data.ClientIndex;

            IService client = data.Client;

            BrokerQueueItem item = data.BrokerQueueItem;

            // Bug #16197: if request action field is dropped by wcf, restore it back
            if (string.IsNullOrEmpty(item.Message.Headers.Action))
            {
                item.Message.Headers.Action = data.RequestAction;
            }

            this.dispatcher.items[clientIndex] = null;

            this.dispatcher.DecreaseProcessingCount();

            Guid messageId = Utility.GetMessageIdFromMessage(item.Message);

            try
            {
                // Get the response message
                reply = client.EndProcessMessage(data.AsyncResult);

                data.ReplyMessage = reply;

                // following method needs to be called before setting bServiceInitalizationCompleted flag
                this.PostProcessMessage(reply);

                // mark bServiceInitalizationCompleted flag to true;
                if (!this.dispatcher.ServiceInitializationCompleted)
                {
                    this.dispatcher.ServiceInitializationCompleted = true;

                    // nofity that it is connected to service host
                    this.dispatcher.OnServiceInstanceConnected(null);
                }

                BrokerTracing.EtwTrace.LogBackendResponseReceived(data.SessionId, taskId, messageId, reply.IsFault);
            }
            catch (EndpointNotFoundException e)
            {
                data.Exception = e;

                // TODO: need ExceptionHandler
                this.dispatcher.HandleEndpointNotFoundException(clientIndex, client, item, messageId, e);

                return;
            }
            catch (StorageException e)
            {
                data.Exception = e;

                // TODO: need ExceptionHandler
                this.dispatcher.HandleStorageException(dispatchTime, clientIndex, client, item, messageId, e);

                return;
            }
            catch (Exception e)
            {
                data.Exception = e;

                // TODO: need ExceptionHandler
                this.dispatcher.HandleException(dispatchTime, clientIndex, client, item, messageId, e);

                return;
            }

            if (reply.IsFault)
            {
                // If any fault message is received, consider passing binding data again.
                // TODO: pass binding data only on special error code
                this.dispatcher.PassBindingFlags[clientIndex] = true;
            }

            bool servicePreempted = false;

            if (reply.IsFault)
            {
                BrokerTracing.TraceVerbose(
                    BrokerTracing.GenerateTraceString(
                        "ResponseReceiver",
                        "ReceiveResponse",
                        taskId,
                        clientIndex,
                        client.ToString(),
                        messageId,
                        "The response is a fault message."));

                // TODO: need ExceptionHandler
                data.ExceptionHandled = this.dispatcher.HandleFaultExceptionRetry(clientIndex, item, reply, dispatchTime, out servicePreempted);
            }
            else
            {
                // if it is a normal response, check if the CancelEvent happens when request is being processed.
                int index = reply.Headers.FindHeader(Constant.MessageHeaderPreemption, Constant.HpcHeaderNS);

                if (index >= 0 && index < reply.Headers.Count)
                {
                    servicePreempted = true;

                    int messageCount = reply.Headers.GetHeader <int>(index);

                    BrokerTracing.TraceVerbose(
                        BrokerTracing.GenerateTraceString(
                            "ResponseReceiver",
                            "ReceiveResponse",
                            taskId,
                            clientIndex,
                            client.ToString(),
                            messageId,
                            string.Format("The count of processing message in the counterpart host is {0}.", messageCount)));

                    // will remove the dispatcher if no processing message left on the host
                    if (messageCount == 0)
                    {
                        // Simulate a SessionFault and reuse the method HandleServiceInstanceFailure,
                        // and the message will be processed later as normal.
                        BrokerTracing.TraceVerbose(
                            BrokerTracing.GenerateTraceString(
                                "ResponseReceiver",
                                "ReceiveResponse",
                                taskId,
                                clientIndex,
                                client.ToString(),
                                messageId,
                                "(Preemption) Call HandleServiceInstanceFailure."));

                        // TODO: need ServiceInstanceFailureHandler
                        this.dispatcher.HandleServiceInstanceFailure(new SessionFault(SOAFaultCode.Service_Preempted, string.Empty));
                    }
                }
            }

            data.ServicePreempted = servicePreempted;

            // Debug Failure Test
            SimulateFailure.FailOperation(1);
        }
예제 #10
0
        /// <summary>
        /// AsyncCallback for ReceiveRequest
        /// </summary>
        /// <param name="ar">async result</param>
        private void ReceiveRequest(IAsyncResult ar)
        {
            ChannelClientState    state   = (ChannelClientState)ar.AsyncState;
            IDuplexSessionChannel channel = (IDuplexSessionChannel)state.Channel;
            BrokerClient          client  = state.Client;
            Message requestMessage;

            try
            {
                requestMessage = channel.EndReceive(ar);
            }
            catch (Exception ce)
            {
                BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[DuplexFrontEnd] Exception while receiving requests: {0}", ce);
                this.FrontendDisconnect(channel, client);

                lock (channel)
                {
                    if (channel.State == CommunicationState.Faulted)
                    {
                        BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[DuplexFrontEnd] Abort faulted channel.");
                        channel.Abort();
                        return;
                    }
                }

                // Retry receiving requests
                if (!ar.CompletedSynchronously)
                {
                    this.TryToBeginReceiveMessagesWithThrottling(state);
                }

                return;
            }

            #region Debug Failure Test
            SimulateFailure.FailOperation(1);
            #endregion

            // After channel timeout, the request will be null if you call channel.Receive()
            // Need to end the channel at this time
            if (requestMessage == null)
            {
                // Indicate that the channel should be closed
                // Close the channel
                lock (channel)
                {
                    if (channel.State == CommunicationState.Opened)
                    {
                        this.FrontendDisconnect(channel, client);
                        try
                        {
                            channel.Close();
                            BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[DuplexFrontEnd] Channel closed");
                        }
                        catch (Exception ce)
                        {
                            BrokerTracing.TraceEvent(TraceEventType.Warning, 0, "[DuplexFrontEnd] Exception throwed while close the channel: {0}", ce);
                            channel.Abort();
                        }
                    }
                }

                return;
            }

            // Try to get the client id
            string callerSID;
            string userName = this.GetUserName(requestMessage, out callerSID);
            string clientId = GetClientId(requestMessage, callerSID);

            try
            {
                ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong);
                ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId);
            }
            catch (ArgumentException)
            {
                BrokerTracing.EtwTrace.LogFrontEndRequestRejectedClientIdInvalid(this.SessionId, clientId, Utility.GetMessageIdFromMessage(requestMessage));
                RequestContextBase requestContextToReject = new DuplexRequestContext(requestMessage, this.binding, channel, this.Observer);
                requestContextToReject.BeginReply(FrontEndFaultMessage.GenerateFaultMessage(requestMessage, requestMessage.Headers.MessageVersion, SOAFaultCode.Broker_InvalidClientIdOrTooLong, SR.InvalidClientIdOrTooLong), this.ReplySentCallback, requestContextToReject);
                return;
            }

            if (client == null)
            {
                if (!this.TryGetClientByChannel(channel, clientId, userName, requestMessage, out client))
                {
                    return;
                }

                state.Client = client;
            }

            // Receive new requests
            if (!ar.CompletedSynchronously)
            {
                this.TryToBeginReceiveMessagesWithThrottling(state);
            }

            // Reject if client id does not match
            if (String.Compare(clientId, client.ClientId, StringComparison.OrdinalIgnoreCase) != 0)
            {
                BrokerTracing.EtwTrace.LogFrontEndRequestRejectedClientIdNotMatch(this.SessionId, clientId, Utility.GetMessageIdFromMessage(requestMessage));
                RequestContextBase requestContextToReject = new DuplexRequestContext(requestMessage, this.binding, channel, this.Observer);
                requestContextToReject.BeginReply(FrontEndFaultMessage.GenerateFaultMessage(requestMessage, requestMessage.Headers.MessageVersion, SOAFaultCode.Broker_ClientIdNotMatch, SR.ClientIdNotMatch), this.ReplySentCallback, requestContextToReject);
                return;
            }

            // Try to get the user info header
            bool userDataFlag = GetUserInfoHeader(requestMessage);

            // Create request context
            RequestContextBase requestContext;
            if (userDataFlag)
            {
                // Message that needs not to reply
                requestContext = DummyRequestContext.GetInstance(requestMessage.Version);
            }
            else
            {
                requestContext = new DuplexRequestContext(requestMessage, this.binding, channel, this.Observer, client);
            }

            // Check auth
            if (!this.CheckAuth(requestContext, requestMessage))
            {
                return;
            }

            // remove security header for websocket
            TryRemoveSecurityHeaderForHttps(requestMessage);

            // Send the request to the broker client
            Task.Run(() => client.RequestReceived(requestContext, requestMessage, null));
        }
예제 #11
0
        /// <summary>
        /// AsyncCallback for ReceiveRequest
        /// </summary>
        /// <param name="ar">async result</param>
        private void ReceiveRequest(IAsyncResult ar)
        {
            ChannelClientState state  = (ChannelClientState)ar.AsyncState;
            BrokerClient       client = state.Client;
            Message            request;

            try
            {
                request = this.azureQueueProxy.EndReceiveRequest(ar);
            }
            catch (TimeoutException)
            {
                BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[AzureQueueFrontEnd] Receive Request timed out");
                if (!ar.CompletedSynchronously)
                {
                    this.TryToBeginReceiveMessagesWithThrottling(state);
                }

                return;
            }
            catch (CommunicationException ce)
            {
                BrokerTracing.TraceEvent(TraceEventType.Information, 0, "[AzureQueueFrontEnd] Exception while receiving requests: {0}", ce.Message);

                // Retry receiving requests
                if (!ar.CompletedSynchronously)
                {
                    this.TryToBeginReceiveMessagesWithThrottling(state);
                }

                return;
            }

            #region Debug Failure Test
            SimulateFailure.FailOperation(1);
            #endregion


            // Try to get the client id and the user name
            string userName = GetUserName(request);
            string clientId = GetClientId(request, string.Empty);

            try
            {
                ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong);
                ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId);
            }
            catch (ArgumentException)
            {
                BrokerTracing.EtwTrace.LogFrontEndRequestRejectedClientIdInvalid(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request));
                return;
            }

            if (client == null || client.State == BrokerClientState.Disconnected || !client.ClientId.Equals(clientId, StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    client = this.ClientManager.GetClient(clientId, userName);
                    client.SingletonInstanceConnected();
                }
                catch (FaultException <SessionFault> e)
                {
                    if (e.Detail.Code == (int)SOAFaultCode.AccessDenied_BrokerQueue)
                    {
                        BrokerTracing.EtwTrace.LogFrontEndRequestRejectedAuthenticationError(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request), userName);
                        return;
                    }
                    else
                    {
                        BrokerTracing.EtwTrace.LogFrontEndRequestRejectedGeneralError(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request), e.ToString());
                        throw;
                    }
                }
                catch (BrokerQueueException e)
                {
                    BrokerTracing.EtwTrace.LogFrontEndRequestRejectedGeneralError(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request), e.ToString());
                    return;
                }
                catch (Exception e)
                {
                    BrokerTracing.EtwTrace.LogFrontEndRequestRejectedGeneralError(this.SessionId, clientId, Utility.GetMessageIdFromMessage(request), e.ToString());
                    throw;
                }

                state.Client = client;
            }

            // Receive new requests
            if (!ar.CompletedSynchronously)
            {
                this.TryToBeginReceiveMessagesWithThrottling(state);
            }

            // Try to get the user info header
            bool userDataFlag = GetUserInfoHeader(request);

            // Create request context
            RequestContextBase requestContext;
            //Message that needs not to reply
            requestContext = DummyRequestContext.GetInstance(request.Version);

            // Bug 15195: Remove security header for https
            TryRemoveSecurityHeaderForHttps(request);

            // Send request to the broker client
            client.RequestReceived(requestContext, request, null);
        }