Ejemplo n.º 1
0
        public TResponse DoTrans <TRequest, TResponse>(TRequest request)
            where TRequest : IHospProxyRequestModel, new()
            where TResponse : IHospProxyResponseModel, new()
        {
            try
            {
                using (MonitorScope.CreateScope(MethodBase.GetCurrentMethod().Name))
                {
                    var soapRequest = request.ConvertToHospRequest();
                    LogRecorder.MonitorTrace(new { doCode = soapRequest.code, doRequest = soapRequest.json }.ToJson());

                    var soapClient = GenerateSoapClient <AppServiceCommonSoap>();
                    var soapResult = soapClient.DoTransAsync(soapRequest.code, soapRequest.json).Result;

                    LogRecorder.MonitorTrace(new { doCode = soapRequest.code, doResponse = soapResult }.ToJson());

                    var result = JsonConvert.DeserializeObject <TResponse>(soapResult.FormatHospResult());
                    LogRecorder.MonitorTrace(new { doCode = soapRequest.code, doFormatResult = soapResult }.ToJson());

                    return(result);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        ///     通过Post调用
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="form"></param>
        /// <returns></returns>
        public ApiValueResult Post(string apiName, string form)
        {
            LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName));
            string ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";

            LogRecorder.MonitorTrace(ctx);
            LogRecorder.MonitorTrace("Arguments:" + form);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));

            req.Method      = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add(HttpRequestHeader.Authorization, ctx);
            try
            {
                using (Stream rs = req.GetRequestStream())
                {
                    byte[] formData = Encoding.UTF8.GetBytes(form);
                    rs.Write(formData, 0, formData.Length);
                }
            }
            catch (Exception ex)
            {
                LogRecorder.Exception(ex);
                LogRecorder.EndStepMonitor();
                return(ErrorResult(-3));
            }
            using (MonitorScope.CreateScope("Caller Remote"))
            {
                return(GetResult(req));
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 重载
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            using (MonitorScope.CreateScope(request.RequestUri.ToString()))
            {
                foreach (var handler in Handlers)
                {
                    try
                    {
                        var task = handler.OnBegin(request, cancellationToken);
                        if (task == null)
                        {
                            continue;
                        }
                        ContextHelper.Remove("ApiContext");
                        return(task);
                    }
                    catch (Exception e)
                    {
                        LogRecorder.Exception(e);
                    }
                }
                var result = base.SendAsync(request, cancellationToken);

                result.ContinueWith((task, state) => OnEnd(request, result.Result, cancellationToken), null,
                                    TaskContinuationOptions.AttachedToParent | TaskContinuationOptions.ExecuteSynchronously);

                return(result);
            }
        }
Ejemplo n.º 4
0
        private void ApiCallByMonitor(ref ZSocket socket, ApiCallItem item)
        {
            using (MonitorScope.CreateScope(item.ApiName))
            {
                LogRecorder.MonitorTrace($"Caller:{item.Caller}");
                LogRecorder.MonitorTrace($"GlobalId:{item.GlobalId}");
                LogRecorder.MonitorTrace(JsonConvert.SerializeObject(item));
                ZeroOperatorStateType state;
                Prepare(item);
                using (MonitorScope.CreateScope("Do"))
                {
                    state = ExecCommand(item);
                }

                if (state != ZeroOperatorStateType.Ok)
                {
                    Interlocked.Increment(ref ErrorCount);
                }
                else
                {
                    Interlocked.Increment(ref SuccessCount);
                }
                LogRecorder.MonitorTrace(item.Result);
                if (!SendResult(ref socket, item, state))
                {
                    ZeroTrace.WriteError(item.ApiName, "SendResult");
                }

                End(item);
            }
        }
