예제 #1
0
        public static void StartTask(string taskId, string source, string taskName, object itemName)
        {
            // create new task object
            BackgroundTask task = new BackgroundTask();

            task.TaskId          = String.IsNullOrEmpty(taskId) ? Guid.NewGuid().ToString("N") : taskId;
            task.UserId          = SecurityContext.User.UserId;
            task.EffectiveUserId = SecurityContext.User.IsPeer ? SecurityContext.User.OwnerId : task.UserId;
            task.StartDate       = DateTime.Now;
            task.Source          = source;
            task.TaskName        = taskName;
            task.ItemName        = itemName != null?itemName.ToString() : "";

            task.Severity   = 0; //info
            task.TaskThread = Thread.CurrentThread;

            // new "parent" task?
            if (TasksStack.Count == 0)
            {
                // register task globally
                tasks[task.TaskId] = task;
            }
            else
            {
                // child task
                // add log record to the root task
                BackgroundTaskLogRecord logRecord = new BackgroundTaskLogRecord();
                logRecord.InnerTaskStart = true;
                logRecord.Text           = source + "_" + taskName;
                logRecord.TextParameters = new string[] { itemName != null?itemName.ToString() : "" };
                logRecord.TextIdent      = TasksStack.Count - 1;
                RootTask.LogRecords.Add(logRecord);

                // change log records destination
                // for nested task
                task.LogRecords = RootTask.LogRecords;
            }

            // call event handler
            CallTaskEventHandler(task, false);

            // push task on the stack
            TasksStack.Add(task);
        }
예제 #2
0
 private static void StopProcess(BackgroundTask task)
 {
     if (_taskThreadsDictionary.ContainsKey(task.Id))
     {
         if (_taskThreadsDictionary[task.Id] != null)
         {
             if (_taskThreadsDictionary[task.Id].IsAlive)
             {
                 if (!task.Completed)
                 {
                     _taskThreadsDictionary[task.Id].Abort();
                 }
                 _taskThreadsDictionary[task.Id] = null;
             }
         }
         Thread deleted;
         _taskThreadsDictionary.TryRemove(task.Id, out deleted);
     }
 }
예제 #3
0
        public static BackgroundTask GetTaskWithLogRecords(string taskId, DateTime startLogTime)
        {
            BackgroundTask task = GetTask(taskId);

            if (task == null)
            {
                return(null);
            }

            // fill log records
            foreach (BackgroundTaskLogRecord record in task.LogRecords)
            {
                if (record.Date >= startLogTime)
                {
                    task.LastLogRecords.Add(record);
                }
            }

            return(task);
        }
예제 #4
0
        private void SendMailMessage(string url, string message, string content)
        {
            BackgroundTask topTask = TaskManager.TopTask;

            // input parameters
            string mailFrom    = (string)topTask.GetParamValue("MAIL_FROM");
            string mailTo      = (string)topTask.GetParamValue("MAIL_TO");
            string mailSubject = (string)topTask.GetParamValue("MAIL_SUBJECT");
            string mailBody    = (string)topTask.GetParamValue("MAIL_BODY");

            if (String.IsNullOrEmpty(mailTo))
            {
                TaskManager.WriteWarning("The e-mail message has not been sent because 'Mail To' is empty.");
            }
            else
            {
                if (String.IsNullOrEmpty(mailFrom))
                {
                    mailFrom = "automatic@localhost";
                }

                if (!String.IsNullOrEmpty(mailSubject))
                {
                    mailSubject = Utils.ReplaceStringVariable(mailSubject, "url", url);
                }

                if (!String.IsNullOrEmpty(mailBody))
                {
                    mailBody = Utils.ReplaceStringVariable(mailBody, "url", url);
                    mailBody = Utils.ReplaceStringVariable(mailBody, "message", message);
                    mailBody = Utils.ReplaceStringVariable(mailBody, "content", content);
                }
                else
                {
                    mailBody = message;
                }

                // send mail message
                MailHelper.SendMessage(mailFrom, mailTo, mailSubject, mailBody, false);
            }
        }
예제 #5
0
        public static void StopTask(string taskId)
        {
            BackgroundTask task = (BackgroundTask)tasks[taskId];

            if (task == null)
            {
                return;
            }

            try
            {
                task.TaskThread.Abort();
            }
            catch
            {
                // nope
            }

            // remove it from stack
            tasks.Remove(taskId);
        }
예제 #6
0
        public override void DoWork()
        {
            // Input parameters:
            //  - MAIL_FROM
            //  - MAIL_TO
            //  - MAIL_SUBJECT
            //  - MAIL_BODY

            BackgroundTask topTask = TaskManager.TopTask;

            // get input parameters
            string mailFrom    = (string)topTask.GetParamValue("MAIL_FROM");
            string mailTo      = (string)topTask.GetParamValue("MAIL_TO");
            string mailSubject = (string)topTask.GetParamValue("MAIL_SUBJECT");
            string mailBody    = (string)topTask.GetParamValue("MAIL_BODY");

            // check input parameters
            if (String.IsNullOrEmpty(mailFrom))
            {
                TaskManager.WriteWarning("Specify 'Mail From' task parameter");
                return;
            }

            if (String.IsNullOrEmpty(mailTo))
            {
                TaskManager.WriteWarning("Specify 'Mail To' task parameter");
                return;
            }

            if (String.IsNullOrEmpty(mailSubject))
            {
                TaskManager.WriteWarning("Specify 'Mail Subject' task parameter");
                return;
            }

            // send mail message
            MailHelper.SendMessage(mailFrom, mailTo, mailSubject, mailBody, false);
        }
