Exemplo n.º 1
0
 internal void TestApi(object arg)
 {
     try
     {
         SelecTestItem.RequestId = RandomOperate.Generate(8);
         GlobalContext.SetRequestContext(ZeroApplication.Config.ServiceKey, SelecTestItem.RequestId);
         User.ContextJson = JsonConvert.SerializeObject(GlobalContext.Current, Formatting.Indented);
         var client = new ApiClient
         {
             Station  = SelecTestItem.Station,
             Commmand = SelecTestItem.Api,
             Argument = SelecTestItem.Arguments
         };
         client.CallCommand();
         SelecTestItem.GlobalId = client.GlobalId;
         var result = JsonConvert.DeserializeObject <ApiResult>(client.Result);
         Tree.SelectItem.StatusIcon = result?.Success ?? false
             ? Application.Current.Resources["async_Succeed"] as BitmapImage
             : Application.Current.Resources["async_Faulted"] as BitmapImage;
         var obj = JsonConvert.DeserializeObject(client.Result);
         SelecTestItem.ResultJson = JsonConvert.SerializeObject(obj, Formatting.Indented);
         SaveApiScript();
     }
     catch (Exception ex)
     {
         Trace.WriteLine(ex);
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// 格式化身份名称
        /// </summary>
        /// <param name="isService"></param>
        /// <param name="ranges"></param>
        /// <returns></returns>
        public static string CreateRealName(bool isService, params string[] ranges)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(UseIpc ? '-' : '+');
            sb.Append(isService ? "<" : ">");
            //sb.Append(ZeroApplication.Config.ServiceName);
            //sb.Append("-");
            sb.Append(ZeroApplication.Config.ShortName);
            if (ZeroApplication.Config.ServiceKey != "*")
            {
                sb.Append("-");
                sb.Append(ZeroApplication.Config.ServiceKey);
            }
            foreach (var range in ranges)
            {
                if (range == null)
                {
                    continue;
                }
                sb.Append("-");
                sb.Append(range);
            }
            sb.Append("-");
            sb.Append(RandomOperate.Generate(4));
            return(sb.ToString());
        }
Exemplo n.º 3
0
        /// <summary>
        /// 初始化,必须先调用
        /// </summary>
        public static void InitializeBase(bool bear)
        {
            if (IsInitialize)
            {
                return;
            }

            IocHelper.Update();
            IocHelper.AddScoped <GlobalContext, BusinessContext>();
            IocHelper.AddSingleton <IZeroPublisher, ZeroNetBridge>();
            IocHelper.AddSingleton <IGlobalContext, BusinessContext>(p => BusinessContext.Context);
            IocHelper.Update();

            Environment.CurrentDirectory = ConfigurationManager.BasePath = HttpContext.Current.Server.MapPath("~");

            LogRecorder.Initialize();
            LogRecorder.SystemLog("启动");
            LogRecorder.GetRequestIdFunc = () => RandomOperate.Generate(8);
            GlobalConfiguration.Configuration.MapHttpAttributeRoutes(new CustomDirectRouteProvider());
            HttpHandler.Handlers.Add(new CorsHandler());
            HttpHandler.Handlers.Add(new HttpIoLogHandler());
            if (bear)
            {
                HttpHandler.Handlers.Add(new BearerHandler());
            }
            IsInitialize = true;
        }
Exemplo n.º 4
0
        /// <summary>
        ///     请求命令
        /// </summary>
        /// <returns></returns>
        public static object Call(string command)
        {
            var    ev     = new ManualResetEvent(false);
            object result = null;
            var    cmd    = new CommandArgument
            {
                userToken   = ApiContext.MyServiceKey,
                commandName = command,
                requestId   = RandomOperate.Generate(12),
                cmdId       = RpcEnvironment.NET_COMMAND_CALL,
                Data        = new StringArgumentData(),
                OnEnd       = res =>
                {
                    var data = (StringArgumentData)res.Data;
                    result = data?.Argument;
                    ev.Set();
                }
            };

            cmd.RequestStateChanged += OnRequestStateChanged;
            Message = "Start";
            RpcCore.Singleton.Request.request_net_cmmmand(cmd);
            ev.WaitOne();
            Message = "End";
            return(result);
        }
Exemplo n.º 5
0
        /// <summary>
        /// 心跳
        /// </summary>
        /// <returns></returns>
        public static void ApiTest()
        {
            var request = new RequestSocket();
            var config  = StationProgram.GetConfig(station);

            try
            {
                int id = 1;
                request.Options.Identity          = RandomOperate.Generate(8).ToAsciiBytes();
                request.Options.ReconnectInterval = new TimeSpan(0, 0, 0, 0, 200);
                request.Connect(config.OutAddress);
                //for (int i = 0; i < 1024; i++)//
                {
                    Console.WriteLine("request...");
                    DateTime s = DateTime.Now;
                    request.SendFrame(api, true);
                    request.SendFrame($"{++id}", true);
                    request.SendFrame("{}", true);
                    if (!request.TrySendFrame(new TimeSpan(0, 0, 0, 3), argument))
                    {
                        Console.WriteLine("*  3");
                        return;
                    }
                    bool more = true;
                    //收完消息
                    while (more)
                    {
                        string result;
                        if (request.TryReceiveFrameString(new TimeSpan(0, 0, 0, 500), out result, out more))
                        {
                            Console.WriteLine(result);
                            continue;
                        }
                        Console.WriteLine("*  4");
                        return;
                    }
                    time += (DateTime.Now - s).TotalMilliseconds;
                    cnt++;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                request.Close();
                //tasks.Remove(Task.CurrentId.Value);
            }
        }
Exemplo n.º 6
0
        /// <summary>
        ///     初始化基本上下文
        /// </summary>
        private bool InitializeContext()
        {
            ApiContext.Current.Request.Bear         = Data.Bearer;
            ApiContext.Current.Request.RequestId    = RandomOperate.Generate(8);
            ApiContext.Current.Request.Ip           = HttpContext.Connection.RemoteIpAddress.ToString();
            ApiContext.Current.Request.Port         = HttpContext.Connection.RemotePort.ToString();
            ApiContext.Current.Request.ServiceKey   = ApiContext.MyServiceKey;
            ApiContext.Current.Request.ArgumentType = ArgumentType.Json;
            ApiContext.Current.Request.UserAgent    = Request.Headers["User-Agent"];

            if (!AppConfig.Config.RouteMap.TryGetValue(Data.HostName, out Data.RouteHost))
            {
                Data.RouteHost = HostConfig.DefaultHost;
            }
            return(true);
        }
Exemplo n.º 7
0
        /// <summary>
        ///     广播
        /// </summary>
        /// <returns></returns>
        public static CommandArgument Publish <T>(string command, T argument)
        {
            var cmd = new CommandArgument
            {
                userToken   = ApiContext.MyServiceKey,
                commandName = command,
                requestId   = RandomOperate.Generate(12),
                cmdId       = RpcEnvironment.NET_COMMAND_BUSINESS_NOTIFY,
                Data        = new StringArgumentData
                {
                    Argument = JsonConvert.SerializeObject(argument)
                }
            };

            cmd.RequestStateChanged += OnRequestStateChanged;
            RpcCore.Singleton.Request.request_net_cmmmand(cmd, false);
            return(cmd);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 发送广播
        /// </summary>
        /// <param name="station"></param>
        /// <param name="title"></param>
        /// <param name="sub"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        private static bool DoPublish(string station, string title, string sub, string value)
        {
            var socket = ZeroConnectionPool.GetSocket(station, RandomOperate.Generate(8));

            if (socket.Socket == null)
            {
                return(false);
            }
            using (socket)
            {
                return(socket.Socket.Publish(new PublishItem
                {
                    Station = station,
                    Title = title,
                    SubTitle = sub,
                    RequestId = GlobalContext.RequestInfo.RequestId,
                    Content = value ?? "{}"
                }));
            }
        }
Exemplo n.º 9
0
        /// <summary>
        ///     检查上下文,如果信息为空,加入系统匿名用户上下文
        /// </summary>
        public static void TryCheckByAnymouse()
        {
            if (Current._requestContext == null)
            {
                Current._requestContext = new CallContext
                {
                    RequestId   = RandomOperate.Generate(8),
                    Bear        = "<error>",
                    RequestType = RequestType.None
                }
            }
            ;
            if (Current._user == null)
            {
                Current._user = LoginUserInfo.CreateAnymouse(Current._requestContext.Bear, "<error>", "<error>");
            }
        }

        #endregion
    }
Exemplo n.º 10
0
        /// <summary>
        ///     准备
        /// </summary>
        /// <param name="context"></param>
        public void Prepare(HttpContext context)
        {
            var request = context.Request;

            Uri = request.GetUri();
            string userAgent = null;

            foreach (var head in request.Headers)
            {
                var key = head.Key.ToUpper();
                var vl  = head.Value.ToList();
                Headers.Add(key, vl);
                switch (key)
                {
                case "AUTHORIZATION":
                    Token = vl.LinkToString();
                    break;

                case "USER-AGENT":
                    userAgent = head.Value.LinkToString("|");
                    break;
                }
            }
            HttpMethod = request.Method.ToUpper();


            GlobalContext.SetRequestContext(new RequestInfo
            {
                RequestId    = RandomOperate.Generate(8),
                UserAgent    = userAgent,
                Token        = Token,
                RequestType  = RequestType.Http,
                ArgumentType = ArgumentType.Json,
                Ip           = context.Connection.RemoteIpAddress?.ToString(),
                Port         = context.Connection.RemotePort.ToString(),
            });
        }
Exemplo n.º 11
0
 /// <inheritdoc />
 protected override bool OnStart()
 {
     _inporcName = $"inproc://{StationName}_{RandomOperate.Generate(8)}.pub";
     return(base.OnStart());
 }
Exemplo n.º 12
0
        /// <summary>
        ///     执行检查
        /// </summary>
        /// <returns>
        ///     0:表示通过验证,可以继续
        ///     1:令牌为空或不合格
        ///     2:令牌是伪造的
        /// </returns>
        private int Check(HttpRequestMessage request)
        {
            if (Request.RequestUri.LocalPath == "/v1/oauth/getdid")
            {
                return(ErrorCode.Success);
            }
            if (Request.RequestUri.LocalPath == "/v1/sys/flush")
            {
                return(ErrorCode.Success);
            }
            var token = GlobalContext.Current.Request.Token = ExtractToken(request);

            if (string.IsNullOrWhiteSpace(GlobalContext.Current.Token))
            {
                return(ErrorCode.DenyAccess);
            }
            int state;

            switch (token[0])
            {
            case '{':
                state = CheckServiceKey(token);
                break;

            case '$':
                state = RevertCallContext(token);
                break;

            case '#':
                GlobalContext.SetRequestContext(new RequestInfo(GlobalContext.ServiceKey, RandomOperate.Generate(8))
                {
                    Token = token
                });
                state = CheckAccessToken(GlobalContext.Current.Token);
                break;

            case '%':
                GlobalContext.SetRequestContext(new RequestInfo(GlobalContext.ServiceKey, RandomOperate.Generate(8))
                {
                    Token = token
                });
                state = 0;
                break;

            default:
                GlobalContext.SetRequestContext(new RequestInfo(GlobalContext.ServiceKey, RandomOperate.Generate(8))
                {
                    Token = token
                });
                state = CheckDeviceId(token);
                break;
            }

            if (state != 0)
            {
                return(state);
            }
            var page = Request.RequestUri.Segments[2];

            BusinessContext.Context.PowerChecker?.LoadAuthority(page);
            return(0);
        }
Exemplo n.º 13
0
 /// <summary>
 /// 取请求ID
 /// </summary>
 public static string GetRequestId()
 {
     return(GetRequestIdFunc?.Invoke() ?? RandomOperate.Generate(8));
 }
Exemplo n.º 14
0
 /// <summary>
 /// 构造
 /// </summary>
 public RequestInfo() : this($"{GlobalContext.ServiceName}-{RandomOperate.Generate(6)}")
 {
 }
Exemplo n.º 15
0
        /// <summary>
        ///     配置校验
        /// </summary>
        private static void CheckConfig()
        {
            var    curPath = ConfigurationManager.Root.GetValue("contentRoot", Environment.CurrentDirectory);
            string rootPath;

            if (ConfigurationManager.Root["ASPNETCORE_ENVIRONMENT_"] == "Development")
            {
                ZeroTrace.SystemLog("Option", "Development");
                AppName  = ConfigurationManager.Root["AppName"];
                rootPath = curPath;
            }
            else
            {
                ZeroTrace.SystemLog("Option", RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? "Linux" : "Windows");
                rootPath = Path.GetDirectoryName(curPath);
                AppName  = Path.GetFileName(curPath);
                // ReSharper disable once AssignNullToNotNullAttribute
                var file = Path.Combine(rootPath, "config", "zero.json");
                if (File.Exists(file))
                {
                    ConfigurationManager.Load(file);
                }
                file = Path.Combine(rootPath, "config", $"{AppName}.json");
                if (File.Exists(file))
                {
                    ConfigurationManager.Load(file);
                }
                var name = ConfigurationManager.Root["AppName"];
                if (name == null)
                {
                    ConfigurationManager.Root["AppName"] = AppName;
                }
                else
                {
                    AppName = name;
                }
            }

            ConfigurationManager.Root["rootPath"] = rootPath;

            var sec = ConfigurationManager.Get("Zero");

            if (sec == null)
            {
                throw new Exception("无法找到主配置节点,路径为Zero,在appsettings.json中设置");
            }
            var global = sec.Child <ZeroAppConfig>("Global");

            if (global == null)
            {
                throw new Exception("无法找到主配置节点,路径为Zero.Global,在appsettings.json中设置");
            }
            Config = string.IsNullOrWhiteSpace(AppName)
                ? sec.Child <ZeroAppConfig>("Station")
                : sec.Child <ZeroAppConfig>(AppName) ?? sec.Child <ZeroAppConfig>("Station");


            if (Config == null)
            {
                throw new Exception($"无法找到主配置节点,路径为Zero.{AppName}或Zero.Station,在appsettings.json中设置");
            }
            Config.BinPath  = curPath;
            Config.RootPath = rootPath;

            var socketOption = sec.Child <SocketOption>("socketOption");

            if (socketOption != null)
            {
                ZSocket.Option = socketOption;
            }

            if (string.IsNullOrWhiteSpace(AppName))
            {
                ConfigurationManager.Root["AppName"] = AppName = Config.StationName;
            }

            Config.IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);

            global.LogFolder    = string.IsNullOrWhiteSpace(global.LogFolder) ? IOHelper.CheckPath(rootPath, "logs") : global.LogFolder.Trim();
            global.DataFolder   = string.IsNullOrWhiteSpace(global.DataFolder) ? IOHelper.CheckPath(rootPath, "datas") : global.DataFolder.Trim();
            global.ServiceName  = string.IsNullOrWhiteSpace(global.ServiceName) ? Dns.GetHostName() : global.ServiceName.Trim();
            global.ServiceKey   = string.IsNullOrWhiteSpace(global.ServiceKey) ? RandomOperate.Generate(8) : global.ServiceKey.Trim();
            global.ConfigFolder = string.IsNullOrWhiteSpace(global.ConfigFolder) ? IOHelper.CheckPath(rootPath, "config") : global.ConfigFolder.Trim();

            global.ZeroAddress = string.IsNullOrWhiteSpace(global.ZeroAddress) ? "127.0.0.1" : global.ZeroAddress.Trim();
            if (global.ZeroManagePort <= 1024 || Config.ZeroManagePort >= 65000)
            {
                global.ZeroManagePort = 8000;
            }
            if (global.ZeroMonitorPort <= 1024 || Config.ZeroMonitorPort >= 65000)
            {
                global.ZeroMonitorPort = 8001;
            }


            if (global.StationIsolate || Config.StationIsolate)
            {
                Config.ServiceName = string.IsNullOrWhiteSpace(Config.ServiceName) ? global.ServiceName : Config.ServiceName.Trim();
                Config.ServiceKey  = string.IsNullOrWhiteSpace(Config.ServiceKey) ? global.ServiceKey : Config.ServiceKey.Trim();
                Config.ZeroAddress = string.IsNullOrWhiteSpace(Config.ZeroAddress) ? global.ZeroAddress : Config.ZeroAddress.Trim();
                if (Config.ZeroManagePort <= 1024 || Config.ZeroManagePort >= 65000)
                {
                    Config.ZeroManagePort = global.ZeroManagePort;
                }
                if (Config.ZeroMonitorPort <= 1024 || Config.ZeroMonitorPort >= 65000)
                {
                    Config.ZeroMonitorPort = global.ZeroMonitorPort;
                }

                Config.DataFolder   = string.IsNullOrWhiteSpace(Config.DataFolder) ? global.DataFolder : IOHelper.CheckPath(global.DataFolder, AppName, "datas");
                Config.LogFolder    = string.IsNullOrWhiteSpace(Config.LogFolder) ? global.LogFolder : IOHelper.CheckPath(global.LogFolder, AppName, "logs");
                Config.ConfigFolder = string.IsNullOrWhiteSpace(Config.ConfigFolder) ? global.ConfigFolder : IOHelper.CheckPath(rootPath, AppName, "config");
            }
            else
            {
                Config.ServiceName     = global.ServiceName;
                Config.ServiceKey      = global.ServiceKey;
                Config.ZeroAddress     = global.ZeroAddress;
                Config.ZeroManagePort  = global.ZeroManagePort;
                Config.ZeroMonitorPort = global.ZeroMonitorPort;

                Config.DataFolder   = global.DataFolder;
                Config.LogFolder    = global.LogFolder;
                Config.ConfigFolder = global.ConfigFolder;
            }
            TxtRecorder.LogPath = Config.LogFolder;
            ConfigurationManager.Get("LogRecorder")["txtPath"] = Config.LogFolder;

            Config.ZeroManageAddress  = ZeroIdentityHelper.GetRequestAddress("SystemManage", Config.ZeroManagePort);
            Config.ZeroMonitorAddress = ZeroIdentityHelper.GetWorkerAddress("SystemMonitor", Config.ZeroMonitorPort);
            Config.LocalIpAddress     = GetHostIps();
            Config.ShortName          = string.IsNullOrWhiteSpace(Config.ShortName) ? Config.StationName : Config.ShortName.Trim();
            Config.RealName           = ZeroIdentityHelper.CreateRealName(false);
            Config.Identity           = Config.RealName.ToAsciiBytes();
            //模式选择

            if (Config.SpeedLimitModel < SpeedLimitType.Single || Config.SpeedLimitModel > SpeedLimitType.WaitCount)
            {
                Config.SpeedLimitModel = SpeedLimitType.ThreadCount;
            }

            if (Config.TaskCpuMultiple <= 0)
            {
                Config.TaskCpuMultiple = 1;
            }
            else if (Config.TaskCpuMultiple > 128)
            {
                Config.TaskCpuMultiple = 128;
            }

            if (Config.MaxWait < 0xFF)
            {
                Config.MaxWait = 0xFF;
            }
            else if (Config.MaxWait > 0xFFFFF)
            {
                Config.MaxWait = 0xFFFFF;
            }

            ShowOptionInfo(rootPath);
        }