Exemplo n.º 1
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            var tracer = _oneAgentSdk.TraceIncomingMessageProcess(
                _oneAgentSdk.CreateMessagingSystemInfo("Orleans Incoming", context?.Grain?.ToString(),
                                                       MessageDestinationType.QUEUE, ChannelType.IN_PROCESS,
                                                       ""));


            if (RequestContext.Get("TraceId") != null)
            {
                tracer.SetCorrelationId(RequestContext.Get("TraceId").ToString());
                tracer.SetDynatraceByteTag((byte[])RequestContext.Get(OneAgentSdkConstants.DYNATRACE_MESSAGE_PROPERTYNAME));
                //_logger.LogDebug("Incoming Dyntrace Byte Tag  : {byte_tag}", RequestContext.Get(OneAgentSdkConstants.DYNATRACE_MESSAGE_PROPERTYNAME));
                _logger.LogDebug("Tracing Incoming {grainType} Correlation Id {traceId}", context.Grain.GetType().FullName, RequestContext.Get("TraceId"));

                await tracer.TraceAsync(async() =>
                {
                    await context.Invoke();
                });
            }
            else
            {
                await context.Invoke();
            }
        }
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            LogWrite(context, () =>
            {
                Console.WriteLine($"{this.GetType().Name} Grain Before Invoke");
                Console.WriteLine($"{this.GetType().Name} Grain Name: {context.Grain.GetType().FullName}");
                Console.WriteLine($"{this.GetType().Name} Grain Interface Type: {context.InterfaceMethod.DeclaringType?.FullName}");
                Console.WriteLine($"{this.GetType().Name} Grain Implementation Type: {context.ImplementationMethod.DeclaringType?.FullName}");
                Console.WriteLine($"{this.GetType().Name} Grain PrimaryKey: {context.Grain.GetPrimaryKeyLong()}");
                Console.WriteLine($"{this.GetType().Name} Grain Method Arguments: {string.Join(",", context.Arguments)}");
            });

            try
            {
                await context.Invoke();

                LogWrite(context, () => Console.WriteLine($"{this.GetType().Name} Grain After Invoke"));
            }
            catch (Exception e)
            {
                LogWrite(context, () => Console.WriteLine($"{this.GetType().Name} Grain Exception: {e}"));
                throw;
            }
            finally
            {
                LogWrite(context, () => Console.WriteLine($"{this.GetType().Name} Grain Result: {context.Result}"));
            }
        }
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            Console.WriteLine("Hello! Start to invoke our grain.");
            await context.Invoke();

            Console.WriteLine(" I am done with invoking");
        }
Exemplo n.º 4
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            if (context.Arguments?.FirstOrDefault() is string phrase && string.Equals("please", phrase))
            {
                _throttleScore = 0;
            }

            // Work out how long it's been since the last call
            var elapsedSeconds = _stopwatch.Elapsed.TotalSeconds;

            _stopwatch.Restart();

            // Calculate a new score based on a constant rate of score decay and the time which elapsed since the last call.
            _throttleScore = Math.Max(0, _throttleScore - elapsedSeconds * DecayRate) + 1;

            // If the user has exceeded the threshold, deny their request and give them a helpful warning.
            if (_throttleScore > ThrottleThreshold)
            {
                var remainingSeconds = Math.Max(0, (int)Math.Ceiling((_throttleScore - (ThrottleThreshold - 1)) / DecayRate));
                _logger.LogError("Throttling");
                throw new ThrottlingException($"Request rate exceeded, wait {remainingSeconds}s before retrying");
            }

            await context.Invoke();
        }
