/// <summary>
        /// Adds CancellationToken to the grain extension
        /// so that it can be cancelled through remote call to the CancellationSourcesExtension.
        /// </summary>
        /// <param name="target"></param>
        /// <param name="request"></param>
        /// <param name="logger"></param>
        internal static void RegisterCancellationTokens(IAddressable target, InvokeMethodRequest request, Logger logger)
        {
            for (var i = 0; i < request.Arguments.Length; i++)
            {
                var arg = request.Arguments[i];
                if (!(arg is GrainCancellationToken)) continue;
                var grainToken = ((GrainCancellationToken) request.Arguments[i]);

                CancellationSourcesExtension cancellationExtension;
                if (!SiloProviderRuntime.Instance.TryGetExtensionHandler(out cancellationExtension))
                {
                    cancellationExtension = new CancellationSourcesExtension();
                    if (!SiloProviderRuntime.Instance.TryAddExtension(cancellationExtension))
                    {
                        logger.Error(
                            ErrorCode.CancellationExtensionCreationFailed,
                            $"Could not add cancellation token extension to: {target}");
                        return;
                    }
                }

                // Replacing the half baked GrainCancellationToken that came from the wire with locally fully created one.
                request.Arguments[i] = cancellationExtension.RecordCancellationToken(grainToken.Id, grainToken.IsCancellationRequested);
            }
        }
Esempio n. 2
0
 public M6502(IAddressable mem)
 {
     this.mem = mem;
     InstallOpcodes();
     Clock = 0;
     RunClocks = 0;
     RunClocksMultiple = 1;
     P = 1 << 5;
 }
        public Task<object> Invoke(IAddressable grain, InvokeMethodRequest request)
        {
            var interceptor = grain as IGrainInvokeInterceptor;
            if (interceptor != null)
            {
                var methodInfo = this.GetMethodInfo(request.MethodId);
                return interceptor.Invoke(methodInfo, request, this.invoker);
            }

            return this.invoker.Invoke(grain, request);
        }
        /// <summary>
        /// Invoke a grain method.
        /// Invoker classes in generated code implement this method to provide a method call jump-table to map invoke
        /// data to a strongly typed call to the correct method on the correct interface.
        /// </summary>
        /// <param name="grain">Reference to the grain to be invoked.</param>
        /// <param name="request">The request being invoked.</param>
        /// <returns>Value promise for the result of the method invoke.</returns>
        public Task<object> Invoke(IAddressable grain, InvokeMethodRequest request)
        {
            // If the grain implements IGrainInvokeInterceptor then call its implementation, passing
            // the underlying invoker so that the grain can easily dispatch invocation to the correct method.
            var interceptor = grain as IGrainInvokeInterceptor;
            if (interceptor != null)
            {
                var methodInfo = this.GetMethodInfo(request.MethodId);
                return interceptor.Invoke(methodInfo, request, this.invoker);
            }

            // Otherwise, call the underlying invoker directly.
            return this.invoker.Invoke(grain, request);
        }
Esempio n. 5
0
            /// <summary>
            /// Invokes the appropriate grain or extension method for the request interface ID and method ID.
            /// First each extension invoker is tried; if no extension handles the request, then the base
            /// invoker is used to handle the request.
            /// The base invoker will throw an appropriate exception if the request is not recognized.
            /// </summary>
            /// <param name="grain"></param>
            /// <param name="interfaceId"></param>
            /// <param name="methodId"></param>
            /// <param name="arguments"></param>
            /// <returns></returns>
            public Task<object> Invoke(IAddressable grain, int interfaceId, int methodId, object[] arguments)
            {
                if (extensionMap == null || !extensionMap.ContainsKey(interfaceId))
                    throw new InvalidOperationException(
                        String.Format("Extension invoker invoked with an unknown inteface ID:{0}.", interfaceId));

                var invoker = extensionMap[interfaceId].Item2;
                var extension = extensionMap[interfaceId].Item1;
                return invoker.Invoke(extension, interfaceId, methodId, arguments);
            }
Esempio n. 6
0
 /// <summary>
 /// Called from generated code.
 /// </summary>
 public static Task <GrainReference> CreateObjectReference(IAddressable o, IGrainMethodInvoker invoker)
 {
     return(RuntimeClient.Current.CreateObjectReference(o, invoker));
 }
Esempio n. 7
0
 public static IClient Cast(IAddressable grainRef)
 {
     
     return (IClient) GrainReference.CastInternal(typeof(IClient), (GrainReference gr) => { return new ClientReference(gr);}, grainRef, 523268002);
 }
Esempio n. 8
0
 public static IDestination Cast(IAddressable grainRef)
 {
     
     return DestinationReference.Cast(grainRef);
 }
Esempio n. 9
0
 public async System.Threading.Tasks.Task<Object> Invoke(IAddressable grain, int interfaceId, int methodId, object[] arguments)
 {
         if (grain == null) throw new System.ArgumentNullException("grain");
         switch (interfaceId)
         {
             case 523268002:  // IClient
                 switch (methodId)
                 {
                     case 1975541297: 
                         await ((IClient)grain).Run();
                       return true;
                     case -2060440583: 
                         await ((IClient)grain).Pong((IDestination)arguments[0], (Message)arguments[1]);
                       return true;
                     case 1682027821: 
                         await ((IClient)grain).Initialize((IDestination)arguments[0], (Int64)arguments[1]);
                       return true;
                     case -1238941369: 
                         await ((IClient)grain).Subscribe((IClientObserver)arguments[0]);
                       return true;
                     default: 
                         throw new NotImplementedException("interfaceId="+interfaceId+",methodId="+methodId);
                 }
             default:
                 throw new System.InvalidCastException("interfaceId="+interfaceId);
         }
 }
