Пример #1
0
        /// <summary>
        /// 命令轮询
        /// </summary>
        /// <returns></returns>
        private void Run()
        {
            _inprocPollSocket =
                ZSocket.CreateServiceSocket($"inproc://{Config.StationName}_Proxy", ZSocketType.ROUTER);
            _inprocPollSocket.Backlog = 4096;
            _callPollSocket           = ZSocket.CreateClientSocket(Config.RequestAddress, ZSocketType.DEALER);

            WaitCount = 0;
            ZeroTrace.WriteInfo($"{Config.StationName}(proxy)", "Listen");
            _waitToken.Release();
            using (var pool = ZmqPool.CreateZmqPool())
            {
                pool.Prepare(new[] { _inprocPollSocket, _callPollSocket }, ZPollEvent.In);
                //SystemManager.Instance.HeartReady(StationName, RealName);
                while (!RunTaskCancel.Token.IsCancellationRequested)
                {
                    if (!pool.Poll())
                    {
                        continue;
                    }
                    CheckCall(pool);

                    CheckResult(pool);
                }
            }
            _waitToken.Release();
        }
Пример #2
0
        /// <summary>
        /// 尝试安装站点
        /// </summary>
        /// <param name="station"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public bool TryInstall(string station, string type)
        {
            if (ZeroApplication.Config.TryGetConfig(station, out _))
            {
                return(true);
            }
            ZeroTrace.WriteInfo(station, "No find,try install ...");
            var r = CallCommand("install", type, station, station, station);

            if (!r.InteractiveSuccess)
            {
                ZeroTrace.WriteError(station, "Test install failed");
                return(false);
            }

            if (r.State != ZeroOperatorStateType.Ok && r.TryGetValue(ZeroFrameType.Status, out var json))
            {
                ZeroApplication.Config.UpdateConfig(station, json, out _);
            }
            ZeroTrace.WriteInfo(station, "Is install ,try start it ...");
            r = CallCommand("start", station);
            if (!r.InteractiveSuccess && r.State != ZeroOperatorStateType.Ok && r.State != ZeroOperatorStateType.Runing)
            {
                ZeroTrace.WriteError(station, "Can't start station");
                return(false);
            }
            LoadConfig(station);
            ZeroTrace.WriteInfo(station, "Station runing");
            return(true);
        }
Пример #3
0
 /// <summary>
 /// 开始
 /// </summary>
 public void Start()
 {
     ZeroTrace.WriteInfo($"{Config.StationName}(proxy)", "Start");
     RunTaskCancel = new CancellationTokenSource();
     Task.Factory.StartNew(Run);
     _waitToken.Wait();
 }
Пример #4
0
 /// <summary>
 ///     系统关闭时调用
 /// </summary>
 internal static void OnZeroEnd()
 {
     RaiseEvent(ZeroNetEventType.AppStop);
     using (OnceScope.CreateScope(ZeroObjects))
     {
         ZeroTrace.WriteLine("[OnZeroEnd>>");
         SystemManager.Instance.HeartLeft();
         ApplicationState = StationState.Closing;
         if (HaseActiveObject)
         {
             Parallel.ForEach(ActiveObjects.ToArray(), obj =>
             {
                 try
                 {
                     ZeroTrace.WriteInfo(obj.Name, "*Close");
                     obj.OnZeroEnd();
                 }
                 catch (Exception e)
                 {
                     ZeroTrace.WriteException(obj.Name, e, "*Close");
                 }
             });
             WaitAllObjectSemaphore();
         }
         GC.Collect();
         ApplicationState = StationState.Closed;
         ZeroTrace.WriteLine("<<OnZeroEnd]");
     }
 }
Пример #5
0
 /// <summary>
 /// 开始
 /// </summary>
 public void Start()
 {
     ZeroTrace.WriteInfo("ConnectionProxy", "Start");
     RunTaskCancel = new CancellationTokenSource();
     Task.Factory.StartNew(Run);
     _waitToken.Wait();
 }
