private void Io_OnClientMessage(MasterControlClient session, RouterMessage msg) { if (session.authenticated) { //Authenticated commands if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_CONFIG) { HandleRequestConfigCommand(session, msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_GETUSERCFG) { HandleGetUserConfigCmd(session, msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_INSTANCE_LOG) { HandleInstanceLogCommand(session, msg); } else { logger.Log("Io_OnClientMessage", $"Client {session.GetDebugName()} sent an unknown command.", DeltaLogLevel.Debug); } } else { //Unauthenticated commands if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_LOGIN) { HandleLoginCommand(session, msg); } else { logger.Log("Io_OnClientMessage", $"Client {session.GetDebugName()} sent unauthenticated command that was not LOGIN.", DeltaLogLevel.Debug); } } }
private void reipcHandler(RouterMessage obj) { lock (tslistlock) { tslist.Add(string.Format(" Task ID: {0} Progess: {1}", obj.TaskID, obj.Progress)); } }
private void OnCmdRemoveInstance(RouterMessage msg) { //Decode arguments and create logger ManagerUpdateInstance args = msg.DeserializeAs <ManagerUpdateInstance>(); MasterCommandLogger logger = new MasterCommandLogger(msg); //Find instance ManagerInstance instance = session.GetInstanceById(long.Parse(args.instance_id)); if (instance == null) { logger.FinishFail("Could not find that instance on the server."); return; } //Run try { instance.DestoryInstance(session, logger); } catch (Exception ex) { logger.FinishFail($"Unexpected error: {ex.Message}{ex.StackTrace}"); } }
public static void Run( [QueueTrigger("routermessage")] RouterMessage routerMessage, [Table("installation", "{InstallationId}", "{RepoName}")] Installation installation, [Table("installation")] ICollector <Installation> installations, [Queue("compressimagesmessage")] ICollector <CompressImagesMessage> compressImagesMessages, TraceWriter log) { if (installation == null) { installations.Add(new Installation(routerMessage.InstallationId, routerMessage.RepoName) { AccessTokensUrl = routerMessage.AccessTokensUrl, CloneUrl = routerMessage.CloneUrl, Owner = routerMessage.Owner, }); } /* * TODO: add logic for routing * https://github.com/dabutvin/ImgBot/issues/98 */ log.Info($"Routing {routerMessage.CloneUrl} to {nameof(compressImagesMessages)}."); compressImagesMessages.Add(new CompressImagesMessage { AccessTokensUrl = routerMessage.AccessTokensUrl, CloneUrl = routerMessage.CloneUrl, InstallationId = routerMessage.InstallationId, Owner = routerMessage.Owner, RepoName = routerMessage.RepoName, }); }
private void OnCmdAssignSite(RouterMessage msg) { //Decode arguments and create logger ManagerAssignSite args = msg.DeserializeAs <ManagerAssignSite>(); MasterCommandLogger logger = new MasterCommandLogger(msg); //Update if it was supposed to be null if (args.site_id == "") { args.site_id = null; } //Find instance ManagerInstance instance = session.GetInstanceById(long.Parse(args.instance_id)); if (instance == null) { logger.FinishFail("Could not find that instance on the server."); return; } //Run try { //Update instance.site_id = args.site_id; session.Save(); session.RefreshSites(); } catch (Exception ex) { logger.FinishFail($"Unexpected error: {ex.Message}{ex.StackTrace}"); } }
private void OnCmdRebootInstance(RouterMessage msg) { //Decode arguments and create logger ManagerRebootInstance args = msg.DeserializeAs <ManagerRebootInstance>(); MasterCommandLogger logger = new MasterCommandLogger(msg); //Find instance ManagerInstance instance = session.GetInstanceById(long.Parse(args.instance_id)); if (instance == null) { logger.FinishFail("Could not find that instance on the server."); return; } //Run try { //Shut down instance logger.Log("REBOOT", "Shutting down instance..."); bool graceful = instance.StopInstance(); if (!graceful) { logger.Log("REBOOT", "Instance was shut down forcefully!"); } //Start instance.StartInstance(session); } catch (Exception ex) { logger.FinishFail($"Unexpected error: {ex.Message}{ex.StackTrace}"); } }
public static void Run( [QueueTrigger("routermessage")] RouterMessage routerMessage, [Table("installation", "{InstallationId}", "{RepoName}")] Installation installation, [Table("installation")] ICollector <Installation> installations, [Queue("compressimagesmessage")] ICollector <CompressImagesMessage> compressImagesMessages, ILogger logger) { if (installation == null) { installations.Add(new Installation(routerMessage.InstallationId, routerMessage.RepoName) { CloneUrl = routerMessage.CloneUrl, Owner = routerMessage.Owner, }); } /* * TODO: add logic for routing * https://github.com/dabutvin/ImgBot/issues/98 */ compressImagesMessages.Add(new CompressImagesMessage { CloneUrl = routerMessage.CloneUrl, InstallationId = routerMessage.InstallationId, Owner = routerMessage.Owner, RepoName = routerMessage.RepoName, }); logger.LogInformation("RouterFunction: Added CompressImagesMessage for {Owner}/{RepoName}", routerMessage.Owner, routerMessage.RepoName); }
internal static async void SendIPCUpdate(RouterMessage ipc) { if (connection.State == HubConnectionState.Disconnected) { return; } await connection.SendAsync("SendRouterEngineStatusToClients", UrlStrings.ReIPCGroupName, ipc, source.Token); }
private void HandleRequestLogCommand(RouterSession session, RouterMessage msg) { //Add the instance ID to the beginning of the payload, then send to the master byte[] data = new byte[msg.payload.Length + 8]; //Set instance ID and copy BitConverter.GetBytes(session.linkedInstance.id).CopyTo(data, 0); msg.payload.CopyTo(data, 8); //Send to master this.session.masterConnection.SendMessage(MasterConnectionOpcodes.OPCODE_MASTER_INSTANCE_LOG, data); }
private void HandleRequestConfigCommand(RouterSession session, RouterMessage msg) { //Create LoginServerInfo to return LoginServerInfo response = new LoginServerInfo { success = true, instance_id = session.linkedInstance.id.ToString(), user_ports = session.linkedInstance.ports, config = this.session.remoteConfig }; //Respond msg.RespondJson(response, true); }
private void HandleRequestConfigCommand(MasterControlClient session, RouterMessage msg) { msg.RespondJson(new LoginServerConfig { enviornment = Program.cfg.general.enviornment, mongodb_connection = Program.cfg.general.mongodb_connection, steam_api_key = Program.cfg.general.steam_api_token, steam_cache_expire_minutes = Program.cfg.general.steam_cache_expire_minutes, firebase_uc_bucket = Program.cfg.general.firebase_uc_bucket, log = Program.cfg.general.log, steam_token_key = Program.cfg.secrets.steam_token_key, hosts = Program.cfg.hosts }, true); }
private void OnCmdAddPackage(RouterMessage msg) { //Decode arguments and create logger ManagerAddPackage args = msg.DeserializeAs <ManagerAddPackage>(); MasterCommandLogger logger = new MasterCommandLogger(msg); //Run try { session.AddPackage(args, logger); } catch (Exception ex) { logger.FinishFail($"Unexpected error: {ex.Message}{ex.StackTrace}"); } }
private void HandleRequestRPCCommand(RouterSession session, RouterMessage msg) { //We're going to attempt to dispatch this to all connected RPC servers locally. //In the future, we'll likely send this to the master and let it dispatch it to all machines and regions, but not yet //This will make only RPC sessions connected to this machine work, even if they're in a different process //Find all connected RPC clients var clients = this.session.GetConnectedInstancesByType(DeltaCoreNetServerType.API_RPC); //Dispatch foreach (var c in clients) { c.linkedSession.SendMessage(RouterConnection.OPCODE_SYS_RPC, msg.payload); } }
private void OnCmdGetStatus(RouterMessage msg) { //Produce and respond with thatus msg.RespondJson(new ManagerStatusMessage { host_name = System.Environment.MachineName, host_os = System.Environment.OSVersion.Platform.ToString().ToUpper(), current_time = DateTime.UtcNow, start_time = Program.startTime, version_app_major = Program.APP_VERSION_MAJOR, version_app_minor = Program.APP_VERSION_MINOR, version_lib_major = DeltaConnection.LIB_VERSION_MAJOR, version_lib_minor = DeltaConnection.LIB_VERSION_MINOR }, true); }
public static void Run( [QueueTrigger("routermessage")] RouterMessage routerMessage, [Table("installation", "{InstallationId}", "{RepoName}")] Installation installation, [Table("installation")] ICollector <Installation> installations, [Queue("compressimagesmessage")] ICollector <CompressImagesMessage> compressImagesMessages, ILogger logger) { var compress = routerMessage.GetType().GetProperty("Compress") == null || routerMessage.Compress == true; if (installation == null) { installations.Add(new Installation(routerMessage.InstallationId, routerMessage.RepoName) { CloneUrl = routerMessage.CloneUrl, Owner = routerMessage.Owner, LastChecked = DateTime.UtcNow, IsOptimized = compress, IsPrivate = routerMessage.IsPrivate, }); } else { installation.LastChecked = DateTime.UtcNow; } if (routerMessage.GetType().GetProperty("Update") != null && routerMessage.Update == true) { installation.IsOptimized = compress; } /* * TODO: add logic for routing * https://github.com/dabutvin/ImgBot/issues/98 */ if (compress) { compressImagesMessages.Add(new CompressImagesMessage { CloneUrl = routerMessage.CloneUrl, InstallationId = routerMessage.InstallationId, Owner = routerMessage.Owner, RepoName = routerMessage.RepoName, }); logger.LogInformation("RouterFunction: Added CompressImagesMessage for {Owner}/{RepoName}", routerMessage.Owner, routerMessage.RepoName); } }
private static void OnIncomingRPCCommand(RouterMessage msg) { //Decode header byte cmdOpcode = msg.payload[0]; byte cmdFlags = msg.payload[1]; //Switch on message opcode switch (cmdOpcode) { case RPCMessageTool.TYPECODE_MESSAGE: OnIncomingRPCCommand_RPCMessage(msg.payload); break; case RPCMessageTool.TYPECODE_GROUP_RESET: OnIncomingRPCCommand_RefreshGroups(msg.payload); break; case RPCMessageTool.TYPECODE_PRIVILEGED_MESSAGE_SERVER: OnIncomingRPCCommand_PrivledgedMessage(msg.payload); break; default: throw new Exception("Unknwon command opcode " + cmdOpcode + "!"); } }
private void HandleLoginCommand(MasterControlClient session, RouterMessage msg) { //Get details int loginId = BitConverter.ToInt16(msg.payload, 0); byte[] loginKey = new byte[16]; Array.Copy(msg.payload, 2, loginKey, 0, 16); //Search for a server DeltaManagerServer server = null; lock (Program.servers) { foreach (var s in Program.servers) { if (s.id == loginId) { //Authenticate key if (BinaryTool.CompareBytes(s.key, loginKey)) { server = s; } } } } //Check if it was successful if (server != null) { //Set server.SetTransport(session); session.authenticated = true; //Log logger.Log("HandleLoginCommand", $"Client {session.GetDebugName()} successfully logged in as server ID {server.id}.", DeltaLogLevel.Low); } else { //Failed logger.Log("HandleLoginCommand", $"Client {session.GetDebugName()} attempted login, but failed.", DeltaLogLevel.Low); } }
private async Task OnCmdGetInstanceStatus(RouterMessage msg) { //Create buffer for output. It consists of this format, each a byte unless otherwise stated: [status, reserved, appVersionMajor, appVersionMinor, libVersionMajor, libVersionMinor, (ushort)time] byte[] buffer = new byte[8]; buffer[0] = (byte)InstanceStatusResult.NOT_CONNECTED; //Find instance ManagerInstance instance = session.GetInstanceById(BitConverter.ToInt64(msg.payload, 0)); if (instance != null && instance.linkedSession != null) { try { //Send ping DateTime start = DateTime.UtcNow; var pingResult = await instance.linkedSession.SendPing(4000); if (pingResult != null) { //Success buffer[0] = (byte)InstanceStatusResult.ONLINE; buffer[2] = pingResult.Value.lib_version_major; buffer[3] = pingResult.Value.lib_version_minor; buffer[4] = pingResult.Value.app_version_major; buffer[5] = pingResult.Value.app_version_minor; BitConverter.GetBytes((ushort)Math.Min(ushort.MaxValue, (DateTime.UtcNow - start).TotalMilliseconds)).CopyTo(buffer, 6); } else { //Timed out buffer[0] = (byte)InstanceStatusResult.PING_TIMED_OUT; } } catch { buffer[0] = (byte)InstanceStatusResult.PING_FAILED; } } //Send msg.Respond(buffer, true); }
private void Io_OnClientMessage(RouterSession session, RouterMessage msg) { if (session.authenticated) { //Authenticated commands if (msg.opcode == RouterConnection.OPCODE_SYS_GETCFG) { HandleRequestConfigCommand(session, msg); } else if (msg.opcode == RouterConnection.OPCODE_SYS_USERCFG) { HandleRequestUserConfigCommand(session, msg); } else if (msg.opcode == RouterConnection.OPCODE_SYS_RPC) { HandleRequestRPCCommand(session, msg); } else if (msg.opcode == RouterConnection.OPCODE_SYS_LOG) { HandleRequestLogCommand(session, msg); } else { logger.Log("Io_OnClientMessage", $"Client {session.GetDebugName()} sent an unknown command ({msg.opcode}).", DeltaLogLevel.Debug); } } else { //Unauthenticated commands if (msg.opcode == RouterConnection.OPCODE_SYS_LOGIN) { HandleLoginCommand(session, msg); } else { logger.Log("Io_OnClientMessage", $"Client {session.GetDebugName()} sent unauthenticated command that was not LOGIN ({msg.opcode}).", DeltaLogLevel.Debug); } } }
private void HandleGetUserConfigCmd(MasterControlClient session, RouterMessage msg) { //Read strings int nameLen = BitConverter.ToInt32(msg.payload, 0); string name = Encoding.UTF8.GetString(msg.payload, 4, nameLen); int defaultLen = BitConverter.ToInt32(msg.payload, nameLen + 4); string defaultValue = Encoding.UTF8.GetString(msg.payload, 4 + nameLen + 4, defaultLen); //Get file path string path = Program.cfg.general.sub_configs_directory + name; //Create default if needed if (!File.Exists(path)) { File.WriteAllText(path, defaultValue); } //Load and return string content = File.ReadAllText(path); msg.Respond(Encoding.UTF8.GetBytes(content), true); }
private void HandleLoginCommand(RouterSession session, RouterMessage msg) { //Get details DeltaCoreNetServerType type = (DeltaCoreNetServerType)BitConverter.ToInt32(msg.payload, 0); long loginKey = BitConverter.ToInt64(msg.payload, 4); //Find the linked instance ManagerInstance instance = null; lock (this.session.instances) { foreach (var s in this.session.instances) { if (loginKey == s.id) { instance = s; } } } //If this failed, abort if (instance == null) { logger.Log("HandleLoginCommand", $"Logging in client {session.GetDebugName()} with key {loginKey} FAILED. Dropping client...", DeltaLogLevel.Medium); io.DropClient(session); return; } //Set properties on session session.authenticatedType = type; instance.linkedSession = session; session.linkedInstance = instance; session.authenticated = true; //Log logger.Log("HandleLoginCommand", $"Logged in client {session.GetDebugName()} as {type.ToString().ToUpper()} as {instance.id} (v {instance.version_id}).", DeltaLogLevel.Low); }
private void Io_OnRouterReceiveMessage(RouterMessage msg) { //Dispatch bool handled = false; if (boundReceiveEvents.ContainsKey(msg.opcode)) { for (int i = 0; i < boundReceiveEvents[msg.opcode].Count; i++) { try { boundReceiveEvents[msg.opcode][i](msg); } catch (Exception ex) { conn.Log("Io_OnRouterReceiveMessage", $"Error handling incoming message from bound event: {ex.Message}{ex.StackTrace}", DeltaLogLevel.High); } } handled = boundReceiveEvents[msg.opcode].Count > 0; } if (!handled) { conn.Log("Io_OnRouterReceiveMessage", $"Got unknown opcode {msg.opcode}, and nothing was able to handle it!", DeltaLogLevel.Low); } }
private void OnCmdDeleteVersion(RouterMessage msg) { //Decode arguments and create logger ManagerDeleteVersion args = msg.DeserializeAs <ManagerDeleteVersion>(); MasterCommandLogger logger = new MasterCommandLogger(msg); //Find package if (!session.versions.ContainsKey(args.version_id)) { logger.FinishFail("Could not find that version on the server."); return; } ManagerVersion version = session.versions[args.version_id]; //Run try { version.DeleteVersion(session, logger); } catch (Exception ex) { logger.FinishFail($"Unexpected error: {ex.Message}{ex.StackTrace}"); } }
private void OnCmdAddInstance(RouterMessage msg) { //Decode arguments and create logger ManagerAddInstance args = msg.DeserializeAs <ManagerAddInstance>(); MasterCommandLogger logger = new MasterCommandLogger(msg); //Find package if (!session.packages.ContainsKey(args.package_name)) { logger.FinishFail("Could not find that package on the server."); return; } ManagerPackage package = session.packages[args.package_name]; //Run try { session.CreateNewInstance(package, logger, args.count, true); } catch (Exception ex) { logger.FinishFail($"Unexpected error: {ex.Message}{ex.StackTrace}"); } }
private void MasterConnection_OnRouterReceiveMessage(RouterMessage msg) { if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_STATUS) { OnCmdGetStatus(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_ADDPACKAGE) { OnCmdAddPackage(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_ADDVERSION) { OnCmdAddVersion(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_ADDINSTANCE) { OnCmdAddInstance(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_LISTPACKAGES) { msg.RespondJson(MiscTools.DictToList(session.packages), true); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_LISTVERSIONS) { msg.RespondJson(MiscTools.DictToList(session.versions), true); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_LISTINSTANCES) { msg.RespondJson(session.instances, true); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_UPDATEINSTANCE) { OnCmdUpdateInstance(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_DESTROYINSTANCE) { OnCmdRemoveInstance(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_DELETEVERSION) { OnCmdDeleteVersion(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_ADDSITE) { OnCmdAddSite(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_LISTSITES) { msg.RespondJson(MiscTools.DictToList(session.sites), true); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_M_ASSIGNSITE) { OnCmdAssignSite(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_REBOOT_INSTANCE) { OnCmdRebootInstance(msg); } else if (msg.opcode == MasterConnectionOpcodes.OPCODE_MASTER_PING_INSTANCE) { OnCmdGetInstanceStatus(msg).GetAwaiter().GetResult(); } else { Log("MasterConnection_OnRouterReceiveMessage", $"Got message with unknown opcode {msg.opcode}.", DeltaLogLevel.Medium); } }
public override void RouterReceiveMessage(RouterMessage msg) { server.OnIncomingClientMessage(this, msg); }
public MasterCommandLogger(RouterMessage message) { this.message = message; }
public async Task SendRouterEngineStatusToClients(string grpname, RouterMessage msg) { await Clients.Group(grpname).SendRouterIPC(msg); }
public override void RouterReceiveMessage(RouterMessage msg) { handlingMessages.Enqueue(msg); }
private void HandleInstanceLogCommand(MasterControlClient session, RouterMessage msg) { session.DispatchInstanceLogEvent(msg.payload); }