예제 #7
0
        public override void DoWork()
        {
            // Input parameters:
            //  - FOLDER
            //  - ZIP_FILE

            BackgroundTask topTask = TaskManager.TopTask;

            // get input parameters
            string filesList = (string)topTask.GetParamValue("FOLDER");
            string zipFile   = (string)topTask.GetParamValue("ZIP_FILE");

            // check input parameters
            if (String.IsNullOrEmpty(filesList))
            {
                TaskManager.WriteWarning("Specify 'Files List' task parameter");
                return;
            }

            if (String.IsNullOrEmpty(zipFile))
            {
                TaskManager.WriteWarning("Specify 'Zip File' task parameter");
                return;
            }

            // substitute parameters
            DateTime d    = DateTime.Now;
            string   date = d.ToString("yyyyMMdd");
            string   time = d.ToString("HHmm");

            filesList = Utils.ReplaceStringVariable(filesList, "date", date);
            filesList = Utils.ReplaceStringVariable(filesList, "time", time);
            zipFile   = Utils.ReplaceStringVariable(zipFile, "date", date);
            zipFile   = Utils.ReplaceStringVariable(zipFile, "time", time);

            // zip files and folders
            FilesController.ZipFiles(topTask.PackageId, new string[] { filesList }, zipFile);
        }
예제 #8
0
        public static bool UpdateTask(BackgroundTask task)
        {
            if (task.Status == BackgroundTaskStatus.Abort)
            {
                DeleteBackgroundTasks(task.Guid);

                return(false);
            }

            if (task.Completed)
            {
                DeleteBackgroundTask(task.Id);

                return(false);
            }

            DataProvider.UpdateBackgroundTask(task.Guid, task.Id, task.ScheduleId, task.PackageId, task.TaskName, task.ItemId,
                                              task.ItemName, task.FinishDate, task.IndicatorCurrent,
                                              task.IndicatorMaximum, task.MaximumExecutionTime, task.Source,
                                              task.Severity, task.Completed, task.NotifyOnComplete, task.Status);

            return(true);
        }
예제 #9
0
        /// <summary>
        /// Performs actual backup.
        /// </summary>
        public override void DoWork()
        {
            string backupFileName;
            int    storePackageId;
            string storePackageFolder;
            string storeServerFolder;
            bool   deleteTempBackup;

            BackgroundTask topTask = TaskManager.TopTask;

            try
            {
                backupFileName     = (string)topTask.GetParamValue("BACKUP_FILE_NAME");
                storePackageId     = Convert.ToInt32(topTask.GetParamValue("STORE_PACKAGE_ID"));
                storePackageFolder = (string)topTask.GetParamValue("STORE_PACKAGE_FOLDER");
                storeServerFolder  = (string)topTask.GetParamValue("STORE_SERVER_FOLDER");
                deleteTempBackup   = Convert.ToBoolean(topTask.GetParamValue("DELETE_TEMP_BACKUP"));
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex, "Some parameters are absent or have incorrect value.");
                return;
            }

            try
            {
                PackageInfo package = PackageController.GetPackage(topTask.PackageId);
                // We do not take into account service id as long as scheduled tasks run against packages.
                BackupController.Backup(false, "BackupTask", package.UserId, package.PackageId, 0, 0,
                                        backupFileName, storePackageId, storePackageFolder, storeServerFolder, deleteTempBackup);
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex, "Failed to do backup.");
            }
        }