Exemplo n.º 5
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            if (!context.InterfaceMethod.Name.Equals("DeliverBatch"))
            {
                await context.Invoke();

                return;
            }

            var spanContext = RequestContext.Get("SpanContext") as ISpanContext;

            if (spanContext != null)
            {
                using (GlobalTracer.Instance.BuildSpan(context.ImplementationMethod.Name).AsChildOf(spanContext)
                       .WithTag("grain-id", context.Grain.GetPrimaryKeyString())
                       .WithTag("grain-name", context.Grain.GetType().Name)
                       .StartActive(true))
                {
                    await context.Invoke();
                }
            }
            else
            {
                await context.Invoke();
            }
        }
Exemplo n.º 6
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            await context.Invoke();

            var grainType   = context.Grain.GetType();
            var bufferIdObj = RequestContext.Get(Constants.BufferIdKey);

            if (bufferIdObj != null &&
                grainType.GetCustomAttributes(typeof(BufferInMemAttribute), true).Length > 0)
            {
                var bufferId      = (Guid)bufferIdObj;
                var grainTypeEnum = grainType.Name switch
                {
                    nameof(JobGrainInMem) => BufferedGrainInterfaceType.JobGrain,
                    nameof(DescendantsRefGrainInMem) => BufferedGrainInterfaceType.DescendantsRefGrain,
                    nameof(JobTreeStatisticsGrainInMem) => BufferedGrainInterfaceType.JobTreeStatisticsGrain,
                    _ => BufferedGrainInterfaceType.JobGrain
                };

                await _client.GetGrain <IBufferManagerGrain>(bufferId)
                .AddToBufferAsync(new AddToBufferDto(context.Grain.GetPrimaryKeyLong(),
                                                     grainTypeEnum));
            }
        }
    }
Exemplo n.º 7
0
        public async Task Invoke(IIncomingGrainCallContext ctx)
        {
            var attemptsRemaining = 2;

            while (attemptsRemaining > 0)
            {
                try
                {
                    var interfaceMethod      = ctx.InterfaceMethod ?? throw new ArgumentException("InterfaceMethod is null!");
                    var implementationMethod = ctx.ImplementationMethod ?? throw new ArgumentException("ImplementationMethod is null!");
                    if (!string.Equals(implementationMethod.Name, interfaceMethod.Name))
                    {
                        throw new ArgumentException("InterfaceMethod.Name != ImplementationMethod.Name");
                    }

                    if (RequestContext.Get(Key) is string value)
                    {
                        RequestContext.Set(Key, value + '3');
                    }
                    await ctx.Invoke();

                    return;
                }
                catch (ArgumentOutOfRangeException) when(attemptsRemaining > 1)
                {
                    if (string.Equals(ctx.ImplementationMethod?.Name, nameof(ThrowIfGreaterThanZero)) && ctx.Arguments[0] is int value)
                    {
                        ctx.Arguments[0] = (object)(value - 1);
                    }

                    --attemptsRemaining;
                }
            }
        }
Exemplo n.º 8
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            try
            {
                if (ShowLog(context.ImplementationMethod.Name))
                {
                    var arguments = JsonConvert.SerializeObject(context.Arguments, _serializerSettings);
                    _logger.LogInformation($"LOGGINGFILTER TraceId {_context.TraceId}:{context.Grain.GetType()}-{context.ImplementationMethod.Name}:arguments{arguments} request");
                }

                await context.Invoke();

                if (ShowLog(context.ImplementationMethod.Name))
                {
                    var result = JsonConvert.SerializeObject(context.Result, _serializerSettings);
                    _logger.LogInformation($"LOGGINGFILTERTraceId {_context.TraceId}:{context.Grain.GetType()}-{context.ImplementationMethod.Name}:arguments{result} request");
                    _logger.LogInformation($"");
                }
            }
            catch (Exception ex)
            {
                var arguments = JsonConvert.SerializeObject(context.Arguments, _serializerSettings);
                var result    = JsonConvert.SerializeObject(context.Result, _serializerSettings);
                _logger.LogError($"LOGGINGFILTERTraceId {_context.TraceId}:{context.Grain.GetType()}-{context.ImplementationMethod.Name}: threw exception: {nameof(ex)} request", ex);
                throw;
            }
        }