Esempio n. 10
0
            /// <summary>
            /// Invokes the appropriate grain or extension method for the request interface ID and method ID.
            /// First each extension invoker is tried; if no extension handles the request, then the base
            /// invoker is used to handle the request.
            /// The base invoker will throw an appropriate exception if the request is not recognized.
            /// </summary>
            /// <param name="grain"></param>
            /// <param name="request"></param>
            /// <returns></returns>
            public Task<object> Invoke(IAddressable grain, InvokeMethodRequest request)
            {
                if (extensionMap == null || !extensionMap.ContainsKey(request.InterfaceId))
                    throw new InvalidOperationException(
                        String.Format("Extension invoker invoked with an unknown inteface ID:{0}.", request.InterfaceId));

                var invoker = extensionMap[request.InterfaceId].Item2;
                var extension = extensionMap[request.InterfaceId].Item1;
                return invoker.Invoke(extension, request);
            }
 public async System.Threading.Tasks.Task<Object> Invoke(IAddressable grain, int interfaceId, int methodId, object[] arguments)
 {
         if (grain == null) throw new System.ArgumentNullException("grain");
         switch (interfaceId)
         {
             case -1248350959:  // IDeviceGrain
                 switch (methodId)
                 {
                     case -1788431855: 
                         await ((IDeviceGrain)grain).SetTemperature((Double)arguments[0]);
                       return true;
                     case 98774684: 
                         return await ((IDeviceGrain)grain).GetTemperature();
                     default: 
                         throw new NotImplementedException("interfaceId="+interfaceId+",methodId="+methodId);
                 }
             default:
                 throw new System.InvalidCastException("interfaceId="+interfaceId);
         }
 }
Esempio n. 12
0
 /// <inheritdoc />
 public object Cast(IAddressable grain, Type outputGrainInterfaceType)
 => this.InternalGrainFactory.Cast(grain, outputGrainInterfaceType);
Esempio n. 13
0
        public async Task Invoke(IAddressable target, IInvokable invokable, Message message)
        {
            try
            {
                // Don't process messages that have already timed out
                if (message.IsExpired)
                {
                    message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Invoke);
                    return;
                }

                RequestContextExtensions.Import(message.RequestContextData);
                if (schedulingOptions.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget)
                {
                    UpdateDeadlockInfoInRequestContext(new RequestInvocationHistory(message.TargetGrain, message.TargetActivation, message.DebugContext));
                    // RequestContext is automatically saved in the msg upon send and propagated to the next hop
                    // in RuntimeClient.CreateMessage -> RequestContextExtensions.ExportToMessage(message);
                }

                bool             startNewTransaction = false;
                ITransactionInfo transactionInfo     = message.TransactionInfo;

                if (message.IsTransactionRequired && transactionInfo == null)
                {
                    // TODO: this should be a configurable parameter
                    var transactionTimeout = Debugger.IsAttached ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(10);

                    // Start a new transaction
                    transactionInfo = await this.transactionAgent.StartTransaction(message.IsReadOnly, transactionTimeout);

                    startNewTransaction = true;
                }

                if (transactionInfo != null)
                {
                    TransactionContext.SetTransactionInfo(transactionInfo);
                }

                object resultObject;
                try
                {
                    var request = (InvokeMethodRequest)message.GetDeserializedBody(this.serializationManager);
                    if (request.Arguments != null)
                    {
                        CancellationSourcesExtension.RegisterCancellationTokens(target, request, this.loggerFactory, logger, this, this.cancellationTokenRuntime);
                    }

                    var invoker = invokable.GetInvoker(typeManager, request.InterfaceId, message.GenericGrainType);

                    if (invoker is IGrainExtensionMethodInvoker &&
                        !(target is IGrainExtension) &&
                        !TryInstallExtension(request.InterfaceId, invokable, message.GenericGrainType, ref invoker))
                    {
                        // We are trying the invoke a grain extension method on a grain
                        // -- most likely reason is that the dynamic extension is not installed for this grain
                        // So throw a specific exception here rather than a general InvalidCastException
                        var error = String.Format(
                            "Extension not installed on grain {0} attempting to invoke type {1} from invokable {2}",
                            target.GetType().FullName, invoker.GetType().FullName, invokable.GetType().FullName);
                        var    exc            = new GrainExtensionNotInstalledException(error);
                        string extraDebugInfo = null;
#if DEBUG
                        extraDebugInfo = Utils.GetStackTrace();
#endif
                        logger.Warn(ErrorCode.Stream_ExtensionNotInstalled,
                                    string.Format("{0} for message {1} {2}", error, message, extraDebugInfo), exc);

                        throw exc;
                    }

                    var requestInvoker = new GrainMethodInvoker(target, request, invoker, GrainCallFilters, interfaceToImplementationMapping);
                    await requestInvoker.Invoke();

                    resultObject = requestInvoker.Result;
                }
                catch (Exception exc1)
                {
                    if (message.Direction == Message.Directions.OneWay)
                    {
                        invokeExceptionLogger.Warn(ErrorCode.GrainInvokeException,
                                                   "Exception during Grain method call of message: " + message, exc1);
                    }
                    else if (invokeExceptionLogger.IsEnabled(LogLevel.Debug))
                    {
                        invokeExceptionLogger.Debug(ErrorCode.GrainInvokeException,
                                                    "Exception during Grain method call of message: " + message, exc1);
                    }

                    if (transactionInfo != null)
                    {
                        transactionInfo.ReconcilePending();

                        // Record reason for abort, if not alread set
                        transactionInfo.RecordException(exc1, serializationManager);

                        if (startNewTransaction)
                        {
                            OrleansTransactionAbortedException abortException = transactionInfo.MustAbort(serializationManager);
                            this.transactionAgent.Abort(transactionInfo, abortException);
                            exc1 = abortException;
                        }
                    }

                    // If a grain allowed an inconsistent state exception to escape and the exception originated from
                    // this activation, then deactivate it.
                    var ise = exc1 as InconsistentStateException;
                    if (ise != null && ise.IsSourceActivation)
                    {
                        // Mark the exception so that it doesn't deactivate any other activations.
                        ise.IsSourceActivation = false;

                        var activation = (target as Grain)?.Data;
                        if (activation != null)
                        {
                            invokeExceptionLogger.Info($"Deactivating {activation} due to inconsistent state.");
                            this.DeactivateOnIdle(activation.ActivationId);
                        }
                    }

                    if (message.Direction != Message.Directions.OneWay)
                    {
                        SafeSendExceptionResponse(message, exc1);
                    }
                    return;
                }

                OrleansTransactionException transactionException = null;

                if (transactionInfo != null)
                {
                    try
                    {
                        transactionInfo.ReconcilePending();
                        transactionException = transactionInfo.MustAbort(serializationManager);

                        // This request started the transaction, so we try to commit before returning,
                        // or if it must abort, tell participants that it aborted
                        if (startNewTransaction)
                        {
                            if (transactionException == null)
                            {
                                var status = await this.transactionAgent.Commit(transactionInfo);

                                if (status != TransactionalStatus.Ok)
                                {
                                    transactionException = status.ConvertToUserException(transactionInfo.Id);
                                }
                            }
                            else
                            {
                                this.transactionAgent.Abort(transactionInfo, (OrleansTransactionAbortedException)transactionException);
                            }
                            TransactionContext.Clear();
                        }
                    }
                    catch (Exception e)
                    {
                        // we should never hit this, but if we do, the following message will help us diagnose
                        this.logger.LogError(e, "Error in transaction post-grain-method-invocation code");
                        throw;
                    }
                }

                if (message.Direction != Message.Directions.OneWay)
                {
                    if (transactionException != null)
                    {
                        SafeSendExceptionResponse(message, transactionException);
                    }
                    else
                    {
                        SafeSendResponse(message, resultObject);
                    }
                }
                return;
            }
            catch (Exception exc2)
            {
                logger.Warn(ErrorCode.Runtime_Error_100329, "Exception during Invoke of message: " + message, exc2);

                TransactionContext.Clear();

                if (message.Direction != Message.Directions.OneWay)
                {
                    SafeSendExceptionResponse(message, exc2);
                }
            }
            finally
            {
                TransactionContext.Clear();
            }
        }
