internal static Message CreateMessage(InvokeMethodRequest request, InvokeMethodOptions options) { var message = new Message( Message.Categories.Application, (options & InvokeMethodOptions.OneWay) != 0 ? Message.Directions.OneWay : Message.Directions.Request) { Id = CorrelationId.GetNext(), InterfaceId = request.InterfaceId, MethodId = request.MethodId, IsReadOnly = (options & InvokeMethodOptions.ReadOnly) != 0, IsUnordered = (options & InvokeMethodOptions.Unordered) != 0, BodyObject = request }; if ((options & InvokeMethodOptions.AlwaysInterleave) != 0) message.IsAlwaysInterleave = true; RequestContext.ExportToMessage(message); return message; }
public void InvokeMethod(ManagementOperationObserver watcher, string methodName, ManagementBaseObject inParameters, InvokeMethodOptions options) {}
private void SendRequestMessage( GrainReference target, Message message, TaskCompletionSource <object> context, Action <Message, TaskCompletionSource <object> > callback, string debugContext, InvokeMethodOptions options, string genericArguments = null) { // fill in sender if (message.SendingSilo == null) { message.SendingSilo = MySilo; } if (!String.IsNullOrEmpty(genericArguments)) { message.GenericGrainType = genericArguments; } SchedulingContext schedulingContext = RuntimeContext.Current != null ? RuntimeContext.Current.ActivationContext as SchedulingContext : null; ActivationData sendingActivation = null; if (schedulingContext == null) { throw new InvalidOperationException( String.Format("Trying to send a message {0} on a silo not from within grain and not from within system target (RuntimeContext is not set to SchedulingContext) " + "RuntimeContext.Current={1} TaskScheduler.Current={2}", message, RuntimeContext.Current == null ? "null" : RuntimeContext.Current.ToString(), TaskScheduler.Current)); } switch (schedulingContext.ContextType) { case SchedulingContextType.SystemThread: throw new ArgumentException( String.Format("Trying to send a message {0} on a silo not from within grain and not from within system target (RuntimeContext is of SchedulingContextType.SystemThread type)", message), "context"); case SchedulingContextType.Activation: message.SendingActivation = schedulingContext.Activation.ActivationId; message.SendingGrain = schedulingContext.Activation.Grain; sendingActivation = schedulingContext.Activation; break; case SchedulingContextType.SystemTarget: message.SendingActivation = schedulingContext.SystemTarget.ActivationId; message.SendingGrain = ((ISystemTargetBase)schedulingContext.SystemTarget).GrainId; break; } // fill in destination var targetGrainId = target.GrainId; message.TargetGrain = targetGrainId; if (targetGrainId.IsSystemTarget) { SiloAddress targetSilo = (target.SystemTargetSilo ?? MySilo); message.TargetSilo = targetSilo; message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, targetSilo); message.Category = targetGrainId.Equals(Constants.MembershipOracleId) ? Message.Categories.Ping : Message.Categories.System; } if (target.IsObserverReference) { message.TargetObserverId = target.ObserverId; } if (debugContext != null) { message.DebugContext = debugContext; } var oneWay = (options & InvokeMethodOptions.OneWay) != 0; if (context == null && !oneWay) { logger.Warn(ErrorCode.IGC_SendRequest_NullContext, "Null context {0}: {1}", message, Utils.GetStackTrace()); } if (message.IsExpirableMessage(Config.Globals.DropExpiredMessages)) { message.TimeToLive = ResponseTimeout; } if (!oneWay) { var callbackData = new CallbackData( callback, tryResendMessage, context, message, unregisterCallback, messagingOptions, this.callbackDataLogger, this.timerLogger); callbacks.TryAdd(message.Id, callbackData); callbackData.StartTimer(ResponseTimeout); } if (targetGrainId.IsSystemTarget) { // Messages to system targets bypass the task system and get sent "in-line" this.Dispatcher.TransportMessage(message); } else { this.Dispatcher.SendMessage(message, sendingActivation); } }
public T InvokeMethod <T>(Reference reference, int methodId, object[] arguments, InvokeMethodOptions options) { var sending = InvokerContext.Caller; var request = new InvokeMethodRequest(); request.MethodId = methodId; request.Arguments = arguments; var message = new Message(); message.Guid = Guid.NewGuid(); if (sending != null) { message.SendingSlio = sending.Address; message.SendingId = sending.Identity; } message.TargetSlio = reference.Address; message.TargetId = reference.Identity; message.Direction = options.HasFlag(InvokeMethodOptions.OneWay) ? Message.Directions.OneWay : Message.Directions.Request; message.BodyObject = request; return((T)messageCenter.SendRequest(message)); }
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource <object> context, Action <Message, TaskCompletionSource <object> > callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var message = Message.CreateMessage(request, options); SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments); }
public void SendRequest( GrainReference target, InvokeMethodRequest request, TaskCompletionSource <object> context, InvokeMethodOptions options) { var message = this.messageFactory.CreateMessage(request, options); message.InterfaceType = target.InterfaceType; message.InterfaceVersion = target.InterfaceVersion; // fill in sender if (message.SendingSilo == null) { message.SendingSilo = MySilo; } IGrainContext sendingActivation = RuntimeContext.CurrentGrainContext; if (sendingActivation == null) { var clientAddress = this.HostedClient.Address; message.SendingGrain = clientAddress.Grain; message.SendingActivation = clientAddress.Activation; } else { message.SendingActivation = sendingActivation.ActivationId; message.SendingGrain = sendingActivation.GrainId; } // fill in destination var targetGrainId = target.GrainId; message.TargetGrain = targetGrainId; SharedCallbackData sharedData; if (SystemTargetGrainId.TryParse(targetGrainId, out var systemTargetGrainId)) { message.TargetSilo = systemTargetGrainId.GetSiloAddress(); message.TargetActivation = ActivationId.GetDeterministic(targetGrainId); message.Category = targetGrainId.Type.Equals(Constants.MembershipOracleType) ? Message.Categories.Ping : Message.Categories.System; sharedData = this.systemSharedCallbackData; } else { sharedData = this.sharedCallbackData; } var oneWay = (options & InvokeMethodOptions.OneWay) != 0; if (context is null && !oneWay) { this.logger.Warn(ErrorCode.IGC_SendRequest_NullContext, "Null context {0}: {1}", message, Utils.GetStackTrace()); } if (message.IsExpirableMessage(this.messagingOptions.DropExpiredMessages)) { message.TimeToLive = sharedData.ResponseTimeout; } if (!oneWay) { var callbackData = new CallbackData(sharedData, context, message); callbacks.TryAdd(message.Id, callbackData); } this.messagingTrace.OnSendRequest(message); this.Dispatcher.SendMessage(message, sendingActivation); }
public static bool IsTransactional(this InvokeMethodOptions options) { return((options & InvokeMethodOptions.TransactionMask) != 0); }
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var message = Message.CreateMessage(request, options); SendRequestMessage(target, message, context, callback, debugContext, options, genericArguments); }
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource <object> context, InvokeMethodOptions options) { var message = this.messageFactory.CreateMessage(request, options); OrleansOutsideRuntimeClientEvent.Log.SendRequest(message); SendRequestMessage(target, message, context, options); }
private Task <object> InvokeMethod_Impl(GrainReference reference, InvokeMethodRequest request, string debugContext, InvokeMethodOptions options) { if (debugContext == null && USE_DEBUG_CONTEXT) { if (USE_DEBUG_CONTEXT_PARAMS) { #pragma warning disable 162 // This is normally unreachable code, but kept for debugging purposes debugContext = GetDebugContext(reference.InterfaceName, reference.GetMethodName(reference.InterfaceId, request.MethodId), request.Arguments); #pragma warning restore 162 } else { var hash = reference.InterfaceId ^ request.MethodId; if (!debugContexts.TryGetValue(hash, out debugContext)) { debugContext = GetDebugContext(reference.InterfaceName, reference.GetMethodName(reference.InterfaceId, request.MethodId), request.Arguments); debugContexts[hash] = debugContext; } } } // Call any registered client pre-call interceptor function. CallClientInvokeCallback(reference, request); bool isOneWayCall = ((options & InvokeMethodOptions.OneWay) != 0); var resolver = isOneWayCall ? null : new TaskCompletionSource <object>(); this.RuntimeClient.SendRequest(reference, request, resolver, this.responseCallbackDelegate, debugContext, options, reference.GenericArguments); return(isOneWayCall ? null : resolver.Task); }
public static OperationReturn StopServiceByName(string strServiceName) { OperationReturn optReturn = new OperationReturn(); optReturn.Result = true; optReturn.Code = Defines.RET_SUCCESS; try { InvokeMethodOptions OperationMethodOptions = new InvokeMethodOptions(null, new TimeSpan(0, 10, 0)); ManagementBaseObject LOutStopService; ManagementObjectCollection ObjectCollection; ObjectCollection = GetServiceCollection(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", strServiceName)); int i = ObjectCollection.Count; string LStrProcessId = string.Empty; string LStrDisplayName = string.Empty; int LIntReturnValue = -1; string strStatus = string.Empty; foreach (ManagementObject SingleCollenction in ObjectCollection) { LStrProcessId = SingleCollenction["ProcessId"].ToString(); LStrDisplayName = SingleCollenction["DisplayName"].ToString(); strStatus = SingleCollenction["State"].ToString(); if (strStatus == "Stopped") { return(optReturn); } LOutStopService = SingleCollenction.InvokeMethod("StopService", null, OperationMethodOptions); LIntReturnValue = int.Parse(LOutStopService["ReturnValue"].ToString()); if (LIntReturnValue != 0) { int LIntWaitCount = 0; string LStrServiceCurrentStatus = string.Empty; optReturn = GetComputerServiceStatus(strServiceName); if (!optReturn.Result) { return(optReturn); } LStrServiceCurrentStatus = optReturn.Data as string; while (LStrServiceCurrentStatus != "0" && LIntWaitCount < 30) { System.Threading.Thread.Sleep(1000); LIntWaitCount += 1; optReturn = GetComputerServiceStatus(strServiceName); if (!optReturn.Result) { return(optReturn); } LStrServiceCurrentStatus = optReturn.Data as string; if (LStrServiceCurrentStatus == "0") { break; } } if (LStrServiceCurrentStatus == "0") { LIntReturnValue = 0; } else { KillProcess(LStrProcessId); LIntReturnValue = 0; } } //判断服务状态 直到变成Stopped为止 30s不停止 杀掉进程 optReturn = GetComputerServiceStatus(strServiceName); if (!optReturn.Result) { return(optReturn); } int status = (optReturn.Data as ServiceEnty).ServiceStatus; int iCount = 0; while (status != 1 && iCount < 30) { System.Threading.Thread.Sleep(1000); optReturn = GetComputerServiceStatus(strServiceName); if (!optReturn.Result) { return(optReturn); } status = (optReturn.Data as ServiceEnty).ServiceStatus; iCount++; if (status == 1) { break; } } if (status != 1) { KillProcess(LStrProcessId); } } //保险起见 再杀一次进程 if (!string.IsNullOrEmpty(LStrProcessId)) { KillProcess(LStrProcessId); } return(optReturn); } catch (Exception ex) { optReturn.Result = false; optReturn.Code = ConstDefines.Stop_Service_Exception; optReturn.Message = ex.Message; return(optReturn); } }
public string StartService(string serviceName, int timeout, int retryAttempts, int retryWaitMilliseconds) { string result = string.Empty; string host = Scope.Path.Server; ManagementObjectCollection queryCollection = null; string retCode = string.Empty; bool svcStarted = false; string svcStartMode = string.Empty; try { ObjectQuery query = new ObjectQuery("SELECT Name,ProcessId,State,Started, StartMode FROM Win32_service WHERE name='" + serviceName + "'"); ManagementObjectCollection queryColl = Query(query, WmiPath.Root); int mgmtObjCount = queryColl.Count; queryCollection = Query(query, WmiPath.Root); if (mgmtObjCount > 0) { foreach (ManagementObject service in queryCollection) { svcStartMode = service.GetValue("StartMode"); if (service["Started"].Equals(false)) { InvokeMethodOptions options = new InvokeMethodOptions(); options.Timeout = System.TimeSpan.FromMinutes(0); //spaul-changed this to 0 since we're manually handling it. ManagementBaseObject mbo = service.InvokeMethod("StartService", null, options); retCode = Enum.GetName(typeof(ServiceReturnCode), mbo["returnValue"]); result = string.Format("{0}|{1}", retCode, service.GetValue("StartMode")); } else { result = string.Format("{0}|{1}", "ServiceAlreadyRunning", service.GetValue("StartMode")); } } int retryCount = 0; string state = string.Empty; while (retryCount < retryAttempts && !svcStarted) { Thread.Sleep(retryWaitMilliseconds); //sleeping for 5 seconds queryCollection = Query(query, WmiPath.Root); foreach (ManagementObject service in queryCollection) { state = service.GetValueLower("State"); } if ((result.ToLower().Equals("success")) && (!state.Equals("running") || !state.Equals("started"))) { svcStarted = false; retryCount++; } else { retCode = "Success"; result = string.Format("{0}|{1}", retCode, svcStartMode); svcStarted = true; break; } retryCount++; if (svcStarted) { break; } } } else { string requestStatus = Enum.GetName(typeof(ServiceReturnCode), ServiceReturnCode.ServiceNotFound); result = string.Format("{0}|{1}", requestStatus, "ServiceNotFound"); } } catch (InvalidOperationException ioex) { throw ioex; } catch (Exception ex) { throw ex; } return(result); }
/// <summary> /// StopService /// if timeout value is not provided- we'll wait for 120 seconds, before terminating the process behind the service /// if timeout value is 0 - we'll never terminate the Process /// if timeout value is > 0 - we'll terminate the Process at teh timeoout value specified /// </summary> /// <param name="serviceName"></param> /// <param name="timeoutSeconds"></param> /// <returns></returns> public string StopService(string serviceName, int timeout, int retryAttempts, int retryWaitMilliseconds) { string result = string.Empty; string host = Scope.Path.Server; string processId = string.Empty; ObjectQuery query = null; bool serviceStopped = false; string state = string.Empty; string actionReturnCode = string.Empty; string processStartMode = string.Empty; bool canAcceptStop = false; ManagementObjectCollection queryCollection = null; string serviceStopResult = string.Empty; string requestStatus = string.Empty; try { query = new ObjectQuery("SELECT Name,ProcessId,State,Started, StartMode, AcceptStop FROM Win32_Service WHERE name='" + serviceName + "'"); ManagementObjectCollection queryColl = Query(query, WmiPath.Root); int mgmtObjCount = queryColl.Count; queryCollection = Query(query, WmiPath.Root); if (mgmtObjCount <= 0) { requestStatus = Enum.GetName(typeof(ServiceReturnCode), ServiceReturnCode.ServiceNotFound); state = Enum.GetName(typeof(ServiceReturnCode), ServiceReturnCode.ServiceNotFound); serviceStopResult = "ServiceStopFailed"; result = string.Format("{0}|{1}|{2}|{3}", requestStatus, processStartMode, state, serviceStopResult); } else { foreach (ManagementObject service in queryCollection) { processStartMode = service.GetValue("StartMode"); state = service.GetValue("State"); processId = service.GetValue("ProcessId"); canAcceptStop = Boolean.Parse(service.GetValue("AcceptStop")); if (canAcceptStop.Equals(true) && (service.GetValueLower("State").Equals("running") || service.GetValueLower("State").Equals("started"))) { InvokeMethodOptions options = new InvokeMethodOptions(); options.Timeout = System.TimeSpan.FromMilliseconds(timeout); ManagementBaseObject mbo = service.InvokeMethod("StopService", null, options); actionReturnCode = Enum.GetName(typeof(ServiceReturnCode), mbo["returnValue"]); result = string.Format("{0}|{1}|{2}|{3}", Enum.GetName(typeof(ServiceReturnCode), mbo["returnValue"]), processStartMode, state, state); } else if (service.GetValueLower("State") == "stopped") { requestStatus = "ServiceAlreadyStopped"; serviceStopResult = "Stopped"; result = string.Format("{0}|{1}|{2}|{3}", requestStatus, processStartMode, state, serviceStopResult); serviceStopped = true; } else if (service.GetValueLower("State").Replace(" ", "") == "stoppending" || service.GetValueLower("State").Replace(" ", "") == "stopping") { requestStatus = "StopPending"; serviceStopResult = "ServiceStopping"; result = string.Format("{0}|{1}|{2}|{3}", requestStatus, processStartMode, state, serviceStopResult); serviceStopped = false; } else { requestStatus = "Servicecannotacceptstoprequestatthistime"; serviceStopResult = "ServiceCannotBeStopped"; result = string.Format("{0}|{1}|{2}|{3}", requestStatus, processStartMode, state, serviceStopResult); } } if (!serviceStopped) { //poll-requery to check if the svc has stopped serviceStopped = PollForServiceStop(serviceName, timeout, retryAttempts, retryWaitMilliseconds, ref state, ref processStartMode); if (!state.Trim().ToLower().Equals("stopped")) { if (timeout != 0) { //Terminate Process , since the service has not been stopped yet if (processId != string.Empty) { result = TerminateProcess("", processId.Trim()); //poll to check if service has been ternminated serviceStopped = PollForServiceStop(serviceName, timeout, retryAttempts, retryWaitMilliseconds, ref state, ref processStartMode); requestStatus = actionReturnCode; serviceStopResult = "Terminated"; result = string.Format("{0}|{1}|{2}|{3}", requestStatus, processStartMode, state, serviceStopResult); } } else { requestStatus = Enum.GetName(typeof(ServiceReturnCode), ServiceReturnCode.ServiceRequestTimeout); serviceStopResult = "ServiceStopFailed"; result = string.Format("{0}|{1}|{2}|{3}", requestStatus, processStartMode, state, serviceStopResult); } } } } } catch (InvalidOperationException ioex) { throw ioex; } catch (Exception ex) { throw ex; } return(result); }
/// <summary> /// 重启服务 /// </summary> /// <param name="strServiceName"></param> public static bool RestartService(string strServiceName) { try { InvokeMethodOptions OperationMethodOptions = new InvokeMethodOptions(null, new TimeSpan(0, 10, 0)); ManagementBaseObject LOutStopService; ManagementObjectCollection ObjectCollection; ObjectCollection = GetServiceCollection(string.Format("SELECT * FROM Win32_Service WHERE Name = '{0}'", strServiceName)); int i = ObjectCollection.Count; string LStrProcessId = string.Empty; string LStrDisplayName = string.Empty; int LIntReturnValue = -1; foreach (ManagementObject SingleCollenction in ObjectCollection) { LStrProcessId = SingleCollenction["ProcessId"].ToString(); LStrDisplayName = SingleCollenction["DisplayName"].ToString(); LOutStopService = SingleCollenction.InvokeMethod("StopService", null, OperationMethodOptions); LIntReturnValue = int.Parse(LOutStopService["ReturnValue"].ToString()); UMPService00.WriteLog("StopService ReturnValue = " + LIntReturnValue.ToString()); if (LIntReturnValue != 0) { int LIntWaitCount = 0; string LStrServiceCurrentStatus = GetComputerServiceStatus(strServiceName); if (string.IsNullOrEmpty(LStrServiceCurrentStatus)) { UMPService00.WriteLog("GetComputerServiceStatus null"); return(false); } while (LStrServiceCurrentStatus != "0" && LIntWaitCount < 30) { System.Threading.Thread.Sleep(2000); LIntWaitCount += 1; LStrServiceCurrentStatus = GetComputerServiceStatus(strServiceName); UMPService00.WriteLog("GetComputerServiceStatus LStrServiceCurrentStatus = " + LStrServiceCurrentStatus.ToString()); if (string.IsNullOrEmpty(LStrServiceCurrentStatus)) { UMPService00.WriteLog("GetComputerServiceStatus LStrServiceCurrentStatus is null ,return false"); return(false); } } if (LStrServiceCurrentStatus == "0") { LIntReturnValue = 0; } else { KillProcess(LStrProcessId); LIntReturnValue = 0; } //for (int iStartCount = 0; iStartCount < 30; iStartCount++) //{ // Thread.Sleep(2000); // try // { // UMPService00.IEventLog.WriteEntry("start service begin " + iStartCount.ToString()); // LOutStopService = SingleCollenction.InvokeMethod("StartService", null, OperationMethodOptions); // LIntReturnValue = int.Parse(LOutStopService["ReturnValue"].ToString()); // UMPService00.IEventLog.WriteEntry("Restart service " + strServiceName + ", " + iStartCount.ToString() + ", result = " + LIntReturnValue.ToString(), EventLogEntryType.Warning); // if (LIntReturnValue == 0) // { // return true; // } // } // catch (Exception ex) // { // UMPService00.IEventLog.WriteEntry("start service exception : " + ex.Message); // } //} } UMPService00.WriteLog("stop server success", EventLogEntryType.Information); for (int iStartCount = 0; iStartCount < 30; iStartCount++) { Thread.Sleep(2000); try { UMPService00.WriteLog("start service begin " + iStartCount.ToString()); LOutStopService = SingleCollenction.InvokeMethod("StartService", null, OperationMethodOptions); LIntReturnValue = int.Parse(LOutStopService["ReturnValue"].ToString()); UMPService00.WriteLog(LogMode.Error, "Restart service " + strServiceName + ", " + iStartCount.ToString() + ", result = " + LIntReturnValue.ToString()); if (LIntReturnValue == 0) { return(true); } } catch (Exception ex) { UMPService00.WriteLog("start service exception : " + ex.Message); } } } return(true); } catch (Exception ex) { UMPService00.WriteLog(EventLogEntryType.Error, "Restart service " + strServiceName + " error : " + ex.Message); return(false); } }
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource <object> context, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var targetGrainId = target.GrainId; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; message.SendingGrain = CurrentActivationAddress.Grain; message.SendingActivation = CurrentActivationAddress.Activation; message.TargetGrain = targetGrainId; if (!String.IsNullOrEmpty(genericArguments)) { message.GenericGrainType = genericArguments; } if (targetGrainId.IsSystemTarget) { // If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo message.TargetSilo = target.SystemTargetSilo; if (target.SystemTargetSilo != null) { message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo); } } // Client sending messages to another client (observer). Yes, we support that. if (target.IsObserverReference) { message.TargetObserverId = target.ObserverId; } if (debugContext != null) { message.DebugContext = debugContext; } if (message.IsExpirableMessage(this.clientMessagingOptions.DropExpiredMessages)) { // don't set expiration for system target messages. message.TimeToLive = this.clientMessagingOptions.ResponseTimeout; } if (!oneWay) { var callbackData = new CallbackData(this.sharedCallbackData, context, message); callbacks.TryAdd(message.Id, callbackData); } if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("Send {0}", message); } transport.SendMessage(message); }
internal static Message CreateMessage(InvokeMethodRequest request, InvokeMethodOptions options) { var message = new Message( Categories.Application, (options & InvokeMethodOptions.OneWay) != 0 ? Directions.OneWay : Directions.Request) { Id = CorrelationId.GetNext(), IsReadOnly = (options & InvokeMethodOptions.ReadOnly) != 0, IsUnordered = (options & InvokeMethodOptions.Unordered) != 0, BodyObject = request }; if ((options & InvokeMethodOptions.AlwaysInterleave) != 0) message.IsAlwaysInterleave = true; var contextData = RequestContext.Export(); if (contextData != null) { message.RequestContextData = contextData; } return message; }
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource <object> context, InvokeMethodOptions options) { message.InterfaceType = target.InterfaceType; message.InterfaceVersion = target.InterfaceVersion; var targetGrainId = target.GrainId; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; message.SendingGrain = CurrentActivationAddress.Grain; message.SendingActivation = CurrentActivationAddress.Activation; message.TargetGrain = targetGrainId; if (SystemTargetGrainId.TryParse(targetGrainId, out var systemTargetGrainId)) { // If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo message.TargetSilo = systemTargetGrainId.GetSiloAddress(); message.TargetActivation = ActivationId.GetDeterministic(targetGrainId); } if (message.IsExpirableMessage(this.clientMessagingOptions.DropExpiredMessages)) { // don't set expiration for system target messages. message.TimeToLive = this.clientMessagingOptions.ResponseTimeout; } if (!oneWay) { var callbackData = new CallbackData(this.sharedCallbackData, context, message); callbacks.TryAdd(message.Id, callbackData); } if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace("Send {0}", message); } MessageCenter.SendMessage(message); }
/// <summary> /// Called from generated code. /// </summary> protected Task <T> InvokeMethodAsync <T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None) { return(this.Runtime.InvokeMethodAsync <T>(this, methodId, arguments, options | _shared.InvokeMethodOptions)); }
private Task <object> InvokeMethod_Impl(GrainReference reference, InvokeMethodRequest request, string debugContext, InvokeMethodOptions options) { if (debugContext == null && USE_DEBUG_CONTEXT) { if (USE_DEBUG_CONTEXT_PARAMS) { #pragma warning disable 162 // This is normally unreachable code, but kept for debugging purposes debugContext = GetDebugContext(reference.InterfaceName, reference.GetMethodName(reference.InterfaceId, request.MethodId), request.Arguments); #pragma warning restore 162 } else { var hash = reference.InterfaceId ^ request.MethodId; if (!debugContexts.TryGetValue(hash, out debugContext)) { debugContext = GetDebugContext(reference.InterfaceName, reference.GetMethodName(reference.InterfaceId, request.MethodId), request.Arguments); debugContexts[hash] = debugContext; } } } // Call any registered client pre-call interceptor function. CallClientInvokeCallback(reference, request); if (this.filters?.Length > 0) { return(InvokeWithFilters(reference, request, debugContext, options)); } return(SendRequest(reference, request, debugContext, options)); }
public static bool IsTransactionOption(this InvokeMethodOptions options, InvokeMethodOptions test) { return((options & InvokeMethodOptions.TransactionMask) == test); }
private Task <object> SendRequest(GrainReference reference, InvokeMethodRequest request, string debugContext, InvokeMethodOptions options) { bool isOneWayCall = (options & InvokeMethodOptions.OneWay) != 0; var resolver = isOneWayCall ? null : new TaskCompletionSource <object>(); this.RuntimeClient.SendRequest(reference, request, resolver, this.responseCallbackDelegate, debugContext, options, reference.GenericArguments); return(isOneWayCall ? null : resolver.Task); }
private Task <object> InvokeMethod_Impl(InvokeMethodRequest request, string debugContext, InvokeMethodOptions options) { if (debugContext == null && USE_DEBUG_CONTEXT) { if (USE_DEBUG_CONTEXT_PARAMS) { debugContext = GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments); } else { var hash = InterfaceId ^ request.MethodId; if (!debugContexts.TryGetValue(hash, out debugContext)) { debugContext = GetDebugContext(this.InterfaceName, GetMethodName(this.InterfaceId, request.MethodId), request.Arguments); debugContexts[hash] = debugContext; } } } // Call any registered client pre-call interceptor function. CallClientInvokeCallback(request); bool isOneWayCall = ((options & InvokeMethodOptions.OneWay) != 0); var resolver = isOneWayCall ? null : new TaskCompletionSource <object>(); RuntimeClient.Current.SendRequest(this, request, resolver, ResponseCallback, debugContext, options, genericArguments); return(isOneWayCall ? null : resolver.Task); }
private async Task <object> InvokeWithFilters(GrainReference reference, InvokeMethodRequest request, string debugContext, InvokeMethodOptions options) { var invoker = new OutgoingCallInvoker(reference, request, options, debugContext, this.sendRequestDelegate, this.grainReferenceMethodCache, this.filters); await invoker.Invoke(); return(invoker.Result); }
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource <object> context, Action <Message, TaskCompletionSource <object> > callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var targetGrainId = target.GrainId; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; message.SendingGrain = CurrentActivationAddress.Grain; message.SendingActivation = CurrentActivationAddress.Activation; message.TargetGrain = targetGrainId; if (!String.IsNullOrEmpty(genericArguments)) { message.GenericGrainType = genericArguments; } if (targetGrainId.IsSystemTarget) { // If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo message.TargetSilo = target.SystemTargetSilo; if (target.SystemTargetSilo != null) { message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo); } } // Client sending messages to another client (observer). Yes, we support that. if (target.IsObserverReference) { message.TargetObserverId = target.ObserverId; } if (debugContext != null) { message.DebugContext = debugContext; } if (message.IsExpirableMessage(config)) { // don't set expiration for system target messages. message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW; } if (!oneWay) { var callbackData = new CallbackData(callback, TryResendMessage, context, message, () => UnRegisterCallback(message.Id), config); callbacks.TryAdd(message.Id, callbackData); callbackData.StartTimer(responseTimeout); } if (logger.IsVerbose2) { logger.Verbose2("Send {0}", message); } transport.SendMessage(message); }
/// <inheritdoc /> public void InvokeOneWayMethod(GrainReference reference, int methodId, object[] arguments, InvokeMethodOptions options, SiloAddress silo) { Task <object> resultTask = InvokeMethodAsync <object>(reference, methodId, arguments, options | InvokeMethodOptions.OneWay, silo); if (!resultTask.IsCompleted && resultTask.Result != null) { throw new OrleansException("Unexpected return value: one way InvokeMethod is expected to return null."); } }
/// <summary> /// Incorporates the provided invocation options. /// </summary> /// <param name="options"> /// The options. /// </param> public void AddInvokeMethodOptions(InvokeMethodOptions options) { Options |= options; }
/// <inheritdoc /> public Task <T> InvokeMethodAsync <T>(GrainReference reference, int methodId, object[] arguments, InvokeMethodOptions options, SiloAddress silo) { if (arguments != null) { CheckForGrainArguments(arguments); SetGrainCancellationTokensTarget(arguments, reference); this.serializationManager.DeepCopyElementsInPlace(arguments); } var request = new InvokeMethodRequest(reference.InterfaceId, reference.InterfaceVersion, methodId, arguments); if (IsUnordered(reference)) { options |= InvokeMethodOptions.Unordered; } Task <object> resultTask = InvokeMethod_Impl(reference, request, null, options); if (resultTask == null) { if (typeof(T) == typeof(object)) { // optimize for most common case when using one way calls. return(OrleansTaskExtentions.CompletedTask as Task <T>); } return(Task.FromResult(default(T))); } resultTask = OrleansTaskExtentions.ConvertTaskViaTcs(resultTask); return(resultTask.ToTypedTask <T>()); }
public ManagementBaseObject InvokeMethod(string methodName, ManagementBaseObject inParameters, InvokeMethodOptions options) {}
public void SendRequest( GrainReference target, InvokeMethodRequest request, TaskCompletionSource <object> context, InvokeMethodOptions options, string genericArguments) { var message = this.messageFactory.CreateMessage(request, options); // fill in sender if (message.SendingSilo == null) { message.SendingSilo = MySilo; } if (!String.IsNullOrEmpty(genericArguments)) { message.GenericGrainType = genericArguments; } IGrainContext sendingActivation = RuntimeContext.CurrentGrainContext; if (sendingActivation == null) { var clientAddress = this.HostedClient.ClientAddress; message.SendingGrain = clientAddress.Grain; message.SendingActivation = clientAddress.Activation; } else { message.SendingActivation = sendingActivation.ActivationId; message.SendingGrain = sendingActivation.GrainId; } // fill in destination var targetGrainId = target.GrainId; message.TargetGrain = targetGrainId; SharedCallbackData sharedData; if (targetGrainId.IsSystemTarget()) { SiloAddress targetSilo = (target.SystemTargetSilo ?? MySilo); message.TargetSilo = targetSilo; message.TargetActivation = ActivationId.GetDeterministic(targetGrainId); message.Category = targetGrainId.Equals(Constants.MembershipOracleId) ? Message.Categories.Ping : Message.Categories.System; sharedData = this.systemSharedCallbackData; } else { sharedData = this.sharedCallbackData; } if (target.IsObserverReference) { message.TargetObserverId = target.ObserverId; } var oneWay = (options & InvokeMethodOptions.OneWay) != 0; if (context is null && !oneWay) { this.logger.Warn(ErrorCode.IGC_SendRequest_NullContext, "Null context {0}: {1}", message, Utils.GetStackTrace()); } if (message.IsExpirableMessage(this.messagingOptions.DropExpiredMessages)) { message.TimeToLive = sharedData.ResponseTimeout; } if (!oneWay) { var callbackData = new CallbackData(sharedData, context, message); callbacks.TryAdd(message.Id, callbackData); } this.messagingTrace.OnSendRequest(message); if (targetGrainId.IsSystemTarget()) { // Messages to system targets bypass the task system and get sent "in-line" this.Dispatcher.TransportMessage(message); } else { this.Dispatcher.SendMessage(message, sendingActivation); } }
public void SendRequest(GrainReference target, InvokeMethodRequest request, TaskCompletionSource <object> context, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var message = this.messageFactory.CreateMessage(request, options); EventSourceUtils.EmitEvent(message, OrleansOutsideRuntimeClientEvent.SendRequestAction); SendRequestMessage(target, message, context, debugContext, options, genericArguments); }
/// <summary> /// Constructs a copy of a grain reference. /// </summary> /// <param name="other">The reference to copy.</param> protected GrainReference(GrainReference other) : this(other.GrainId, other.genericArguments, other.SystemTargetSilo, other.ObserverId, other.runtime) { this.invokeMethodOptions = other.invokeMethodOptions; }
protected internal GrainReference(GrainReference other, InvokeMethodOptions invokeMethodOptions) : this(other) { this.invokeMethodOptions = invokeMethodOptions; }
/// <summary> /// Called from generated code. /// </summary> protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { this.Runtime.InvokeOneWayMethod(this, methodId, arguments, options | invokeMethodOptions, silo); }
private void SendRequestMessage( GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext, InvokeMethodOptions options, string genericArguments = null) { // fill in sender if (message.SendingSilo == null) message.SendingSilo = MySilo; if (!String.IsNullOrEmpty(genericArguments)) message.GenericGrainType = genericArguments; SchedulingContext schedulingContext = RuntimeContext.Current != null ? RuntimeContext.Current.ActivationContext as SchedulingContext : null; ActivationData sendingActivation = null; if (schedulingContext == null) { throw new InvalidExpressionException( String.Format("Trying to send a message {0} on a silo not from within grain and not from within system target (RuntimeContext is not set to SchedulingContext) " + "RuntimeContext.Current={1} TaskScheduler.Current={2}", message, RuntimeContext.Current == null ? "null" : RuntimeContext.Current.ToString(), TaskScheduler.Current)); } switch (schedulingContext.ContextType) { case SchedulingContextType.SystemThread: throw new ArgumentException( String.Format("Trying to send a message {0} on a silo not from within grain and not from within system target (RuntimeContext is of SchedulingContextType.SystemThread type)", message), "context"); case SchedulingContextType.Activation: message.SendingActivation = schedulingContext.Activation.ActivationId; message.SendingGrain = schedulingContext.Activation.Grain; sendingActivation = schedulingContext.Activation; break; case SchedulingContextType.SystemTarget: message.SendingActivation = schedulingContext.SystemTarget.ActivationId; message.SendingGrain = schedulingContext.SystemTarget.GrainId; break; } // fill in destination var targetGrainId = target.GrainId; message.TargetGrain = targetGrainId; if (targetGrainId.IsSystemTarget) { SiloAddress targetSilo = (target.SystemTargetSilo ?? MySilo); message.TargetSilo = targetSilo; message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, targetSilo); message.Category = targetGrainId.Equals(Constants.MembershipOracleId) ? Message.Categories.Ping : Message.Categories.System; } if (target.IsObserverReference) { message.TargetObserverId = target.ObserverId; } if (debugContext != null) message.DebugContext = debugContext; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; if (context == null && !oneWay) logger.Warn(ErrorCode.IGC_SendRequest_NullContext, "Null context {0}: {1}", message, new StackTrace()); if (message.IsExpirableMessage(Config.Globals)) message.Expiration = DateTime.UtcNow + ResponseTimeout + Constants.MAXIMUM_CLOCK_SKEW; if (!oneWay) { var callbackData = new CallbackData( callback, TryResendMessage, context, message, () => UnRegisterCallback(message.Id), Config.Globals); callbacks.TryAdd(message.Id, callbackData); callbackData.StartTimer(ResponseTimeout); } if (targetGrainId.IsSystemTarget) { // Messages to system targets bypass the task system and get sent "in-line" dispatcher.TransportMessage(message); } else { dispatcher.SendMessage(message, sendingActivation); } }
/// <summary> /// Called from generated code. /// </summary> protected Task <T> InvokeMethodAsync <T>(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None, SiloAddress silo = null) { return(this.Runtime.InvokeMethodAsync <T>(this, methodId, arguments, options | invokeMethodOptions, silo)); }
private void SendRequestMessage(GrainReference target, Message message, TaskCompletionSource<object> context, Action<Message, TaskCompletionSource<object>> callback, string debugContext = null, InvokeMethodOptions options = InvokeMethodOptions.None, string genericArguments = null) { var targetGrainId = target.GrainId; var oneWay = (options & InvokeMethodOptions.OneWay) != 0; message.SendingGrain = CurrentActivationAddress.Grain; message.SendingActivation = CurrentActivationAddress.Activation; message.TargetGrain = targetGrainId; if (!String.IsNullOrEmpty(genericArguments)) message.GenericGrainType = genericArguments; if (targetGrainId.IsSystemTarget) { // If the silo isn't be supplied, it will be filled in by the sender to be the gateway silo message.TargetSilo = target.SystemTargetSilo; if (target.SystemTargetSilo != null) { message.TargetActivation = ActivationId.GetSystemActivation(targetGrainId, target.SystemTargetSilo); } } // Client sending messages to another client (observer). Yes, we support that. if (target.IsObserverReference) { message.TargetObserverId = target.ObserverId; } if (debugContext != null) { message.DebugContext = debugContext; } if (message.IsExpirableMessage(config)) { // don't set expiration for system target messages. message.Expiration = DateTime.UtcNow + responseTimeout + Constants.MAXIMUM_CLOCK_SKEW; } if (!oneWay) { var callbackData = new CallbackData(callback, TryResendMessage, context, message, () => UnRegisterCallback(message.Id), config); callbacks.TryAdd(message.Id, callbackData); callbackData.StartTimer(responseTimeout); } if (logger.IsVerbose2) logger.Verbose2("Send {0}", message); transport.SendMessage(message); }
/// <summary> /// Called from generated code. /// </summary> protected void InvokeOneWayMethod(int methodId, object[] arguments, InvokeMethodOptions options = InvokeMethodOptions.None) { this.Runtime.InvokeOneWayMethod(this, methodId, arguments, options | _shared.InvokeMethodOptions); }