public static string MakeUnMountScript(JCompDeviceStorage storage) { StringBuilder str = new StringBuilder(); str.Append("umount " + storage.Path); return(str.ToString()); }
public static string MakeMountScript(JCompDeviceStorage storage) { StringBuilder str = new StringBuilder(); str.Append("mount " + storage.DevicePath + " " + storage.Path + " -t auto -o rw,nls=utf8,noatime"); return(str.ToString()); }
public static string MakeSambaConfigBlock(JCompDeviceStorage storage) { StringBuilder str = new StringBuilder(); str.Append("[" + storage.SambaName + "]"); HtmlUtils.AppendDosBr(str); str.Append("comment = " + storage.Name); HtmlUtils.AppendDosBr(str); str.Append("path = " + storage.Path); if (string.IsNullOrEmpty(storage.SambaOptions)) { HtmlUtils.AppendDosBr(str); str.Append("read only = no"); HtmlUtils.AppendDosBr(str); str.Append("locking = no"); HtmlUtils.AppendDosBr(str); str.Append("guest ok = yes"); } else { HtmlUtils.AppendDosBr(str); str.Append(storage.SambaOptions); } HtmlUtils.AppendDosBr(str); return(str.ToString()); }
//public object RemoteSession; static public void CloneDependencies(object cloningObject, object targetObject) { //Console.WriteLine("---- -------- CloneDependencies"); IList <JSoftInstance> siList = Dm.Instance.ResolveOneToManyRelation <JSoftInstance>(cloningObject); foreach (var si in siList) { JSoftInstance siClone = (JSoftInstance)Dm.CloneObject(si, CloneObjectType.ForNew); siClone.JCompDevice = targetObject as JCompDevice; Dm.Instance.SaveObject(siClone); //cloning user accounts IList <JUserAccount> uaList = Dm.Instance.ResolveOneToManyRelation <JUserAccount>(si); foreach (var ua in uaList) { JUserAccount uaClone = (JUserAccount)Dm.CloneObject(ua, CloneObjectType.ForNew); uaClone.JSoftInstance = siClone; Dm.Instance.SaveObject(uaClone); } } IList <JCompDeviceStorage> sdsList = Dm.Instance.ResolveOneToManyRelation <JCompDeviceStorage>(cloningObject); foreach (var sds in sdsList) { JCompDeviceStorage sdsClone = (JCompDeviceStorage)Dm.CloneObject(sds, CloneObjectType.ForNew); sdsClone.JCompDevice = targetObject as JCompDevice; Dm.Instance.SaveObject(sdsClone); } }
override protected void ComplateNodeFromObject(TreeNode node, object o) { base.ComplateNodeFromObject(node, o); object x = (node.Tag is TreeObjectWrap) ? (node.Tag as TreeObjectWrap).Tag : node.Tag; if (x == null) return; if (x is JCompDeviceStorage) { JCompDeviceStorage h = (x as JCompDeviceStorage); if (h.MasterStorage != null && h.MasterStorage.JCompDevice != h.JCompDevice) { node.Text = h.JCompDevice.Name + " " + node.Text; node.ToolTipText = h.JCompDevice.Name + " " + node.ToolTipText; } } else if (x is JSoftInstance) { JSoftInstance h = (x as JSoftInstance); if (h.IsDocker) { SetImageForNode(node, NetworkAccountHelperLibRes.docker, "JSoftInstance_IsDocker"); } } else if (x is JCompDevice) { JCompDevice h = (x as JCompDevice); if (CompDeviceTypeEnum.Virtual.ToString().Equals(h.Stage)) { SetImageForNode(node, NetworkAccountHelperLibRes.virtualbox, "JCompDevice_virtualbox"); } } }
public void MakeContextMenu(IListProcessor list, List <ToolStripItem> menuItemList, object selectedListItem, object selectedObject, string aspectName) { //обработчик вызова контекстного меню JCompDeviceStorage storage = (JCompDeviceStorage)selectedObject; ToolStripMenuItem menuItem = null; menuItem = new ToolStripMenuItem(); menuItem.Text = "Скрипты подключения и синхронизации"; menuItem.Click += (s, em) => { try { ShowSummaryInfo(storage); } catch (Exception ex) { Log.ShowError(ex); } }; menuItemList.Add(menuItem); if (storage.MasterStorage != null) { //если слейв хранилище является локальным и либо находится на данном компе, либо доступно через шару //запускаем локальный процесс WinSCP menuItem = new ToolStripMenuItem(); menuItem.Text = "Синхронизировать с мастер хранилищем через WinSCP (запуск на локальном мастере)"; menuItem.Click += (s, em) => { try { WinSCPUtils.SynchronizeDirectories(storage.MasterStorage.Path, storage, true); } catch (Exception ex) { Log.ShowError(ex); } }; menuItemList.Add(menuItem); //если слейв хранилище является удаленным //то запускаем команду синхронизации menuItem = new ToolStripMenuItem(); menuItem.Text = "Синхронизировать с мастер хранилищем через SSH команду (запуск на удаленном мастере)"; menuItem.Click += (s, em) => { try { string cmd = JCompDeviceStorage.MakeRsyncScript(storage.MasterStorage, storage, false); //необходимо чтобы были настроены доверенные сертификаты или надо пробовать с паролем WinSCPUtils.ExecuteCommand(cmd, storage.MasterStorage.JCompDevice, true); } catch (Exception ex) { Log.ShowError(ex); } }; menuItemList.Add(menuItem); } }
public static string MakeSambaClientConnectFstabScript(JCompDeviceStorage storage) { StringBuilder str = new StringBuilder(); str.Append("//" + storage.JCompDevice.GetInternalAddress() + "/" + storage.SambaName + " /mnt/" + storage.SambaName + " cifs username=root,password= 0 0"); HtmlUtils.AppendDosBr(str); return(str.ToString()); }
public static bool UploadFile(string localPath, JCompDeviceStorage jo, bool remote = true) { //see also https://winscp.net/eng/docs/library_example_moves_files_keeping_directory_structure bool success = false; try { Session session = Reconnect(jo.JCompDevice, remote); // Will continuously report progress of synchronization session.FileTransferred += FileTransferred; // Will continuously report progress of transfer session.FileTransferProgress += SessionFileTransferProgress; // Upload files TransferOptions transferOptions = new TransferOptions(); transferOptions.TransferMode = TransferMode.Binary; TransferOperationResult transferResult = session.PutFiles(localPath + "*", jo.Path, false, transferOptions); // Throw on any error transferResult.Check(); // Print results foreach (TransferEventArgs transfer in transferResult.Transfers) { Console.WriteLine("Upload of {0} succeeded", transfer.FileName); success = true; } CloseRemoteSession(jo.JCompDevice); } catch (SessionLocalException sle) { string errorDetail = "WinSCP: There was an error communicating with winscp process. winscp cannot be found or executed."; errorDetail += Environment.NewLine + "Message:" + sle.Message; errorDetail += Environment.NewLine + "Target Site:" + sle.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sle.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sle.StackTrace; throw sle; } catch (SessionRemoteException sre) { string errorDetail = "WinSCP: Error is reported by the remote server; Local error occurs in WinSCP console session, such as error reading local file."; errorDetail += Environment.NewLine + "Message:" + sre.Message; errorDetail += Environment.NewLine + "Target Site:" + sre.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sre.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sre.StackTrace; throw sre; } catch (Exception ex) { throw ex; } return(success); }
public static string MakeSambaClientPrepareScript(JCompDeviceStorage storage) { StringBuilder str = new StringBuilder(); str.Append("mkdir /mnt/" + storage.SambaName); HtmlUtils.AppendDosBr(str); str.Append("chmod 0777 /mnt/" + storage.SambaName); HtmlUtils.AppendDosBr(str); return(str.ToString()); }
public static void Download(string localPath, JCompDeviceStorage jo, bool remote = true) { try { Session session = Reconnect(jo.JCompDevice, remote); RemoteDirectoryInfo directory = session.ListDirectory(jo.Path); foreach (RemoteFileInfo fileInfo in directory.Files) { Console.WriteLine(jo.Path + fileInfo.Name); /* * TransferOptions transferOptions = new TransferOptions(); * transferOptions.TransferMode = TransferMode.Binary; * transferOptions.FilePermissions = null; * transferOptions.PreserveTimestamp = false; * transferOptions.ResumeSupport.State = TransferResumeSupportState.Off; * TransferOperationResult transferResult; * transferResult = session.GetFiles(jo.ExtraPath + fileInfo.Name, localPath, false, transferOptions); * transferResult.Check(); */ } CloseRemoteSession(jo.JCompDevice); } catch (SessionLocalException sle) { string errorDetail = "WinSCP: There was an error communicating with winscp process. winscp cannot be found or executed."; errorDetail += Environment.NewLine + "Message:" + sle.Message; errorDetail += Environment.NewLine + "Target Site:" + sle.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sle.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sle.StackTrace; throw sle; } catch (SessionRemoteException sre) { string errorDetail = "WinSCP: Error is reported by the remote server; Local error occurs in WinSCP console session, such as error reading local file."; errorDetail += Environment.NewLine + "Message:" + sre.Message; errorDetail += Environment.NewLine + "Target Site:" + sre.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sre.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sre.StackTrace; throw sre; } catch (Exception ex) { throw ex; } }
public static bool SynchronizeDirectories(string localPath, JCompDeviceStorage jo, bool remote = true) { bool success = false; try { Session session = Reconnect(jo.JCompDevice, remote); // Will continuously report progress of synchronization session.FileTransferred += FileTransferred; // Synchronize files SynchronizationResult synchronizationResult; synchronizationResult = session.SynchronizeDirectories( SynchronizationMode.Remote, localPath, jo.Path, false); // Throw on any error synchronizationResult.Check(); success = true; CloseRemoteSession(jo.JCompDevice); } catch (SessionLocalException sle) { string errorDetail = "WinSCP: There was an error communicating with winscp process. winscp cannot be found or executed."; errorDetail += Environment.NewLine + "Message:" + sle.Message; errorDetail += Environment.NewLine + "Target Site:" + sle.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sle.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sle.StackTrace; throw sle; } catch (SessionRemoteException sre) { string errorDetail = "WinSCP: Error is reported by the remote server; Local error occurs in WinSCP console session, such as error reading local file."; errorDetail += Environment.NewLine + "Message:" + sre.Message; errorDetail += Environment.NewLine + "Target Site:" + sre.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sre.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sre.StackTrace; throw sre; } catch (Exception ex) { throw ex; } return(success); }
public static string MakeRsyncScript(JCompDeviceStorage storage, JCompDeviceStorage master, bool full) { //JCompDeviceStorage master = storage.MasterStorage; bool sameComp = (storage.JCompDevice == master.JCompDevice); StringBuilder str = new StringBuilder(); str.Append("rsync -rvz --progress --delete"); if (!sameComp && master.JCompDevice.WebEntryInfo.ExtPortSSH != null) { str.Append(" -e \'ssh -p " + master.JCompDevice.WebEntryInfo.ExtPortSSH + "\'"); } if (!sameComp && full) { str.Append(" -i /root/.ssh/id_rsa -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null'"); } str.Append(" "); str.Append(storage.Path); if (storage.Path.EndsWith("/") == false) { str.Append("/"); } str.Append(" "); if (!sameComp) { str.Append(master.JCompDevice.Login); str.Append("@"); str.Append(master.JCompDevice.JCompDeviceNetworkParentLevel.GetExternalAddress()); str.Append(":"); } str.Append(master.Path); if (master.Path.EndsWith("/") == false) { str.Append("/"); } return(str.ToString()); }
public static HashSet <string> GetRemoteFileList(JCompDeviceStorage jo, bool remote = true) { try { HashSet <string> list = new HashSet <string>(); Session session = Reconnect(jo.JCompDevice, remote); //session.SessionLogPath = ""; RemoteDirectoryInfo directory = session.ListDirectory(jo.Path); foreach (RemoteFileInfo fileInfo in directory.Files) { //Console.WriteLine("{0} with size {1}, permissions {2} and last modification at {3}", // fileInfo.Name, fileInfo.Length, fileInfo.FilePermissions, fileInfo.LastWriteTime); list.Add(fileInfo.Name); } // Select the most recent file /* * RemoteFileInfo latest = * directoryInfo.Files * .Where(file => !file.IsDirectory) * .OrderByDescending(file => file.LastWriteTime) * .FirstOrDefault(); */ /* * DateTime remoteWriteTime = session.GetFileInfo(remotePath).LastWriteTime; * DateTime localWriteTime = File.GetLastWriteTime(localPath); * if (remoteWriteTime > localWriteTime) * { * Console.WriteLine( * "File {0} as well as local backup {1} exist, " + * "but remote file is newer ({2}) than local backup ({3})", * remotePath, localPath, remoteWriteTime, localWriteTime); * download = true; * } * else * { * Console.WriteLine( * "File {0} as well as local backup {1} exist, " + * "but remote file is not newer ({2}) than local backup ({3})", * remotePath, localPath, remoteWriteTime, localWriteTime); * download = false; * } */ CloseRemoteSession(jo.JCompDevice); return(list); } catch (SessionLocalException sle) { string errorDetail = "WinSCP: There was an error communicating with winscp process. winscp cannot be found or executed."; errorDetail += Environment.NewLine + "Message:" + sle.Message; errorDetail += Environment.NewLine + "Target Site:" + sle.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sle.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sle.StackTrace; throw sle; } catch (SessionRemoteException sre) { string errorDetail = "WinSCP: Error is reported by the remote server; Local error occurs in WinSCP console session, such as error reading local file."; errorDetail += Environment.NewLine + "Message:" + sre.Message; errorDetail += Environment.NewLine + "Target Site:" + sre.TargetSite; errorDetail += Environment.NewLine + "Inner Exception:" + sre.InnerException; errorDetail += Environment.NewLine + "Stacktrace: " + sre.StackTrace; throw sre; } catch (Exception ex) { throw ex; } }
static public void ShowSummaryInfo(JCompDeviceStorage storage) { StringBuilder str = new StringBuilder(); str.Append(ModelHelper.ModelPropertyList(storage, "<br/>", null, null)); //str.Append(phone.Number); AppendBr(str); AppendBr(str); str.Append(storage.Name); AppendBr(str); AppendBr(str); if (storage.JCompDevice != null && storage.JCompDevice.Description != null) { AppendBr(str); str.Append(storage.JCompDevice.Name + storage.JCompDevice.GetInternalAddress()); AppendBr(str); str.Append(storage.JCompDevice.Description); AppendBr(str); } if (!string.IsNullOrEmpty(storage.SambaName)) { AppendBr(str); str.Append("Samba config for server"); AppendBr(str); str.Append("<pre>"); str.Append(HttpUtility.HtmlEncode(JCompDeviceStorage.MakeSambaConfigBlock(storage))); str.Append("</pre>"); str.Append("Samba prepare for client"); AppendBr(str); str.Append("<pre>"); if (storage.JCompDevice != null && !string.IsNullOrEmpty(storage.JCompDevice.GetInternalAddress())) { str.Append(HttpUtility.HtmlEncode(JCompDeviceStorage.MakeSambaClientPrepareScript(storage))); str.Append("</pre>"); str.Append("Samba connect for client (/etc/init.d/rc.local)"); AppendBr(str); str.Append("<pre>"); str.Append(HttpUtility.HtmlEncode(JCompDeviceStorage.MakeSambaClientConnectScript(storage))); str.Append("</pre>"); str.Append("Samba connect for client fstab (/etc/fstab )"); AppendBr(str); str.Append("<pre>"); str.Append(HttpUtility.HtmlEncode(JCompDeviceStorage.MakeSambaClientConnectFstabScript(storage))); str.Append("</pre>"); } } if (!string.IsNullOrEmpty(storage.DevicePath)) { AppendBr(str); str.Append("Cкрипт монтирования физического устройства"); AppendBr(str); str.Append("<pre>"); str.Append(HttpUtility.HtmlEncode(JCompDeviceStorage.MakeMountScript(storage))); str.Append("</pre>"); AppendBr(str); str.Append("Cкрипт размонтирования физического устройства"); AppendBr(str); str.Append("<pre>"); str.Append(HttpUtility.HtmlEncode(JCompDeviceStorage.MakeUnMountScript(storage))); str.Append("</pre>"); } if (storage.MasterStorage != null) { JCompDeviceStorage master = storage.MasterStorage; AppendBr(str); str.Append("Синхронизация односторонняя. Файлы, которых нет на базе, будут удалены на целевом. Файлы базы, которых нет на целевом, будут туда добавлены"); AppendBr(str); str.Append("Основной скрипт синхронизации базы мастер хранилища (запускать на нем) \"" + master.JCompDevice.Name + "\" c слейв-хранилищем \"" + storage.JCompDevice.Name + "\" (добавить -n для теста)"); AppendBr(str); str.Append("<pre>"); str.Append(HttpUtility.HtmlEncode(JCompDeviceStorage.MakeRsyncScript(master, storage, false))); str.Append("</pre>"); str.Append("Дополнительный скрипт синхронизации базы слейв хранилища (запускать на нем) \"" + storage.JCompDevice.Name + "\" c мастер-хранилищем \"" + master.JCompDevice.Name + "\" (добавить -n для теста)"); AppendBr(str); str.Append("<pre>"); str.Append(HttpUtility.HtmlEncode(JCompDeviceStorage.MakeRsyncScript(storage, master, false))); str.Append("</pre>"); AppendBr(str); } SimpleHtmlTextEditDialog dlg = new SimpleHtmlTextEditDialog(); dlg.EditedText = str.ToString(); dlg.ShowDialog(); }