Esempio n. 14
0
 private bool IsImplicitSubscriber(IAddressable addressable, StreamId streamId)
 {
     return(implicitPubSub.IsImplicitSubscriber(GrainExtensions.GetGrainId(addressable), streamId));
 }
Esempio n. 15
0
 public void BindGrainReference(IAddressable grain)
 {
     throw new NotImplementedException();
 }
 public TGrainInterface Convert <TGrainInterface>(IAddressable grain)
 {
     return(this.internalGrainFactory.Cast <TGrainInterface>(grain));
 }
Esempio n. 17
0
 /// <inheritdoc />
 public void BindGrainReference(IAddressable grain)
 {
     this.InternalGrainFactory.BindGrainReference(grain);
 }
        internal async Task Invoke(IAddressable target, IInvokable invokable, Message message)
        {
            try
            {
                // Don't process messages that have already timed out
                if (message.IsExpired)
                {
                    message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Invoke);
                    return;
                }

                RequestContext.Import(message.RequestContextData);
                if (Config.Globals.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget)
                {
                    UpdateDeadlockInfoInRequestContext(new RequestInvocationHistory(message));
                    // RequestContext is automatically saved in the msg upon send and propagated to the next hop
                    // in RuntimeClient.CreateMessage -> RequestContext.ExportToMessage(message);
                }

                object resultObject;
                try
                {
                    var request = (InvokeMethodRequest)message.BodyObject;

                    var invoker = invokable.GetInvoker(request.InterfaceId, message.GenericGrainType);

                    if (invoker is IGrainExtensionMethodInvoker &&
                        !(target is IGrainExtension))
                    {
                        // We are trying the invoke a grain extension method on a grain
                        // -- most likely reason is that the dynamic extension is not installed for this grain
                        // So throw a specific exception here rather than a general InvalidCastException
                        var error = String.Format(
                            "Extension not installed on grain {0} attempting to invoke type {1} from invokable {2}",
                            target.GetType().FullName, invoker.GetType().FullName, invokable.GetType().FullName);
                        var    exc            = new GrainExtensionNotInstalledException(error);
                        string extraDebugInfo = null;
#if DEBUG
                        extraDebugInfo = new StackTrace().ToString();
#endif
                        logger.Warn(ErrorCode.Stream_ExtensionNotInstalled,
                                    string.Format("{0} for message {1} {2}", error, message, extraDebugInfo), exc);

                        throw exc;
                    }

                    // If the target has a grain-level interceptor or there is a silo-level interceptor, intercept the call.
                    var shouldCallSiloWideInterceptor = SiloProviderRuntime.Instance.GetInvokeInterceptor() != null && target is IGrain;
                    var intercepted = target as IGrainInvokeInterceptor;
                    if (intercepted != null || shouldCallSiloWideInterceptor)
                    {
                        // Fetch the method info for the intercepted call.
                        var implementationInvoker =
                            invocationMethodInfoMap.GetInterceptedMethodInvoker(target.GetType(), request.InterfaceId,
                                                                                invoker);
                        var methodInfo = implementationInvoker.GetMethodInfo(request.MethodId);
                        if (shouldCallSiloWideInterceptor)
                        {
                            // There is a silo-level interceptor and possibly a grain-level interceptor.
                            var runtime = SiloProviderRuntime.Instance;
                            resultObject =
                                await runtime.CallInvokeInterceptor(methodInfo, request, target, implementationInvoker);
                        }
                        else
                        {
                            // The grain has an interceptor, but there is no silo-wide interceptor.
                            resultObject = await intercepted.Invoke(methodInfo, request, invoker);
                        }
                    }
                    else
                    {
                        // The call is not intercepted.
                        resultObject = await invoker.Invoke(target, request);
                    }
                }
                catch (Exception exc1)
                {
                    if (invokeExceptionLogger.IsVerbose || message.Direction == Message.Directions.OneWay)
                    {
                        invokeExceptionLogger.Warn(ErrorCode.GrainInvokeException,
                                                   "Exception during Grain method call of message: " + message, exc1);
                    }
                    if (message.Direction != Message.Directions.OneWay)
                    {
                        SafeSendExceptionResponse(message, exc1);
                    }
                    return;
                }

                if (message.Direction == Message.Directions.OneWay)
                {
                    return;
                }

                SafeSendResponse(message, resultObject);
            }
            catch (Exception exc2)
            {
                logger.Warn(ErrorCode.Runtime_Error_100329, "Exception during Invoke of message: " + message, exc2);
                if (message.Direction != Message.Directions.OneWay)
                {
                    SafeSendExceptionResponse(message, exc2);
                }
            }
        }
