/// <summary> /// <para /> /// </summary> /// <param name="clientId"> /// <para /> /// </param> /// <param name="session"> /// <para /> /// </param> protected BrokerClientBase(string clientId, SessionBase session) { if (string.IsNullOrEmpty(clientId)) { if (session.Info is SessionInfo) { this.clientId = String.Empty; } else { this.clientId = DefaultClientIdForRestService; } } else { this.clientId = clientId; } ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, this.clientId, "clientId", SR.InvalidClientId); // Associate BrokerClient with session session.AddBrokerClient(this.clientId, this); this.session = session; }
/// <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); } }
/// <summary> /// Send requests /// </summary> /// <param name="message">indicating the message</param> void IBrokerFrontend.SendRequest(Message message) { string clientId = FrontEndBase.GetClientId(message, String.Empty); try { ParamCheckUtility.ThrowIfNull(clientId, "clientId"); ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong); ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId); this.observer.IncomingRequest(); this.GetClient(clientId).RequestReceived(DummyRequestContext.GetInstance(MessageVersion.Default), message, null); } catch (Exception e) { BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[BrokerController] SendRequest {1} Failed: {0}", e, clientId); throw TranslateException(e); } }
/// <summary> /// Purge a client /// </summary> /// <param name="clientId">indicating the client id</param> public void Purge(string clientId) { try { 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] Purge Client {0}", clientId); this.ThrowIfDisposed(); this.CheckAuth(); this.clientManager.PurgeClient(clientId, GetUserName()).GetAwaiter().GetResult(); BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Information, 0, "[BrokerController] Purge Client {0} Succeeded.", clientId); } catch (Exception e) { BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[BrokerController] Purge Client {1} Failed: {0}", e, clientId); throw TranslateException(e); } }
/// <summary> /// Gets number of requests that have been committed into specified client /// </summary> /// <param name="clientId">client id</param> /// <returns>number of committed requests in the client with specified client id</returns> public int GetRequestsCount(string clientId) { try { ParamCheckUtility.ThrowIfNull(clientId, "clientId"); ParamCheckUtility.ThrowIfTooLong(clientId.Length, "clientId", Constant.MaxClientIdLength, SR.ClientIdTooLong); ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.ClientIdValid, clientId, "clientId", SR.InvalidClientId); BrokerTracing.TraceInfo("[BrokerController] Get requests count for Client {0}", clientId); this.ThrowIfDisposed(); this.CheckAuth(); return(this.GetClient(clientId).RequestsCount); } catch (Exception e) { BrokerTracing.TraceError("[BrokerController] Get requests for Client {1} Failed: {0}", e, clientId); throw TranslateException(e); } }
/// <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); } }
/// <summary> /// Gets broker client status /// </summary> /// <param name="clientId">indicating the client id</param> /// <returns>returns the broker client status</returns> public BrokerClientStatus GetBrokerClientStatus(string clientId) { try { 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] Get broker client status for Client {0}", clientId); this.ThrowIfDisposed(); this.CheckAuth(); BrokerClientState state = this.GetClient(clientId).State; return(BrokerClient.MapToBrokerClientStatus(state)); } catch (Exception e) { BrokerTracing.TraceEvent(System.Diagnostics.TraceEventType.Error, 0, "[BrokerController] Get broker client status for Client {1} Failed: {0}", e, clientId); throw TranslateException(e); } }
/// <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); } }
/// <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); }
/// <summary> /// Validate data client id /// </summary> /// <param name="dataClientId">data client id</param> public static void ValidateDataClientId(string dataClientId) { Microsoft.Hpc.Scheduler.Session.Internal.Utility.ThrowIfNullOrEmpty(dataClientId, "dataClientId"); ParamCheckUtility.ThrowIfTooLong(dataClientId.Length, "dataClientId", Internal.Constant.MaxDataClientIdLength, SR.DataClientIdTooLong, Internal.Constant.MaxDataClientIdLength); ParamCheckUtility.ThrowIfNotMatchRegex(ParamCheckUtility.DataClientIdValid, dataClientId, "dataClientId", SR.DataClientIdInvalid); }
/// <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)); }
/// <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); }