Exemplo n.º 1
0
        /// <summary>
        /// 保存请求信息
        /// <para>测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。</para>
        /// </summary>
        /// <param name="logPath">保存日志目录,默认为 ~/App_Data/&lt;模块类型&gt;/&lt;yyyy-MM-dd&gt;/</param>
        public void SaveRequestMessageLog(string logPath = null)
        {
            try
            {
                logPath = logPath ?? GetLogPath();
                SenparcMessageQueue queue = new SenparcMessageQueue();
                var key = Guid.NewGuid().ToString();
                queue.Add(key, () =>
                {
                    if (this.RequestDocument != null)
                    {
                        this.RequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_{1}_{2}.txt", _getRandomFileName(),
                                                                                      this.RequestMessage?.FromUserName,
                                                                                      this.RequestMessage?.MsgType)));
                    }
                    else
                    {
                        System.IO.File.WriteAllText(Path.Combine(logPath, string.Format("{0}_UntreatedRequest.txt", _getRandomFileName())),
                                                    this.TextResponseMessage);
                    }

                    if (this.UsingEncryptMessage && this.EcryptRequestDocument != null)
                    {
                        this.EcryptRequestDocument.Save(Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}_{2}.txt", _getRandomFileName(),
                                                                                            this.RequestMessage.FromUserName,
                                                                                            this.RequestMessage.MsgType)));
                    }
                });
            }
            catch (Exception ex)
            {
                _ = new MessageHandlerException(ex.Message, ex);
            }
        }
Exemplo n.º 2
0
        public virtual Task OnResponseHandlerExceptionAsync(IRawConsumer rawConsumer, IConsumerConfiguration cfg, BasicDeliverEventArgs args, Exception exception)
        {
            _logger.LogError($"An unhandled exception was thrown in the response handler for message '{args.BasicProperties.MessageId}'.", exception);
            var innerException = UnwrapInnerException(exception);
            var rawException   = new MessageHandlerException(
                message: $"An unhandled exception was thrown when consuming a message\n  MessageId: {args.BasicProperties.MessageId}\n  Queue: '{cfg.Queue.FullQueueName}'\n  Exchange: '{cfg.Exchange.ExchangeName}'\nSee inner exception for more details.",
                inner: innerException
                );

            _logger.LogInformation($"Sending MessageHandlerException with CorrelationId '{args.BasicProperties.CorrelationId}'");
            rawConsumer.Model.BasicPublish(
                exchange: string.Empty,
                routingKey: args.BasicProperties?.ReplyTo ?? string.Empty,
                basicProperties: _propertiesProvider.GetProperties <MessageHandlerException>(p =>
            {
                p.CorrelationId = args.BasicProperties?.CorrelationId ?? string.Empty;
                p.Headers.Add(PropertyHeaders.ExceptionHeader, _messageExceptionName);
            }),
                body: _serializer.Serialize(rawException)
                );

            if (!cfg.NoAck)
            {
                _logger.LogDebug($"Nack'ing message with delivery tag '{args.DeliveryTag}'.");
                rawConsumer.Model.BasicNack(args.DeliveryTag, false, false);
            }
            return(Task.FromResult(true));
        }
Exemplo n.º 3
0
        /// <summary>
        /// Applies the plan.
        /// </summary>
        /// <returns></returns>
        private dynamic ApplyPlan()
        {
            Logger.Info("Applying : " + newSpec.ToString());

            if (oldPlan.Deployment.Value != string.Empty && oldPlan.Deployment.Value != newPlan.Deployment.Value)
            {
                MessageHandlerException exception = new MessageHandlerException(string.Format("attempt to apply {0} to {1}", oldPlan.Deployment.Value, newPlan.Deployment.Value));
                Logger.Error(exception.Message);
                throw exception;
            }

            if (newPlan.Configured)
            {
                try
                {
                    Monit.GetInstance().StopServices();
                    // TODO make sure processes have exited, even if windows reports services as stopped
                    Thread.Sleep(10000);
                    ApplyJob();
                    ApplyPackage();
                    ConfigureJob();
                }
                catch (Exception ex)
                {
                    MessageHandlerException exception = new MessageHandlerException(ex.Message, ex);
                    throw exception;
                }
            }
            Config.State.Write(newSpec);
            return(newSpec);
        }