Esempio n. 19
0
 private static string EA(IAddressable mem, ushort PC, int bytes)
 {
     byte lsb = mem[PC];
     byte msb = 0;
     if (bytes == 2)
         msb = mem[(ushort)(PC + 1)];
     ushort ea = (ushort)(lsb | (msb << 8));
     if (bytes == 1)
         return String.Format(CultureInfo.InvariantCulture, "${0:x2}", ea);
     else
         return String.Format(CultureInfo.InvariantCulture, "${0:x4}", ea);
 }
Esempio n. 20
0
 public void BindGrainReference(Assembly assembly, IAddressable grain)
 {
     _clusterClientFactory.Create(assembly).BindGrainReference(grain);
 }
 public static IDeviceGrain Cast(IAddressable grainRef)
 {
     
     return (IDeviceGrain) GrainReference.CastInternal(typeof(IDeviceGrain), (GrainReference gr) => { return new DeviceGrainReference(gr);}, grainRef, -1248350959);
 }
Esempio n. 22
0
 public bool TryRegister(IAddressable obj, GuidId objectId, IGrainMethodInvoker invoker)
 {
     return(this.localObjects.TryAdd(objectId, new LocalObjectData(obj, objectId, invoker)));
 }
Esempio n. 23
0
 public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
 {
     throw new InvalidOperationException("Cannot create a local object reference from a grain.");
 }
Esempio n. 24
0
 /// <inheritdoc />
 object IInternalGrainFactory.Cast(IAddressable grain, Type interfaceType)
 {
     return(this.grainFactory.Cast(grain, interfaceType));
 }
Esempio n. 25
0
 public static IClientObserver Cast(IAddressable grainRef)
 {
     
     return (IClientObserver) GrainReference.CastInternal(typeof(IClientObserver), (GrainReference gr) => { return new ClientObserverReference(gr);}, grainRef, 1126410990);
 }
Esempio n. 26
0
 /// <inheritdoc />
 TGrainInterface IInternalGrainFactory.Cast <TGrainInterface>(IAddressable grain)
 {
     return(this.grainFactory.Cast <TGrainInterface>(grain));
 }
Esempio n. 27
0
 public async System.Threading.Tasks.Task<Object> Invoke(IAddressable grain, int interfaceId, int methodId, object[] arguments)
 {
         if (grain == null) throw new System.ArgumentNullException("grain");
         switch (interfaceId)
         {
             case 1662910789:  // IDestination
                 switch (methodId)
                 {
                     case 1491328371: 
                         await ((IDestination)grain).Ping((IClient)arguments[0], (Message)arguments[1]);
                       return true;
                     default: 
                         throw new NotImplementedException("interfaceId="+interfaceId+",methodId="+methodId);
                 }
             default:
                 throw new System.InvalidCastException("interfaceId="+interfaceId);
         }
 }
Esempio n. 28
0
        private TGrainObserverInterface CreateObjectReferenceImpl <TGrainObserverInterface>(IAddressable obj)
        {
            var interfaceType     = typeof(TGrainObserverInterface);
            var interfaceTypeInfo = interfaceType.GetTypeInfo();

            if (!interfaceTypeInfo.IsInterface)
            {
                throw new ArgumentException(
                          string.Format(
                              "The provided type parameter must be an interface. '{0}' is not an interface.",
                              interfaceTypeInfo.FullName));
            }

            if (!interfaceTypeInfo.IsInstanceOfType(obj))
            {
                throw new ArgumentException(
                          string.Format("The provided object must implement '{0}'.", interfaceTypeInfo.FullName),
                          "obj");
            }

            IGrainMethodInvoker invoker;

            if (!this.invokers.TryGetValue(interfaceType, out invoker))
            {
                invoker = MakeInvoker(interfaceType);
                if (invoker != null)
                {
                    this.invokers.TryAdd(interfaceType, invoker);
                }
            }

            if (invoker == null)
            {
                throw new InvalidOperationException(
                          string.Format(
                              "Cannot find generated IMethodInvoker implementation for interface '{0}'",
                              interfaceType));
            }

            return(Cast <TGrainObserverInterface>(RuntimeClient.Current.CreateObjectReference(obj, invoker)));
        }
Esempio n. 29
0
        public void DeleteObjectReference(IAddressable obj)
        {
            if (!(obj is GrainReference))
                throw new ArgumentException("Argument reference is not a grain reference.");

            var reference = (GrainReference) obj;
            LocalObjectData ignore;
            if (!localObjects.TryRemove(reference.ObserverId, out ignore))
                throw new ArgumentException("Reference is not associated with a local object.", "reference");
        }
Esempio n. 30
0
 /// <summary>
 /// Returns whether part of the primary key is of type long.
 /// </summary>
 /// <param name="grain">The target grain.</param>
 public static bool IsPrimaryKeyBasedOnLong(this IAddressable grain)
 {
     return(GetGrainId(grain).IsLongKey);
 }
