public static int ZipFiles(int packageId, string[] files, string archivePath) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive); if (accountCheck < 0) { return(accountCheck); } // check package int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive); if (packageCheck < 0) { return(packageCheck); } // place log record TaskManager.StartTask("FILES", "ZIP_FILES", archivePath, packageId); if (files != null) { foreach (string file in files) { TaskManager.Write(file); } } try { OS.OperatingSystem os = GetOS(packageId); string zipFilePath = GetFullPackagePath(packageId, archivePath); List <string> archFiles = new List <string>(); string rootFolder = ""; foreach (string file in files) { string archFile = GetFullPackagePath(packageId, file); int idx = archFile.LastIndexOf("\\"); rootFolder = archFile.Substring(0, idx); archFiles.Add(archFile.Substring(idx + 1)); } os.ZipFiles(zipFilePath, rootFolder, archFiles.ToArray()); return(0); } catch (Exception ex) { //Log and return a generic error rather than throwing an exception TaskManager.WriteError(ex); return(BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED); } finally { TaskManager.CompleteTask(); } }
private static IntResult SaveStorageSpaceInternal(StorageSpace space, bool isShared = false) { var result = TaskManager.StartResultTask <IntResult>("STORAGE_SPACES", "SAVE_STORAGE_SPACE"); try { if (space == null) { throw new ArgumentNullException("space"); } var ss = GetStorageSpaceService(space.ServiceId); if (isShared) { var share = ShareStorageSpaceFolderInternal(space.Id, space.Path, space.Name); space.IsShared = true; space.UncPath = share.UncPath; } if (space.Id > 0) { DataProvider.UpdateStorageSpace(space); TaskManager.Write("Updating Storage Space with id = {0}", space.Id.ToString(CultureInfo.InvariantCulture)); result.Value = space.Id; } else { result.Value = DataProvider.InsertStorageSpace(space); TaskManager.Write("Inserting new Storage Space, obtained id = {0}", space.Id.ToString(CultureInfo.InvariantCulture)); space.Id = result.Value; } ss.UpdateStorageSettings(space.Path, space.FsrmQuotaSizeBytes, space.FsrmQuotaType); } catch (Exception exception) { TaskManager.WriteError(exception); result.AddError("Error saving Storage Space", exception); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return(result); }
private static IntResult SaveStorageSpaceLevelInternal(StorageSpaceLevel level, List <ResourceGroupInfo> groups) { var result = TaskManager.StartResultTask <IntResult>("STORAGE_SPACES", "SAVE_STORAGE_SPACE_LEVEL"); try { if (level == null) { throw new ArgumentNullException("level"); } if (level.Id > 0) { DataProvider.UpdateStorageSpaceLevel(level); TaskManager.Write("Updating Storage Space Level with id = {0}", level.Id.ToString(CultureInfo.InvariantCulture)); result.Value = level.Id; } else { result.Value = DataProvider.InsertStorageSpaceLevel(level); TaskManager.Write("Inserting new Storage Space Level, obtained id = {0}", level.Id.ToString(CultureInfo.InvariantCulture)); level.Id = result.Value; } var resultGroup = SaveLevelResourceGroups(result.Value, groups); if (!resultGroup.IsSuccess) { throw new Exception("Error saving resource groups"); } } catch (Exception exception) { TaskManager.WriteError(exception); result.AddError("Error saving Storage Space Level", exception); } finally { if (!result.IsSuccess) { TaskManager.CompleteResultTask(result); } else { TaskManager.CompleteResultTask(); } } return(result); }
public void CalculateBandwidth() { // get all owned packages List<PackageInfo> packages = PackageController.GetPackagePackages(TaskManager.TopTask.PackageId, true); TaskManager.Write("Packages to calculate: " + packages.Count.ToString()); foreach (PackageInfo package in packages) { // calculating package bandwidth CalculatePackage(package.PackageId); } }
public static string[] UnzipFiles(int packageId, string[] files) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive); if (accountCheck < 0) { return(null); } // check package int packageCheck = SecurityContext.CheckPackage(packageId, DemandPackage.IsActive); if (packageCheck < 0) { return(null); } // place log record TaskManager.StartTask("FILES", "UNZIP_FILES", packageId); if (files != null) { foreach (string file in files) { TaskManager.Write(file); } } try { List <string> unzippedFiles = new List <string>(); OS.OperatingSystem os = GetOS(packageId); for (int i = 0; i < files.Length; i++) { string zipFilePath = GetFullPackagePath(packageId, files[i]); string destFolderPath = zipFilePath.Substring(0, zipFilePath.LastIndexOf("\\")); unzippedFiles.AddRange(os.UnzipFiles(zipFilePath, destFolderPath)); } return(unzippedFiles.ToArray()); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } }
public override void DoWork() { try { TaskManager.Write("Start HostedSolutionReportTask"); BackgroundTask topTask = TaskManager.TopTask; bool isExchange = Utils.ParseBool(topTask.GetParamValue(EXCHANGE_REPORT), false); bool isSharePoint = Utils.ParseBool(topTask.GetParamValue(SHAREPOINT_REPORT), false); bool isLync = Utils.ParseBool(topTask.GetParamValue(LYNC_REPORT), false); bool isCRM = Utils.ParseBool(topTask.GetParamValue(CRM_REPORT), false); bool isOrganization = Utils.ParseBool(topTask.GetParamValue(ORGANIZATION_REPORT), false); string email = topTask.GetParamValue(EMAIL).ToString(); TaskManager.WriteParameter("isExchange", isExchange); TaskManager.WriteParameter("isSharePoint", isSharePoint); TaskManager.WriteParameter("isLync", isLync); TaskManager.WriteParameter("isCRM", isCRM); TaskManager.WriteParameter("isOrganization", isOrganization); TaskManager.WriteParameter("email", email); UserInfo user = PackageController.GetPackageOwner(topTask.PackageId); TaskManager.WriteParameter("user", user.Username); EnterpriseSolutionStatisticsReport report = ReportController.GetEnterpriseSolutionStatisticsReport(user.UserId, isExchange, isSharePoint, isCRM, isOrganization, isLync); TaskManager.WriteParameter("report.ExchangeReport.Items.Count", report.ExchangeReport.Items.Count); TaskManager.WriteParameter("report.SharePointReport.Items.Count", report.SharePointReport.Items.Count); TaskManager.WriteParameter("report.CRMReport.Items.Count", report.CRMReport.Items.Count); TaskManager.WriteParameter("report.OrganizationReport.Items.Count", report.OrganizationReport.Items.Count); TaskManager.WriteParameter("report.LyncReport.Items.Count", report.LyncReport.Items.Count); SendMessage(user, email, isExchange && report.ExchangeReport != null ? report.ExchangeReport.ToCSV() : string.Empty, isSharePoint && report.SharePointReport != null ? report.SharePointReport.ToCSV() : string.Empty, isCRM && report.CRMReport != null ? report.CRMReport.ToCSV() : string.Empty, isOrganization && report.OrganizationReport != null ? report.OrganizationReport.ToCSV() : string.Empty, isLync && report.LyncReport != null ? report.LyncReport.ToCSV() : string.Empty); } catch (Exception ex) { TaskManager.WriteError(ex); } TaskManager.Write("End HostedSolutionReportTask"); }
public override void DoWork() { // Input parameters: // - SERVER_NAME // - EXECUTABLE_PATH BackgroundTask topTask = TaskManager.TopTask; // get input parameters string serverName = (string)topTask.GetParamValue("SERVER_NAME"); string execPath = (string)topTask.GetParamValue("EXECUTABLE_PATH"); string execParams = (string)topTask.GetParamValue("EXECUTABLE_PARAMS"); if (execParams == null) { execParams = ""; } // check input parameters if (String.IsNullOrEmpty(serverName)) { TaskManager.WriteWarning("Specify 'Server Name' task parameter"); return; } if (String.IsNullOrEmpty(execPath)) { TaskManager.WriteWarning("Specify 'Executable Path' task parameter"); return; } // find server by name ServerInfo server = ServerController.GetServerByName(serverName); if (server == null) { TaskManager.WriteWarning(String.Format("Server with the name '{0}' was not found", serverName)); return; } // execute system command WindowsServer winServer = new WindowsServer(); ServiceProviderProxy.ServerInit(winServer, server.ServerId); TaskManager.Write(winServer.ExecuteSystemCommand(execPath, execParams)); }
public static int DeleteFiles(int packageId, string[] files) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) { return(accountCheck); } // place log record TaskManager.StartTask("FILES", "DELETE_FILES", packageId); if (files != null) { foreach (string file in files) { TaskManager.Write(file); } } try { OS.OperatingSystem os = GetOS(packageId); for (int i = 0; i < files.Length; i++) { files[i] = GetFullPackagePath(packageId, files[i]); } // delete files os.DeleteFiles(files); return(0); } catch (Exception ex) { //Log and return a generic error rather than throwing an exception TaskManager.WriteError(ex); return(BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED); } finally { TaskManager.CompleteTask(); } }
private void SendMessage(UserInfo user, string email, string exchange_csv, string sharepoint_csv, string crm_csv, string organization_csv, string lync_csv) { TaskManager.Write("SendMessage"); List <Attachment> attacments = new List <Attachment>(); PrepareAttament("exchange.csv", exchange_csv, attacments); PrepareAttament("sharepoint.csv", sharepoint_csv, attacments); PrepareAttament("lync.csv", lync_csv, attacments); PrepareAttament("crm.csv", crm_csv, attacments); PrepareAttament("organization.csv", organization_csv, attacments); // get letter settings UserSettings settings = UserController.GetUserSettings(user.UserId, UserSettings.HOSTED_SOLUTION_REPORT); string from = settings["From"]; string cc = settings["CC"]; string subject = settings["Subject"]; string body = user.HtmlMail ? settings["HtmlBody"] : settings["TextBody"]; bool isHtml = user.HtmlMail; MailPriority priority = MailPriority.Normal; TaskManager.WriteParameter("from", from); TaskManager.WriteParameter("email", email); TaskManager.WriteParameter("subject", subject); TaskManager.WriteParameter("body", body); int res = MailHelper.SendMessage(from, email, cc, subject, body, priority, isHtml, attacments.ToArray()); if (res == 0) { TaskManager.Write("SendMessage OK"); } else { TaskManager.WriteError("SendMessage error ", "error code", res.ToString()); } TaskManager.WriteParameter("", res); TaskManager.Write("End SendMessage"); }
public void DownloadGalleryWebApplication() { SecurityContext.SetThreadPrincipal(UserId); // TaskManager.StartTask(WebAppGalleryController.TASK_MANAGER_SOURCE, "DOWNLOAD_WEB_APP", GalleryApp.Title); TaskManager.WriteParameter("Version", GalleryApp.Version); TaskManager.WriteParameter("Download URL", GalleryApp.DownloadUrl); TaskManager.WriteParameter("Author", GalleryApp.AuthorName); TaskManager.WriteParameter("Last Updated", GalleryApp.LastUpdated); TaskManager.WriteParameter("Web App ID", WebAppId); // try { // WebServer webServer = WebAppGalleryController.GetAssociatedWebServer(PackageId); // TaskManager.Write("Application package download has been started"); // GalleryWebAppStatus appStatus = webServer.DownloadGalleryApplication(WebAppId); // if (appStatus == GalleryWebAppStatus.Failed) { TaskManager.WriteError("Could not download application package requested"); TaskManager.WriteError("Please check WebsitePanel Server log for further information on this issue"); TaskManager.WriteParameter("Status returned", appStatus); return; } // TaskManager.Write("Application package download has been started successfully"); } catch (Exception ex) { TaskManager.WriteError(ex); } finally { // TaskManager.CompleteTask(); } }
public static int MoveFiles(int packageId, string[] files, string destFolder) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) { return(accountCheck); } // check dest folder exists if (!DirectoryExists(packageId, destFolder)) { return(BusinessErrorCodes.ERROR_FILE_DEST_FOLDER_NONEXISTENT); } // place log record TaskManager.StartTask("FILES", "MOVE_FILES", packageId); TaskManager.WriteParameter("Destination folder", destFolder); if (files != null) { foreach (string file in files) { TaskManager.Write(file); } } try { OS.OperatingSystem os = GetOS(packageId); string destFullFolder = GetFullPackagePath(packageId, destFolder); for (int i = 0; i < files.Length; i++) { string srcFilePath = GetFullPackagePath(packageId, files[i]); string destFilePath = Path.Combine(destFullFolder, srcFilePath.Substring(srcFilePath.LastIndexOf("\\") + 1)); if (srcFilePath == destFilePath) { return(BusinessErrorCodes.ERROR_FILE_COPY_TO_SELF); } //Check that we're not trying to copy a folder into its own subfolder else if (destFilePath.StartsWith(srcFilePath + "\\")) { return(BusinessErrorCodes.ERROR_FILE_COPY_TO_OWN_SUBFOLDER); } else if (os.FileExists(destFilePath) || os.DirectoryExists(destFilePath)) { return(BusinessErrorCodes.ERROR_FILE_MOVE_PATH_ALREADY_EXISTS); } else { os.MoveFile(srcFilePath, destFilePath); } } return(0); } catch (Exception ex) { //Log and return a generic error rather than throwing an exception TaskManager.WriteError(ex); return(BusinessErrorCodes.ERROR_FILE_GENERIC_LOGGED); } finally { TaskManager.CompleteTask(); } }
public static int RestoreInternal(string taskId, int userId, int packageId, int serviceId, int serverId, int storePackageId, string storePackageBackupPath, string storeServerBackupPath) { try { // copy backup from remote or local server string backupFileName = (storePackageId > 0) ? Path.GetFileName(storePackageBackupPath) : Path.GetFileName(storeServerBackupPath); TaskManager.StartTask(taskId, "BACKUP", "RESTORE", backupFileName, SecurityContext.User.UserId); // create temp folder string tempFolder = GetTempBackupFolder(); string backupFileNamePath = Path.Combine(tempFolder, backupFileName); if (storePackageId > 0) { try { int osServiceId = PackageController.GetPackageServiceId(storePackageId, ResourceGroups.Os); if (osServiceId > 0) { OS.OperatingSystem os = new OS.OperatingSystem(); ServiceProviderProxy.Init(os, osServiceId); string remoteBackupPath = FilesController.GetFullPackagePath(storePackageId, storePackageBackupPath); FileStream stream = new FileStream(backupFileNamePath, FileMode.Create, FileAccess.Write); byte[] buffer = new byte[FILE_BUFFER_LENGTH]; int offset = 0; do { // read remote content buffer = os.GetFileBinaryChunk(remoteBackupPath, offset, FILE_BUFFER_LENGTH); // write remote content stream.Write(buffer, 0, buffer.Length); offset += FILE_BUFFER_LENGTH; }while (buffer.Length == FILE_BUFFER_LENGTH); stream.Close(); } } catch (Exception ex) { TaskManager.WriteError(ex, "Can't copy source backup set"); return(0); } } else { backupFileNamePath = storeServerBackupPath; } try { // unpack archive FileUtils.UnzipFiles(backupFileNamePath, tempFolder); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't unzip backup set"); return(0); } // load backup catalog XmlDocument doc = new XmlDocument(); try { doc.Load(Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME)); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't find/open backup catalog file"); return(0); } // validate XML document //if (!ValidateXmlDocument(doc)) //{ // TaskManager.WriteError("Corrupted or altered backup catalog file has been read"); // return 0; //} // get the list of items to restore string condition = ""; if (userId > 0) { // get user spaces List <PackageInfo> packages = new List <PackageInfo>(); packages.AddRange(PackageController.GetMyPackages(userId)); packages.AddRange(PackageController.GetPackages(userId)); List <string> parts = new List <string>(); foreach (PackageInfo package in packages) { parts.Add("@packageId = " + package.PackageId.ToString()); } condition = "[" + String.Join(" or ", parts.ToArray()) + "]"; } else if (packageId > 0) { condition = "[@packageId = " + packageId + "]"; } else if (serviceId > 0) { condition = "[@serviceId = " + serviceId + "]"; } else if (serverId > 0) { // get server services List <ServiceInfo> services = ServerController.GetServicesByServerId(serverId); List <string> parts = new List <string>(); foreach (ServiceInfo service in services) { parts.Add("@serviceId = " + service.ServiceId.ToString()); } condition = "[" + String.Join(" or ", parts.ToArray()) + "]"; } XmlNodeList itemNodes = doc.SelectNodes("Backup/Items/Item" + condition); TaskManager.IndicatorMaximum = itemNodes.Count; TaskManager.IndicatorCurrent = 0; // group items by item types Dictionary <int, List <XmlNode> > groupedItems = new Dictionary <int, List <XmlNode> >(); // sort by groups foreach (XmlNode itemNode in itemNodes) { int itemTypeId = Utils.ParseInt(itemNode.Attributes["itemTypeId"].Value, 0); // add to group if (!groupedItems.ContainsKey(itemTypeId)) { groupedItems[itemTypeId] = new List <XmlNode>(); } groupedItems[itemTypeId].Add(itemNode); } // restore grouped items foreach (int itemTypeId in groupedItems.Keys) { // load item type ServiceProviderItemType itemTypeInfo = PackageController.GetServiceItemType(itemTypeId); if (!itemTypeInfo.Backupable) { continue; } Type itemType = Type.GetType(itemTypeInfo.TypeName); // load group ResourceGroupInfo group = ServerController.GetResourceGroup(itemTypeInfo.GroupId); // instantiate controller IBackupController controller = null; try { controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController; if (controller != null) { // backup items foreach (XmlNode itemNode in groupedItems[itemTypeId]) { int itemId = Utils.ParseInt(itemNode.Attributes["itemId"].Value, 0); string itemName = itemNode.Attributes["itemName"].Value; int itemPackageId = Utils.ParseInt(itemNode.Attributes["packageId"].Value, 0); int itemServiceId = Utils.ParseInt(itemNode.Attributes["serviceId"].Value, 0); TaskManager.Write(String.Format("Restore {0} '{1}'", itemTypeInfo.DisplayName, itemName)); try { int restoreResult = controller.RestoreItem(tempFolder, itemNode, itemId, itemType, itemName, itemPackageId, itemServiceId, group); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't restore item"); } TaskManager.IndicatorCurrent++; } } } catch (Exception ex) { TaskManager.WriteError(ex); } } // delete backup folder and all its contents try { Directory.Delete(tempFolder, true); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't delete temporary backup folder"); return(0); } } catch (Exception ex) { TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } return(0); }
public static int BackupInternal(string taskId, int userId, int packageId, int serviceId, int serverId, string backupFileName, int storePackageId, string storePackageFolder, string storeServerFolder, bool deleteTempBackup) { try { TaskManager.StartTask(taskId, "BACKUP", "BACKUP", backupFileName, SecurityContext.User.UserId); // get the list of items to backup TaskManager.Write("Calculate items to backup"); List <ServiceProviderItem> items = GetBackupItems(userId, packageId, serviceId, serverId); if (items.Count == 0) { return(0); } // group items by item types Dictionary <int, List <ServiceProviderItem> > groupedItems = new Dictionary <int, List <ServiceProviderItem> >(); // sort by groups foreach (ServiceProviderItem item in items) { // add to group if (!groupedItems.ContainsKey(item.TypeId)) { groupedItems[item.TypeId] = new List <ServiceProviderItem>(); } groupedItems[item.TypeId].Add(item); } // temp backup folder string tempFolder = GetTempBackupFolder(); // create backup catalog file StringWriter sw = new StringWriter(); XmlTextWriter writer = new XmlTextWriter(sw); // write backup file header writer.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"utf-8\""); writer.WriteStartElement("Backup"); writer.WriteStartElement("Info"); writer.WriteElementString("Name", backupFileName); writer.WriteElementString("Created", DateTime.Now.ToString("r")); writer.WriteElementString("User", GetLoggedUsername()); writer.WriteEndElement(); // Info // determine the number of items to backup int totalItems = 0; foreach (int itemTypeId in groupedItems.Keys) { // load item type ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId); if (!itemType.Backupable) { continue; } totalItems += groupedItems[itemTypeId].Count; } TaskManager.IndicatorMaximum = totalItems + 2; TaskManager.IndicatorCurrent = 0; // backup grouped items writer.WriteStartElement("Items"); foreach (int itemTypeId in groupedItems.Keys) { // load item type ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId); if (!itemType.Backupable) { continue; } // load group ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId); // instantiate controller IBackupController controller = null; try { if (group.GroupController != null) { controller = Activator.CreateInstance(Type.GetType(group.GroupController)) as IBackupController; } if (controller != null) { // backup items foreach (ServiceProviderItem item in groupedItems[itemTypeId]) { TaskManager.Write(String.Format("Backup {0} of {1} - {2} '{3}'", TaskManager.IndicatorCurrent + 1, totalItems, itemType.DisplayName, item.Name)); try { int backupResult = BackupItem(tempFolder, writer, item, group, controller); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't backup item"); } // increment progress TaskManager.IndicatorCurrent += 1; } } } catch (Exception ex) { TaskManager.WriteError(ex); } } writer.WriteEndElement(); // Items // close catalog writer writer.WriteEndElement(); // Backup writer.Close(); // convert to Xml document XmlDocument doc = new XmlDocument(); doc.LoadXml(sw.ToString()); // sign XML document //SignXmlDocument(doc); // save signed doc to file try { doc.Save(Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME)); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't save backup catalog file: " + Path.Combine(tempFolder, BACKUP_CATALOG_FILE_NAME)); return(0); } TaskManager.Write("Packaging backup..."); // compress backup files string[] zipFiles = Directory.GetFiles(tempFolder); string[] zipFileNames = new string[zipFiles.Length]; for (int i = 0; i < zipFiles.Length; i++) { zipFileNames[i] = Path.GetFileName(zipFiles[i]); } string backupFileNamePath = Path.Combine(tempFolder, backupFileName); try { FileUtils.ZipFiles(backupFileNamePath, tempFolder, zipFileNames); // delete packed files foreach (string zipFile in zipFiles) { File.Delete(zipFile); } } catch (Exception ex) { TaskManager.WriteError(ex, "Can't zip backed up files"); return(0); } TaskManager.IndicatorCurrent += 1; TaskManager.Write("Copying backup..."); // move/copy backup file if (!String.IsNullOrEmpty(storeServerFolder)) { // copy to local folder or UNC try { string destFile = Path.Combine(storeServerFolder, backupFileName); File.Copy(backupFileNamePath, destFile, true); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't copy backup to destination location"); return(0); } } else if (storePackageId > 0) { try { // copy to space folder int osServiceId = PackageController.GetPackageServiceId(storePackageId, ResourceGroups.Os); if (osServiceId > 0) { OS.OperatingSystem os = new OS.OperatingSystem(); ServiceProviderProxy.Init(os, osServiceId); string remoteBackupPath = FilesController.GetFullPackagePath(storePackageId, Path.Combine(storePackageFolder, backupFileName)); FileStream stream = new FileStream(backupFileNamePath, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[FILE_BUFFER_LENGTH]; int readBytes = 0; do { // read package file readBytes = stream.Read(buffer, 0, FILE_BUFFER_LENGTH); if (readBytes < FILE_BUFFER_LENGTH) { // resize buffer Array.Resize <byte>(ref buffer, readBytes); } // write remote backup file os.AppendFileBinaryContent(remoteBackupPath, buffer); }while (readBytes == FILE_BUFFER_LENGTH); stream.Close(); } } catch (Exception ex) { TaskManager.WriteError(ex, "Can't copy backup to destination hosting space"); return(0); } } TaskManager.IndicatorCurrent += 1; // delete backup file if required if (deleteTempBackup) { try { // delete backup folder and all its contents Directory.Delete(tempFolder, true); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't delete temporary backup folder"); return(0); } } BackgroundTask topTask = TaskManager.TopTask; topTask.IndicatorCurrent = topTask.IndicatorMaximum; TaskController.UpdateTask(topTask); } catch (Exception ex) { TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } return(0); }
private void ProcessServiceItems(bool changeState, bool enabled, int serviceId, List <ServiceProviderItem> items) { string methodName = changeState ? "ChangeServiceItemsState" : "DeleteServiceItems"; int PACKET_SIZE = 10; int ATTEMPTS = 3; TaskManager.Write(String.Format("Start analyze {0} service ({1} items)", serviceId, items.Count)); try { // convert items to SoapObjects by packets of 0 int startItem = 0; List <SoapServiceProviderItem> objItems = new List <SoapServiceProviderItem>(); for (int i = 0; i < items.Count; i++) { // add to the packet objItems.Add(SoapServiceProviderItem.Wrap(items[i])); if (((i > 0) && (i % PACKET_SIZE == 0)) || i == (items.Count - 1)) // packet is ready { if (objItems.Count == 0) { continue; } int attempt = 0; bool success = false; while (attempt < ATTEMPTS) { // increment attempt attempt++; try { // send packet for calculation // invoke service provider TaskManager.Write(String.Format("Invoke {0} method ('{1}' - '{2}' items) - {3} attempt", methodName, items[startItem].Name, items[i].Name, attempt)); ServiceProvider prov = new ServiceProvider(); ServiceProviderProxy.Init(prov, serviceId); if (changeState) { prov.ChangeServiceItemsState(objItems.ToArray(), enabled); } else { prov.DeleteServiceItems(objItems.ToArray()); } // exit from the loop success = true; break; } catch (Exception ex) { TaskManager.WriteWarning(ex.ToString()); } } if (!success) { throw new Exception("The number of attemtps has been reached. The whole operation aborted."); } // reset packet counter startItem = i + 1; objItems.Clear(); } } // end for items } catch (Exception ex) { // log exception TaskManager.WriteWarning(ex.ToString()); } TaskManager.Write(String.Format("End analyze {0} service ({1} items)", serviceId, items.Count)); }
public override void DoWork() { // Input parameters: // - DISKSPACE_OVERUSED // - BANDWIDTH_OVERUSED BackgroundTask topTask = TaskManager.TopTask; // get the list of all packages List <PackageInfo> packages = PackageController.GetPackagePackages(topTask.PackageId, false); TaskManager.Write("Packages to verify: " + packages.Count.ToString()); bool checkMSSQL = (String.Compare((string)topTask.GetParamValue("MSSQL_OVERUSED"), "true", true) == 0); bool checkMySQL = (String.Compare((string)topTask.GetParamValue("MYSQL_OVERUSED"), "true", true) == 0); bool sendWarningEmail = Convert.ToBoolean(topTask.GetParamValue("SEND_WARNING_EMAIL")); bool sendOverusedEmail = Convert.ToBoolean(topTask.GetParamValue("SEND_OVERUSED_EMAIL")); int warningUsageThreshold = Convert.ToInt32(topTask.GetParamValue("WARNING_USAGE_THRESHOLD")); int overusedUsageThreshold = Convert.ToInt32(topTask.GetParamValue("OVERUSED_USAGE_THRESHOLD")); string warningMailFrom = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_FROM")); string warningMailBcc = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_BCC")); string warningMailSubject = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_SUBJECT")); string warningMailBody = Convert.ToString(topTask.GetParamValue("WARNING_MAIL_BODY")); string overusedMailFrom = Convert.ToString(topTask.GetParamValue("OVERUSED_MAIL_FROM")); string overusedMailBcc = Convert.ToString(topTask.GetParamValue("OVERUSED_MAIL_BCC")); string overusedMailSubject = Convert.ToString(topTask.GetParamValue("OVERUSED_MAIL_SUBJECT")); string overusedMailBody = Convert.ToString(topTask.GetParamValue("OVERUSED_MAIL_BODY")); int overusedPackages = 0; foreach (PackageInfo package in packages) { UserInfo userInfo = UserController.GetUser(package.UserId); List <DatabaseQuota> quotaMSSQL = new List <DatabaseQuota>(); List <DatabaseQuota> quotaMYSQL = new List <DatabaseQuota>(); if (checkMSSQL || checkMySQL) { QuotaValueInfo dsQuota = null; DataSet Diskspace = PackageController.GetPackageDiskspace(package.PackageId); foreach (DataRow spaceRow in Diskspace.Tables[0].Rows) { string groupName = spaceRow["GroupName"].ToString(); if (checkMSSQL && groupName.ToUpper().Contains("MSSQL")) { dsQuota = PackageController.GetPackageQuota(package.PackageId, groupName + ".MaxDatabaseSize"); if (dsQuota.QuotaAllocatedValue > 0) { int databaseSpaceUsage = Convert.ToInt32(spaceRow["Diskspace"]) * 100 / dsQuota.QuotaAllocatedValue; quotaMSSQL.Add(new DatabaseQuota(groupName.ToUpper().Replace("MSSQL", "SQL Server "), Convert.ToInt32(spaceRow["Diskspace"]), dsQuota.QuotaAllocatedValue, databaseSpaceUsage < warningUsageThreshold, databaseSpaceUsage < overusedUsageThreshold)); } } if (checkMySQL && groupName.ToUpper().Contains("MYSQL")) { dsQuota = PackageController.GetPackageQuota(package.PackageId, groupName + ".MaxDatabaseSize"); if (dsQuota.QuotaAllocatedValue > 0) { int databaseSpaceUsage = Convert.ToInt32(spaceRow["Diskspace"]) * 100 / dsQuota.QuotaAllocatedValue; quotaMYSQL.Add(new DatabaseQuota(groupName.ToUpper().Replace("MYSQL", "MySQL "), Convert.ToInt32(spaceRow["Diskspace"]), dsQuota.QuotaAllocatedValue, databaseSpaceUsage < warningUsageThreshold, databaseSpaceUsage < overusedUsageThreshold)); } } } string userName = String.Format("{0} {1} ({2})/{3}", userInfo.FirstName, userInfo.LastName, userInfo.Username, userInfo.Email); bool notifyOverusedByMail = false; bool notifyWarningByMail = false; List <string> formatItems = new List <string>(); List <string> formatWarningThreshold = new List <string>(); List <string> formatOverusedThreshold = new List <string>(); // add Microsoft SQL usage if enabled if (checkMSSQL) { foreach (DatabaseQuota q in quotaMSSQL) { if (!q.BelowWarningThreshold || !q.BelowUsageThreshold) { formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, q.ProviderName, q.SpaceUsed, q.SpaceUsed * 100 / q.SpaceAllocated)); } if (!q.BelowWarningThreshold) { formatWarningThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated)); notifyWarningByMail = true; } if (!q.BelowUsageThreshold) { formatOverusedThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated)); notifyOverusedByMail = true; } } } // add MySQL usage if enabled if (checkMySQL) { foreach (DatabaseQuota q in quotaMYSQL) { if (!q.BelowWarningThreshold || !q.BelowUsageThreshold) { formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, q.ProviderName, q.SpaceUsed, (q.SpaceUsed * 100) / q.SpaceAllocated)); } if (!q.BelowWarningThreshold) { formatWarningThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated)); notifyWarningByMail = true; } if (!q.BelowUsageThreshold) { formatOverusedThreshold.Add(String.Format(ALLOC_FORMAT_STRING, q.ProviderName, q.SpaceAllocated)); notifyOverusedByMail = true; } } } // build usage strings string usage = String.Join("\n", formatItems.ToArray()); string usageWarning = String.Join("\n", formatWarningThreshold.ToArray()); string usageOverused = String.Join("\n", formatOverusedThreshold.ToArray()); string warningMailSubjectProcessed = ReplaceVariables(warningMailSubject, usageWarning, usage, package.PackageName, userName); string warningMailBodyProcessed = ReplaceVariables(warningMailBody, usageWarning, usage, package.PackageName, userName); string overusedMailSubjectProcessed = ReplaceVariables(overusedMailSubject, usageOverused, usage, package.PackageName, userName); string overusedMailBodyProcessed = ReplaceVariables(overusedMailBody, usageOverused, usage, package.PackageName, userName); // Send email notifications if (sendWarningEmail && notifyWarningByMail) { // Send warning email. this.SendEmail(warningMailFrom, userInfo.Email, warningMailBcc, warningMailSubjectProcessed, warningMailBodyProcessed, false); } if (sendOverusedEmail && notifyOverusedByMail) { // Send overused email. this.SendEmail(overusedMailFrom, userInfo.Email, overusedMailBcc, overusedMailSubjectProcessed, overusedMailBodyProcessed, false); } if (notifyOverusedByMail) { overusedPackages++; } } } // log results TaskManager.Write("Total packages overused: " + overusedPackages.ToString()); }
public static int ImportItemsInternal(string taskId, int packageId, string[] items) { PackageInfo package = PackageController.GetPackage(packageId); TaskManager.StartTask(taskId, "IMPORT", "IMPORT", package.PackageName, packageId); TaskManager.IndicatorMaximum = items.Length; TaskManager.IndicatorCurrent = 0; Dictionary <int, List <string> > groupedItems = new Dictionary <int, List <string> >(); List <string> customItems = new List <string>(); // sort by groups foreach (string item in items) { string[] itemParts = item.Split('|'); if (!item.StartsWith("+")) { int itemTypeId = Utils.ParseInt(itemParts[0], 0); string itemName = itemParts[1]; // add to group if (!groupedItems.ContainsKey(itemTypeId)) { groupedItems[itemTypeId] = new List <string>(); } groupedItems[itemTypeId].Add(itemName); } else { switch (itemParts[0]) { case ("+100"): if (itemParts.Length > 2) { customItems.Add(item); } break; } } } // import each group foreach (int itemTypeId in groupedItems.Keys) { // load item type ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId); // load group ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId); // instantiate controller IImportController ctrl = null; try { ctrl = Activator.CreateInstance(Type.GetType(group.GroupController)) as IImportController; if (ctrl != null) { foreach (string itemName in groupedItems[itemTypeId]) { TaskManager.Write(String.Format("Import {0} '{1}'", itemType.DisplayName, itemName)); try { // perform import ctrl.ImportItem(packageId, itemTypeId, Type.GetType(itemType.TypeName), group, itemName); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't import item"); } TaskManager.IndicatorCurrent++; } } } catch { /* do nothing */ } } foreach (string s in customItems) { try { string[] sParts = s.Split('|'); switch (sParts[0]) { case "+100": TaskManager.Write(String.Format("Import {0}", sParts[4])); int result = WebServerController.ImporHostHeader(int.Parse(sParts[2], 0), int.Parse(sParts[3], 0), int.Parse(sParts[5], 0)); if (result < 0) { TaskManager.WriteError(String.Format("Failed to Import {0} ,error: {1}: ", sParts[4], result.ToString())); } break; } } catch { /* do nothing */ } TaskManager.IndicatorCurrent++; } TaskManager.IndicatorCurrent = items.Length; TaskManager.CompleteTask(); return(0); }
public override void DoWork() { // Input parameters: // - FILE_PATH // - FTP_SERVER // - FTP_USERNAME // - FTP_PASSWORD // - FTP_FOLDER // get input parameters string filePath = (string)TaskManager.TaskParameters["FILE_PATH"]; string ftpServer = (string)TaskManager.TaskParameters["FTP_SERVER"]; string ftpUsername = (string)TaskManager.TaskParameters["FTP_USERNAME"]; string ftpPassword = (string)TaskManager.TaskParameters["FTP_PASSWORD"]; string ftpFolder = (string)TaskManager.TaskParameters["FTP_FOLDER"]; // check input parameters if (String.IsNullOrEmpty(filePath)) { TaskManager.WriteWarning("Specify 'File' task parameter"); return; } if (String.IsNullOrEmpty(ftpServer)) { TaskManager.WriteWarning("Specify 'FTP Server' task parameter"); return; } // substitute parameters DateTime d = DateTime.Now; string date = d.ToString("yyyyMMdd"); string time = d.ToString("HHmm"); filePath = Utils.ReplaceStringVariable(filePath, "date", date); filePath = Utils.ReplaceStringVariable(filePath, "time", time); // build FTP command file StringBuilder sb = new StringBuilder(); StringWriter writer = new StringWriter(sb); // FTP server writer.WriteLine("open " + ftpServer); // check if anonymous mode if (String.IsNullOrEmpty(ftpUsername)) { ftpUsername = "******"; ftpPassword = "******"; } // FTP username/password writer.WriteLine(ftpUsername); writer.WriteLine(ftpPassword); // check if we need to change remote folder if (!String.IsNullOrEmpty(ftpFolder)) { writer.WriteLine("cd " + ftpFolder.Replace("\\", "/")); } // file to send writer.WriteLine("binary"); writer.WriteLine("put " + FilesController.GetFullPackagePath(TaskManager.PackageId, filePath)); // bye writer.WriteLine("bye"); string cmdBatch = sb.ToString(); // create temp file in user space string cmdPath = Utils.GetRandomString(10) + ".txt"; string fullCmdPath = FilesController.GetFullPackagePath(TaskManager.PackageId, cmdPath); // upload batch FilesController.UpdateFileBinaryContent(TaskManager.PackageId, cmdPath, Encoding.UTF8.GetBytes(cmdBatch)); // execute system command // load OS service int serviceId = PackageController.GetPackageServiceId(TaskManager.PackageId, ResourceGroups.Os); // load service ServiceInfo service = ServerController.GetServiceInfo(serviceId); if (service == null) { return; } WindowsServer winServer = new WindowsServer(); ServiceProviderProxy.ServerInit(winServer, service.ServerId); TaskManager.Write(winServer.ExecuteSystemCommand("ftp.exe", "-s:" + fullCmdPath)); // delete batch file FilesController.DeleteFiles(TaskManager.PackageId, new string[] { cmdPath }); }
public override void DoWork() { // Input parameters: // - DISKSPACE_OVERUSED // - BANDWIDTH_OVERUSED // get the list of all packages List <PackageInfo> packages = PackageController.GetPackagePackages(TaskManager.PackageId, false); TaskManager.Write("Packages to verify: " + packages.Count.ToString()); bool checkDiskspace = (String.Compare((string)TaskManager.TaskParameters["DISKSPACE_OVERUSED"], "true", true) == 0); bool checkBandwidth = (String.Compare((string)TaskManager.TaskParameters["BANDWIDTH_OVERUSED"], "true", true) == 0); bool suspendOverused = Convert.ToBoolean(TaskManager.TaskParameters["SUSPEND_OVERUSED"]); bool sendWarningEmail = Convert.ToBoolean(TaskManager.TaskParameters["SEND_WARNING_EMAIL"]); bool sendSuspensionEmail = Convert.ToBoolean(TaskManager.TaskParameters["SEND_SUSPENSION_EMAIL"]); int warningUsageThreshold = Convert.ToInt32(TaskManager.TaskParameters["WARNING_USAGE_THRESHOLD"]); int suspensionUsageThreshold = Convert.ToInt32(TaskManager.TaskParameters["SUSPENSION_USAGE_THRESHOLD"]); string warningMailFrom = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_FROM"]); string warningMailBcc = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_BCC"]); string warningMailSubject = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_SUBJECT"]); string warningMailBody = Convert.ToString(TaskManager.TaskParameters["WARNING_MAIL_BODY"]); string suspensionMailFrom = Convert.ToString(TaskManager.TaskParameters["SUSPENSION_MAIL_FROM"]); string suspensionMailBcc = Convert.ToString(TaskManager.TaskParameters["SUSPENSION_MAIL_BCC"]); string suspensionMailSubject = Convert.ToString(TaskManager.TaskParameters["SUSPENSION_MAIL_SUBJECT"]); string suspensionMailBody = Convert.ToString(TaskManager.TaskParameters["SUSPENSION_MAIL_BODY"]); int suspendedPackages = 0; foreach (PackageInfo package in packages) { bool isBandwidthBelowWarningThreshold = true; bool isBandwidthBelowSuspensionThreshold = true; bool isDiskSpaceBelowWarningThreshold = true; bool isDiskSpaceBelowSuspensionThreshold = true; UserInfo userInfo = UserController.GetUser(package.UserId); int diskSpaceUsage = 0; int bandwidthUsage = 0; // disk space if (checkDiskspace) { QuotaValueInfo dsQuota = PackageController.GetPackageQuota(package.PackageId, Quotas.OS_DISKSPACE); if (dsQuota.QuotaAllocatedValue > 0) { diskSpaceUsage = (dsQuota.QuotaUsedValue * 100 / dsQuota.QuotaAllocatedValue); isDiskSpaceBelowWarningThreshold = diskSpaceUsage < warningUsageThreshold; isDiskSpaceBelowSuspensionThreshold = diskSpaceUsage < suspensionUsageThreshold; } } // bandwidth if (checkBandwidth) { QuotaValueInfo bwQuota = PackageController.GetPackageQuota(package.PackageId, Quotas.OS_BANDWIDTH); if (bwQuota.QuotaAllocatedValue > 0) { bandwidthUsage = (bwQuota.QuotaUsedValue * 100 / bwQuota.QuotaAllocatedValue); isBandwidthBelowWarningThreshold = bandwidthUsage < warningUsageThreshold; isBandwidthBelowSuspensionThreshold = bandwidthUsage < suspensionUsageThreshold; } } string userName = String.Format("{0} {1} ({2})/{3}", userInfo.FirstName, userInfo.LastName, userInfo.Username, userInfo.Email); // List <string> formatItems = new List <string>(); // add diskspace usage if enabled if (checkDiskspace) { formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, diskSpaceUsage)); } // add bandwidth usage if enabled if (checkBandwidth) { formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, bandwidthUsage)); } // build usage string string usage = String.Join(", ", formatItems.ToArray()); // cleanup items formatItems.Clear(); // add diskspace warning max usage if (checkDiskspace) { formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, warningUsageThreshold)); } // add bandwidth warning max usage if (checkBandwidth) { formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, warningUsageThreshold)); } // build warning max usage string string warningMaxUsage = String.Join(", ", formatItems.ToArray()); // cleanup items formatItems.Clear(); // add diskspace suspension max usage if (checkDiskspace) { formatItems.Add(String.Format(DISKSPACE_FORMAT_STRING, suspensionUsageThreshold)); } // add bandwidth suspension max usage if (checkBandwidth) { formatItems.Add(String.Format(BANDWIDTH_FORMAT_STRING, suspensionUsageThreshold)); } // build suspension max usage string string suspensionMaxUsage = String.Join(", ", formatItems.ToArray()); string warningMailSubjectProcessed = ReplaceVariables(warningMailSubject, warningMaxUsage, usage, package.PackageName, userName); string warningMailBodyProcessed = ReplaceVariables(warningMailBody, warningMaxUsage, usage, package.PackageName, userName); string suspensionMailSubjectProcessed = ReplaceVariables(suspensionMailSubject, suspensionMaxUsage, usage, package.PackageName, userName); string suspensionMailBodyProcessed = ReplaceVariables(suspensionMailBody, suspensionMaxUsage, usage, package.PackageName, userName); // Send email notifications if (sendWarningEmail && (!isDiskSpaceBelowWarningThreshold || !isBandwidthBelowWarningThreshold)) { // Send warning email. this.SendEmail(warningMailFrom, userInfo.Email, warningMailBcc, warningMailSubjectProcessed, warningMailBodyProcessed, false); } if (sendSuspensionEmail && (!isDiskSpaceBelowSuspensionThreshold || !isBandwidthBelowSuspensionThreshold)) { // Send suspension email. this.SendEmail(suspensionMailFrom, userInfo.Email, suspensionMailBcc, suspensionMailSubjectProcessed, suspensionMailBodyProcessed, false); } // suspend package if required if (suspendOverused && (!isDiskSpaceBelowSuspensionThreshold || !isBandwidthBelowSuspensionThreshold)) { suspendedPackages++; // load user details UserInfo user = PackageController.GetPackageOwner(package.PackageId); TaskManager.Write(String.Format("Suspend space '{0}' of user '{1}'", package.PackageName, user.Username)); try { PackageController.ChangePackageStatus(null, package.PackageId, PackageStatus.Suspended, false); } catch (Exception ex) { TaskManager.WriteError("Error while changing space status: " + ex.ToString()); } } } // log results TaskManager.Write("Total packages suspended: " + suspendedPackages.ToString()); }
public static int ImportItemsInternal(string taskId, int packageId, string[] items) { PackageInfo package = PackageController.GetPackage(packageId); TaskManager.StartTask(taskId, "IMPORT", "IMPORT", package.PackageName); TaskManager.ItemId = packageId; TaskManager.IndicatorMaximum = items.Length; TaskManager.IndicatorCurrent = 0; Dictionary <int, List <string> > groupedItems = new Dictionary <int, List <string> >(); // sort by groups foreach (string item in items) { string[] itemParts = item.Split('|'); int itemTypeId = Utils.ParseInt(itemParts[0], 0); string itemName = itemParts[1]; // add to group if (!groupedItems.ContainsKey(itemTypeId)) { groupedItems[itemTypeId] = new List <string>(); } groupedItems[itemTypeId].Add(itemName); } // import each group foreach (int itemTypeId in groupedItems.Keys) { // load item type ServiceProviderItemType itemType = PackageController.GetServiceItemType(itemTypeId); // load group ResourceGroupInfo group = ServerController.GetResourceGroup(itemType.GroupId); // instantiate controller IImportController ctrl = null; try { ctrl = Activator.CreateInstance(Type.GetType(group.GroupController)) as IImportController; if (ctrl != null) { foreach (string itemName in groupedItems[itemTypeId]) { TaskManager.Write(String.Format("Import {0} '{1}'", itemType.DisplayName, itemName)); try { // perform import ctrl.ImportItem(packageId, itemTypeId, Type.GetType(itemType.TypeName), group, itemName); } catch (Exception ex) { TaskManager.WriteError(ex, "Can't import item"); } TaskManager.IndicatorCurrent++; } } } catch { /* do nothing */ } } TaskManager.CompleteTask(); return(0); }