Exemplo n.º 4
0
        /// <summary>
        /// 保存请求信息
        /// <para>测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。</para>
        /// </summary>
        /// <param name="logPath">保存日志目录,默认为 ~/App_Data/&lt;模块类型&gt;/&lt;yyyy-MM-dd&gt;/</param>
        public void SaveRequestMessageLog(string logPath = null)
        {
            try
            {
                logPath = logPath ?? GetLogPath();
                SenparcMessageQueue queue = new SenparcMessageQueue();
                var key = Guid.NewGuid().ToString();
                queue.Add(key, async() =>
                {
                    if (this.RequestDocument != null)
                    {
                        var filePath = Path.Combine(logPath, string.Format("{0}_Request_{1}_{2}.txt", _getRandomFileName(),
                                                                           this.RequestMessage?.FromUserName,
                                                                           this.RequestMessage?.MsgType));
#if NETSTANDARD2_1_OR_GREATER
                        using (var fs = new FileStream(filePath, FileMode.CreateNew))
                        {
                            await this.RequestDocument.SaveAsync(fs, System.Xml.Linq.SaveOptions.None, new CancellationToken());
                        }
#else
                        this.RequestDocument.Save(filePath);
#endif
                    }
                    else
                    {
                        System.IO.File.WriteAllText(Path.Combine(logPath, string.Format("{0}_UntreatedRequest.txt", _getRandomFileName())),
                                                    this.TextResponseMessage);
                    }

                    if (this.UsingEncryptMessage && this.EcryptRequestDocument != null)
                    {
                        var filePath = Path.Combine(logPath, string.Format("{0}_Request_Ecrypt_{1}_{2}.txt", _getRandomFileName(),
                                                                           this.RequestMessage.FromUserName,
                                                                           this.RequestMessage.MsgType));
#if NETSTANDARD2_1_OR_GREATER
                        using (var fs = new FileStream(filePath, FileMode.CreateNew))
                        {
                            await this.RequestDocument.SaveAsync(fs, System.Xml.Linq.SaveOptions.None, new CancellationToken());
                        }
#else
                        this.EcryptRequestDocument.Save(filePath);
#endif
                    }
                });
            }
            catch (Exception ex)
            {
                _ = new MessageHandlerException(ex.Message, ex);
            }
        }
Exemplo n.º 5
0
 private void InvokeAndHandleException(Action action)
 {
     try
     {
         action();
     }
     catch (Exception ex)
     {
         if (ex is WeixinException)
         {
             if (ex is ErrorJsonResultException)
             {
                 ErrorJsonResultException ex2 = ex as ErrorJsonResultException;
                 this.ShowMsg(ex2.JsonResult.errcode.ToString(), false);
                 goto end_IL_000f;
             }
             if (ex is MessageHandlerException)
             {
                 MessageHandlerException ex3 = ex as MessageHandlerException;
                 this.ShowMsg(ex3.Message, false);
                 goto end_IL_000f;
             }
             if (ex is UnknownRequestMsgTypeException)
             {
                 UnknownRequestMsgTypeException ex4 = ex as UnknownRequestMsgTypeException;
                 this.ShowMsg(ex4.Message, false);
                 goto end_IL_000f;
             }
             if (ex is WeixinMenuException)
             {
                 WeixinMenuException ex5 = ex as WeixinMenuException;
                 this.ShowMsg(ex5.Message, false);
                 goto end_IL_000f;
             }
         }
         if (!(ex is ThreadAbortException))
         {
             NameValueCollection param = new NameValueCollection
             {
                 this.Page.Request.Form,
                 this.Page.Request.QueryString
             };
             Globals.WriteExceptionLog_Page(ex, param, "AdminError");
             this.ShowMsg(ex.Message, false);
         }
         end_IL_000f :;
     }
 }
        protected virtual Task HandleRespondException(ExceptionInformation exceptionInfo, IPipeContext context)
        {
            _logger.Info("An unhandled exception occured when remote tried to handle request.\n  Message: {exceptionMessage}\n  Stack Trace: {stackTrace}", exceptionInfo.Message, exceptionInfo.StackTrace);

            if (HandlerFunc != null)
            {
                return(HandlerFunc(exceptionInfo, context));
            }

            var exception = new MessageHandlerException(exceptionInfo.Message)
            {
                InnerExceptionType = exceptionInfo.ExceptionType,
                InnerStackTrace    = exceptionInfo.StackTrace,
                InnerMessage       = exceptionInfo.InnerMessage
            };

            return(TaskUtil.FromException(exception));
        }