Esempio n. 31
0
 /// <summary>
 /// Called from generated code.
 /// </summary>
 public static Task DeleteObjectReference(IAddressable observer)
 {
     return(RuntimeClient.Current.DeleteObjectReference(observer));
 }
Esempio n. 32
0
 public static string MemDump(IAddressable mem, ushort atAddr, ushort untilAddr)
 {
     StringBuilder result = new StringBuilder();
     int length = untilAddr - atAddr;
     while (length-- >= 0) {
         result.AppendFormat(CultureInfo.InvariantCulture, "{0:x4}: ", atAddr);
         for (int i = 0; i < 8; ++i) {
             result.AppendFormat(CultureInfo.InvariantCulture, "{0:x2} ", mem[atAddr++]);
             if (i == 3)
                 result.Append(" ");
         }
         result.Append(Environment.NewLine);
     }
     if (result.Length > 0)
         result.Length--; // Trim trailing newline
     return result.ToString();
 }
Esempio n. 33
0
 /// <summary>
 /// Returns the Guid representation of a grain primary key.
 /// </summary>
 /// <param name="grain">The grain to find the primary key for.</param>
 /// <returns>A Guid representing the primary key for this grain.</returns>
 public static Guid GetPrimaryKey(this IAddressable grain)
 {
     return(GetGrainId(grain).GetPrimaryKey());
 }
Esempio n. 34
0
 public object Convert(IAddressable grain, Type interfaceType)
 => this.internalGrainFactory.Cast(grain, interfaceType);
Esempio n. 35
0
 public static string Disassemble(IAddressable mem, ushort atAddr, ushort untilAddr)
 {
     StringBuilder result = new StringBuilder();
     ushort dPC = atAddr;
     while (atAddr < untilAddr) {
         result.AppendFormat(CultureInfo.InvariantCulture, "{0:x4}: ", dPC);
         int len = InstructionLength(mem, dPC);
         for (int i = 0; i < 3; i++) {
             if (i < len)
                 result.AppendFormat(CultureInfo.InvariantCulture, "{0:x2} ", mem[atAddr++]);
             else
                 result.Append("   ");
         }
         result.AppendFormat(CultureInfo.InvariantCulture, "{0,-15:s}{1}",
             OpCodeDecode(mem, dPC), Environment.NewLine);
         dPC += (ushort)len;
     }
     if (result.Length > 0)
         result.Length--;  // Trim trailing newline
     return result.ToString();
 }
Esempio n. 36
0
 /// <summary>
 /// Returns the string primary key of the grain.
 /// </summary>
 /// <param name="grain">The grain to find the primary key for.</param>
 /// <returns>A string representing the primary key for this grain.</returns>
 public static string GetPrimaryKeyString(this IAddressable grain)
 {
     return(GetGrainId(grain).GetPrimaryKeyString());
 }
Esempio n. 37
0
 public static string OpCodeDecode(IAddressable mem, ushort PC)
 {
     int num_operands = InstructionLength(mem, PC) - 1;
     ushort PC1 = (ushort)(PC + 1);
     string addrmodeStr;
     switch (addressingModeMatrix[mem[PC]]) {
         case a.REL:
             addrmodeStr = String.Format(CultureInfo.InvariantCulture,
                 "${0:x4}", (ushort)(PC + (sbyte)(mem[PC1]) + 2));
             break;
         case a.ZPG:
         case a.ABS:
             addrmodeStr = EA(mem, PC1, num_operands);
             break;
         case a.ZPX:
         case a.ABX:
             addrmodeStr = EA(mem, PC1, num_operands) + ",X";
             break;
         case a.ZPY:
         case a.ABY:
             addrmodeStr = EA(mem, PC1, num_operands) + ",Y";
             break;
         case a.IDX:
             addrmodeStr = "(" + EA(mem, PC1, num_operands) + ",X)";
             break;
         case a.IDY:
             addrmodeStr = "(" + EA(mem, PC1, num_operands) + "),Y";
             break;
         case a.IND:
             addrmodeStr = "(" + EA(mem, PC1, num_operands) + ")";
             break;
         case a.IMM:
             addrmodeStr = "#" + EA(mem, PC1, num_operands);
             break;
         default:
             // a.IMP, a.ACC
             addrmodeStr = "";
             break;
     }
     return String.Format(CultureInfo.InvariantCulture,
         "{0} {1}", mnemonicMatrix[mem[PC]], addrmodeStr);
 }
Esempio n. 38
0
 /// <summary>
 /// Casts a grain to a specific grain interface.
 /// </summary>
 /// <typeparam name="TGrainInterface">The type of the grain interface.</typeparam>
 /// <param name="grain">The grain to cast.</param>
 public static TGrainInterface Cast <TGrainInterface>(this IAddressable grain)
 {
     return(grain.AsReference <TGrainInterface>());
 }
Esempio n. 39
0
 private static int InstructionLength(IAddressable mem, ushort PC)
 {
     switch (addressingModeMatrix[mem[PC]]) {
         case a.ACC:
         case a.IMP:
             return 1;
         case a.REL:
         case a.ZPG:
         case a.ZPX:
         case a.ZPY:
         case a.IDX:
         case a.IDY:
         case a.IMM:
             return 2;
         case a.ABS:
         case a.ABX:
         case a.ABY:
         case a.IND:
         default:
             return 3;
     }
 }
Esempio n. 40
0
 /// <summary>
 /// Binds the grain reference to the provided <see cref="IGrainFactory"/>.
 /// </summary>
 /// <param name="grain">The grain reference.</param>
 /// <param name="grainFactory">The grain factory.</param>
 public static void BindGrainReference(this IAddressable grain, IGrainFactory grainFactory)
 {
     grainFactory.BindGrainReference(grain);
 }
 public static IDeviceGrain Cast(IAddressable grainRef)
 {
     
     return DeviceGrainReference.Cast(grainRef);
 }