Exemplo n.º 9
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            var name = $"Grain/{context.Grain?.GetType().Name}/{context.ImplementationMethod?.Name}";

            using (Telemetry.Activities.StartActivity(name))
            {
                try
                {
                    await context.Invoke();
                }
                catch (DomainException ex)
                {
                    if (ex.InnerException != null)
                    {
                        Log(context, ex.InnerException);
                    }

                    throw;
                }
                catch (Exception ex)
                {
                    Log(context, ex);
                    throw;
                }
            }
        }
Exemplo n.º 10
0
        public async Task Invoke(IIncomingGrainCallContext ctx)
        {
            var attemptsRemaining = 2;

            while (attemptsRemaining > 0)
            {
                try
                {
                    if (RequestContext.Get(Key) is string value)
                    {
                        RequestContext.Set(Key, value + '3');
                    }
                    await ctx.Invoke();

                    return;
                }
                catch (ArgumentOutOfRangeException) when(attemptsRemaining > 1)
                {
                    if (string.Equals(ctx.ImplementationMethod?.Name, nameof(ThrowIfGreaterThanZero)) && ctx.Arguments[0] is int value)
                    {
                        ctx.Arguments[0] = value - 1;
                    }

                    --attemptsRemaining;
                }
            }
        }
Exemplo n.º 11
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            try
            {
                await context.Invoke();

                var msg = string.Format(
                    "{0}.{1}({2}) returned value {3}",
                    context.Grain.GetType(),
                    context.InterfaceMethod.Name,
                    string.Join(", ", context.Arguments),
                    context.Result);

                _log.LogInformation(msg);
            }
            catch (Exception e)
            {
                var msg = string.Format(
                    "{0}.{1}({2}) threw an exception: {3}",
                    context.Grain.GetType(),
                    context.InterfaceMethod.Name,
                    string.Join(", ", context.Arguments),
                    e);

                _log.LogInformation(msg);

                throw;
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// 拦截器记录日志
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            string sw8              = RequestContext.Get(IdentityServerConsts.ClaimTypes.SkyWalking) as string;
            string OperId           = this.GrainId.ToString();
            var    tracingTimestamp = _diagnosticListener.OrleansInvokeBefore(context.Grain.GetType(), context.InterfaceMethod, OperId, this.RuntimeIdentity, sw8);

            try
            {
                await context.Invoke();

                _diagnosticListener.OrleansInvokeAfter(tracingTimestamp);
            }
            catch (Exception exception)
            {
                Logger.LogError($"Grain执行异常", exception);
                if (FuncExceptionHandler != null)
                {
                    await FuncExceptionHandler(exception);
                }

                _diagnosticListener.OrleansInvokeError(tracingTimestamp, exception);

                throw exception;
            }
        }
Exemplo n.º 13
0
 private void TryDeactivate(IIncomingGrainCallContext context)
 {
     if (context.Grain is Grain grain)
     {
         runtime.DeactivateOnIdle(grain);
     }
 }
Exemplo n.º 14
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            try
            {
                await context.Invoke();
            }
            catch (DomainObjectNotFoundException)
            {
                TryDeactivate(context);

                throw;
            }
            catch (WrongEventVersionException)
            {
                TryDeactivate(context);

                throw;
            }
            catch (InconsistentStateException)
            {
                TryDeactivate(context);

                throw;
            }
        }
Exemplo n.º 15
0
        public async Task Invoke(IIncomingGrainCallContext ctx)
        {
            //
            // NOTE: this grain demonstrates incorrect usage of grain call interceptors and should not be used
            // as an example of proper usage. Specifically, storing the context for later execution is invalid.
            //

            this.context = ctx;
            if (string.Equals(ctx.ImplementationMethod.Name, nameof(CallWithBadInterceptors)) && (bool)ctx.Arguments[0])
            {
                await ctx.Invoke();
            }

            if (RequestContext.Get(Key) is string value)
            {
                RequestContext.Set(Key, value + '3');
            }
            await ctx.Invoke();

            if (string.Equals(ctx.ImplementationMethod?.Name, nameof(CallWithBadInterceptors)) && (bool)ctx.Arguments[1])
            {
                await ctx.Invoke();
            }

            this.context = null;
        }