예제 #10
0
        public override void DoWork()
        {
            BackgroundTask topTask            = TaskManager.TopTask;
            var            domainUsers        = new Dictionary <int, UserInfo>();
            var            checkedDomains     = new List <DomainInfo>();
            var            expiredDomains     = new List <DomainInfo>();
            var            nonExistenDomains  = new List <DomainInfo>();
            var            allDomains         = new List <DomainInfo>();
            var            allTopLevelDomains = new List <DomainInfo>();

            // get input parameters
            int  daysBeforeNotify;
            bool sendEmailNotifcation     = Convert.ToBoolean(topTask.GetParamValue(EnableNotification));
            bool includeNonExistenDomains = Convert.ToBoolean(topTask.GetParamValue(IncludeNonExistenDomains));

            // check input parameters
            if (String.IsNullOrEmpty((string)topTask.GetParamValue("MAIL_TO")))
            {
                TaskManager.WriteWarning("The e-mail message has not been sent because 'Mail To' is empty.");
                return;
            }

            int.TryParse((string)topTask.GetParamValue(DaysBeforeNotify), out daysBeforeNotify);

            var user = UserController.GetUser(topTask.EffectiveUserId);

            var packages = GetUserPackages(user.UserId, user.Role);


            foreach (var package in packages)
            {
                var domains = ServerController.GetDomains(package.PackageId);

                allDomains.AddRange(domains);

                domains = domains.Where(x => !x.IsSubDomain && !x.IsDomainPointer).ToList(); //Selecting top-level domains

                allTopLevelDomains.AddRange(domains);

                var domainUser = UserController.GetUser(package.UserId);

                if (!domainUsers.ContainsKey(package.PackageId))
                {
                    domainUsers.Add(package.PackageId, domainUser);
                }

                foreach (var domain in domains)
                {
                    if (checkedDomains.Any(x => x.DomainId == domain.DomainId))
                    {
                        continue;
                    }

                    checkedDomains.Add(domain);

                    ServerController.UpdateDomainWhoisData(domain);

                    if (CheckDomainExpiration(domain.ExpirationDate, daysBeforeNotify))
                    {
                        expiredDomains.Add(domain);
                    }

                    if (domain.ExpirationDate == null && domain.CreationDate == null)
                    {
                        nonExistenDomains.Add(domain);
                    }

                    Thread.Sleep(100);
                }
            }

            var subDomains = allDomains.Where(x => !checkedDomains.Any(z => z.DomainId == x.DomainId && z.ExpirationDate != null)).GroupBy(p => p.DomainId).Select(g => g.First()).ToList();

            foreach (var subDomain in subDomains)
            {
                var mainDomain = checkedDomains.Where(x => subDomain.DomainId != x.DomainId && subDomain.DomainName.ToLowerInvariant().Contains(x.DomainName.ToLowerInvariant())).OrderByDescending(s => s.DomainName.Length).FirstOrDefault();;

                if (mainDomain != null)
                {
                    ServerController.UpdateDomainWhoisData(subDomain, mainDomain.CreationDate, mainDomain.ExpirationDate, mainDomain.RegistrarName);

                    var nonExistenDomain = nonExistenDomains.FirstOrDefault(x => subDomain.DomainId == x.DomainId);

                    if (nonExistenDomain != null)
                    {
                        nonExistenDomains.Remove(nonExistenDomain);
                    }

                    Thread.Sleep(100);
                }
            }

            expiredDomains = expiredDomains.GroupBy(p => p.DomainId).Select(g => g.First()).ToList();

            if (expiredDomains.Count > 0 && sendEmailNotifcation)
            {
                SendMailMessage(user, expiredDomains, domainUsers, nonExistenDomains, includeNonExistenDomains);
            }
        }