Esempio n. 42
0
 /// <inheritdoc />
 public TGrainObserverInterface CreateObjectReference <TGrainObserverInterface>(IAddressable obj)
     where TGrainObserverInterface : IAddressable
 {
     return(this.CreateObjectReferenceImpl <TGrainObserverInterface>(obj));
 }
Esempio n. 43
0
 internal bool IsImplicitSubscriber(IAddressable addressable, StreamId streamId)
 {
     return implicitTable.IsImplicitSubscriber(GrainExtensions.GetGrainId(addressable), streamId);
 }
Esempio n. 44
0
        private TGrainObserverInterface CreateObjectReferenceImpl <TGrainObserverInterface>(IAddressable obj) where TGrainObserverInterface : IAddressable
        {
            var interfaceType = typeof(TGrainObserverInterface);

            if (!interfaceType.IsInterface)
            {
                throw new ArgumentException(
                          $"The provided type parameter must be an interface. '{interfaceType.FullName}' is not an interface.");
            }

            if (!interfaceType.IsInstanceOfType(obj))
            {
                throw new ArgumentException($"The provided object must implement '{interfaceType.FullName}'.", nameof(obj));
            }

            IGrainMethodInvoker invoker;

            if (!this.invokers.TryGetValue(interfaceType, out invoker))
            {
                invoker = this.MakeInvoker(interfaceType);
                this.invokers.TryAdd(interfaceType, invoker);
            }

            return(this.Cast <TGrainObserverInterface>(this.runtimeClient.CreateObjectReference(obj, invoker)));
        }
Esempio n. 45
0
        internal async Task Invoke(IAddressable target, IInvokable invokable, Message message)
        {
            try
            {
                // Don't process messages that have already timed out
                if (message.IsExpired)
                {
                    message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Invoke);
                    return;
                }

                RequestContext.Import(message.RequestContextData);
                if (Config.Globals.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget)
                {
                    UpdateDeadlockInfoInRequestContext(new RequestInvocationHistory(message));
                    // RequestContext is automatically saved in the msg upon send and propagated to the next hop
                    // in RuntimeClient.CreateMessage -> RequestContext.ExportToMessage(message);
                }

                object resultObject;
                try
                {
                    var request = (InvokeMethodRequest) message.BodyObject;

                    var invoker = invokable.GetInvoker(request.InterfaceId, message.GenericGrainType);

                    if (invoker is IGrainExtensionMethodInvoker
                        && !(target is IGrainExtension))
                    {
                        // We are trying the invoke a grain extension method on a grain 
                        // -- most likely reason is that the dynamic extension is not installed for this grain
                        // So throw a specific exception here rather than a general InvalidCastException
                        var error = String.Format(
                            "Extension not installed on grain {0} attempting to invoke type {1} from invokable {2}", 
                            target.GetType().FullName, invoker.GetType().FullName, invokable.GetType().FullName);
                        var exc = new GrainExtensionNotInstalledException(error);
                        string extraDebugInfo = null;
#if DEBUG
                        extraDebugInfo = new StackTrace().ToString();
#endif
                        logger.Warn(ErrorCode.Stream_ExtensionNotInstalled, 
                            string.Format("{0} for message {1} {2}", error, message, extraDebugInfo), exc);

                        throw exc;
                    }

                    // If the target has a grain-level interceptor or there is a silo-level interceptor, intercept the call.
                    var shouldCallSiloWideInterceptor = SiloProviderRuntime.Instance.GetInvokeInterceptor() != null && target is IGrain;
                    var intercepted = target as IGrainInvokeInterceptor;
                    if (intercepted != null || shouldCallSiloWideInterceptor)
                    {
                        // Fetch the method info for the intercepted call.
                        var implementationInvoker =
                            invocationMethodInfoMap.GetInterceptedMethodInvoker(target.GetType(), request.InterfaceId,
                                invoker);
                        var methodInfo = implementationInvoker.GetMethodInfo(request.MethodId);
                        if (shouldCallSiloWideInterceptor)
                        {
                            // There is a silo-level interceptor and possibly a grain-level interceptor.
                            var runtime = SiloProviderRuntime.Instance;
                            resultObject =
                                await runtime.CallInvokeInterceptor(methodInfo, request, target, implementationInvoker);
                        }
                        else
                        {
                            // The grain has an interceptor, but there is no silo-wide interceptor.
                            resultObject = await intercepted.Invoke(methodInfo, request, invoker);
                        }
                    }
                    else
                    {
                        // The call is not intercepted.
                        resultObject = await invoker.Invoke(target, request);
                    }
                }
                catch (Exception exc1)
                {
                    if (invokeExceptionLogger.IsVerbose || message.Direction == Message.Directions.OneWay)
                    {
                        invokeExceptionLogger.Warn(ErrorCode.GrainInvokeException,
                            "Exception during Grain method call of message: " + message, exc1);
                    }
                    if (message.Direction != Message.Directions.OneWay)
                    {
                        SafeSendExceptionResponse(message, exc1);
                    }
                    return;
                }

                if (message.Direction == Message.Directions.OneWay) return;

                SafeSendResponse(message, resultObject);
            }
            catch (Exception exc2)
            {
                logger.Warn(ErrorCode.Runtime_Error_100329, "Exception during Invoke of message: " + message, exc2);
                if (message.Direction != Message.Directions.OneWay)
                    SafeSendExceptionResponse(message, exc2);             
            }
        }