Exemplo n.º 16
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            //调用方法前获取参数,调用方法后修改返回值
            //if (context.Arguments != null)
            //{
            //    foreach (var arg in context.Arguments)
            //    {
            //        Console.WriteLine($"参数:{arg}");
            //    }
            //    if (context.Arguments.Length > 0)
            //    {
            //        context.Arguments[0] = "桂素伟加一";
            //    }
            //}
            //await context.Invoke();
            //// Change the result of the call from 7 to 38.
            //if (string.Equals(context.InterfaceMethod.Name, nameof(this.GetFavoriteNumber)))
            //{
            //    context.Result = 38;
            //}

            //用特性的方式控制访问
            var isAdminMethod = context.ImplementationMethod.GetCustomAttribute <AdminOnlyAttribute>() != null;

            if (isAdminMethod && !(bool)RequestContext.Get("isAdmin"))
            {
                throw new Exception($"只有 admins 能访问 {context.ImplementationMethod.Name}!");
            }
            await context.Invoke();
        }
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            Console.WriteLine("Before Method Invoke, incoming call filter");
            await context.Invoke();

            Console.WriteLine("After Method Invoke, incoming call filter");
        }
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            try
            {
                if (ShouldLod(context.InterfaceMethod.Name))
                {
                    var arguments = JsonConvert.SerializeObject(context.Arguments, _jsonSerializerSettings);

                    _logger.LogInformation($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: arguments: {arguments} request");
                }

                await context.Invoke();

                if (ShouldLod(context.InterfaceMethod.Name))
                {
                    var result = JsonConvert.SerializeObject(context.Result, _jsonSerializerSettings);

                    _logger.LogInformation($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: result: {result} request");
                }
            }
            catch (Exception ex)
            {
                var arguments = JsonConvert.SerializeObject(context.Arguments, _jsonSerializerSettings);
                var result    = JsonConvert.SerializeObject(context.Result, _jsonSerializerSettings);
                _logger.LogError($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: threw an exception: {nameof(ex)} request", ex);

                throw;
            }
        }
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            try
            {
                if (!(context.Grain is IHelloGrain))
                {
                    var grain = _grainFactory.GetGrain <IHelloGrain>(new Guid());

                    // Perform some grain call here.
                    await grain.Other();
                }

                await context.Invoke();

                if (context.InterfaceMethod.Name == "GetFavoriteNumber")
                {
                    var msg = $"调用方法为: {context.Grain.GetType()}.{context.InterfaceMethod.Name}({(context.Arguments != null ? string.Join(", ", context.Arguments) : "")}) 返回值为: {context.Result}";
                    Console.WriteLine(msg);
                }
            }
            catch (Exception exception)
            {
                var msg = $"{context.Grain.GetType()}.{context.InterfaceMethod.Name}({(context.Arguments != null ? string.Join(", ", context.Arguments) : "")}) 抛出了一个异常: {exception.Message}";
                Console.WriteLine(msg);
                throw;
            }
        }
Exemplo n.º 20
0
        Task IIncomingGrainCallFilter.Invoke(IIncomingGrainCallContext ctx)
        {
            if (ctx.InterfaceMethod is null)
            {
                throw new Exception("InterfaceMethod is null");
            }
            if (!ctx.InterfaceMethod.DeclaringType.IsInterface)
            {
                throw new Exception("InterfaceMethod is not an interface method");
            }

            if (ctx.ImplementationMethod is null)
            {
                throw new Exception("ImplementationMethod is null");
            }
            if (ctx.ImplementationMethod.DeclaringType.IsInterface)
            {
                throw new Exception("ImplementationMethod is an interface method");
            }

            if (RequestContext.Get("tag") is string tag)
            {
                var ifaceTag = ctx.InterfaceMethod.GetCustomAttribute <TestMethodTagAttribute>()?.Tag;
                var implTag  = ctx.ImplementationMethod.GetCustomAttribute <TestMethodTagAttribute>()?.Tag;
                if (!string.Equals(tag, ifaceTag, StringComparison.Ordinal) ||
                    !string.Equals(tag, implTag, StringComparison.Ordinal))
                {
                    throw new Exception($"Expected method tags to be equal to request context tag: RequestContext: {tag} Interface: {ifaceTag} Implementation: {implTag}");
                }
            }

            return(ctx.Invoke());
        }
Exemplo n.º 21
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            try
            {
                if (ShouldLog(context.InterfaceMethod.Name))
                {
                    var args = JsonConvert.SerializeObject(context.Arguments, _serializerSettings);
                    _logger.LogInformation($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: arguments: {args} REQUEST");
                }


                // triggers called method
                await context.Invoke();

                if (ShouldLog(context.InterfaceMethod.Name))
                {
                    var result = JsonConvert.SerializeObject(context.Arguments, _serializerSettings);
                    _logger.LogInformation($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: result: {result} RESULT");
                }
            }
            catch (Exception e)
            {
                var args   = JsonConvert.SerializeObject(context.Arguments, _serializerSettings);
                var result = JsonConvert.SerializeObject(context.Arguments, _serializerSettings);

                _logger.LogError($"LOGGINGFILTER TraceId: {_orleansRequestContext.TraceId} {context.Grain.GetType()}.{context.InterfaceMethod.Name}: threw an exception: {nameof(e)} RESULT", e);
                throw;
            }
        }
Exemplo n.º 22
0
        private bool ShouldSkipProfiling(IIncomingGrainCallContext context)
        {
            var grainMethod = context.ImplementationMethod;

            if (grainMethod == null)
            {
                return(false);
            }

            if (!shouldSkipCache.TryGetValue(grainMethod, out var shouldSkip))
            {
                try
                {
                    var grainType = context.Grain.GetType();

                    shouldSkip =
                        grainType.GetCustomAttribute <NoProfilingAttribute>() != null ||
                        grainMethod.GetCustomAttribute <NoProfilingAttribute>() != null;
                }
                catch (Exception ex)
                {
                    logger.LogError(100003, ex, "error reading NoProfilingAttribute attribute for grain");

                    shouldSkip = false;
                }

                shouldSkipCache.TryAdd(grainMethod, shouldSkip);
            }

            return(shouldSkip);
        }
        private bool VerifyPolicy(IIncomingGrainCallContext context, ClaimsPrincipal principal, AuthorizeAttribute authAttr)
        {
            string policy = string.Empty;

            if (!string.IsNullOrEmpty(authAttr.Roles))
            {
                policy = authAttr.Roles;
            }
            else if (!string.IsNullOrEmpty(authAttr.Policy))
            {
                policy = authAttr.Policy;
            }

            if (!string.IsNullOrEmpty(policy))
            {
                var claim = principal.FindFirst(authAttr.Policy);
                if (claim == null)
                {
                    this.Logger.LogError("Authorization ClaimsPrincipal Does not contain " + policy);
                    throw new AuthenticationException("Authorization ClaimsPrincipal Does not contain " + policy);
                }
            }

            return(true);
        }
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            bool isOrleansGrain = context.InterfaceMethod == null || context.InterfaceMethod.DeclaringType == null || context.InterfaceMethod.Module.Assembly.FullName.StartsWith("Orleans");
            //TODO add test that validate that we are not introducing new grain in micro dot
            bool isMicrodotGrain = isOrleansGrain == false && context.InterfaceMethod.DeclaringType.Name == nameof(IRequestProcessingGrain);
            bool isServiceGrain  = isOrleansGrain == false && isMicrodotGrain == false;

            var grainTags = new Lazy <GrainTags>(() => new GrainTags(context));
            // Drop the request if we're overloaded
            var loadSheddingConfig = _loadSheddingConfig();

            if (
                (loadSheddingConfig.ApplyToMicrodotGrains && isMicrodotGrain) ||
                (loadSheddingConfig.ApplyToServiceGrains && isServiceGrain)
                )
            {
                //Can brake the flow by throwing Overloaded
                RejectRequestIfLateOrOverloaded(grainTags);
            }
            var loggingConfig = _grainLoggingConfig();

            bool shouldLog = (loggingConfig.LogOrleansGrains && isOrleansGrain) ||
                             (loggingConfig.LogMicrodotGrains && isMicrodotGrain) ||
                             (loggingConfig.LogServiceGrains && isServiceGrain);

            shouldLog = shouldLog && !ShouldSkipLoggingUnderRatio(loggingConfig, TracingContext.TryGetRequestID());
            GrainCallEvent grainEvent = null;

            if (shouldLog)
            {
                RequestTimings.GetOrCreate(); // Ensure request timings is created here and not in the grain call.
                RequestTimings.Current.Request.Start();
                grainEvent = _eventPublisher.CreateEvent();

                grainEvent.ParentSpanId = TracingContext.TryGetParentSpanID();
                grainEvent.SpanId       = Guid.NewGuid().ToString("N");
                TracingContext.SetParentSpan(grainEvent.SpanId);
            }

            Exception ex = null;

            try
            {
                await context.Invoke();
            }
            catch (Exception e)
            {
                ex = e;
                throw;
            }
            finally
            {
                if (shouldLog)
                {
                    RequestTimings.Current.Request.Stop();
                    PublishEvent(ex, grainTags, grainEvent);
                }
            }
        }
Exemplo n.º 25
0
 private void Log(IIncomingGrainCallContext context, Exception ex)
 {
     log.LogError(ex, w => w
                  .WriteProperty("action", "GrainInvoked")
                  .WriteProperty("status", "Failed")
                  .WriteProperty("grain", context.Grain.ToString())
                  .WriteProperty("grainMethod", context.ImplementationMethod.ToString()));
 }
        public Task Invoke(IIncomingGrainCallContext context)
        {
            if (context.Grain is GrainBase grainBase)
            {
                grainBase.ReportIAmAlive();
            }

            return(context.Invoke());
        }
Exemplo n.º 27
0
 public async Task Invoke(IIncomingGrainCallContext context)
 {
     if (!context.Grain.GetType().Namespace !.StartsWith("Orleans", StringComparison.OrdinalIgnoreCase))
     {
         using (localCache.StartContext())
         {
             await context.Invoke();
         }
     }
Exemplo n.º 28
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            await context.Invoke();

            // Change the result of the call from 7 to 38.
            if (string.Equals(context.InterfaceMethod.Name, nameof(this.GetFavoriteNumber)))
            {
                context.Result = 38;
            }
        }
        private void LogWrite(IIncomingGrainCallContext context, Action action)
        {
            var hasLoggingAttribute = context.InterfaceMethod.GetCustomAttributes <GrainLoggingAttribute>().Any() ||
                                      (context.InterfaceMethod.DeclaringType?.GetCustomAttributes <GrainLoggingAttribute>().Any() ?? false);

            if (hasLoggingAttribute)
            {
                action();
            }
        }
Exemplo n.º 30
0
        public async Task Invoke(IIncomingGrainCallContext context)
        {
            if (context.ImplementationMethod.Name == nameof(GetInputAsString))
            {
                context.Result = $"Hah! You wanted {context.Arguments[0]}, but you got me!";
                return;
            }

            await context.Invoke();
        }