Example #1
0
        public void CalculatePackage(int packageId)
        {
            DateTime since      = PackageController.GetPackageBandwidthUpdate(packageId);
            DateTime nextUpdate = DateTime.Now;

            try
            {
                // get all package items
                List <ServiceProviderItem> items = PackageController.GetServiceItemsForStatistics(
                    0, packageId, false, true, false, false);

                // order items by service
                Dictionary <int, List <ServiceProviderItem> > orderedItems =
                    PackageController.OrderServiceItemsByServices(items);

                // calculate statistics for each service set
                List <ServiceProviderItemBandwidth> itemsBandwidth = new List <ServiceProviderItemBandwidth>();
                foreach (int serviceId in orderedItems.Keys)
                {
                    ServiceProviderItemBandwidth[] serviceBandwidth = CalculateItems(serviceId,
                                                                                     orderedItems[serviceId], since);
                    if (serviceBandwidth != null)
                    {
                        itemsBandwidth.AddRange(serviceBandwidth);
                    }
                }

                // update info in the database
                string xml = BuildDiskBandwidthStatisticsXml(itemsBandwidth.ToArray());
                PackageController.UpdatePackageBandwidth(packageId, xml);

                // if everything is OK
                // update date
                PackageController.UpdatePackageBandwidthUpdate(packageId, nextUpdate);

                // suspend package if requested
                if (suspendOverused)
                {
                    // disk space
                    QuotaValueInfo dsQuota = PackageController.GetPackageQuota(packageId, Quotas.OS_BANDWIDTH);

                    if (dsQuota.QuotaExhausted)
                    {
                        PackageController.ChangePackageStatus(null, packageId, PackageStatus.Suspended, false);
                    }
                }
            }
            catch (Exception ex)
            {
                // load package details
                PackageInfo package = PackageController.GetPackage(packageId);

                // load user details
                UserInfo user = PackageController.GetPackageOwner(package.PackageId);

                // log error
                TaskManager.WriteError(String.Format("Error calculating bandwidth for '{0}' space of user '{1}': {2}",
                                                     package.PackageName, user.Username, ex.ToString()));
            }
        }
        public void CalculatePackage(int packageId)
        {
            try
            {
                // get all package items
                List <ServiceProviderItem> items = PackageController.GetServiceItemsForStatistics(
                    0, packageId, true, false, false, false);

                //TaskManager.Write("Items: " + items.Count);

                // order items by service
                Dictionary <int, List <ServiceProviderItem> > orderedItems =
                    PackageController.OrderServiceItemsByServices(items);

                // calculate statistics for each service set
                List <ServiceProviderItemDiskSpace> itemsDiskspace = new List <ServiceProviderItemDiskSpace>();
                foreach (int serviceId in orderedItems.Keys)
                {
                    ServiceProviderItemDiskSpace[] serviceDiskspace = CalculateItems(serviceId, orderedItems[serviceId]);
                    if (serviceDiskspace != null)
                    {
                        itemsDiskspace.AddRange(serviceDiskspace);
                    }
                }

                // update info in the database
                string xml = BuildDiskSpaceStatisticsXml(itemsDiskspace.ToArray());
                PackageController.UpdatePackageDiskSpace(packageId, xml);
                //TaskManager.Write("XML: " + xml);

                // suspend package if requested
                if (suspendOverused)
                {
                    // disk space
                    QuotaValueInfo dsQuota = PackageController.GetPackageQuota(packageId, Quotas.OS_DISKSPACE);

                    if (dsQuota.QuotaExhausted)
                    {
                        PackageController.ChangePackageStatus(null, packageId, PackageStatus.Suspended, false);
                    }
                }
            }
            catch (Exception ex)
            {
                // load package details
                PackageInfo package = PackageController.GetPackage(packageId);

                // load user details
                UserInfo user = PackageController.GetPackageOwner(package.PackageId);

                // log error
                TaskManager.WriteError(String.Format("Error calculating diskspace for '{0}' space of user '{1}': {2}",
                                                     package.PackageName, user.Username, ex.ToString()));
            }
        }