예제 #11
0
        public int InstallWebApplication(InstallationInfo inst)
        {
            // place log record
            TaskManager.StartTask("APP_INSTALLER", "INSTALL_APPLICATION", inst.PackageId);

            TaskManager.WriteParameter("Virtual directory", inst.VirtualDir);
            TaskManager.WriteParameter("Database group", inst.DatabaseGroup);

            try
            {
                // get application info
                app = GetApplication(inst.PackageId, inst.ApplicationId);

                BackgroundTask topTask = TaskManager.TopTask;

                topTask.ItemName = app.Name;

                TaskController.UpdateTask(topTask);

                // check web site for existance
                WebSite webSite = WebServerController.GetWebSite(inst.WebSiteId);

                if (webSite == null)
                {
                    return(BusinessErrorCodes.ERROR_WEB_INSTALLER_WEBSITE_NOT_EXISTS);
                }

                TaskManager.WriteParameter("Web site", webSite.Name);

                webSiteName = webSite.Name;
                siteId      = webSite.SiteId;

                // change web site properties if required
                if (String.IsNullOrEmpty(inst.VirtualDir))
                {
                    ChangeVirtualDirectoryProperties(webSite, app.WebSettings);
                    WebServerController.UpdateWebSite(webSite);
                }

                // get OS service
                int osId = PackageController.GetPackageServiceId(inst.PackageId, "os");
                os = new OS.OperatingSystem();
                ServiceProviderProxy.Init(os, osId);

                // get remote content path
                contentPath = webSite.ContentPath;

                // create virtual dir if required
                if (!String.IsNullOrEmpty(inst.VirtualDir))
                {
                    // check if the required virtual dir already exists
                    contentPath = Path.Combine(contentPath, inst.VirtualDir);

                    WebVirtualDirectory vdir = null;
                    int result = WebServerController.AddVirtualDirectory(inst.WebSiteId, inst.VirtualDir, contentPath);
                    if (result == BusinessErrorCodes.ERROR_VDIR_ALREADY_EXISTS)
                    {
                        // the directory alredy exists
                        vdir = WebServerController.GetVirtualDirectory(
                            inst.WebSiteId, inst.VirtualDir);

                        contentPath = vdir.ContentPath;
                    }
                    else
                    {
                        vdir = WebServerController.GetVirtualDirectory(
                            inst.WebSiteId, inst.VirtualDir);

                        inst[PROPERTY_VDIR_CREATED] = "True";
                    }

                    // change virtual directory properties if required
                    ChangeVirtualDirectoryProperties(vdir, app.WebSettings);
                    WebServerController.UpdateVirtualDirectory(inst.WebSiteId, vdir);
                }

                // deploy application codebase ZIP and then unpack it
                string codebasePath       = app.Codebase;
                string remoteCodebasePath = Path.Combine(contentPath, Path.GetFileName(app.Codebase));

                // make content path absolute
                string absContentPath = FilesController.GetFullPackagePath(inst.PackageId, contentPath);

                // save content path
                inst[PROPERTY_CONTENT_PATH]          = contentPath;
                inst[PROPERTY_ABSOLUTE_CONTENT_PATH] = absContentPath;

                // copy ZIP to the target server
                FileStream stream        = File.OpenRead(codebasePath);
                int        BUFFER_LENGTH = 5000000;

                byte[] buffer    = new byte[BUFFER_LENGTH];
                int    readBytes = 0;
                while (true)
                {
                    readBytes = stream.Read(buffer, 0, BUFFER_LENGTH);

                    if (readBytes < BUFFER_LENGTH)
                    {
                        Array.Resize <byte>(ref buffer, readBytes);
                    }

                    FilesController.AppendFileBinaryChunk(inst.PackageId, remoteCodebasePath, buffer);

                    if (readBytes < BUFFER_LENGTH)
                    {
                        break;
                    }
                }



                // unpack codebase
                inst[PROPERTY_INSTALLED_FILES] = String.Join(";",
                                                             FilesController.UnzipFiles(inst.PackageId, new string[] { remoteCodebasePath }));

                // delete codebase zip
                FilesController.DeleteFiles(inst.PackageId, new string[] { remoteCodebasePath });

                // check/create databases
                if (!String.IsNullOrEmpty(inst.DatabaseGroup) &&
                    String.Compare(inst.DatabaseGroup, "None", true) != 0)
                {
                    // database
                    if (inst.DatabaseId == 0)
                    {
                        TaskManager.WriteParameter("Database name", inst.DatabaseName);

                        // we should create a new database
                        SqlDatabase db = new SqlDatabase();
                        db.PackageId    = inst.PackageId;
                        db.Name         = inst.DatabaseName;
                        inst.DatabaseId = DatabaseServerController.AddSqlDatabase(db, inst.DatabaseGroup);
                        if (inst.DatabaseId < 0)
                        {
                            // rollback installation
                            RollbackInstallation(inst);

                            // return error
                            return(inst.DatabaseId); // there was an error when creating database
                        }

                        inst[PROPERTY_DATABASE_CREATED] = "True";
                    }
                    else
                    {
                        // existing database
                        SqlDatabase db = DatabaseServerController.GetSqlDatabase(inst.DatabaseId);
                        inst.DatabaseName = db.Name;

                        TaskManager.WriteParameter("Database name", inst.DatabaseName);
                    }

                    SqlUser user = null;
                    // database user
                    if (inst.UserId == 0)
                    {
                        TaskManager.WriteParameter("Database user", inst.Username);

                        // NEW USER
                        user           = new SqlUser();
                        user.PackageId = inst.PackageId;
                        user.Name      = inst.Username;
                        user.Databases = new string[] { inst.DatabaseName };
                        user.Password  = inst.Password;
                        inst.UserId    = DatabaseServerController.AddSqlUser(user, inst.DatabaseGroup);
                        if (inst.UserId < 0)
                        {
                            // rollback installation
                            RollbackInstallation(inst);

                            // return error
                            return(inst.UserId); // error while adding user
                        }

                        inst[PROPERTY_USER_CREATED] = "True";
                    }
                    else
                    {
                        // EXISTING USER
                        user          = DatabaseServerController.GetSqlUser(inst.UserId);
                        inst.Username = user.Name;

                        TaskManager.WriteParameter("Database user", inst.Username);

                        List <string> databases = new List <string>();
                        databases.AddRange(user.Databases);

                        if (!databases.Contains(inst.DatabaseName))
                        {
                            databases.Add(inst.DatabaseName);

                            user.Databases = databases.ToArray();
                            DatabaseServerController.UpdateSqlUser(user);
                        }
                    }

                    // check connectivity with SQL Server and credentials provided
                    // load user item
                    int sqlServiceId = PackageController.GetPackageServiceId(inst.PackageId, inst.DatabaseGroup);
                    sql = new DatabaseServer();
                    ServiceProviderProxy.Init(sql, sqlServiceId);

                    if (!sql.CheckConnectivity(inst.DatabaseName, inst.Username,
                                               inst.Password))
                    {
                        // can't connect to the database
                        RollbackInstallation(inst);

                        return(BusinessErrorCodes.ERROR_WEB_INSTALLER_CANT_CONNECT_DATABASE);
                    }

                    // read SQL server settings
                    StringDictionary settings = ServerController.GetServiceSettings(sqlServiceId);
                    serverIpAddressExternal = settings["ExternalAddress"];
                    if (settings.ContainsKey("InternalAddress"))
                    {
                        serverIpAddressInternal = settings["InternalAddress"];
                    }
                }

                // ********* RUN INSTALL SCENARIO ***********
                int scriptResult = RunInstallScenario(inst);
                if (scriptResult < 0)
                {
                    // rollback installation
                    RollbackInstallation(inst);

                    // return error
                    return(scriptResult);
                }

                // add new installation to the database
                return(0);
            }
            catch (Exception ex)
            {
                // rollback installation
                RollbackInstallation(inst);

                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
예제 #12
0
        public static int StartSchedule(int scheduleId)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);

            if (accountCheck < 0)
                return accountCheck;

            SchedulerJob schedule = GetScheduleComplete(scheduleId);
            if (schedule == null)
                return 0;

            if (TaskController.GetScheduleTasks(scheduleId).Any(x => x.Status == BackgroundTaskStatus.Run
                                                                     || x.Status == BackgroundTaskStatus.Starting))
                return 0;

            var parameters = schedule.ScheduleInfo.Parameters.Select(
                prm => new BackgroundTaskParameter(prm.ParameterId, prm.ParameterValue)).ToList();

            var userInfo = PackageController.GetPackageOwner(schedule.ScheduleInfo.PackageId);

            var backgroundTask = new BackgroundTask(
                Guid.NewGuid(),
                Guid.NewGuid().ToString("N"),
                userInfo.OwnerId == 0 ? userInfo.UserId : userInfo.OwnerId,
                userInfo.UserId,
                "SCHEDULER",
                "RUN_SCHEDULE",
                schedule.ScheduleInfo.ScheduleName,
                schedule.ScheduleInfo.ScheduleId,
                schedule.ScheduleInfo.ScheduleId,
                schedule.ScheduleInfo.PackageId,
                schedule.ScheduleInfo.MaxExecutionTime, parameters)
                                     {
                                         Status = BackgroundTaskStatus.Starting
                                     };
            
            TaskController.AddTask(backgroundTask);

            // update next run (if required)
            CalculateNextStartTime(schedule.ScheduleInfo);
            
            // disable run once task
            if (schedule.ScheduleInfo.ScheduleType == ScheduleType.OneTime)
                schedule.ScheduleInfo.Enabled = false;

            schedule.ScheduleInfo.LastRun = DateTime.Now;
            UpdateSchedule(schedule.ScheduleInfo);

            return 0;
        }        