Пример #6
0
        static void ShowOptionInfo(string root)
        {
            ZeroTrace.WriteInfo("Option", "ZeroMQ", zmq.LibraryVersion);
            ZeroTrace.WriteInfo("Option", "AppName", AppName);
            ZeroTrace.WriteInfo("Option", "RootPath", root);
            string model;

            switch (Config.SpeedLimitModel)
            {
            default:
                model = "单线程:线程(1) 等待(0)";
                break;

            case SpeedLimitType.ThreadCount:
                var max = (int)(Environment.ProcessorCount * Config.TaskCpuMultiple);
                if (max < 1)
                {
                    max = 1;
                }
                model =
                    $"按线程数限制:线程({Environment.ProcessorCount}×{Config.TaskCpuMultiple}={max}) 等待({Config.MaxWait})";
                break;

            case SpeedLimitType.WaitCount:
                model = $"按等待数限制:线程(1) 等待({Config.MaxWait})";
                break;
            }

            ZeroTrace.WriteInfo("Option", model);
            ZeroTrace.WriteInfo("Option", "ZeroCenter", Config.ZeroManageAddress, Config.ZeroMonitorAddress);
        }
Пример #7
0
 /// <summary>
 ///     对象活动时登记
 /// </summary>
 public static void OnGlobalStart(IZeroObject obj)
 {
     lock (GlobalObjects)
     {
         GlobalObjects.Add(obj);
         ZeroTrace.WriteInfo(obj.Name, "GlobalStart");
     }
 }
Пример #8
0
 private static void center_start(string content)
 {
     if (Interlocked.CompareExchange(ref ZeroApplication._appState, StationState.Initialized, StationState.Failed) == StationState.Failed)
     {
         ZeroTrace.WriteInfo("center_start", content);
         ZeroApplication.JoinCenter();
     }
 }
Пример #9
0
 private static void center_stop(string content)
 {
     if (ZeroApplication.ZerCenterStatus == ZeroCenterState.Destroy)
     {
         return;
     }
     ZeroApplication.ZerCenterStatus = ZeroCenterState.Destroy;
     ZeroTrace.WriteInfo("center_stop ", content);
 }
Пример #10
0
 /// <summary>
 ///     对象活动时登记
 /// </summary>
 public static void OnGlobalEnd(IZeroObject obj)
 {
     lock (GlobalObjects)
     {
         GlobalObjects.Remove(obj);
         ZeroTrace.WriteInfo(obj.Name, "GlobalEnd");
         if (GlobalObjects.Count == 0)
         {
             GlobalSemaphore.Release();
         }
     }
 }
Пример #11
0
 /// <summary>
 ///     对象关闭时登记
 /// </summary>
 public static void OnObjectFailed(IZeroObject obj)
 {
     lock (ActiveObjects)
     {
         FailedObjects.Add(obj);
         ZeroTrace.WriteInfo(obj.Name, "Failed");
         if (ActiveObjects.Count + FailedObjects.Count == ZeroObjects.Count)
         {
             ActiveSemaphore.Release(); //发出完成信号
         }
     }
 }
Пример #12
0
 /// <summary>
 ///     对象关闭时登记
 /// </summary>
 public static void OnObjectClose(IZeroObject obj)
 {
     lock (ActiveObjects)
     {
         ActiveObjects.Remove(obj);
         ZeroTrace.WriteInfo(obj.Name, "Closed");
         if (ActiveObjects.Count == 0)
         {
             ActiveSemaphore.Release(); //发出完成信号
         }
     }
 }
Пример #13
0
 /// <summary>
 /// 结束
 /// </summary>
 /// <returns></returns>
 public bool End()
 {
     if (RunTaskCancel == null)
     {
         return(false);
     }
     RunTaskCancel.Cancel();
     _waitToken.Wait();
     RunTaskCancel.Dispose();
     RunTaskCancel = null;
     ZeroTrace.WriteInfo($"{Config.StationName}(proxy)", "End");
     return(true);
 }
Пример #14
0
 /// <summary>
 /// 结束
 /// </summary>
 /// <returns></returns>
 public bool End()
 {
     if (RunTaskCancel == null)
     {
         return(false);
     }
     RunTaskCancel.Cancel();
     _waitToken.Wait();
     RunTaskCancel.Dispose();
     RunTaskCancel = null;
     ZeroTrace.WriteInfo("ConnectionProxy", "End");
     return(true);
 }
Пример #15
0
 private static void station_resume(string name)
 {
     if (!ZeroApplication.Config.TryGetConfig(name, out var config))
     {
         return;
     }
     ZeroTrace.WriteInfo("station_resume", name);
     config.State = ZeroCenterState.Run;
     if (ZeroApplication.InRun)
     {
         ZeroApplication.OnStationStateChanged(config);
     }
     ZeroApplication.InvokeEvent(ZeroNetEventType.CenterStationResume, null, config);
 }