Example #3
0
        public void Cancel()
        {
            int packageId = Utils.ParseInt(ServiceSettings[PACKAGE_ID], -1);

            if (packageId > -1)
            {
                RememberCurrentStatus(packageId);

                int status = PackageController.ChangePackageStatus(packageId, PackageStatus.Cancelled, false);

                if (status < 0)
                {
                    throw new Exception("Unable to change package status. Status code: " + status);
                }
            }
        }
Example #4
0
        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());
        }
Example #5
0
 public int ChangePackageStatus(int packageId, PackageStatus status)
 {
     return(PackageController.ChangePackageStatus(packageId, status, true));
 }
Example #6
0
        protected void RollbackOperation(int packageId)
        {
            // check input parameters first
            if (packageId < 1)
            {
                return;                 // exit
            }
            //
            try
            {
                TaskManager.Write("Trying rollback operation");
                // restore service
                HostingPackageSvc packageSvc = (HostingPackageSvc)RestoreObjectState("ServiceInfo");
                // restore consumer
                UserInfo consumer = (UserInfo)RestoreObjectState("ConsumerInfo");

                //
                int apiResult = 0;

                // rollback consumer changes first
                apiResult = UserController.UpdateUser(consumer);
                // check WebsitePanel API result
                if (apiResult < 0)
                {
                    //
                    TaskManager.WriteError("Could not rollback consumer changes");
                    //
                    TaskManager.WriteParameter("ResultCode", apiResult);
                }

                // during rollback package should be reverted to its original state
                // compensation logic - revert back package status
                switch (packageSvc.Status)
                {
                // Active State
                case ServiceStatus.Active:
                    apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Active, false);
                    break;

                // Suspended State
                case ServiceStatus.Suspended:
                    apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Suspended, false);
                    break;

                // Cancelled State
                case ServiceStatus.Cancelled:
                    apiResult = PackageController.ChangePackageStatus(packageId, PackageStatus.Cancelled, false);
                    break;

                // service has been just ordered & during rollback should be removed
                case ServiceStatus.Ordered:
                    // compensation logic - remove created package
                    apiResult = PackageController.DeletePackage(packageId);
                    break;
                }
                // check WebsitePanel API result
                if (apiResult < 0)
                {
                    //
                    if (packageSvc.Status == ServiceStatus.Ordered)
                    {
                        TaskManager.WriteError("Could not rollback operation and delete package");
                    }
                    else
                    {
                        TaskManager.WriteError("Could not rollback operation and revert package state");
                    }
                    //
                    TaskManager.WriteParameter("ResultCode", apiResult);
                }

                // rollback service changes in EC metabase
                apiResult = UpdateServiceInfo(packageSvc);
                // check API result
                if (apiResult < 0)
                {
                    //
                    TaskManager.WriteError("Could not rollback service changes");
                    //
                    TaskManager.WriteParameter("ResultCode", apiResult);
                }

                //
                TaskManager.Write("Rollback succeed");
            }
            catch (Exception ex)
            {
                TaskManager.WriteError(ex);
            }
        }