예제 #13
0
        public static int AddUser(UserInfo user, bool sendLetter, string password)
        {
            // check account
            int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo);

            if (accountCheck < 0)
            {
                return(accountCheck);
            }

            string pattern = @"[\\/:*?<>|""]+";

            if (String.IsNullOrEmpty(user.Username))
            {
                return(BusinessErrorCodes.ERROR_INVALID_USER_NAME);
            }

            if (Regex.IsMatch(user.Username, pattern))
            {
                return(BusinessErrorCodes.ERROR_INVALID_USER_NAME);
            }

            if (UserExists(user.Username))
            {
                return(BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS);
            }

            // only administrators can set admin role
            if (!SecurityContext.User.IsInRole(SecurityContext.ROLE_ADMINISTRATOR) &&
                user.Role == UserRole.Administrator)
            {
                user.Role = UserRole.User;
            }

            // check integrity when creating a user account
            if (user.Role == UserRole.User)
            {
                user.EcommerceEnabled = false;
            }

            // place log record
            TaskManager.StartTask("USER", "ADD", user.Username);

            try
            {
                // add user to database
                int userId = DataProvider.AddUser(
                    SecurityContext.User.UserId,
                    user.OwnerId,
                    user.RoleId,
                    user.StatusId,
                    user.SubscriberNumber,
                    user.LoginStatusId,
                    user.IsDemo,
                    user.IsPeer,
                    user.Comments,
                    user.Username.Trim(),
                    CryptoUtils.Encrypt(password),
                    user.FirstName,
                    user.LastName,
                    user.Email,
                    user.SecondaryEmail,
                    user.Address,
                    user.City,
                    user.Country,
                    user.State,
                    user.Zip,
                    user.PrimaryPhone,
                    user.SecondaryPhone,
                    user.Fax,
                    user.InstantMessenger,
                    user.HtmlMail,
                    user.CompanyName,
                    user.EcommerceEnabled);

                if (userId == -1)
                {
                    TaskManager.WriteWarning("Account with such username already exists");
                    return(BusinessErrorCodes.ERROR_USER_ALREADY_EXISTS);
                }

                BackgroundTask topTask = TaskManager.TopTask;

                topTask.ItemId = userId;
                topTask.UpdateParamValue("SendLetter", sendLetter);

                TaskController.UpdateTaskWithParams(topTask);

                return(userId);
            }
            catch (Exception ex)
            {
                throw TaskManager.WriteError(ex);
            }
            finally
            {
                TaskManager.CompleteTask();
            }
        }
예제 #14
0
 public static bool HasErrors(BackgroundTask task)
 {
     return(task.Severity == 2);
 }