Exemplo n.º 7
0
        public virtual Task OnResponseRecievedAsync(BasicDeliverEventArgs args, TaskCompletionSource <object> responseTcs)
        {
            var containsException = args?.BasicProperties?.Headers?.ContainsKey(PropertyHeaders.ExceptionHeader) ?? false;

            if (containsException)
            {
                _logger.LogInformation($"Message '{args.BasicProperties.MessageId}' withh CorrelationId '{args.BasicProperties.CorrelationId}' contains exception. Deserialize and re-throw.");
                var exceptionInfo = _serializer.Deserialize <MessageHandlerExceptionInformation>(args.Body);
                var exception     = new MessageHandlerException(exceptionInfo.Message)
                {
                    InnerExceptionType = exceptionInfo.ExceptionType,
                    InnerStackTrace    = exceptionInfo.StackTrace,
                    InnerMessage       = exceptionInfo.InnerMessage
                };
                responseTcs.TrySetException(exception);
            }

            return(Task.FromResult(true));
        }
Exemplo n.º 8
0
        private object RunDrainScript(string jobUpdated, string hashUpdated, string[] updatedPackages)
        {
            int    result         = 0;
            string standardOutput = string.Empty;
            string standardError  = string.Empty;

            Logger.Info(string.Format(CultureInfo.InvariantCulture, "Running drain script with job updated: {0}, hash updated: {1} and updated packages {2}", jobUpdated, hashUpdated, string.Join(" ", updatedPackages)));
            ProcessStartInfo info = new ProcessStartInfo();

            info.FileName = drainFile;
            info.EnvironmentVariables.Add("job_change", jobUpdated);
            info.EnvironmentVariables.Add("hash_change", hashUpdated);
            info.EnvironmentVariables.Add("updated_packages", String.Join(" ", updatedPackages));
            info.RedirectStandardOutput = true;
            info.RedirectStandardError  = true;
            info.UseShellExecute        = false;

            using (System.Diagnostics.Process p = new Process())
            {
                p.StartInfo = info;
                p.Start();
                p.WaitForExit();
                result         = p.ExitCode;
                standardOutput = p.StandardOutput.ReadToEnd();
                standardError  = p.StandardError.ReadToEnd();
            }
            if (!String.IsNullOrEmpty(standardError))
            {
                string errorMessage = string.Format(CultureInfo.InvariantCulture, "Drain script error exit {0} : {1}", result, standardError);
                MessageHandlerException massageHandlerException = new MessageHandlerException(errorMessage);
                Logger.Error(errorMessage);
                throw massageHandlerException;
            }
            else
            {
                Logger.Info(string.Format(CultureInfo.InvariantCulture, "Finished running drain script, output :{0}", standardOutput));
            }

            return(result);
        }
Exemplo n.º 9
0
        /// <summary>
        /// 保存响应信息
        /// <para>测试时可开启此记录,帮助跟踪数据,使用前请确保App_Data文件夹存在,且有读写权限。</para>
        /// </summary>
        /// <param name="logPath">保存日志目录,默认为 ~/App_Data/&lt;模块类型&gt;/&lt;yyyy-MM-dd&gt;/</param>
        public void SaveResponseMessageLog(string logPath = null)
        {
            try
            {
                logPath = logPath ?? GetLogPath();

                SenparcMessageQueue queue = new SenparcMessageQueue();
                var key = Guid.NewGuid().ToString();
                queue.Add(key, () =>
                {
                    if (this.ResponseDocument != null && this.ResponseDocument.Root != null)
                    {
                        this.ResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_{1}_{2}.txt", _getRandomFileName(),
                                                                                       this.ResponseMessage?.ToUserName,
                                                                                       this.ResponseMessage?.MsgType)));
                    }

                    if (this.UsingEcryptMessage &&
                        this.FinalResponseDocument != null && this.FinalResponseDocument.Root != null)
                    {
                        //记录加密后的响应信息
                        this.FinalResponseDocument.Save(Path.Combine(logPath, string.Format("{0}_Response_Final_{1}_{2}.txt", _getRandomFileName(),
                                                                                            this.ResponseMessage?.ToUserName,
                                                                                            this.ResponseMessage?.MsgType)));
                    }

                    if (this.ResponseDocument == null && this.TextResponseMessage != null)
                    {
                        System.IO.File.WriteAllText(Path.Combine(logPath, string.Format("{0}_TextResponse_{1}_{2}.txt", _getRandomFileName(),
                                                                                        this.RequestMessage?.ToUserName,
                                                                                        this.RequestMessage?.MsgType)), this.TextResponseMessage);
                    }
                });
            }
            catch (Exception ex)
            {
                _ = new MessageHandlerException(ex.Message, ex);
            }
        }