public Boolean ExecuteExitCommand(String unitKey) { if (!this.Useable) { return(false); } if (this.UnitDictionary.Count < 1 || !this.UnitDictionary.ContainsKey(unitKey)) { return(false); } if (this.UnitDictionary[unitKey].State != 2) { return(false); } try { this.UnitDictionary[unitKey].Process.Refresh(); this.UnitDictionary[unitKey].Process.StandardInput.Write("\x3" + this.UnitDictionary[unitKey].Process.StandardInput.NewLine); this.UnitDictionary[unitKey].Process.StandardInput.Flush(); //this.UnitDictionary[unitKey].Process.StandardInput.Close(); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.UnitManageModule.ExecuteExitCommand[Error]", $"单元输入指令异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return(false); } return(true); }
/// <summary> /// 移除单元 /// </summary> /// <param name="unitKey"></param> public Boolean RemoveUnit(String unitKey) { if (!this.Useable) { return(false); } if (this.UnitDictionary.Count < 1 || !this.UnitDictionary.ContainsKey(unitKey)) { return(false); } LoggerModuleHelper.TryLog("Modules.UnitManageModule.RemoveUnit", $"正在移除\"{unitKey}\"单元"); if (!this.StopUnit(unitKey)) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.RemoveUnit", $"停止\"{unitKey}\"单元失败"); return(false); } Boolean b1 = this.UnitDictionary.TryRemove(unitKey, out _); if (b1) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.RemoveUnit", $"已移除\"{unitKey}\"单元"); } else { LoggerModuleHelper.TryLog("Modules.UnitManageModule.RemoveUnit", $"移除\"{unitKey}\"单元失败"); } return(b1); }
/// <summary> /// 链接服务端 /// </summary> /// <returns></returns> public Boolean Start() { try { this.Client.Start(); }catch (Exception exception) { LoggerModuleHelper.TryLog("Modules.WebSocketControlModule.Setup[Error]", $"链接服务器异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return(false); } SpinWait.SpinUntil(() => this.Client.Connected, 4000); return(this.Client.Connected);//true or false(timeout) }
/// <summary> /// 初始化 /// </summary> /// <param name="address"></param> /// <param name="port"></param> /// <param name="controlKey"></param> /// <returns></returns> public Boolean Setup(String address, Int32 port, String controlKey) { if (this.Useable) { return(true); } //校验参数 if (String.IsNullOrWhiteSpace(address) || port > Int16.MaxValue || port < 1024) { LoggerModuleHelper.TryLog("Modules.WebSocketControlModule.Setup[Error]", $"初始化模块失败,参数错误\naddress:{address},port:{port}"); return(false); } if (address == "localhost") { address = "127.0.0.1"; } Boolean isV4 = this.RegexAddress4.IsMatch(address); /*Boolean isV6=this.RegexAddress6.IsMatch(address);*/ if (!isV4 /* && !isV6*/) { LoggerModuleHelper.TryLog("Modules.WebSocketControlModule.Setup[Error]", $"初始化模块失败,参数错误\naddress:{address},port:{port}"); return(false); } if (String.IsNullOrWhiteSpace(controlKey) || !this.RegexControlKey.IsMatch(controlKey)) { LoggerModuleHelper.TryLog("Modules.WebSocketControlModule.Setup[Error]", $"初始化模块失败,参数错误\ncontrolKey:{controlKey}"); return(false); } this.ControlKey = controlKey; //初始化定时器 try { this.Timer = new Timer(this.TimerCallback, null, 0, 8000); }catch (Exception exception) { LoggerModuleHelper.TryLog("Modules.WebSocketControlModule.Setup[Error]", $"初始化定时器异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return(false); } this.TimerEnable = true; //初始化客户端 try { this.Client = new WatsonWsClient(address, port, false); }catch (Exception exception) { LoggerModuleHelper.TryLog("Modules.WebSocketControlModule.Setup[Error]", $"初始化客户端异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return(false); } //this.Client.ServerConnected+=this.ServerConnected; this.Client.ServerDisconnected += this.ServerDisconnected; this.Client.MessageReceived += this.ClientMessageReceived; //完成 this.Useable = true; return(true); }
/// <summary> /// 客户端向服务端请求验证ControlKey /// </summary> private void ClientOfferControlKey() { if (!this.Client.Connected) { return; } LoggerModuleHelper.TryLog("Modules.WebSocketControlModule.ClientOfferControlKey", "向服务端请求验证"); ClientOfferControlKeyProtobuf clientOfferControlKeyProtobuf = new ClientOfferControlKeyProtobuf { Type = 12, ConnectionId = this.ClientConnectionId, ControlKey = this.ControlKey, SupportNotify = true }; _ = this.Client.SendAsync(clientOfferControlKeyProtobuf.ToByteArray()); }
/// <summary> /// 加载单元 /// </summary> /// <param name="unitKey"></param> /// <returns></returns> public UnitSettings LoadUnit(String unitKey) { if (!this.Useable) { return(null); } /*特殊处理*/ if (unitKey == "self" || unitKey == "wind" || unitKey == "daemon") { return(null); } /*特殊处理*/ LoggerModuleHelper.TryLog("Modules.UnitManageModule.LoadUnit", "开始加载单元配置文件"); //读取文件 String unitFilePath = String.Concat(this.UnitsDirectory, Path.DirectorySeparatorChar, unitKey, ".json"); if (!File.Exists(unitFilePath)) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.LoadUnit[Error]", $"单元配置文件 {unitFilePath} 不存在"); return(null); } FileInfo fileInfo; try { fileInfo = new FileInfo(unitFilePath); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.UnitManageModule.LoadUnit[Error]", $"单元配置文件 {unitFilePath} 文件信息异常,: {exception.Message}\n异常堆栈: {exception.StackTrace}"); return(null); } //setting UnitSettings unitSettings = UnitManageModuleHelper.ParseUnitSettingsFile(fileInfo); if (unitSettings == null) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.LoadUnit[Warning]", $"单元文件\"{unitFilePath}\"读取失败"); return(null); } //检查是新增或更新 if (this.UnitDictionary.ContainsKey(unitKey)) { this.UnitDictionary[unitKey].Settings = unitSettings; } else { _ = this.UnitDictionary.TryAdd(unitKey, new Unit { Key = unitKey, Settings = unitSettings }); } LoggerModuleHelper.TryLog("Modules.UnitManageModule.LoadUnit", $"单元\"{unitKey}\"读取成功,已加入单元列表"); return(unitSettings); }
/// <summary> /// LogsNotify /// </summary> /// <param name="bytes"></param> private void LogsNotify(Byte[] bytes) { //解析数据 LogsNotifyProtobuf logsNotifyProtobuf; try { logsNotifyProtobuf = LogsNotifyProtobuf.Parser.ParseFrom(bytes); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.WebSocketControlModule.LogsNotify[Error]", $"解析数据包时异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return; } //调用 NotifyHelper.Logs(logsNotifyProtobuf); }
/// <summary> /// windctl remove-all /// </summary> /// <param name="bytes"></param> private void RemoveAllResponse(Byte[] bytes) { //解析数据 RemoveAllResponseProtobuf removeAllResponseProtobuf; try { removeAllResponseProtobuf = RemoveAllResponseProtobuf.Parser.ParseFrom(bytes); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.WebSocketControlModule.RemoveAllResponse[Error]", $"解析数据包时异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return; } //调用 CommandHelper.RemoveAll(removeAllResponseProtobuf); Program.InAction = false; }
/// <summary> /// windctl daemon-shutdown /// </summary> /// <param name="bytes"></param> private void DaemonShutdownResponse(Byte[] bytes) { //解析数据 DaemonShutdownResponseProtobuf daemonShutdownResponseProtobuf; try { daemonShutdownResponseProtobuf = DaemonShutdownResponseProtobuf.Parser.ParseFrom(bytes); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.WebSocketControlModule.DaemonShutdown[Error]", $"解析数据包时异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return; } //调用 CommandHelper.DaemonShutdown(daemonShutdownResponseProtobuf); Program.InAction = false; }
public void Add(Int32 processId) { if (!this.Useable) { return; } if (this.CpuPerformanceCounterDictionary.ContainsKey(processId) || this.RamPerformanceCounterDictionary.ContainsKey(processId)) { this.Remove(processId); } String instanceName = UnitPerformanceCounterModuleHelper.GetActuallyInstanceNameByProcessId(processId); if (String.IsNullOrWhiteSpace(instanceName)) { return; } try { PerformanceCounter performanceCounter = new PerformanceCounter { CategoryName = "Process", CounterName = "% Processor Time", InstanceName = instanceName, ReadOnly = true }; _ = performanceCounter.NextValue();//预热 if (!this.CpuPerformanceCounterDictionary.TryAdd(processId, performanceCounter)) { Helpers.LoggerModuleHelper.TryLog("Modules.UnitPerformanceCounterModule.Add[Error]", $"创建CPU性能计数器成功但加入列表失败"); } }catch (Exception exception) { Helpers.LoggerModuleHelper.TryLog( "Modules.UnitPerformanceCounterModule.Add[Error]", $"创建CPU性能计数器异常,{exception.Message}\n异常堆栈: {exception.StackTrace}"); } try { PerformanceCounter performanceCounter = new PerformanceCounter { CategoryName = "Process", CounterName = "Working Set", InstanceName = instanceName, ReadOnly = true }; _ = performanceCounter.NextValue();//预热 if (!this.RamPerformanceCounterDictionary.TryAdd(processId, performanceCounter)) { Helpers.LoggerModuleHelper.TryLog("Modules.UnitPerformanceCounterModule.Add[Error]", $"创建RAM性能计数器成功但加入列表失败"); } }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.UnitPerformanceCounterModule.Add[Error]", $"创建RAM性能计数器异常,{exception.Message}\n异常堆栈: {exception.StackTrace}"); } }
/// <summary> /// 服务端回复客户端ControlKey验证结果 /// </summary> /// <param name="bytes"></param> private void ServerValidateConnection(Byte[] bytes) { //解析数据 ServerValidateConnectionProtobuf serverValidateConnectionProtobuf; try { serverValidateConnectionProtobuf = ServerValidateConnectionProtobuf.Parser.ParseFrom(bytes); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.WebSocketControlModule.ServerValidateConnection[Error]", $"解析数据包时异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return; } //验证结果 LoggerModuleHelper.TryLog( "Modules.WebSocketControlModule.ServerValidateConnection", $"已收到客户端验证结果 {serverValidateConnectionProtobuf.Valid}"); this.ClientConnectionValid = serverValidateConnectionProtobuf.Valid;//用于解除自旋锁 }
/// <summary> /// 服务端响应客户端链接事件,并回复给客户端 /// </summary> /// <param name="bytes"></param> private void ServerAcceptConnection(Byte[] bytes) { //解析数据 ServerAcceptConnectionProtobuf serverAcceptConnectionProtobuf; try { serverAcceptConnectionProtobuf = ServerAcceptConnectionProtobuf.Parser.ParseFrom(bytes); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.WebSocketControlModule.ServerAcceptConnection[Error]", $"解析数据包时异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return; } //设置客户端链接Id LoggerModuleHelper.TryLog( "Modules.WebSocketControlModule.ServerAcceptConnection", $"已收到客户端链接Id {serverAcceptConnectionProtobuf.ConnectionId}"); this.ClientConnectionId = serverAcceptConnectionProtobuf.ConnectionId; //请求验证客户端 this.ClientOfferControlKey(); }
public Single GetRamValue(Int32 processId) { if (!this.Useable) { return(0F); } if (this.RamPerformanceCounterDictionary.Count < 1 || !this.RamPerformanceCounterDictionary.ContainsKey(processId)) { return(0F); } Single value; try{ value = this.RamPerformanceCounterDictionary[processId].NextValue(); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.UnitPerformanceCounterModule.GetRamValue[Error]", $"读取RAM性能计数器异常,{exception.Message}\n异常堆栈: {exception.StackTrace}"); value = this.GetRamValueEx(processId); } return(value); }
public Boolean ExecuteCommand(String unitKey, String commandLine) { if (!this.Useable) { return(false); } if (this.UnitDictionary.Count < 1 || !this.UnitDictionary.ContainsKey(unitKey)) { return(false); } if (this.UnitDictionary[unitKey].State != 2) { return(false); } if (String.IsNullOrWhiteSpace(commandLine)) { return(false); } try { this.UnitDictionary[unitKey].Process.Refresh(); this.UnitDictionary[unitKey].Process.StandardInput.WriteLine(commandLine); /*this.UnitDictionary[unitKey].Process.StandardInput.Write(commandLine+this.UnitDictionary[unitKey].Process.StandardInput.NewLine); * this.UnitDictionary[unitKey].Process.StandardInput.Flush();*/ //记录日志 Program.UnitLoggerModule.Log(unitKey, "> " + commandLine); //记录输出 Program.UnitLoggerModule.LogOutput(unitKey, "> " + commandLine); //记录通知 Program.RemoteControlModule.LogsNotify(unitKey, "> " + commandLine); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.UnitManageModule.ExecuteCommand[Error]", $"单元输入指令异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return(false); } return(true); }
/// <summary> /// 初始化 /// </summary> /// <returns></returns> private static Boolean Initialize() { //互斥 AppMutex = new Mutex(true, "WindCommandLineController", out Boolean mutex); if (!mutex) { LoggerModuleHelper.TryLog("Program.Initialize[Error]", "已存在实例"); return(false); } //读取配置 if (!Directory.Exists(AppEnvironment.BaseDirectory)) { return(false); } String appSettingsFilePath = String.Concat(AppEnvironment.DataDirectory, Path.DirectorySeparatorChar, "AppSettings.json"); if (!File.Exists(appSettingsFilePath)) { return(false); } Entities.Common.AppSettings appSettings; FileStream fs = null; try { fs = File.Open(appSettingsFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); if (fs.Length < 1 || fs.Length > 4096) { return(false); } Span <Byte> bufferSpan = new Span <Byte>(new Byte[fs.Length]); fs.Read(bufferSpan); fs.Dispose(); appSettings = JsonSerializer.Deserialize <Entities.Common.AppSettings>(bufferSpan); }catch (Exception exception) { LoggerModuleHelper.TryLog("Program.Initialize[Error]", $"读取应用程序配置文件异常,{exception.Message}\n异常堆栈: {exception.StackTrace}"); return(false); }finally{ fs?.Dispose(); } if (appSettings == null || String.IsNullOrWhiteSpace(appSettings.RemoteControlAddress) || String.IsNullOrWhiteSpace(appSettings.RemoteControlKey) || appSettings.RemoteControlPort < 1024 || appSettings.RemoteControlPort > Int16.MaxValue) { return(false); } Regex regex = new Regex(@"^[0-9\.]{7,15}$", RegexOptions.Compiled); if (appSettings.RemoteControlAddress != "localhost" && !regex.IsMatch(appSettings.RemoteControlAddress)) { return(false); } Regex regex2 = new Regex(@"^\S{32,4096}$", RegexOptions.Compiled); if (!regex2.IsMatch(appSettings.RemoteControlKey)) { return(false); } AppSettings.RemoteControlAddress = appSettings.RemoteControlAddress; AppSettings.RemoteControlPort = appSettings.RemoteControlPort; AppSettings.RemoteControlKey = appSettings.RemoteControlKey; //初始化日志模块 if (!LoggerModule.Setup(AppEnvironment.LogsDirectory, 1000)) { LoggerModuleHelper.TryLog("Program.Initialize[Error]", "初始化日志模块失败"); return(false); } //初始化控制模块 if (!RemoteControlModule.Setup(AppSettings.RemoteControlAddress, AppSettings.RemoteControlPort, AppSettings.RemoteControlKey)) { LoggerModuleHelper.TryLog("Program.Initialize[Error]", "初始化远程控制模块失败"); return(false); } // Console.CancelKeyPress += ConsoleCancelKeyPress; return(true); }
/// <summary> /// 启动单元 /// </summary> /// <param name="unitKey"></param> /// <param name="forAutoStart"></param> public Int32 StartUnit(String unitKey, Boolean forAutoStart) { if (!this.Useable) { return(0); } if (this.UnitDictionary.Count < 1 || !this.UnitDictionary.ContainsKey(unitKey)) { return(0); } LoggerModuleHelper.TryLog("Modules.UnitManageModule.StartUnit", $"正在启动\"{unitKey}\"单元"); Unit unit = this.UnitDictionary[unitKey]; if (unit.State == 1 || unit.State == 2) { return(unit.ProcessId); } if (unit.State == 3) { SpinWait.SpinUntil(() => false, 1000); } unit.State = 1; unit.RunningSettings = unit.Settings.DeepClone(); ProcessStartInfo processStartInfo = new ProcessStartInfo { FileName = unit.RunningSettings.AbsoluteExecutePath, WorkingDirectory = unit.RunningSettings.AbsoluteWorkDirectory, Arguments = unit.RunningSettings.Arguments, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true, StandardOutputEncoding = UnitManageModuleHelper.GetEncoding(unit.RunningSettings.StandardOutputEncoding), StandardErrorEncoding = UnitManageModuleHelper.GetEncoding(unit.RunningSettings.StandardErrorEncoding), StandardInputEncoding = UnitManageModuleHelper.GetEncoding(unit.RunningSettings.StandardInputEncoding) }; if (unit.RunningSettings.EnvironmentVariables != null) { foreach (KeyValuePair <String, String> item in unit.RunningSettings.EnvironmentVariables) { processStartInfo.EnvironmentVariables[item.Key] = item.Value; } } unit.Process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; unit.Process.Exited += this.OnUnitProcessExited; unit.Process.OutputDataReceived += this.OnProcessOutputDataReceived; unit.Process.ErrorDataReceived += this.OnProcessErrorDataReceived; if (forAutoStart && unit.RunningSettings.AutoStartDelay > 0) { SpinWait.SpinUntil(() => false, unit.RunningSettings.AutoStartDelay * 1000); } try { if (!unit.Process.Start()) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.StartUnit", $"启动\"{unitKey}\"单元失败"); unit.State = 0; if (Program.RemoteControlModule.Useable) { Program.RemoteControlModule.StopNotify(unitKey); } return(0); } }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.UnitManageModule.StartUnit[Error]", $"启动\"{unitKey}\"单元异常,{exception.Message}\n异常堆栈: {exception.StackTrace}"); unit.State = 0; if (Program.RemoteControlModule.Useable) { Program.RemoteControlModule.StopNotify(unitKey); } return(0); } if (!String.IsNullOrWhiteSpace(unit.RunningSettings.PriorityClass)) { try{ unit.Process.PriorityClass = UnitManageModuleHelper.GetProcessPriorityClassFromString(unit.RunningSettings.PriorityClass); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.UnitManageModule.StartUnit[Error]", $"设置\"{unitKey}\"单元优先级异常,{exception.Message}\n异常堆栈: {exception.StackTrace}"); } } if (!String.IsNullOrWhiteSpace(unit.RunningSettings.ProcessorAffinity)) { Nullable <IntPtr> ptr = UnitManageModuleHelper.GetProcessorAffinityFormString(unit.RunningSettings.ProcessorAffinity); if (ptr.HasValue) { try{ unit.Process.ProcessorAffinity = ptr.Value; }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.UnitManageModule.StartUnit[Error]", $"设置\"{unitKey}\"单元亲和性异常,{exception.Message}\n异常堆栈: {exception.StackTrace}"); } } } unit.Process.BeginOutputReadLine(); unit.Process.BeginErrorReadLine(); //unit.Process.StandardInput.AutoFlush=true; unit.ProcessId = unit.Process.Id; unit.State = 2; if (unit.RunningSettings.MonitorPerformanceUsage && Program.UnitPerformanceCounterModule.Useable) { Program.UnitPerformanceCounterModule.Add(unit.ProcessId); } if (unit.RunningSettings.MonitorNetworkUsage && Program.UnitNetworkCounterModule.Useable) { _ = Program.UnitNetworkCounterModule.Add(unit.ProcessId); } if (Program.RemoteControlModule.Useable) { Program.RemoteControlModule.StartNotify(unit.Key); } LoggerModuleHelper.TryLog("Modules.UnitManageModule.StartUnit", $"已启动\"{unitKey}\"单元"); return(unit.ProcessId); }
/// <summary> /// 解析所有单元配置文件 /// </summary> /// <returns>解析成功单元列表</returns> public List <UnitSettings> LoadAllUnits() { if (!this.Useable) { return(null); } //读取文件目录 LoggerModuleHelper.TryLog("Modules.UnitManageModule.LoadAllUnits", "开始解析所有单元配置文件"); FileInfo[] fileInfoArray; try { DirectoryInfo directoryInfo = new DirectoryInfo(this.UnitsDirectory); fileInfoArray = directoryInfo.GetFiles("*.json", SearchOption.TopDirectoryOnly); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.UnitManageModule.LoadAllUnits[Error]", $"读取单元存放目录异常,{exception.Message}\n异常堆栈: {exception.StackTrace}"); return(null); } if (fileInfoArray.Length < 1) { return(null); } //解析文件 List <UnitSettings> unitSettingsList = new List <UnitSettings>(); for (Int32 i1 = 0; i1 < fileInfoArray.Length; i1++) { //key String unitKey = UnitManageModuleHelper.GetUnitKey(fileInfoArray[i1]); /*特殊处理*/ if (unitKey == "self" || unitKey == "wind" || unitKey == "daemon") { continue; } /*特殊处理*/ if (String.IsNullOrWhiteSpace(unitKey) || unitKey.Length > 32) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.LoadAllUnits[Warning]", $"单元文件\"{fileInfoArray[i1].FullName}\"标识错误,已跳过"); continue; } //setting UnitSettings unitSettings = UnitManageModuleHelper.ParseUnitSettingsFile(fileInfoArray[i1]); if (unitSettings == null) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.LoadAllUnits[Warning]", $"单元文件\"{fileInfoArray[i1].FullName}\"读取失败,已跳过"); continue; } //检查是新增或更新 if (this.UnitDictionary.ContainsKey(unitKey)) { this.UnitDictionary[unitKey].Settings = unitSettings; } else { _ = this.UnitDictionary.TryAdd(unitKey, new Unit { Key = unitKey, Settings = unitSettings }); } unitSettingsList.Add(unitSettings); LoggerModuleHelper.TryLog("Modules.UnitManageModule.LoadAllUnits", $"单元\"{unitKey}\"读取成功,已加入单元列表"); } //完成 LoggerModuleHelper.TryLog("Modules.UnitManageModule.LoadAllUnits", $"已解析 {this.UnitDictionary.Count} 个单元配置文件"); return(this.UnitDictionary.Count > 0?unitSettingsList:null); }
/// <summary> /// 收到服务端数据 /// </summary> /// <param name="sender"></param> /// <param name="messageReceivedEventArgs"></param> private void ClientMessageReceived(object sender, MessageReceivedEventArgs messageReceivedEventArgs) { //解析数据 if (messageReceivedEventArgs.Data.GetLength(0) < 1) { return; } PacketTestProtobuf packetTestProtobuf; try { packetTestProtobuf = PacketTestProtobuf.Parser.ParseFrom(messageReceivedEventArgs.Data); }catch (Exception exception) { LoggerModuleHelper.TryLog( "Modules.WebSocketControlModule.ClientMessageReceived[Error]", $"探测数据包时异常,{exception.Message}\n异常堆栈:{exception.StackTrace}"); return; } //分拣处理 LoggerModuleHelper.TryLog( "Modules.WebSocketControlModule.ClientMessageReceived", $"分拣处理 {packetTestProtobuf.Type} in {messageReceivedEventArgs.Data.GetLength(0)} bytes"); switch (packetTestProtobuf.Type) { case 21: this.ServerAcceptConnection(messageReceivedEventArgs.Data); break; case 22: this.ServerValidateConnection(messageReceivedEventArgs.Data); break; // case 2001: this.StatusResponse(messageReceivedEventArgs.Data); break; case 2002: this.StartResponse(messageReceivedEventArgs.Data); break; case 2003: this.StopResponse(messageReceivedEventArgs.Data); break; case 2004: this.RestartResponse(messageReceivedEventArgs.Data); break; case 2005: this.LoadResponse(messageReceivedEventArgs.Data); break; case 2006: this.RemoveResponse(messageReceivedEventArgs.Data); break; case 2007: this.LogsResponse(messageReceivedEventArgs.Data); break; case 2008: this.CommandlineResponse(messageReceivedEventArgs.Data); break; // case 2101: this.StatusAllResponse(messageReceivedEventArgs.Data); break; case 2102: this.StartAllResponse(messageReceivedEventArgs.Data); break; case 2103: this.StopAllResponse(messageReceivedEventArgs.Data); break; case 2104: this.RestartAllResponse(messageReceivedEventArgs.Data); break; case 2105: this.LoadAllResponse(messageReceivedEventArgs.Data); break; case 2106: this.RemoveAllResponse(messageReceivedEventArgs.Data); break; // case 2200: this.DaemonVersionResponse(messageReceivedEventArgs.Data); break; case 2201: this.DaemonStatusResponse(messageReceivedEventArgs.Data); break; case 2299: this.DaemonShutdownResponse(messageReceivedEventArgs.Data); break; // case 3002: this.StartNotify(messageReceivedEventArgs.Data); break; case 3003: this.StopNotify(messageReceivedEventArgs.Data); break; case 3007: this.LogsNotify(messageReceivedEventArgs.Data); break; default: break; } }
/// <summary> /// 单元退出 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnUnitProcessExited(object sender, EventArgs eventArgs) { Process exitedProcess = sender as Process; Int32 exitedProcessExitCode = exitedProcess.ExitCode; Int32 exitedProcessId = exitedProcess.Id; exitedProcess.CancelOutputRead(); exitedProcess.CancelErrorRead(); exitedProcess.OutputDataReceived -= this.OnProcessOutputDataReceived; exitedProcess.ErrorDataReceived -= this.OnProcessErrorDataReceived; exitedProcess.Exited -= this.OnUnitProcessExited; exitedProcess.Dispose(); LoggerModuleHelper.TryLog( "Modules.UnitManageModule.OnUnitProcessExited", $"进程[#{exitedProcessId}]退出,退出代码[{exitedProcessExitCode}]"); Unit unit = null; foreach (KeyValuePair <String, Unit> item in this.UnitDictionary) { if (item.Value.ProcessId != exitedProcessId) { continue; } unit = item.Value; break; } if (unit == null) { return; } //if(unit.Process!=null){ unit.Process.Dispose(); } if (Program.UnitPerformanceCounterModule.Useable) { if (!Program.UnitPerformanceCounterModule.Remove(exitedProcessId)) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.OnUnitProcessExited[Warning]", $"进程[#{exitedProcessId}]单元退出时,没有正确移除性能计数器"); } } if (Program.UnitNetworkCounterModule.Useable) { if (!Program.UnitNetworkCounterModule.Remove(exitedProcessId)) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.OnUnitProcessExited[Warning]", $"进程[#{exitedProcessId}]单元退出时,没有正确移除网络计数器"); } } //如果是单元停止,此时state==3,否则可能是1||2 if (unit.State == 3) { return; } unit.State = 0; if (Program.RemoteControlModule.Useable) { Program.RemoteControlModule.StopNotify(unit.Key); } Program.LoggerModule.Log("Modules.UnitManageModule.OnUnitProcessExited", $"单元\"{unit.Key}\"异常退出"); if (!unit.RunningSettings.RestartWhenException) { return; } this.StartUnit(unit.Key, false); Program.LoggerModule.Log("Modules.UnitManageModule.OnUnitProcessExited", $"单元\"{unit.Key}\"已重新启动"); }
/// <summary> /// 停止单元 /// </summary> /// <param name="unitKey"></param> public Boolean StopUnit(String unitKey) { if (!this.Useable) { return(false); } if (this.UnitDictionary.Count < 1 || !this.UnitDictionary.ContainsKey(unitKey)) { return(false); } Unit unit = this.UnitDictionary[unitKey]; if (unit.State == 0 || unit.State == 3) { return(true); } LoggerModuleHelper.TryLog("Modules.UnitManageModule.StopUnit", $"正在停止\"{unitKey}\"单元,Type={unit.RunningSettings.Type}"); unit.State = 3; if (unit.Process != null) { //正常停止单元避免触发退出事件 try { unit.Process.CancelOutputRead(); unit.Process.CancelErrorRead(); unit.Process.OutputDataReceived -= this.OnProcessOutputDataReceived; unit.Process.ErrorDataReceived -= this.OnProcessErrorDataReceived; unit.Process.Exited -= this.OnUnitProcessExited; } catch { //忽略异常 } //强制杀死单元 try { switch (unit.RunningSettings.Type) { case 1: unit.Process.Kill(true); ProcessHelper.KillChildProcessByParentProcess(unit.ProcessId); break; default: unit.Process.Kill(true); break; } } catch (Exception exception) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.StopUnit[Error]", $"停止\"{unitKey}\"单元异常,{exception.Message}\n异常堆栈: {exception.StackTrace}"); } finally { unit.Process.Dispose(); unit.Process = null; } } unit.RunningSettings = null; if (Program.UnitPerformanceCounterModule.Useable) { if (!Program.UnitPerformanceCounterModule.Remove(unit.ProcessId)) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.StopUnit[Error]", $"停止\"{unitKey}\"单元时没有正确移除性能计数器"); } } if (Program.UnitNetworkCounterModule.Useable) { if (!Program.UnitNetworkCounterModule.Remove(unit.ProcessId)) { LoggerModuleHelper.TryLog("Modules.UnitManageModule.StopUnit[Error]", $"停止\"{unitKey}\"单元时没有正确移除网络计数器"); } } if (Program.RemoteControlModule.Useable) { Program.RemoteControlModule.StopNotify(unit.Key); } unit.ProcessId = 0; unit.State = 0; LoggerModuleHelper.TryLog("Modules.UnitManageModule.StopUnit", $"已停止\"{unitKey}\"单元"); return(true); }