protected override void MessageHandler(InterProcessMessage msg) { if (_handlers == null) { _handlers = new Dictionary <string, Action <InterProcessMessage> >() { ["instantiate"] = instantiate, ["ensuredir"] = ensuredir, ["deletedir"] = deleteDir, ["movedir"] = moveDir, ["extracttar"] = extractTar } } ; if (_handlers.ContainsKey(msg.Command)) { _handlers[msg.Command](msg); } else { SendMessage(InterProcessMessage.CommandNotFoundMessage(ModuleName, msg.Token)); } } }
private void moveDir(InterProcessMessage msg) { var args = msg.Args; string error = null; if (!args.TryGetJsonString(PathKey, out var path) || !args.TryGetJsonString(TargetKey, out var target)) { error = "invalid args"; SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject( new[] { new JsonObjectKeyValuePair(PathKey, new JsonNull()), new JsonObjectKeyValuePair(TargetKey, new JsonNull()), new JsonObjectKeyValuePair(ErrorKey, error) } ))); } else { new DirectoryInfo(path).CopyTo(new DirectoryInfo(target)); try { Directory.Delete(path, true); } catch (Exception) { ; } SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject( new[] { new JsonObjectKeyValuePair(PathKey, path), new JsonObjectKeyValuePair(TargetKey, target) } ))); } }
private void extractTar(InterProcessMessage msg) { var args = msg.Args; if (!args.TryGetJsonString(PathKey, out var path) || !args.TryGetJsonString(TargetKey, out var target)) { SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject( new[] { new JsonObjectKeyValuePair(SucceededKey, false) } ))); } else { Process.Start("mkdir", $"-p {target.Value}").WaitForExit(); var startInfo = new ProcessStartInfo("tar", $"-x -f {path.Value} -C {target.Value}") { RedirectStandardOutput = true, RedirectStandardError = true }; var process = Process.Start(startInfo); process.WaitForExit(); new StreamWriter(Console.OpenStandardError()).Write(process.StandardError.ReadToEnd()); SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject( new[] { new JsonObjectKeyValuePair(SucceededKey, process.ExitCode == 0) } ))); } }
private void ensuredir(InterProcessMessage msg) { var args = msg.Args; string error = null; if (!args.TryGetJsonObject(RootKey, out var root)) { error = "invalid args"; SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject( new[] { new JsonObjectKeyValuePair(PathKey, new JsonNull()), new JsonObjectKeyValuePair(ErrorKey, error) } ))); return; } string rv = ensuredirNode(".", root); SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject( new[] { new JsonObjectKeyValuePair(PathKey, rv) } ))); }
private void deleteDir(InterProcessMessage msg) { var args = msg.Args; string error = null; if (!args.TryGetJsonString(PathKey, out var path)) { error = "invalid args"; SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject( new[] { new JsonObjectKeyValuePair(PathKey, new JsonNull()), new JsonObjectKeyValuePair(ErrorKey, error) } ))); } else { try { Directory.Delete(path, true); } catch (Exception) { ; // if any file don't want to leave, let it go } SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject( new[] { new JsonObjectKeyValuePair(PathKey, path) } ))); } }
private void dockerCreate(InterProcessMessage msg) { var args = msg.Args; var imageName = "$invalidimg"; var portmap = new List <(int Host, int Docker)>(); var dirmap = new List <(string Host, string Docker, bool Readonly)>(); var ulimits = new List <(string Item, string Value)>(); var extra = ""; if (args.TryGetJsonString(ImageNameKey, out var image)) { imageName = image; } if (args.TryGetJsonArray(PortMapKey, out var portarray)) { foreach (var it in portarray) { if (it is JsonObject o && o.TryReadInt(HostKey, out var host) && o.TryReadInt(DockerKey, out var docker)) { portmap.Add((host, docker)); } } } if (args.TryGetJsonArray(DirMapKey, out var dirarray)) { foreach (var it in dirarray) { if (it is JsonObject o && o.TryGetJsonString(HostKey, out var host) && o.TryGetJsonString(DockerKey, out var docker)) { dirmap.Add((host, docker, o.TryGetJsonBool(ReadonlyKey, out var ro) && ro.Value)); } } } if (args.TryGetJsonArray(UlimitKey, out var ulimitarray)) { foreach (var it in ulimitarray) { if (it is JsonObject o && o.TryGetJsonString(ItemKey, out var item) && o.TryGetJsonString(ValueKey, out var value)) { ulimits.Add((item, value)); } } } if (args.TryGetJsonString(ExtraKey, out var ext)) { extra = ext; } var portmapStr = portmap.Count > 0 ? $"{portmap.Select(map => $"-p {map.Host}:{map.Docker}").JoinBy(" ")}" : ""; var dirmapStr = dirmap.Count > 0 ? $"{dirmap.Select(map => $"-v {map.Host}:{map.Docker}" + (map.Readonly ? ":ro" : "")).JoinBy(" ")}" : ""; var ulimitsStr = ulimits.Count > 0 ? $"--ulimit {ulimits.Select(limit => $"{limit.Item}={limit.Value}").JoinBy(" ")}" : ""; dockerContainerOpWrapper("create", $"{portmapStr} {dirmapStr} {ulimitsStr} {extra} {imageName}", msg.Token); }
protected override void MessageHandler(InterProcessMessage msg) { if (_handlers == null) { _handlers = new Dictionary <string, Action <InterProcessMessage> >() { ["create"] = dockerCreate, ["start"] = dockerStart, ["kill"] = dockerKill, ["killmany"] = dockerKillMany, ["ps"] = dockerPs, ["psall"] = dockerPsall } } ; if (_handlers.ContainsKey(msg.Command)) { _handlers[msg.Command](msg); } else { SendMessage(InterProcessMessage.CommandNotFoundMessage(ModuleName, msg.Token)); } } }
public virtual void MessageLoop() { while (true) { InterProcessMessage msg; lock (_msg) { msg = _msg.Count > 0 ? _msg.Dequeue() : null; } if (msg == null) { Thread.Sleep(MessageWaitingInterval); continue; } if (InterProcessMessage.IsTerminator(msg)) { break; } try { MessageHandler(msg); } catch (Exception ex) { Console.Error.WriteLine(ex.GetType().FullName); Console.Error.WriteLine(ex.Message); Console.Error.WriteLine(ex.StackTrace); throw new Exception(); } } }
private void dockerPsall(InterProcessMessage msg) { var p = new Process { StartInfo = getStartInfo("ps -a --no-trunc") }; p.Start(); p.WaitForExit(); if (p.ExitCode == 0) { var cids = p.StandardOutput .ReadToEnd() .Split('\n') .Skip(1) .Select(line => line.Trim()) .Where(line => line.Length > 0) .Select(line => line.Split(' ')[0]) .Where(line => line.Length == 64) .Select(cid => new JsonString(cid)); SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject(new[] { new JsonObjectKeyValuePair("cid", new JsonArray(cids)) }))); } else { SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject(new[] { new JsonObjectKeyValuePair("cid", new JsonNull()), new JsonObjectKeyValuePair("error", p.StandardError.ReadToEnd()) }))); } }
private void dockerContainerOpWrapper(string command, string args, int token) { SendMessage(InterProcessMessage.GetResultMessage(ModuleName, token, new JsonObject( dockerWrapper(command, args, out var rv) ? new[] { new JsonObjectKeyValuePair(CidKey, rv) } : new[] { new JsonObjectKeyValuePair(CidKey, new JsonNull()), new JsonObjectKeyValuePair(ErrorKey, rv) } ))); }
private void dockerKill(InterProcessMessage msg) { var args = msg.Args; var cid = "$invalidcid"; if (args.TryGetJsonString(CidKey, out var cidStr)) { cid = cidStr; } dockerContainerOpWrapper("kill", cid, msg.Token); }
private void dockerKillMany(InterProcessMessage msg) { var args = msg.Args; var list = new List <string>(); if (!args.TryGetJsonArray(CidsKey, out var cids)) { SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject(new[] { new JsonObjectKeyValuePair(ErrorKey, "invalid args") }))); return; } foreach (var i in cids) { if (i is JsonString str) { list.Add(str); } } if (list.Count == 0) { SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject(new[] { new JsonObjectKeyValuePair(ErrorKey, new JsonArray()) }))); } else { var p = new Process { StartInfo = getStartInfo($"kill {list.JoinBy(" ")}") }; p.Start(); p.WaitForExit(); var rcids = p.StandardOutput .ReadToEnd() .Split('\n') .Select(line => line.Trim()) .Where(line => line.Length == 64) .Select(cid => new JsonString(cid)); if (p.ExitCode == 0) { SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject(new[] { new JsonObjectKeyValuePair(CidsKey, new JsonArray(rcids)) }))); } else { SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject(new[] { new JsonObjectKeyValuePair(CidsKey, new JsonArray(rcids)), new JsonObjectKeyValuePair(ErrorKey, p.StandardError.ReadToEnd()) }))); } } }
// all path here should be absolute!!! private void instantiate(InterProcessMessage msg) { var args = msg.Args; JsonValue dirmap = new JsonNull(); JsonValue error = new JsonNull(); if (!args.TryGetJsonObject(RootKey, out var root) || !args.TryGetJsonString(TargetKey, out var target)) { error = "invalid params"; } else { dirmap = new JsonArray(instantiateNode(root, new DirectoryInfo(target), ".").Select(m => new JsonObject(new[] { new JsonObjectKeyValuePair(DockerKey, m.Docker), new JsonObjectKeyValuePair(HostKey, m.Host), new JsonObjectKeyValuePair(ReadonlyKey, m.Readonly) }))); } SendMessage(InterProcessMessage.GetResultMessage(ModuleName, msg.Token, new JsonObject( dirmap is JsonNull ? new[] { new JsonObjectKeyValuePair(DirMapKey, dirmap), new JsonObjectKeyValuePair(ErrorKey, error) } : new[] { new JsonObjectKeyValuePair(DirMapKey, dirmap) } ))); }
protected virtual void SendMessage(InterProcessMessage msg) { Daemon?.SendMessage(msg); }
protected virtual void MessageHandler(InterProcessMessage msg) { // do nothing here }
public virtual void OnMessage(InterProcessMessage msg) { lock (_msg) _msg.Enqueue(msg); }