Example #7
0
        public GenericSvcResult CancelService(ProvisioningContext context)
        {
            GenericSvcResult result = new GenericSvcResult();

            //
            SaveObjectState(SERVICE_INFO, context.ServiceInfo);
            //
            SaveObjectState(CONSUMER_INFO, context.ConsumerInfo);

            // concretize service to be provisioned
            HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;

            //
            try
            {
                //
                TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_CANCEL);
                // LOG INFO
                TaskManager.Write(START_CANCELLATION_MSG);
                TaskManager.WriteParameter(CONTRACT_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]);
                TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName);
                TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId);

                // 0. Do security checks
                if (!CheckOperationClientPermissions(result))
                {
                    // LOG ERROR
                    TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
                    // EXIT
                    return(result);
                }
                //
                if (!CheckOperationClientStatus(result))
                {
                    // LOG ERROR
                    TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
                    // EXIT
                    return(result);
                }

                // cancel hosting package
                int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId,
                                                                      PackageStatus.Cancelled, false);

                // check WebsitePanel API result
                if (apiResult < 0)
                {
                    //
                    result.ResultCode = apiResult;
                    //
                    result.Succeed = false;

                    // LOG ERROR
                    TaskManager.WriteError(ERROR_CANCEL_PCKG_MSG);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);

                    // EXIT
                    return(result);
                }

                // change service status to Cancelled
                packageSvc.Status = ServiceStatus.Cancelled;
                // put data into metabase
                int svcResult = UpdateServiceInfo(packageSvc);

                //
                if (svcResult < 0)
                {
                    result.ResultCode = svcResult;
                    //
                    result.Error = ERROR_SVC_UPDATE_MSG;
                    //
                    result.Succeed = false;

                    // ROLLBACK CHANGES
                    RollbackOperation(packageSvc.PackageId);

                    // LOG ERROR
                    TaskManager.WriteError(result.Error);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);

                    // EXIT
                    return(result);
                }
                //
                SetOutboundParameters(context);
                // LOG INFO
                TaskManager.Write(PCKG_PROVISIONED_MSG);
                //
                result.Succeed = true;
            }
            catch (Exception ex)
            {
                //
                TaskManager.WriteError(ex);

                // ROLLBACK CHANGES
                RollbackOperation(packageSvc.PackageId);

                //
                result.Succeed = false;
                //
                result.Error = ex.Message;
            }
            finally
            {
                // complete task
                TaskManager.CompleteTask();
            }

            //
            return(result);
        }