Пример #16
0
 private static void station_update(string name, string content)
 {
     if (!ZeroApplication.Config.UpdateConfig(name, content, out var config))
     {
         return;
     }
     ZeroTrace.WriteInfo("station_update", name, content);
     if (!ZeroApplication.InRun)
     {
         return;
     }
     ZeroApplication.OnStationStateChanged(config);
     ZeroApplication.InvokeEvent(ZeroNetEventType.CenterStationUpdate, content, config);
 }
Пример #17
0
 private static void station_stop(string name)
 {
     if (!ZeroApplication.Config.TryGetConfig(name, out var config))
     {
         return;
     }
     ZeroTrace.WriteInfo("station_stop", name);
     if (config.State < ZeroCenterState.Stop)
     {
         config.State = ZeroCenterState.Stop;
     }
     if (!ZeroApplication.InRun)
     {
         return;
     }
     ZeroApplication.OnStationStateChanged(config);
     ZeroApplication.InvokeEvent(ZeroNetEventType.CenterStationLeft, null, config);
 }
Пример #18
0
 /// <summary>
 /// 刷新配置
 /// </summary>
 /// <param name="json"></param>
 public bool FlushConfigs(string json)
 {
     try
     {
         var configs = JsonConvert.DeserializeObject <List <StationConfig> >(json);
         foreach (var config in configs)
         {
             AddStation(config);
         }
         ZeroTrace.WriteInfo("LoadAllConfig", json);
         return(true);
     }
     catch (Exception e)
     {
         ZeroTrace.WriteException("LoadAllConfig", e, json);
         return(false);
     }
 }
Пример #19
0
        /// <summary>
        ///     注销时调用
        /// </summary>
        internal static void OnZeroDestory()
        {
            if (!Monitor.TryEnter(ZeroObjects))
            {
                return;
            }
            ZeroTrace.WriteLine("[OnZeroDestory>>");
            RaiseEvent(ZeroNetEventType.AppEnd);
            using (OnceScope.CreateScope(ZeroObjects))
            {
                var array = ZeroObjects.Values.ToArray();
                ZeroObjects.Clear();
                Parallel.ForEach(array, obj =>
                {
                    try
                    {
                        ZeroTrace.WriteInfo(obj.Name, "*Destory");
                        obj.OnZeroDestory();
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "*Destory");
                    }
                });

                GC.Collect();
                ZeroTrace.WriteLine("<<OnZeroDestory]");

                ZeroTrace.WriteLine("[OnZeroDispose>>");
                Parallel.ForEach(array, obj =>
                {
                    try
                    {
                        ZeroTrace.WriteInfo(obj.Name, "*Dispose");
                        obj.Dispose();
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "*Dispose");
                    }
                });
                ZeroTrace.WriteLine("<<OnZeroDispose]");
            }
        }
Пример #20
0
        /// <summary>
        ///     命令行方式管理
        /// </summary>
        public static void CommandConsole()
        {
            while (true)
            {
                var cmd = Console.ReadLine();
                if (String.IsNullOrWhiteSpace(cmd))
                {
                    continue;
                }
                switch (cmd.Trim().ToLower())
                {
                case "quit":
                case "exit":
                    Shutdown();
                    return;

                case "start":
                    Start();
                    continue;
                }

                var words = cmd.Split(' ', '\t', '\r', '\n');
                if (words.Length == 0)
                {
                    ZeroTrace.WriteLine("请输入正确命令");
                    continue;
                }

                var result = SystemManager.Instance.CallCommand(words);
                if (result.InteractiveSuccess)
                {
                    ZeroTrace.WriteInfo("Console", result.TryGetValue(ZeroFrameType.Status, out var value)
                        ? value
                        : result.State.Text());
                }
                else
                {
                    ZeroTrace.WriteError("Console", result.TryGetValue(ZeroFrameType.Status, out var value)
                        ? value
                        : result.State.Text());
                }
            }
        }
Пример #21
0
        /// <summary>
        ///     注册对象
        /// </summary>
        public static bool RegistZeroObject(IZeroObject obj)
        {
            if (obj.GetType().IsSubclassOf(typeof(ApiStation)))
            {
                ZeroDiscover.DiscoverApiDocument(obj.GetType());
            }
            using (OnceScope.CreateScope(ZeroObjects))
            {
                if (ZeroObjects.ContainsKey(obj.Name))
                {
                    return(false);
                }
                ZeroTrace.WriteInfo("RegistZeroObject", obj.Name);
                ZeroObjects.Add(obj.Name, obj);
                if (ApplicationState >= StationState.Initialized)
                {
                    try
                    {
                        obj.OnZeroInitialize();
                        ZeroTrace.WriteInfo(obj.Name, "Initialize");
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "Initialize");
                    }
                }

                if (!CanDo)
                {
                    return(true);
                }
                try
                {
                    ZeroTrace.WriteInfo(obj.Name, "Start");
                    obj.OnZeroStart();
                }
                catch (Exception e)
                {
                    ZeroTrace.WriteException(obj.Name, e, "Start");
                }
            }
            return(true);
        }