예제 #15
0
        public override void DoWork()
        {
            BackgroundTask topTask = TaskManager.TopTask;

            List <DomainDnsChanges> domainsChanges = new List <DomainDnsChanges>();
            var domainUsers = new Dictionary <int, UserInfo>();

            // get input parameters
            string dnsServersString = (string)topTask.GetParamValue(DnsServersParameter);
            string serverName       = (string)topTask.GetParamValue(ServerNameParameter);

            int pause;

            // check input parameters
            if (String.IsNullOrEmpty(dnsServersString))
            {
                TaskManager.WriteWarning("Specify 'DNS' task parameter.");
                return;
            }

            if (String.IsNullOrEmpty((string)topTask.GetParamValue("MAIL_TO")))
            {
                TaskManager.WriteWarning("The e-mail message has not been sent because 'Mail To' is empty.");
                return;
            }


            if (!int.TryParse((string)topTask.GetParamValue(PauseBetweenQueriesParameter), out pause))
            {
                TaskManager.WriteWarning("The 'pause between queries' parameter is not valid.");
                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;
            }

            WindowsServer winServer = new WindowsServer();

            ServiceProviderProxy.ServerInit(winServer, server.ServerId);

            var user = UserController.GetUser(topTask.UserId);

            var dnsServers = dnsServersString.Split(';');

            var packages = ObjectUtils.CreateListFromDataReader <PackageInfo>(DataProvider.GetAllPackages());


            foreach (var package in packages)
            {
                var domains = ServerController.GetDomains(package.PackageId);

                domains = domains.Where(x => !x.IsSubDomain && !x.IsDomainPointer).ToList(); //Selecting top-level domains

                //domains = domains.Where(x => x.ZoneItemId > 0).ToList(); //Selecting only dns enabled domains

                foreach (var domain in domains)
                {
                    if (domainsChanges.Any(x => x.DomainName == domain.DomainName))
                    {
                        continue;
                    }

                    if (!domainUsers.ContainsKey(domain.PackageId))
                    {
                        var domainUser = UserController.GetUser(packages.First(x => x.PackageId == domain.PackageId).UserId);

                        domainUsers.Add(domain.PackageId, domainUser);
                    }

                    DomainDnsChanges domainChanges = new DomainDnsChanges();
                    domainChanges.DomainName     = domain.DomainName;
                    domainChanges.PackageId      = domain.PackageId;
                    domainChanges.Registrar      = domain.RegistrarName;
                    domainChanges.ExpirationDate = domain.ExpirationDate;

                    var dbDnsRecords = ObjectUtils.CreateListFromDataReader <DnsRecordInfo>(DataProvider.GetDomainAllDnsRecords(domain.DomainId));

                    //execute server
                    foreach (var dnsServer in dnsServers)
                    {
                        var dnsMxRecords = GetDomainDnsRecords(winServer, domain.DomainName, dnsServer, DnsRecordType.MX, pause) ?? dbDnsRecords.Where(x => x.RecordType == DnsRecordType.MX).ToList();
                        var dnsNsRecords = GetDomainDnsRecords(winServer, domain.DomainName, dnsServer, DnsRecordType.NS, pause) ?? dbDnsRecords.Where(x => x.RecordType == DnsRecordType.NS).ToList();

                        FillRecordData(dnsMxRecords, domain, dnsServer);
                        FillRecordData(dnsNsRecords, domain, dnsServer);

                        domainChanges.DnsChanges.AddRange(ApplyDomainRecordsChanges(dbDnsRecords.Where(x => x.RecordType == DnsRecordType.MX), dnsMxRecords, dnsServer));
                        domainChanges.DnsChanges.AddRange(ApplyDomainRecordsChanges(dbDnsRecords.Where(x => x.RecordType == DnsRecordType.NS), dnsNsRecords, dnsServer));

                        domainChanges.DnsChanges = CombineDnsRecordChanges(domainChanges.DnsChanges, dnsServer).ToList();
                    }

                    domainsChanges.Add(domainChanges);
                }
            }

            var changedDomains = FindDomainsWithChangedRecords(domainsChanges);

            SendMailMessage(user, changedDomains, domainUsers);
        }
예제 #16
0
        public static List<BackgroundTaskLogRecord> GetLogs(BackgroundTask task, DateTime startLogTime)
        {
            if (startLogTime <= task.StartDate)
            {
                startLogTime = task.StartDate;
            }

            List<BackgroundTaskLogRecord> logs = ObjectUtils.CreateListFromDataReader<BackgroundTaskLogRecord>(
                DataProvider.GetBackgroundTaskLogs(task.Id, startLogTime));

            foreach (BackgroundTaskLogRecord log in logs)
            {
                log.TextParameters = ReBuildParametersXml(log.XmlParameters);
            }

            return logs;
        }
예제 #17
0
 public static void UpdateTaskWithParams(BackgroundTask task)
 {
     if (UpdateTask(task))
     {
         UpdateBackgroundTaskParams(task);
     }
 }
예제 #18
0
        public static bool UpdateTask(BackgroundTask task)
        {
            if (task.Status == BackgroundTaskStatus.Abort)
            {
                DeleteBackgroundTasks(task.Guid);

                return false;
            }

            if (task.Completed)
            {
                DeleteBackgroundTask(task.Id);

                return false;
            }

            DataProvider.UpdateBackgroundTask(task.Guid, task.Id, task.ScheduleId, task.PackageId, task.TaskName, task.ItemId,
                                              task.ItemName, task.FinishDate, task.IndicatorCurrent,
                                              task.IndicatorMaximum, task.MaximumExecutionTime, task.Source,
                                              task.Severity, task.Completed, task.NotifyOnComplete, task.Status);

            return true;
        }
예제 #19
0
        private static void RunBackgroundTask(BackgroundTask backgroundTask)
        {
            UserInfo user = PackageController.GetPackageOwner(backgroundTask.PackageId);
            
            SecurityContext.SetThreadPrincipal(user.UserId);
            
            var schedule = SchedulerController.GetScheduleComplete(backgroundTask.ScheduleId);

            backgroundTask.Guid = TaskManager.Guid;
            backgroundTask.Status = BackgroundTaskStatus.Run;


            TaskController.UpdateTask(backgroundTask);
            
            try
            {
                var objTask = (SchedulerTask)Activator.CreateInstance(Type.GetType(schedule.Task.TaskType));

                objTask.DoWork();
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex, "Error executing scheduled task");
            }
            finally
            {
                try
                {
                    TaskManager.CompleteTask();
                }
                catch (Exception)
                {
                }
            }
        }