Example #8
0
        public GenericSvcResult ActivateService(ProvisioningContext context)
        {
            GenericSvcResult result = new GenericSvcResult();

            //
            SaveObjectState(SERVICE_INFO, context.ServiceInfo);
            //
            SaveObjectState(CONSUMER_INFO, context.ConsumerInfo);

            // concretize service to be provisioned
            HostingPackageSvc packageSvc = (HostingPackageSvc)context.ServiceInfo;

            //
            try
            {
                //
                TaskManager.StartTask(SystemTasks.SOURCE_ECOMMERCE, SystemTasks.SVC_ACTIVATE);

                // LOG INFO
                TaskManager.Write(START_ACTIVATION_MSG);
                TaskManager.WriteParameter(USERNAME_PARAM, context.ConsumerInfo[ContractAccount.USERNAME]);
                TaskManager.WriteParameter(SVC_PARAM, context.ServiceInfo.ServiceName);
                TaskManager.WriteParameter(SVC_ID_PARAM, context.ServiceInfo.ServiceId);
                TaskManager.TaskParameters[SystemTaskParams.PARAM_SEND_EMAIL] = context.SendEmail;

                // 0. Do security checks
                if (!CheckOperationClientPermissions(result))
                {
                    // LOG ERROR
                    TaskManager.WriteError(ERROR_CLIENT_OPERATION_PERMISSIONS);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
                    // EXIT
                    return(result);
                }
                //
                if (!CheckOperationClientStatus(result))
                {
                    // LOG ERROR
                    TaskManager.WriteError(ERROR_CLIENT_OPERATION_STATUS);
                    TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);
                    // EXIT
                    return(result);
                }

                // 1. Hosting package is just ordered
                if (context.ServiceInfo.Status == ServiceStatus.Ordered && context.ContractInfo.CustomerId > 0)
                {
                    // LOG INFO
                    TaskManager.Write(CREATE_PCKG_MSG);
                    // create new package
                    PackageResult apiResult = PackageController.AddPackage(context.ContractInfo.CustomerId, packageSvc.PlanId,
                                                                           packageSvc.ServiceName, String.Empty, (int)packageSvc.InitialStatus, DateTime.Now, true, true);

                    // failed to instantiate package
                    if (apiResult.Result <= 0)
                    {
                        result.ResultCode = apiResult.Result;
                        //
                        result.Succeed = false;

                        // LOG ERROR
                        TaskManager.WriteError(CREATE_PCKG_ERROR_MSG);
                        TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);

                        // EXIT
                        return(result);
                    }
                    // save result PackageId
                    packageSvc.PackageId = apiResult.Result;
                }
                else                 // 2. Package requires only to update its status
                {
                    // LOG INFO
                    TaskManager.Write(START_ACTIVATION_MSG);

                    //
                    int apiResult = PackageController.ChangePackageStatus(packageSvc.PackageId,
                                                                          PackageStatus.Active, false);
                    //
                    if (apiResult < 0)
                    {
                        result.ResultCode = apiResult;
                        //
                        result.Succeed = false;

                        // LOG ERROR
                        TaskManager.WriteError(ERROR_ACTIVATE_PCKG_MSG);
                        TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);

                        // EXIT
                        return(result);
                    }
                }
                // check user role
                if (context.ContractInfo.CustomerId > 0)
                {
                    UserInfo user = UserController.GetUserInternally(context.ContractInfo.CustomerId);
                    // check user status
                    //
                    if (user.Status != UserStatus.Active)
                    {
                        // LOG INFO
                        TaskManager.Write(START_USR_ACTIVATION_MSG);

                        // trying to change user status
                        int userResult = UserController.ChangeUserStatus(context.ContractInfo.CustomerId,
                                                                         UserStatus.Active);
                        // failed to activate user account
                        if (userResult < 0)
                        {
                            result.ResultCode = userResult;
                            //
                            result.Succeed = false;

                            // LOG ERROR
                            TaskManager.WriteError(ERROR_USR_ACTIVATION_MSG);
                            TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);

                            // ROLLBACK CHANGES
                            RollbackOperation(result.ResultCode);

                            // EXIT
                            return(result);
                        }
                    }
                    // check user role
                    if (user.Role != packageSvc.UserRole)
                    {
                        // LOG INFO
                        TaskManager.Write(START_CHANGE_USR_ROLE_MSG);
                        //
                        user.Role = packageSvc.UserRole;
                        // trying to change user role
                        int roleResult = UserController.UpdateUser(user);
                        // failed to change user role
                        if (roleResult < 0)
                        {
                            result.ResultCode = roleResult;
                            //
                            result.Succeed = false;

                            //
                            TaskManager.WriteError(ERROR_CHANGE_USR_ROLE_MSG);
                            TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);

                            // ROLLBACK CHANGES
                            RollbackOperation(result.ResultCode);

                            // EXIT
                            return(result);
                        }
                    }
                }
                // update plan status if necessary
                if (packageSvc.Status != ServiceStatus.Active)
                {
                    // change service status to active
                    packageSvc.Status = ServiceStatus.Active;
                    // put data into metabase
                    int svcResult = UpdateServiceInfo(packageSvc);

                    // error updating svc details
                    if (svcResult < 0)
                    {
                        result.ResultCode = svcResult;
                        //
                        result.Succeed = false;

                        // ROLLBACK CHANGES
                        RollbackOperation(packageSvc.PackageId);

                        // LOG ERROR
                        TaskManager.WriteError(ERROR_SVC_UPDATE_MSG);
                        TaskManager.WriteParameter(RESULT_CODE_PARAM, result.ResultCode);

                        // EXIT
                        return(result);
                    }
                }
                //
                SetOutboundParameters(context);
                // LOG INFO
                TaskManager.Write(PCKG_PROVISIONED_MSG);

                //
                result.Succeed = true;
            }
            catch (Exception ex)
            {
                //
                TaskManager.WriteError(ex);

                // ROLLBACK CHANGES
                RollbackOperation(packageSvc.PackageId);

                //
                result.Succeed = false;
                //
                result.Error = ex.Message;
            }
            finally
            {
                // complete task
                TaskManager.CompleteTask();
            }

            //
            return(result);
        }