Esempio n. 46
0
        /// <summary>
        /// Casts the provided <paramref name="grain"/> to the specified interface
        /// </summary>
        /// <typeparam name="TGrainInterface">The target grain interface type.</typeparam>
        /// <param name="grain">The grain reference being cast.</param>
        /// <returns>
        /// A reference to <paramref name="grain"/> which implements <typeparamref name="TGrainInterface"/>.
        /// </returns>
        public TGrainInterface Cast <TGrainInterface>(IAddressable grain)
        {
            var interfaceType = typeof(TGrainInterface);

            return((TGrainInterface)this.Cast(grain, interfaceType));
        }
Esempio n. 47
0
 public void DeleteObjectReference(IAddressable obj)
 {
     throw new InvalidOperationException("Cannot delete a local object reference from a grain.");
 }
Esempio n. 48
0
        /// <summary>
        /// Handles the an InvokeMethodRequest message on given target.
        /// </summary>
        /// <remarks>
        /// Options when we receive a InvokeMethodRequest
        /// ----------------------------------------------
        /// 1) Intercepted RPC
        /// 2) Request to start a reactive computation for this method invocation
        /// 3) KeepAlive request of the reactive computation for this method invocation
        /// 4) Normal Application RPC
        /// 5) System RPC
        /// </remarks>
        /// <returns></returns>
        internal async Task Invoke(IAddressable target, IInvokable invokable, Message message)
        {
            try
            {
                // Don't process messages that have already timed out
                if (message.IsExpired)
                {
                    message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Invoke);
                    return;
                }

                RequestContext.Import(message.RequestContextData);
                if (Config.Globals.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget)
                {
                    UpdateDeadlockInfoInRequestContext(new RequestInvocationHistory(message));
                    // RequestContext is automatically saved in the msg upon send and propagated to the next hop
                    // in RuntimeClient.CreateMessage -> RequestContext.ExportToMessage(message);
                }

                object resultObject;
                try
                {
                    var request = (InvokeMethodRequest)message.BodyObject;
                    if (request.Arguments != null)
                    {
                        CancellationSourcesExtension.RegisterCancellationTokens(target, request, logger);
                    }

                    // Get the invoker for this invocation
                    IGrainMethodInvoker invoker = GetGrainMethodInvoker(target, invokable, message, request);

                    // Check whether this call should be intercepted
                    var siloWideInterceptor  = SiloProviderRuntime.Instance.GetInvokeInterceptor();
                    var grainWithInterceptor = target as IGrainInvokeInterceptor;

                    // Silo-wide interceptors do not operate on system targets.
                    var hasSiloWideInterceptor   = siloWideInterceptor != null && target is IGrain;
                    var hasGrainLevelInterceptor = grainWithInterceptor != null;

                    // Normal Application Call = an application call made from grain to grain or from client to grain.
                    // Some system-related calls such as the IReminderTable are encoded as Application messages, therefore we needed this check.
                    var NormalApplicationCall = message.Category == Message.Categories.Application && message.TargetGrain.IsGrain && (message.SendingGrain.IsGrain || message.SendingGrain.IsClient);

                    // 1) If the target has a grain-level interceptor or there is a silo-level interceptor, intercept the
                    // call.
                    if (hasGrainLevelInterceptor || hasSiloWideInterceptor)
                    {
                        resultObject = await InvokeWithInterceptors(target, request, invoker, hasSiloWideInterceptor, siloWideInterceptor, hasGrainLevelInterceptor, grainWithInterceptor);
                    }

                    else if (NormalApplicationCall)
                    {
                        // 2) Request to start a reactive computation for this method invocation
                        if (message.IsRcExecute())
                        {
                            HandleReactiveComputationExecute(target, request, message, invoker);
                            return; // Does not expect a return (OneWay Message)
                        }

                        // 3) Refresh Reactive Computation Subscription
                        else if (message.IsRcKeepAlive())
                        {
                            HandleReactiveComputationExecute(target, request, message, invoker, true);
                            return; // Does not expect a return (OneWay Message)
                        }

                        // 4) Normal application RPC call
                        else
                        {
                            // Invoke the method
                            resultObject = await invoker.Invoke(target, request);

                            // Check if there are any active reactive computations in this grain that require recomputation after this call
                            InsideRcManager.RecomputeSummaries();
                        }
                    }

                    // 5) System RPC call
                    else
                    {
                        resultObject = await invoker.Invoke(target, request);
                    }
                }
                catch (Exception exc1)
                {
                    if (invokeExceptionLogger.IsVerbose || message.Direction == Message.Directions.OneWay)
                    {
                        invokeExceptionLogger.Warn(ErrorCode.GrainInvokeException,
                                                   "Exception during Grain method call of message: " + message, exc1);
                    }
                    if (message.Direction != Message.Directions.OneWay)
                    {
                        SafeSendExceptionResponse(message, exc1);
                    }
                    return;
                }

                if (message.Direction == Message.Directions.OneWay)
                {
                    return;
                }

                SafeSendResponse(message, resultObject);
            }
            catch (Exception exc2)
            {
                logger.Warn(ErrorCode.Runtime_Error_100329, "Exception during Invoke of message: " + message, exc2);
                if (message.Direction != Message.Directions.OneWay)
                {
                    SafeSendExceptionResponse(message, exc2);
                }
            }
        }
Esempio n. 49
0
 public static IClientObserver Cast(IAddressable grainRef)
 {
     
     return ClientObserverReference.Cast(grainRef);
 }
Esempio n. 50
0
 public void StartQuery <T>(object activationKey, IAddressable target, InvokeMethodRequest request, IGrainMethodInvoker invoker, Message message, bool refresh = false)
 {
     InsideRcManager.CreateAndStartSummary <T>(activationKey, target, request, invoker, message, refresh);
 }
Esempio n. 51
0
 public async System.Threading.Tasks.Task<Object> Invoke(IAddressable grain, int interfaceId, int methodId, object[] arguments)
 {
         if (grain == null) throw new System.ArgumentNullException("grain");
         switch (interfaceId)
         {
             case 1126410990:  // IClientObserver
                 switch (methodId)
                 {
                     case -1778340467: 
                         ((IClientObserver)grain).Done((Int64)arguments[0], (Int64)arguments[1]); return true;
                     default: 
                         throw new NotImplementedException("interfaceId="+interfaceId+",methodId="+methodId);
                 }
             default:
                 throw new System.InvalidCastException("interfaceId="+interfaceId);
         }
 }