예제 #20
0
        public static int AddTask(BackgroundTask task)
        {
            int taskId = DataProvider.AddBackgroundTask(task.Guid, task.TaskId, task.ScheduleId, task.PackageId, task.UserId,
                                                        task.EffectiveUserId, task.TaskName, task.ItemId, task.ItemName,
                                                        task.StartDate, task.IndicatorCurrent, task.IndicatorMaximum,
                                                        task.MaximumExecutionTime, task.Source, task.Severity, task.Completed,
                                                        task.NotifyOnComplete, task.Status);

            AddTaskParams(taskId, task.Params);

            DataProvider.AddBackgroundTaskStack(taskId);

            return taskId;
        }
예제 #21
0
        public override void DoWork()
        {
            // Input parameters:
            //  - URL
            //  - USERNAME
            //  - PASSWORD
            //  - RESPONSE_STATUS
            //  - RESPONSE_CONTAIN
            //  - RESPONSE_DOESNT_CONTAIN
            //  - MAIL_FROM
            //  - MAIL_TO
            //  - MAIL_SUBJECT
            //  - MAIL_BODY

            BackgroundTask topTask = TaskManager.TopTask;

            // get input parameters
            string url                 = (string)topTask.GetParamValue("URL");
            string username            = (string)topTask.GetParamValue("USERNAME");
            string password            = (string)topTask.GetParamValue("PASSWORD");
            string strResponseStatus   = (string)topTask.GetParamValue("RESPONSE_STATUS");
            string responseContains    = (string)topTask.GetParamValue("RESPONSE_CONTAIN");
            string responseNotContains = (string)topTask.GetParamValue("RESPONSE_DOESNT_CONTAIN");

            bool useResponseStatus        = Convert.ToBoolean(topTask.GetParamValue("USE_RESPONSE_STATUS"));
            bool useResponseContains      = Convert.ToBoolean(topTask.GetParamValue("USE_RESPONSE_CONTAIN"));
            bool useResponseDoesntContain = Convert.ToBoolean(topTask.GetParamValue("USE_RESPONSE_DOESNT_CONTAIN"));

            // check input parameters
            if (String.IsNullOrEmpty(url))
            {
                TaskManager.WriteWarning("Specify 'Web Site URL' task parameter.");
                return;
            }

            if ((String.IsNullOrEmpty(strResponseStatus) || !useResponseStatus) &&
                (String.IsNullOrEmpty(responseContains) || !useResponseContains) &&
                (String.IsNullOrEmpty(responseNotContains) || !useResponseDoesntContain))
            {
                TaskManager.WriteWarning("Specify one of 'Response Status', 'Response Contain' or 'Response Doesn't Contain' parameters.");
                return;
            }

            int responseStatus = Utils.ParseInt(strResponseStatus, -1);

            if (!String.IsNullOrEmpty(strResponseStatus) && responseStatus == -1)
            {
                TaskManager.WriteWarning("Specify correct response HTTP status, e.g. 404, 500, 503, etc.");
                return;
            }

            // load web site
            WebSiteResponse resp = GetWebDocument(url, username, password);

            // check if there was a generic error
            if (resp.Status == -1)
            {
                SendMailMessage(url, resp.Text, "");
            }

            bool sendMessage = false;

            // check status
            if (responseStatus != -1)
            {
                sendMessage |= ((resp.Status == responseStatus) && useResponseStatus);
            }

            // check "contains"
            if (!String.IsNullOrEmpty(responseContains))
            {
                sendMessage |= ((resp.Text.ToLower().IndexOf(responseContains.ToLower()) != -1) && useResponseContains);
            }

            // check "not contains"
            if (!String.IsNullOrEmpty(responseNotContains))
            {
                sendMessage |= ((resp.Text.ToLower().IndexOf(responseNotContains.ToLower()) == -1) && useResponseDoesntContain);
            }

            if (sendMessage)
            {
                SendMailMessage(url, "", resp.Text);
            }
        }
예제 #22
0
        private void BindTask(VMInfo vm)
        {
            task = ES.Services.Tasks.GetTaskWithLogRecords(vm.CurrentTaskId, DateTime.MinValue);
            if (task == null)
                return;

            // bind task details
            litTaskName.Text = String.Format("{0} &quot;{1}&quot;",
                GetAuditLogTaskName(task.Source, task.TaskName),
                task.ItemName);

            // time
            litStarted.Text = task.StartDate.ToString("T");
            TimeSpan d = (TimeSpan)(DateTime.Now - task.StartDate);
            litElapsed.Text = new TimeSpan(d.Hours, d.Minutes, d.Seconds).ToString();

            // bind records
            repRecords.DataSource = task.LastLogRecords;
            repRecords.DataBind();
        }
