/// <summary> /// Carica una configurazione precedentemente salvata tramite Backup() /// </summary> /// <param name="version">Versione della configurazione: data con formato 'yyyyMMddHHmmss'</param> /// <returns></returns> public static MachineConfig Read(string version) { var filePath = CommonString.Append(Parameter.AntdCfgRestore, "/", fileName, version, fileExtension); if (!File.Exists(filePath)) { return(null); } var text = File.ReadAllText(filePath); return(JsonConvert.DeserializeObject <MachineConfig>(text)); }
/// <summary> /// ip tuntap add dev tap0 mode tap /// </summary> /// <param name="netInterface"></param> /// <returns></returns> public static bool SetTapInterface(NetTap netInterface) { if (CheckTuntapModule()) { Mod.Add(tuntapMudule); } var args = CommonString.Append(tuntapArg, " add dev ", netInterface.Id, " mode tap"); CommonProcess.Do(ipFileLocation, args); Ip.EnableNetworkAdapter(netInterface.Id); ConsoleLogger.Log($"[network] tap '{netInterface.Id}' created"); return(true); }
public static string[] GetList() { var args = CommonString.Append("--no-pager --no-legend list-units"); var result = CommonProcess.Execute(systemctlFileLocation, args).Where(_ => !_.Contains("device")).ToArray(); var status = new string[result.Length]; for (var i = 0; i < result.Length; i++) { var currentLineData = result[i].Split(new[] { ' ' }, 2, StringSplitOptions.RemoveEmptyEntries); status[i] = currentLineData[0]; } return(status); }
/// <summary> /// Crea una copia di backup dell'ultima configurazione salvata /// </summary> public static void Backup() { Directory.CreateDirectory(Parameter.AntdCfgRestore); var filePath = CommonString.Append(Parameter.AntdCfg, "/", fileName, fileExtension); if (!File.Exists(filePath)) { return; } var version = DateTime.Now.ToString("yyyyMMddHHmmss"); var backupFilePath = CommonString.Append(Parameter.AntdCfgRestore, "/", fileName, version, fileExtension); File.Copy(filePath, backupFilePath, true); }
public static SystemService[] Get(SystemctlType type = SystemctlType.none) { string filter = ""; switch (type) { case SystemctlType.none: break; case SystemctlType.Service: filter = "--type=service"; break; case SystemctlType.Mount: filter = "--type=mount"; break; case SystemctlType.Timer: filter = "--type=timer"; break; case SystemctlType.Target: filter = "--type=target"; break; default: break; } var args = CommonString.Append("--no-pager --no-legend ", filter); var result = CommonProcess.Execute(systemctlFileLocation, args).ToArray(); var status = new SystemService[result.Length]; for (var i = 0; i < result.Length; i++) { var currentLine = result[i]; var currentLineData = currentLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); status[i] = new SystemService() { Type = type, Service = currentLineData[0], Active = IsEnabled(currentLineData[0]) ? true : false, Start = IsActive(currentLineData[0]) ? true : false, ForceRestart = false, Masking = false }; } return(status); }
public static bool IsEnabled(string unit) { var args = CommonString.Append(isEnabledArg, " ", unit); var status = CommonProcess.Execute(systemctlFileLocation, args); if (status == null) { return(false); } if (string.IsNullOrEmpty(status.FirstOrDefault())) { return(false); } return(!status.FirstOrDefault().Contains("disabled")); }
/// <summary> /// qemu-img create vhd001.qed 16G /// </summary> /// <param name="diskFilepath"></param> /// <param name="size"></param> public static void CreateVirtualDisk(string diskFilepath, string size) { if (!diskFilepath.EndsWith(qemuImgDiskExtension)) { diskFilepath = CommonString.Append(diskFilepath, qemuImgDiskExtension); } if (File.Exists(diskFilepath)) { ConsoleLogger.Log($"[qemu] disk creation skipped because a disk with this name already exists"); return; } var args = CommonString.Append("create ", diskFilepath, " -f qed ", size); CommonProcess.Do(qemuImgFileLocation, args); }
public static void Main() { var resetEvent = new AutoResetEvent(initialState: false); Console.CancelKeyPress += (s, e) => { e.Cancel = true; resetEvent.Set(); }; STOPWATCH = new Stopwatch(); STOPWATCH.Start(); ConsoleLogger.Log($"[{KeyName}] start"); Scheduler = new JobManager(); var urlFile = $"{Parameter.AntdCfg}/host_reference"; while (!File.Exists(urlFile)) { Thread.Sleep(500); ConsoleLogger.Warn($"[{KeyName}] waiting for server"); } while (string.IsNullOrEmpty(File.ReadAllText(urlFile))) { Thread.Sleep(500); ConsoleLogger.Warn($"[{KeyName}] waiting for server"); } ServerUrl = File.ReadAllText(urlFile); CurrentConfiguration = Help.GetCurrentConfiguration(); while (CurrentConfiguration == null) { ConsoleLogger.Warn($"[{KeyName}] waiting for server"); Thread.Sleep(500); CurrentConfiguration = Help.GetCurrentConfiguration(); } var port = CurrentConfiguration.WebService.GuiWebServicePort; var uri = $"http://localhost:{port}/"; var webService = new NancyHost(new Uri(uri)); webService.Start(); StaticConfiguration.DisableErrorTraces = false; ConsoleLogger.Log($"[{KeyName}] web service is listening on port {port}"); ConsoleLogger.Log($"[{KeyName}] loaded in: {STOPWATCH.ElapsedMilliseconds} ms"); #region [ Set Parameters ] ServerUrl = CommonString.Append(CurrentConfiguration.WebService.Protocol, "://", CurrentConfiguration.WebService.Host, ":", CurrentConfiguration.WebService.Port.ToString()); #endregion resetEvent.WaitOne(); webService.Stop(); STOPWATCH.Stop(); ConsoleLogger.Log($"[{KeyName}] stop"); Environment.Exit(0); }
public GatewayModule() : base("/gateway") { this.RequiresAuthentication(); Get["/"] = x => { return(ApiConsumer.GetJson(CommonString.Append(Application.ServerUrl, Request.Path))); }; Post["/save"] = x => { string data = Request.Form.Data; var dict = new Dictionary <string, string> { { "Data", data } }; return(ApiConsumer.Post(CommonString.Append(Application.ServerUrl, Request.Path), dict)); }; }
public InfoModule() : base("/info") { this.RequiresAuthentication(); Get["/memory"] = x => { return(ApiConsumer.GetJson(CommonString.Append(Application.ServerUrl, Request.Path))); }; Get["/free"] = x => { return(ApiConsumer.GetJson(CommonString.Append(Application.ServerUrl, Request.Path))); }; Get["/cpu"] = x => { return(ApiConsumer.GetJson(CommonString.Append(Application.ServerUrl, Request.Path))); }; }
public static bool SetAuthorizedKey() { if (Application.CurrentConfiguration.Services.Ssh.AuthorizedKey == null) { return(false); } var keys = Application.CurrentConfiguration.Services.Ssh.AuthorizedKey; var lines = new string[keys.Length]; for (var i = 0; i < keys.Length; i++) { var ak = keys[i]; lines[i] = CommonString.Append(ak.Key, " ", ak.User, "@", ak.Host); } File.WriteAllLines(authorizedKeysFile, lines); return(true); }
/// <summary> /// Lancia il comando per creare uno snapshot in base a un timer /// </summary> public static void Launch() { var result = Application.RunningConfiguration.Storage.Zpools; if (result.Length < 1) { return; } var dateArgument = DateTime.Now.ToString("yyyyMMdd-HHmmss"); for (var i = 0; i < result.Length; i++) { var currentPool = result[i]; CommonProcess.Do(zfsFileLocation, CommonString.Append(snapshotLaunchArgs, currentPool.Name, "@", dateArgument)); ConsoleLogger.Log($"[zfs] snapshot create for '{currentPool.Name}'"); } }
/// <summary> /// Prepara le cartelle e i parametri necessari per avviare i servizi del cluster /// </summary> private static void Prepare() { Directory.CreateDirectory(haproxyVarLib); Bash.Execute($"chown haproxy:haproxy {haproxyVarLib}"); Bash.Execute($"chmod 755 {haproxyVarLib}"); if (File.Exists(ipNonlocalBindSysctlFile)) { File.WriteAllText(ipNonlocalBindSysctlFile, ipNonlocalBindSysctlValue); } Directory.CreateDirectory(clusterCfgFolder); var nodes = Application.CurrentConfiguration.Cluster.Nodes; for (var i = 0; i < nodes.Length; i++) { var nodeFolder = CommonString.Append(clusterCfgFolder, "/", nodes[i].MachineUid); Directory.CreateDirectory(nodeFolder); } }
public static bool Blacklist(string module) { if (!File.Exists(blacklistFileLocation)) { return(false); } var blacklistLine = CommonString.Append("blacklist ", module); var runningBlacklist = File.ReadAllLines(blacklistFileLocation); if (runningBlacklist.Contains(blacklistLine)) { return(true); } File.AppendAllLines(blacklistFileLocation, new[] { blacklistLine }); CommonProcess.Do(rmmodFileLocation, module); ConsoleLogger.Log($"[mod] blacklist module '{module}'"); return(true); }
/// <summary> /// Salva su disco la configurazione /// </summary> /// <param name="data">Configurazione presa da Application.CurrentConfiguration</param> public static void Save() { var settings = new JsonSerializerSettings { ObjectCreationHandling = ObjectCreationHandling.Replace, Formatting = Formatting.Indented }; var text = JsonConvert.SerializeObject(Application.CurrentConfiguration, settings); var filePath = CommonString.Append(Parameter.AntdCfg, "/", fileName, fileExtension); Backup(); //if(File.Exists(filePath)) { // var backupFilePath = CommonString.Append(Parameter.AntdCfg, "/", fileName, fileExtension, ".bck"); // File.Copy(filePath, backupFilePath, true); //} using (var file = File.CreateText(filePath)) { file.Write(text); } }
/// <summary> /// Ottiene tutte le coppie Key-Value da Sysctl /// </summary> /// <returns></returns> public static SystemParameter[] GetAll() { var args = CommonString.Append("--all"); var result = CommonProcess.Execute(sysctlFileLocation).ToArray(); var status = new SystemParameter[result.Length]; for (var i = 0; i < result.Length; i++) { var currentLine = result[i]; var currentLineData = currentLine.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); status[i] = new SystemParameter() { Key = GetKeyFilePath(currentLineData[0].Trim()), Value = currentLineData[1].Trim() }; } Array.Sort(status, (a, b) => (a.Key.CompareTo(b.Key))); return(status); }
public static NetRoute[] Get() { var args = CommonString.Append(route, " ", show); var result = CommonProcess.Execute(ipFileLocation, args).Where(_ => !_.Contains(protoKernel)).ToArray(); var routes = new NetRoute[result.Length]; for (var i = 0; i < result.Length; i++) { var currentLine = result[i]; var currentLineData = currentLine.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); routes[i] = new NetRoute() { Default = currentLine.Contains(@default) ? true : false, Destination = currentLine.Contains(@default) ? @default : currentLineData[0], Gateway = Help.CaptureGroup(currentLine, "(via [0-9\\.]+)").Replace("via", "").Trim(), Device = Help.CaptureGroup(currentLine, "(dev [a-zA-Z0-9\\.]+)").Replace("dev", "").Trim() }; } return(routes); }
private static void MountVolume(string volumeLabel, ClusterNode[] nodes) { //ogni nodo monterà sul proprio filesystem il volume di gluster configurato su se stesso //i nodi in questo caso so già che conterranno le informazioni del volume for (var i = 0; i < nodes.Length; i++) { var currentVolume = nodes[i].Volumes.FirstOrDefault(_ => _.Label == volumeLabel); //per evitare errori controllo che ci siano le info del volume if (currentVolume == null) { continue; } //poi lancio i comandi ssh per creare la cartella e montarla ConsoleLogger.Log($"[gluster] ssh root@{nodes[i].Hostname} mkdir -p {currentVolume.MountPoint}"); var prepareMountPointCommand = CommonString.Append("mkdir -p ", currentVolume.MountPoint); Ssh.Do("root", nodes[i].Hostname, prepareMountPointCommand); ConsoleLogger.Log($"[gluster] ssh root@{nodes[i].Hostname} mount -t glusterfs {nodes[i].Hostname}:{volumeLabel} {currentVolume.MountPoint}"); var mountVolumeCommand = CommonString.Append("mount -t glusterfs ", nodes[i].Hostname, ":", volumeLabel, " ", currentVolume.MountPoint); Ssh.Do("root", nodes[i].Hostname, mountVolumeCommand); } }
/// <summary> /// Quando un file viene modificato lo invio agli altri nodi del cluster /// E verrà salvato nella cartella /cfg/antd/cluster/{machineUid}/DIR_etc_libvirt_qemu /// </summary> /// <param name="source"></param> /// <param name="e"></param> private void FileChanged(object source, FileSystemEventArgs e) { var fileName = Path.GetFileName(e.FullPath); if (!File.Exists(e.FullPath)) { return; } ConsoleLogger.Log($"[watcher] file '{e.FullPath}' changed"); var nodes = Application.CurrentConfiguration.Cluster.Nodes; for (var i = 0; i < nodes.Length; i++) { if (CommonString.AreEquals(nodes[i].MachineUid, Application.CurrentConfiguration.Host.MachineUid.ToString()) == true) { continue; } var destinationPath = CommonString.Append(clusterCfgFolder, "/", Application.CurrentConfiguration.Host.MachineUid.ToString(), "/", destinationFolderName, "/", e.Name); ConsoleLogger.Log($"sync '{e.FullPath}' -> '{destinationPath}'"); StorageClient.CreateFile(nodes[i], e.FullPath, destinationPath); } }
public static AuthorizedKey[] GetAuthorizedKey() { if (!File.Exists(authorizedKeysFile)) { return(new AuthorizedKey[0]); } var result = File.ReadAllLines(authorizedKeysFile).Where(_ => !string.IsNullOrEmpty(_) && _.StartsWith(sshKeyType) && _.Contains("@")).ToArray(); var keys = new AuthorizedKey[result.Length]; for (var i = 0; i < result.Length; i++) { var lineData = result[i].Split(new[] { ' ' }, 3, StringSplitOptions.RemoveEmptyEntries); var userData = lineData[2].Split(new[] { '@' }, 2, StringSplitOptions.RemoveEmptyEntries); keys[i] = new AuthorizedKey() { User = userData[0], Host = userData[1], Key = CommonString.Append(lineData[0], " ", lineData[1]) }; } return(keys); }
private static void StartVolume(string volumeLabel, ClusterNode[] nodes) { ConsoleLogger.Log($"[gluster] create {volumeLabel}"); int volumeCount = 0; string replicaString = ""; List <ClusterNode> activeNodes = new List <ClusterNode>(); for (var i = 0; i < nodes.Length; i++) { var currentNode = nodes[i]; var currentVolume = currentNode.Volumes.FirstOrDefault(_ => _.Label == volumeLabel); if (currentVolume != null) { //qui ho trovato all'interno della conf del nodo una conf del volume corrispondente all'etichetta presa in considerazione //quindi prendo queste info relative all'host e al suo volume per comporre la stringa di creazione del volume stesso replicaString += $"{currentNode.Hostname}:{currentVolume.Brick} "; //e incremento di 1 il counter, sempre per comporre il comando di creazione del vol volumeCount = volumeCount + 1; activeNodes.Add(currentNode); } } if (volumeCount == 0) { //non ci sono volumi configurati... evito possibili errori return; } //creo il volume di gluster e lo avvio ConsoleLogger.Log($"[gluster] gluster volume create {volumeLabel} replica {volumeCount} transport tcp {replicaString} force"); var glusterCreateArg = CommonString.Append("volume create ", volumeLabel, " replica ", volumeCount.ToString(), " transport tcp ", replicaString, " force"); CommonProcess.Do(glusterFileLocation, glusterCreateArg); System.Threading.Thread.Sleep(500); ConsoleLogger.Log($"[gluster] gluster volume start {volumeLabel}"); var glusterStartArg = CommonString.Append("volume start ", volumeLabel); CommonProcess.Do(glusterFileLocation, glusterStartArg); //a questo punto posso montare il volume di Gluster sul filesystem, su ogni nodo MountVolume(volumeLabel, activeNodes.ToArray()); }
public static string[] GetList() { var kernel = Uname.GetKernel(); if (string.IsNullOrEmpty(kernel)) { return(new string[0]); } var modulesLocation = CommonString.Append(modulesDirectory, "/", kernel); if (!Directory.Exists(modulesLocation)) { return(new string[0]); } var files = Directory.EnumerateFiles(modulesLocation, "*", SearchOption.AllDirectories).Where(_ => _.Contains(moduleExtension)).ToArray(); var list = new string[files.Length]; for (var i = 0; i < files.Length; i++) { list[i] = Path.GetFileName(files[i]).Replace(moduleExtension, ""); } return(list); }
public JournalctlModule() : base("/journalctl") { this.RequiresAuthentication(); Get["/"] = x => { return(ApiConsumer.GetJson(CommonString.Append(Application.ServerUrl, Request.Path))); }; Get["/unit/{unitname}"] = x => { return(ApiConsumer.GetJson(CommonString.Append(Application.ServerUrl, Request.Path))); }; Get["/unit/antd"] = x => { return(ApiConsumer.GetJson(CommonString.Append(Application.ServerUrl, Request.Path))); }; Get["/unit/antdui"] = x => { return(ApiConsumer.GetJson(CommonString.Append(Application.ServerUrl, Request.Path))); }; Get["/last/{hours}"] = x => { return(ApiConsumer.GetJson(CommonString.Append(Application.ServerUrl, Request.Path))); }; }
public static bool SetRoutingTable() { if (!Directory.Exists("/etc/iproute2")) { return(true); } var currentHosts = CommonArray.Merge(DefaultRoutingTables, Application.CurrentConfiguration.Network.RoutingTables); var runningHosts = Application.RunningConfiguration.Network.RoutingTables; if (currentHosts.Select(_ => _.ToString()).SequenceEqual(runningHosts.Select(_ => _.ToString())) == false) { if (File.Exists(routingTableFile)) { File.Copy(routingTableFile, routingTableFileBackup, true); } var lines = new string[currentHosts.Length]; for (var i = 0; i < currentHosts.Length; i++) { lines[i] = CommonString.Append(currentHosts[i].Id, " ", currentHosts[i].Alias); } File.WriteAllLines(routingTableFile, lines); } return(true); }
public static bool Set() { var current = Application.CurrentConfiguration.NsSwitch; var running = Application.RunningConfiguration.NsSwitch.ToString(); if (CommonString.AreEquals(current.ToString(), running)) { return(true); } var lines = new List <string>(); if (!string.IsNullOrEmpty(current.Aliases)) { lines.Add(CommonString.Append("aliases ", current.Aliases)); } if (!string.IsNullOrEmpty(current.Ethers)) { lines.Add(CommonString.Append("ethers ", current.Ethers)); } if (!string.IsNullOrEmpty(current.Group)) { lines.Add(CommonString.Append("group ", current.Group)); } if (!string.IsNullOrEmpty(current.Hosts)) { lines.Add(CommonString.Append("hosts ", current.Hosts)); } if (!string.IsNullOrEmpty(current.Initgroups)) { lines.Add(CommonString.Append("initgroups ", current.Initgroups)); } if (!string.IsNullOrEmpty(current.Netgroup)) { lines.Add(CommonString.Append("netgroup ", current.Netgroup)); } if (!string.IsNullOrEmpty(current.Networks)) { lines.Add(CommonString.Append("networks ", current.Networks)); } if (!string.IsNullOrEmpty(current.Passwd)) { lines.Add(CommonString.Append("passwd ", current.Passwd)); } if (!string.IsNullOrEmpty(current.Protocols)) { lines.Add(CommonString.Append("protocols ", current.Protocols)); } if (!string.IsNullOrEmpty(current.Publickey)) { lines.Add(CommonString.Append("publickey ", current.Publickey)); } if (!string.IsNullOrEmpty(current.Rpc)) { lines.Add(CommonString.Append("rpc ", current.Rpc)); } if (!string.IsNullOrEmpty(current.Services)) { lines.Add(CommonString.Append("services ", current.Services)); } if (!string.IsNullOrEmpty(current.Shadow)) { lines.Add(CommonString.Append("shadow ", current.Services)); } if (!string.IsNullOrEmpty(current.Netmasks)) { lines.Add(CommonString.Append("netmasks ", current.Netmasks)); } if (!string.IsNullOrEmpty(current.Bootparams)) { lines.Add(CommonString.Append("bootparams ", current.Bootparams)); } if (!string.IsNullOrEmpty(current.Automount)) { lines.Add(CommonString.Append("automount ", current.Automount)); } if (File.Exists(nsswitchFile)) { File.Copy(nsswitchFile, nsswitchFileBackup, true); } File.WriteAllLines(nsswitchFile, lines); return(true); }
private static void IncludeNode(string nodeName) { var args = CommonString.Append(includeNodeArg, " ", nodeName); CommonProcess.Do(glusterFileLocation, args); }
public static void MountWithBind(string source, string destination) { var args = CommonString.Append(bind, " ", source, " ", destination); CommonProcess.Do(mountFileLocation, args); }
public StorageServerModule() : base("/storageserver") { #region [ Folder Actions ] Get["/folder/get"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string folderPath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); if (!Directory.Exists(folderPath)) { return(HttpStatusCode.InternalServerError); } var folderInfo = new DirectoryInfo(folderPath); var requestedFolder = new StorageServerFolder() { FolderPath = folderPath, CreationTime = folderInfo.CreationTime, LastAccessTime = folderInfo.LastAccessTime, LastWriteTime = folderInfo.LastWriteTime }; var folders = Directory.EnumerateDirectories(folderPath, "*", SearchOption.TopDirectoryOnly).ToArray(); var contentFolders = new StorageServerFolder[folders.Length]; for (var i = 0; i < folders.Length; i++) { var subFolderInfo = new DirectoryInfo(folders[i]); contentFolders[i] = new StorageServerFolder() { FolderPath = folders[i], CreationTime = subFolderInfo.CreationTime, LastAccessTime = subFolderInfo.LastAccessTime, LastWriteTime = subFolderInfo.LastWriteTime }; } requestedFolder.Folders = contentFolders; var files = Directory.EnumerateFiles(folderPath, "*", SearchOption.TopDirectoryOnly).ToArray(); var contentFiles = new StorageServerFileMetadata[files.Length]; for (var i = 0; i < files.Length; i++) { var fileInfo = new FileInfo(files[i]); contentFiles[i] = new StorageServerFileMetadata() { FilePath = files[i], CreationTime = fileInfo.CreationTime, LastAccessTime = fileInfo.LastAccessTime, LastWriteTime = fileInfo.LastWriteTime, Size = fileInfo.Length }; } requestedFolder.Files = contentFiles; return(JsonConvert.SerializeObject(requestedFolder)); }; Get["/folder/verify"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string folderPath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); if (!Directory.Exists(folderPath)) { return(HttpStatusCode.InternalServerError); } return(HttpStatusCode.OK); }; Post["/folder/create"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string folderPath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); if (Directory.Exists(folderPath)) { return(HttpStatusCode.InternalServerError); } Directory.CreateDirectory(folderPath); return(HttpStatusCode.OK); }; Put["/folder/move"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string folderPath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); string newPath = GetValueFromHeader(Request.Headers, HeaderFolderNewPathKey); if (!Directory.Exists(folderPath)) { return(HttpStatusCode.InternalServerError); } var folderName = folderPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault().Trim('/'); var newFolderPath = CommonString.Append(newPath, "/", folderName); Directory.CreateDirectory(newPath); Directory.Move(folderPath, newFolderPath); return(HttpStatusCode.OK); }; Put["/folder/rename"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string folderPath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); string newName = GetValueFromHeader(Request.Headers, HeaderFolderNewNameKey); if (!Directory.Exists(folderPath)) { return(HttpStatusCode.InternalServerError); } var folderName = folderPath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault().Trim('/'); var newFolderPath = folderPath.Replace(folderName, newName); Directory.Move(folderPath, newFolderPath); return(HttpStatusCode.OK); }; Delete["/folder/delete"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string folderPath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); if (!Directory.Exists(folderPath)) { return(HttpStatusCode.InternalServerError); } Directory.Delete(folderPath, true); return(HttpStatusCode.OK); }; #endregion #region [ File Actions ] Get["/file/get"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string filePath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); if (!File.Exists(filePath)) { return(HttpStatusCode.InternalServerError); } var fileName = Path.GetFileName(filePath); var response = new Response(); response.Headers.Add("Content-Disposition", "attachment; filename=" + Nancy.Helpers.HttpUtility.UrlEncode(fileName, System.Text.Encoding.ASCII)); response.ContentType = "application/zip"; response.Contents = stream => { using (var fileStream = File.OpenRead(filePath)) { using (var memoryStream = new MemoryStream()) { fileStream.CopyTo(stream); int data; while ((data = memoryStream.ReadByte()) != -1) { memoryStream.WriteByte((byte)data); } } } }; return(response); }; Get["/file/verify"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string filePath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); if (!File.Exists(filePath)) { return(HttpStatusCode.InternalServerError); } return(HttpStatusCode.OK); }; Post["/file/create"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string filePath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); if (File.Exists(filePath)) { return(HttpStatusCode.InternalServerError); } var files = Request.Files.ToArray(); if (!files.Any()) { return(HttpStatusCode.BadRequest); } var file = files.FirstOrDefault(); //todo usa rsync using (var fileStream = new FileStream(filePath, FileMode.Create)) { file.Value.CopyTo(fileStream); } return(HttpStatusCode.OK); }; Put["/file/move"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string filePath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); string newPath = GetValueFromHeader(Request.Headers, HeaderFolderNewPathKey); if (!File.Exists(filePath)) { return(HttpStatusCode.InternalServerError); } var fileName = filePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault().Trim('/'); var newFolderPath = CommonString.Append(newPath, "/", fileName); if (File.Exists(newFolderPath)) { File.Delete(newFolderPath); } File.Move(filePath, newFolderPath); return(HttpStatusCode.OK); }; Put["/file/rename"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string filePath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); string newName = GetValueFromHeader(Request.Headers, HeaderFolderNewNameKey); if (!File.Exists(filePath)) { return(HttpStatusCode.InternalServerError); } var fileName = filePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries).LastOrDefault().Trim('/'); var newFolderPath = filePath.Replace(fileName, newName); if (File.Exists(newFolderPath)) { File.Delete(newFolderPath); } File.Move(filePath, newFolderPath); return(HttpStatusCode.OK); }; Delete["/file/delete"] = x => { string sourceNode = GetValueFromHeader(Request.Headers, HeaderMachineUidKey); string filePath = GetValueFromHeader(Request.Headers, HeaderFolderPathKey); if (!File.Exists(filePath)) { return(HttpStatusCode.InternalServerError); } File.Delete(filePath); return(HttpStatusCode.OK); }; #endregion }
public static string[] GetUnitLog(string unitName) { var args = CommonString.Append(journalctlOptions, " -u ", unitName); return(CommonProcess.Execute(journalctlFileLocation, args).ToArray()); }
public static string[] GetLastHours(int hours) { var args = CommonString.Append(journalctlOptions, " --since='", hours.ToString(), "h ago'"); return(CommonProcess.Execute(journalctlFileLocation, args).ToArray()); }