Esempio n. 52
0
        internal async Task Invoke(IAddressable target, IInvokable invokable, Message message)
        {
            try
            {
                // Don't process messages that have already timed out
                if (message.IsExpired)
                {
                    message.DropExpiredMessage(MessagingStatisticsGroup.Phase.Invoke);
                    return;
                }

                //MessagingProcessingStatisticsGroup.OnRequestProcessed(message, "Invoked");
                if (Message.WriteMessagingTraces)
                {
                    message.AddTimestamp(Message.LifecycleTag.InvokeIncoming);
                }

                RequestContext.Import(message.RequestContextData);
                if (Config.Globals.PerformDeadlockDetection && !message.TargetGrain.IsSystemTarget)
                {
                    UpdateDeadlockInfoInRequestContext(new RequestInvocationHistory(message));
                    // RequestContext is automatically saved in the msg upon send and propagated to the next hop
                    // in RuntimeClient.CreateMessage -> RequestContext.ExportToMessage(message);
                }

                var invoker = invokable.GetInvoker(message.InterfaceId, message.GenericGrainType);

                object resultObject;
                try
                {
                    var request = (InvokeMethodRequest)message.BodyObject;

                    if (invoker is IGrainExtensionMethodInvoker &&
                        !(target is IGrainExtension))
                    {
                        // We are trying the invoke a grain extension method on a grain
                        // -- most likely reason is that the dynamic extension is not installed for this grain
                        // So throw a specific exception here rather than a general InvalidCastException
                        var error = String.Format(
                            "Extension not installed on grain {0} attempting to invoke type {1} from invokable {2}",
                            target.GetType().FullName, invoker.GetType().FullName, invokable.GetType().FullName);
                        var    exc            = new GrainExtensionNotInstalledException(error);
                        string extraDebugInfo = null;
#if DEBUG
                        extraDebugInfo = new StackTrace().ToString();
#endif
                        logger.Warn(ErrorCode.Stream_ExtensionNotInstalled,
                                    string.Format("{0} for message {1} {2}", error, message, extraDebugInfo), exc);

                        throw exc;
                    }
                    resultObject = await invoker.Invoke(target, request.InterfaceId, request.MethodId, request.Arguments);
                }
                catch (Exception exc1)
                {
                    if (invokeExceptionLogger.IsVerbose || message.Direction == Message.Directions.OneWay)
                    {
                        invokeExceptionLogger.Warn(ErrorCode.GrainInvokeException,
                                                   "Exception during Grain method call of message: " + message, exc1);
                    }
                    if (message.Direction != Message.Directions.OneWay)
                    {
                        SafeSendExceptionResponse(message, exc1);
                    }
                    return;
                }

                if (message.Direction == Message.Directions.OneWay)
                {
                    return;
                }

                SafeSendResponse(message, resultObject);
            }
            catch (Exception exc2)
            {
                logger.Warn(ErrorCode.Runtime_Error_100329, "Exception during Invoke of message: " + message, exc2);
                if (message.Direction != Message.Directions.OneWay)
                {
                    SafeSendExceptionResponse(message, exc2);
                }
            }
        }
Esempio n. 53
0
 public static IDestination Cast(IAddressable grainRef)
 {
     
     return (IDestination) GrainReference.CastInternal(typeof(IDestination), (GrainReference gr) => { return new DestinationReference(gr);}, grainRef, 1662910789);
 }
Esempio n. 54
0
 public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
 {
     throw new InvalidOperationException("Cannot create a local object reference from a grain.");
 }
Esempio n. 55
0
 public static IClient Cast(IAddressable grainRef)
 {
     
     return ClientReference.Cast(grainRef);
 }
Esempio n. 56
0
 public void DeleteObjectReference(IAddressable obj)
 {
     throw new InvalidOperationException("Cannot delete a local object reference from a grain.");
 }
Esempio n. 57
0
        public GrainReference CreateObjectReference(IAddressable obj, IGrainMethodInvoker invoker)
        {
            if (obj is GrainReference)
                throw new ArgumentException("Argument obj is already a grain reference.");

            GrainReference gr = GrainReference.NewObserverGrainReference(clientId, GuidId.GetNewGuidId());
            if (!localObjects.TryAdd(gr.ObserverId, new LocalObjectData(obj, gr.ObserverId, invoker)))
            {
                throw new ArgumentException(String.Format("Failed to add new observer {0} to localObjects collection.", gr), "gr");
            }
            return gr;
        }
Esempio n. 58
0
 /// <summary>
 /// Returns the long representation of a grain primary key.
 /// </summary>
 /// <param name="grain">The grain to find the primary key for.</param>
 /// <param name="keyExt">The output paramater to return the extended key part of the grain primary key, if extened primary key was provided for that grain.</param>
 /// <returns>A long representing the primary key for this grain.</returns>
 public static long GetPrimaryKeyLong(this IAddressable grain, out string keyExt)
 {
     return(GetGrainId(grain).GetPrimaryKeyLong(out keyExt));
 }
Esempio n. 59
0
 internal LocalObjectData(IAddressable obj, GuidId observerId, IGrainMethodInvoker invoker)
 {
     LocalObject = new WeakReference(obj);
     ObserverId = observerId;
     Invoker = invoker;
     Messages = new Queue<Message>();
     Running = false;
 }
 internal bool IsImplicitSubscriber(IAddressable addressable, InternalStreamId streamId)
 {
     return(implicitTable.IsImplicitSubscriber(GrainExtensions.GetGrainId(addressable), streamId));
 }