예제 #23
0
        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 checkDiskspace = (String.Compare((string)topTask.GetParamValue("DISKSPACE_OVERUSED"), "true", true) == 0);
            bool checkBandwidth = (String.Compare((string)topTask.GetParamValue("BANDWIDTH_OVERUSED"), "true", true) == 0);

            bool suspendOverused = Convert.ToBoolean(topTask.GetParamValue("SUSPEND_OVERUSED"));

            bool   sendWarningEmail         = Convert.ToBoolean(topTask.GetParamValue("SEND_WARNING_EMAIL"));
            bool   sendSuspensionEmail      = Convert.ToBoolean(topTask.GetParamValue("SEND_SUSPENSION_EMAIL"));
            int    warningUsageThreshold    = Convert.ToInt32(topTask.GetParamValue("WARNING_USAGE_THRESHOLD"));
            int    suspensionUsageThreshold = Convert.ToInt32(topTask.GetParamValue("SUSPENSION_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 suspensionMailFrom       = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_FROM"));
            string suspensionMailBcc        = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_BCC"));
            string suspensionMailSubject    = Convert.ToString(topTask.GetParamValue("SUSPENSION_MAIL_SUBJECT"));
            string suspensionMailBody       = Convert.ToString(topTask.GetParamValue("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());
        }
예제 #24
0
        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());
        }
예제 #25
0
        public static void UpdateBackgroundTaskParams(BackgroundTask task)
        {
            DataProvider.DeleteBackgroundTaskParams(task.Id);

            AddTaskParams(task.Id, task.Params);
        }
예제 #26
0
        public override void DoWork()
        {
            // Input parameters:
            //  - DATABASE_GROUP
            //  - DATABASE_NAME
            //  - BACKUP_FOLDER
            //  - BACKUP_NAME
            //  - ZIP_BACKUP

            BackgroundTask topTask = TaskManager.TopTask;

            string databaseGroup = (string)topTask.GetParamValue("DATABASE_GROUP");
            string databaseName  = (string)topTask.GetParamValue("DATABASE_NAME");
            string backupFolder  = (string)topTask.GetParamValue("BACKUP_FOLDER");
            string backupName    = (string)topTask.GetParamValue("BACKUP_NAME");
            string strZipBackup  = (string)topTask.GetParamValue("ZIP_BACKUP");

            // check input parameters
            if (String.IsNullOrEmpty(databaseName))
            {
                TaskManager.WriteWarning("Specify 'Database Name' task parameter.");
                return;
            }

            bool zipBackup = (strZipBackup.ToLower() == "true");

            if (String.IsNullOrEmpty(backupName))
            {
                backupName = databaseName + (zipBackup ? ".zip" : ".bak");
            }
            else
            {
                // check extension
                string ext = Path.GetExtension(backupName);
                if (zipBackup && String.Compare(ext, ".zip", true) != 0)
                {
                    // change extension to .zip
                    backupName = Path.GetFileNameWithoutExtension(backupName) + ".zip";
                }
            }

            // try to find database
            SqlDatabase item = (SqlDatabase)PackageController.GetPackageItemByName(topTask.PackageId, databaseGroup,
                                                                                   databaseName, typeof(SqlDatabase));

            if (item == null)
            {
                TaskManager.WriteError("Database with the specified name was not found in the current hosting space.");
                return;
            }

            if (String.IsNullOrEmpty(backupFolder))
            {
                backupFolder = "\\";
            }

            // substitute parameters
            DateTime d    = DateTime.Now;
            string   date = d.ToString("yyyyMMdd");
            string   time = d.ToString("HHmm");

            backupFolder = Utils.ReplaceStringVariable(backupFolder, "date", date);
            backupFolder = Utils.ReplaceStringVariable(backupFolder, "time", time);
            backupName   = Utils.ReplaceStringVariable(backupName, "date", date);
            backupName   = Utils.ReplaceStringVariable(backupName, "time", time);

            // backup database
            DatabaseServerController.BackupSqlDatabase(item.Id, backupName, zipBackup, false, backupFolder);
        }
예제 #27
0
        public static void UpdateBackgroundTaskParams(BackgroundTask task)
        {
            DataProvider.DeleteBackgroundTaskParams(task.Id);

            AddTaskParams(task.Id, task.Params);
        }
예제 #28
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);
        }
예제 #29
0
        public override void DoWork()
        {
            // Input parameters:
            //  - FILE_PATH
            //  - FTP_SERVER
            //  - FTP_USERNAME
            //  - FTP_PASSWORD
            //  - FTP_FOLDER

            BackgroundTask topTask = TaskManager.TopTask;

            // get input parameters
            string filePath    = (string)topTask.GetParamValue("FILE_PATH");
            string ftpServer   = (string)topTask.GetParamValue("FTP_SERVER");
            string ftpUsername = (string)topTask.GetParamValue("FTP_USERNAME");
            string ftpPassword = (string)topTask.GetParamValue("FTP_PASSWORD");
            string ftpFolder   = (string)topTask.GetParamValue("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(topTask.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(topTask.PackageId, cmdPath);

            // upload batch
            FilesController.UpdateFileBinaryContent(topTask.PackageId, cmdPath, Encoding.UTF8.GetBytes(cmdBatch));

            // execute system command
            // load OS service
            int serviceId = PackageController.GetPackageServiceId(topTask.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(topTask.PackageId, new string[] { cmdPath });
        }