Пример #22
0
 /// <summary>
 ///     系统启动时调用
 /// </summary>
 internal static void OnZeroInitialize()
 {
     using (OnceScope.CreateScope(ZeroObjects))
     {
         ZeroTrace.WriteLine("[OnZeroInitialize>>");
         Parallel.ForEach(ZeroObjects.Values.ToArray(), obj =>
         {
             try
             {
                 obj.OnZeroInitialize();
                 ZeroTrace.WriteInfo(obj.Name, "Initialize");
             }
             catch (Exception e)
             {
                 ZeroTrace.WriteException(obj.Name, e, "*Initialize");
             }
         });
         ZeroTrace.WriteLine("<<OnZeroInitialize]");
     }
 }
Пример #23
0
        /// <summary>
        ///     系统启动时调用
        /// </summary>
        internal static void OnZeroStart()
        {
            Debug.Assert(!HaseActiveObject);
            using (OnceScope.CreateScope(ZeroObjects, ResetObjectActive))
            {
                ZeroTrace.WriteLine("[OnZeroStart>>");
#if DEBUG
                foreach (var obj in ZeroObjects.Values.ToArray())
                {
                    try
                    {
                        ZeroTrace.WriteInfo(obj.Name, "*Start");
                        obj.OnZeroStart();
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "*Start");
                    }
                }
#else
                Parallel.ForEach(ZeroObjects.Values.ToArray(), obj =>
                {
                    try
                    {
                        ZeroTrace.WriteInfo(obj.Name, "*Start");
                        obj.OnZeroStart();
                    }
                    catch (Exception e)
                    {
                        ZeroTrace.WriteException(obj.Name, e, "*Start");
                    }
                });
#endif
                WaitAllObjectSemaphore();
            }
            SystemManager.Instance.HeartReady();
            ApplicationState = StationState.Run;
            RaiseEvent(ZeroNetEventType.AppRun);
            ZeroTrace.WriteLine("<<OnZeroStart]");
        }
Пример #24
0
        /// <summary>
        /// 命令轮询
        /// </summary>
        /// <returns></returns>
        private void Run()
        {
            var configs = ZeroApplication.Config.GetConfigs(p => p.StationType != ZeroStationType.Dispatcher);

            ZSocket[] sockets = new ZSocket[configs.Length * 2];
            int       idx     = 0;

            foreach (var config in configs)
            {
                sockets[idx++] = ZSocket.CreateServiceSocket($"inproc://{config.StationName}_Proxy", ZSocketType.ROUTER);
                sockets[idx++] = ZSocket.CreateClientSocket(config.RequestAddress, ZSocketType.DEALER);
            }

            WaitCount = 0;
            ZeroTrace.WriteInfo("ConnectionProxy", "Listen");

            using (var pool = ZmqPool.CreateZmqPool())
            {
                pool.Prepare(sockets, ZPollEvent.In);
                _waitToken.Release();
                //SystemManager.Instance.HeartReady(StationName, RealName);
                while (!RunTaskCancel.Token.IsCancellationRequested)
                {
                    if (!pool.Poll())
                    {
                        continue;
                    }
                    Parallel.For(0, configs.Length, index =>
                    {
                        CheckCall(pool, index * 2);
                        CheckResult(pool, index * 2 + 1);
                    });
                }
            }
            _waitToken.Release();
        }
Пример #25
0
        /// <summary>
        ///     配置校验
        /// </summary>
        private static void CheckConfig()
        {
            AppName = ConfigurationManager.Root["AppName"];
            var    curPath = ConfigurationManager.Root.GetValue("contentRoot", Environment.CurrentDirectory);
            string rootPath;

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

            ConfigurationManager.Root["rootPath"] = rootPath;

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

            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中设置");
            }
            if (String.IsNullOrWhiteSpace(AppName))
            {
                ConfigurationManager.Root["AppName"] = AppName = Config.StationName;
            }

            Config.IsLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
            var global = sec.Child <ZeroAppConfig>("Global");

            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);
        }