Ejemplo n.º 5
0
 /// <summary>
 ///     远程调用
 /// </summary>
 /// <returns></returns>
 public void CallCommand()
 {
     using (MonitorScope.CreateScope("内部Zero调用"))
     {
         Prepare();
         Call();
         End();
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        ///     远程调用
        /// </summary>
        /// <returns></returns>
        private async Task <string> CallHttp()
        {
            var host = Data.RouteHost as HttpHost;

            if (host == null)
            {
                LogRecorder.MonitorTrace("Host Type Failed");
                return(Data.ResultMessage);
            }
            // 当前请求调用的模型对应的主机名称
            string httpHost;

            // 当前请求调用的Api名称
            var httpApi = host == HttpHost.DefaultHost
                ? Data.Uri.PathAndQuery
                : $"{Data.ApiName}{Data.Uri.Query}";

            // 查找主机
            if (host.Hosts.Length == 1)
            {
                httpHost = host.Hosts[0];
            }
            else
            {
                lock (host)
                {
                    //平均分配
                    httpHost = host.Hosts[host.Next];
                    if (++host.Next >= host.Hosts.Length)
                    {
                        host.Next = 0;
                    }
                }
            }

            // 远程调用
            using (MonitorScope.CreateScope("CallHttp"))
            {
                var caller = new HttpApiCaller(httpHost)
                {
                    Bearer = $"Bearer {ApiContext.RequestContext.Bear}"
                };
                caller.CreateRequest(httpApi, Data.HttpMethod, Request, Data);

                Data.ResultMessage = await caller.Call();

                Data.Status = caller.Status;
                LogRecorder.MonitorTrace(caller.Status.ToString());
                LogRecorder.MonitorTrace(Data.ResultMessage);
            }
            return(Data.ResultMessage);
        }
Ejemplo n.º 7
0
        private async Task <ZeroOperatorStateType> ApiCallByMonitor()
        {
            using (MonitorScope.CreateScope($"{Station.ServiceName}/{Item.ApiName}"))
            {
                LogRecorder.MonitorTrace(() => $"GlobalId:{Item.GlobalId}");
                LogRecorder.MonitorTrace(() => JsonConvert.SerializeObject(Item, Formatting.Indented));

                ZeroOperatorStateType state = RestoryContext();
                if (state != ZeroOperatorStateType.Ok)
                {
                    LogRecorder.MonitorTrace("Restory context failed");
                    Interlocked.Increment(ref Station.ErrorCount);
                    return(state);
                }
                using (MonitorScope.CreateScope("Do"))
                {
                    state = CommandPrepare(true, out var action);
                    if (state == ZeroOperatorStateType.Ok)
                    {
                        object res;
                        if (CancellationToken.IsCancellationRequested)
                        {
                            res = ZeroOperatorStateType.Unavailable;
                        }
                        else
                        {
                            res = CommandExec(true, action);
                        }

                        state = await CheckCommandResult(res);
                    }
                }

                if (state != ZeroOperatorStateType.Ok)
                {
                    Interlocked.Increment(ref Station.ErrorCount);
                }
                else
                {
                    Interlocked.Increment(ref Station.SuccessCount);
                }

                LogRecorder.MonitorTrace(Item.Result);
                return(state);
            }
        }
Ejemplo n.º 8
0
        private ApiResult <LoginUserInfo> CheckToken(string name, string api, out string result)
        {
            // 远程调用
            using (MonitorScope.CreateScope($"Check{name}:{Data.Token}"))
            {
                ApiClient caller = new ApiClient
                {
                    Simple   = true,
                    Station  = RouteOption.Option.Security.AuthStation,
                    Commmand = api,
                    Argument = $"{{\"Token\":\"{Data.Token}\"}}"
                };
                caller.CallCommand();

                result = caller.Result;
                LogRecorder.MonitorTrace($"Result:{caller.Result}");
                return(caller.Result == null
                    ? ApiResult.Succees(LoginUserInfo.CreateAnymouse(Data.Token, "*", "*"))
                    : JsonConvert.DeserializeObject <ApiResult <LoginUserInfo> >(caller.Result) ?? DenyAccessResult);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     通过Get调用
        /// </summary>
        /// <param name="apiName"></param>
        /// <param name="arguments"></param>
        /// <returns></returns>
        public ApiValueResult Get(string apiName, string arguments)
        {
            LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName));
            string ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}";

            LogRecorder.MonitorTrace(ctx);
            LogRecorder.MonitorTrace("Arguments:" + arguments);
            if (!string.IsNullOrWhiteSpace(arguments))
            {
                apiName = $"{apiName}?{arguments}";
            }
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName));

            req.Method      = "GET";
            req.ContentType = "application/x-www-form-urlencoded";
            req.Headers.Add(HttpRequestHeader.Authorization, ctx);
            using (MonitorScope.CreateScope("Caller Remote"))
            {
                return(GetResult(req));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        ///     远程调用
        /// </summary>
        /// <returns></returns>
        private string CallZero()
        {
            if (!(Data.RouteHost is ZeroHost host))
            {
                LogRecorder.MonitorTrace("Host Type Failed");
                return(Data.ResultMessage);
            }
            try
            {
                var arguments = new Dictionary <string, string>();
                if (Request.QueryString.HasValue)
                {
                    foreach (var key in Request.Query.Keys)
                    {
                        arguments.TryAdd(key, Request.Query[key]);
                    }
                }
                if (Request.HasFormContentType)
                {
                    foreach (var key in Request.Form.Keys)
                    {
                        arguments.TryAdd(key, Request.Form[key]);
                    }
                }
                if (arguments.Count > 0)
                {
                    Data.Form = JsonConvert.SerializeObject(arguments);
                }
                if (Request.ContentLength != null)
                {
                    using (var texter = new StreamReader(Request.Body))
                    {
                        Data.Context = texter.ReadToEnd();
                        if (string.IsNullOrEmpty(Data.Context))
                        {
                            Data.Context = null;
                        }
                        texter.Close();
                    }
                }
            }
            catch (Exception e)
            {
                LogRecorder.Exception(e, "读取远程参数");
                return(Data.ResultMessage = ApiResult.ArgumentErrorJson);
            }
            // 远程调用
            using (MonitorScope.CreateScope("CallZero"))
            {
                var caller = new ApiClient
                {
                    Station        = host.Station,
                    Commmand       = Data.ApiName,
                    Argument       = Data.Context ?? Data.Form,
                    ExtendArgument = Data.Form
                };
                caller.CallCommand();
                Data.ResultMessage = caller.Result;
                Data.Status        = caller.State.ToOperatorStatus(true);

                LogRecorder.MonitorTrace($"State : {caller.State}");
            }
            return(Data.ResultMessage);
        }
Ejemplo n.º 11
0
        /// <summary>
        ///     远程调用
        /// </summary>
        /// <returns></returns>
        private string CallZero()
        {
            var host = Data.RouteHost as ZeroHost;

            if (host == null)
            {
                LogRecorder.MonitorTrace("Host Type Failed");
                return(Data.ResultMessage);
            }

            string context;

            //参数解析
            if (Request.HasFormContentType)
            {
                var values = new Dictionary <string, string>();
                foreach (var form in Request.Form.Keys)
                {
                    values.TryAdd(form, Request.Form[form]);
                }
                context = JsonConvert.SerializeObject(values);
            }
            else if (Request.ContentLength > 0)
            {
                using (var texter = new StreamReader(Request.Body))
                {
                    context = texter.ReadToEnd();
                }
            }
            else
            {
                var values = new Dictionary <string, string>();
                foreach (var query in Request.Query.Keys)
                {
                    values.TryAdd(query, Request.Query[query]);
                }
                context = JsonConvert.SerializeObject(values);
            }

            // 远程调用
            using (MonitorScope.CreateScope("CallZero"))
            {
                var caller = new ApiClient
                {
                    Station  = host.Station,
                    Commmand = Data.ApiName,
                    Argument = context
                };
                caller.CallCommand();
                if (caller.State < ZeroOperatorStateType.Failed)
                {
                    Data.Status = RouteStatus.None;
                }
                else if (caller.State < ZeroOperatorStateType.Bug)
                {
                    Data.Status = RouteStatus.LogicalError;
                }
                else if (caller.State < ZeroOperatorStateType.Error)
                {
                    Data.Status = RouteStatus.FormalError;
                }
                else if (caller.State <= ZeroOperatorStateType.NotSupport)
                {
                    Data.Status = RouteStatus.NotFind;
                }
                else if (caller.State == ZeroOperatorStateType.DenyAccess)
                {
                    Data.Status = RouteStatus.DenyAccess;
                }
                else if (caller.State == ZeroOperatorStateType.Unavailable)
                {
                    Data.Status = RouteStatus.Unavailable;
                }
                else if (caller.State == ZeroOperatorStateType.LocalException)
                {
                    Data.Status = RouteStatus.LocalException;
                }
                else if (caller.State >= ZeroOperatorStateType.LocalNoReady ||
                         caller.State == ZeroOperatorStateType.TimeOut)
                {
                    Data.Status = RouteStatus.LocalError;
                }
                else
                {
                    Data.Status = RouteStatus.RemoteError;
                }
                Data.ResultMessage = caller.Result;
                LogRecorder.MonitorTrace(caller.State.Text());
                LogRecorder.MonitorTrace(Data.ResultMessage);
            }

            return(Data.ResultMessage);
        }