async Task UpgradeServiceControlInstance(InstanceDetailsViewModel model, ServiceControlInstance instance, ServiceControlUpgradeOptions upgradeOptions)
        {
            using (var progress = model.GetProgressObject($"UPGRADING {model.Name}"))
            {
                var reportCard   = new ReportCard();
                var restartAgain = model.IsRunning;

                var stopped = await model.StopService(progress);

                if (!stopped)
                {
                    eventAggregator.PublishOnUIThread(new RefreshInstances());

                    reportCard.Errors.Add("Failed to stop the service");
                    reportCard.SetStatus();
                    windowManager.ShowActionReport(reportCard, "ISSUES UPGRADING INSTANCE", "Could not upgrade instance because of the following errors:");

                    return;
                }

                reportCard = await Task.Run(() => serviceControlInstaller.Upgrade(instance, upgradeOptions, progress));

                if (reportCard.HasErrors || reportCard.HasWarnings)
                {
                    windowManager.ShowActionReport(reportCard, "ISSUES UPGRADING INSTANCE", "Could not upgrade instance because of the following errors:", "There were some warnings while upgrading the instance:");
                }
                else
                {
                    if (restartAgain)
                    {
                        var serviceStarted = await model.StartService(progress);

                        if (!serviceStarted)
                        {
                            reportCard.Errors.Add("The Service failed to start. Please consult the service control logs for this instance");
                            windowManager.ShowActionReport(reportCard, "UPGRADE FAILURE", "Instance reported this error after upgrade:");
                        }
                    }
                }
            }
        }
示例#2
0
 ServiceControlAuditNewInstance CreateSplitOutAuditInstance(ServiceControlInstance source)
 {
     return(new ServiceControlAuditNewInstance
     {
         AuditQueue = source.AuditQueue,
         AuditLogQueue = source.AuditLogQueue,
         ForwardAuditMessages = source.ForwardAuditMessages,
         // ReSharper disable once PossibleInvalidOperationException
         AuditRetentionPeriod = source.AuditRetentionPeriod.Value,
         TransportPackage = source.TransportPackage,
         ConnectionString = source.ConnectionString,
         HostName = source.HostName,
         Name = $"{source.Name}.Audit",
         ServiceAccount = source.Service.Account,
         // NOTE: The password should always be blank, as we don't read it back
         ServiceAccountPwd = source.ServiceAccountPwd,
         DisplayName = $"{source.Service.DisplayName}.Audit",
         ServiceDescription = $"{source.Service.Description} (Audit)",
         ServiceControlQueueAddress = source.Name
     });
 }
示例#3
0
        public bool AddRemoteInstance(ServiceControlInstance instance, string[] remoteInstanceAddresses, ILogging log)
        {
            if (Compatibility.RemoteInstancesDoNotNeedQueueAddress.SupportedFrom > instance.Version)
            {
                log.Error($"Cannot add remote instances to instances older than {Compatibility.RemoteInstancesDoNotNeedQueueAddress.SupportedFrom}");
                return(false);
            }

            instance.ReportCard = new ReportCard();

            var restartService = instance.Service.Status == ServiceControllerStatus.Running;

            if (!instance.TryStopService())
            {
                logger.Error("Service failed to stop or service stop timed out");
            }

            try
            {
                foreach (var remoteInstanceAddress in remoteInstanceAddresses)
                {
                    instance.AddRemoteInstance(remoteInstanceAddress);
                }

                instance.ApplyConfigChange();

                if (restartService && !instance.TryStartService())
                {
                    logger.Error("Service failed to start after adding remote instances - please check configuration for {0}", instance.Name);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Adding remote instances Failed: {0}", ex.Message);
                return(false);
            }

            return(true);
        }
示例#4
0
        internal ReportCard Add(ServiceControlInstanceMetadata details, IProgress <ProgressDetails> progress, Func <PathInfo, bool> promptToProceed)
        {
            ZipInfo.ValidateZip();

            var instanceInstaller = details;

            instanceInstaller.ReportCard = new ReportCard();

            //Validation
            instanceInstaller.Validate(promptToProceed);
            if (instanceInstaller.ReportCard.HasErrors || instanceInstaller.ReportCard.CancelRequested)
            {
                instanceInstaller.ReportCard.Status = Status.FailedValidation;
                return(instanceInstaller.ReportCard);
            }

            progress.Report(3, 9, "Copying files...");
            instanceInstaller.CopyFiles(ZipInfo.FilePath);
            progress.Report(4, 9, "Writing configurations...");
            instanceInstaller.WriteConfigurationFile();
            progress.Report(5, 9, "Registering URL ACLs...");
            instanceInstaller.RegisterUrlAcl();
            progress.Report(6, 9, "Creating queues...");
            instanceInstaller.SetupInstance();

            if (!instanceInstaller.ReportCard.HasErrors)
            {
                progress.Report(7, 9, "Registering service...");
                instanceInstaller.RegisterService();
                //Post Installation
                progress.Report(8, 9, "Starting service...");
                var instance = ServiceControlInstance.FindByName(instanceInstaller.Name);
                if (!instance.TryStartService())
                {
                    instanceInstaller.ReportCard.Warnings.Add($"New instance did not startup - please check configuration for {instance.Name}");
                }
            }
            instanceInstaller.ReportCard.SetStatus();
            return(instanceInstaller.ReportCard);
        }
示例#5
0
        internal ReportCard Upgrade(string instanceName, InstanceUpgradeOptions upgradeOptions, IProgress <ProgressDetails> progress = null)
        {
            progress = progress ?? new Progress <ProgressDetails>();

            var instance = ServiceControlInstance.FindByName(instanceName);

            instance.ReportCard = new ReportCard();
            ZipInfo.ValidateZip();

            progress.Report(0, 5, "Stopping instance...");
            if (!instance.TryStopService())
            {
                return(new ReportCard
                {
                    Errors = { "Service failed to stop" },
                    Status = Status.Failed
                });
            }

            progress.Report(1, 5, "Backing up app.config...");
            var backupFile = instance.BackupAppConfig();

            try
            {
                progress.Report(2, 5, "Upgrading Files...");
                instance.UpgradeFiles(ZipInfo.FilePath);
            }
            finally
            {
                progress.Report(3, 5, "Restoring app.config...");
                instance.RestoreAppConfig(backupFile);
            }

            upgradeOptions.ApplyChangesToInstance(instance);

            progress.Report(4, 5, "Running Queue Creation...");
            instance.SetupInstance();
            instance.ReportCard.SetStatus();
            return(instance.ReportCard);
        }
示例#6
0
        public static ActionResult ServiceControlUnattendedRemoval(Session session)
        {
            var logger = new MSILogger(session);
            var removeInstancesPropertyValue = session["REMOVEALLINSTANCESANDDATA"];

            if (string.IsNullOrWhiteSpace(removeInstancesPropertyValue))
            {
                return(ActionResult.NotExecuted);
            }

            switch (removeInstancesPropertyValue.ToUpper())
            {
            case "YES":
            case "TRUE":
                break;

            default:
                return(ActionResult.NotExecuted);
            }

            if (ServiceControlInstance.Instances().Count == 0)
            {
                return(ActionResult.Success);
            }

            var unattendedInstaller = new UnattendInstaller(logger, session["APPDIR"]);

            foreach (var instance in ServiceControlInstance.Instances())
            {
                try
                {
                    unattendedInstaller.Delete(instance.Name, true, true);
                }
                catch (Exception ex)
                {
                    logger.Error($"Error thrown when removing instance {instance.Name} - {ex}");
                }
            }
            return(ActionResult.Success);
        }
        public InstanceDetailsViewModel(
            ServiceControlInstance serviceControlInstance,
            EditInstanceCommand showEditInstanceScreenCommand,
            UpgradeInstanceCommand upgradeInstanceToNewVersionCommand,
            AdvanceOptionsCommand advanceOptionsCommand,
            Installer installer)
        {
            ServiceControlInstance = serviceControlInstance;

            NewVersion = installer.ZipInfo.Version;

            OpenUrl         = new OpenURLCommand();
            CopyToClipboard = new CopyToClipboardCommand();

            EditCommand = showEditInstanceScreenCommand;
            UpgradeToNewVersionCommand = upgradeInstanceToNewVersionCommand;

            StartCommand = Command.Create(() => StartService());
            StopCommand  = Command.Create(() => StopService());

            AdvanceOptionsCommand = advanceOptionsCommand;
        }
        public InstanceAddViewModel()
        {
            DisplayName = "Add new instance";

            SelectDestinationPath = new SelectPathCommand(p => DestinationPath = p, isFolderPicker: true, defaultPath: DestinationPath);
            SelectDatabasePath    = new SelectPathCommand(p => DatabasePath = p, isFolderPicker: true, defaultPath: DatabasePath);
            SelectLogPath         = new SelectPathCommand(p => LogPath = p, isFolderPicker: true, defaultPath: LogPath);

            var serviceControlInstances = ServiceControlInstance.Instances();

            if (!serviceControlInstances.Any())
            {
                InstanceName = "Particular.ServiceControl";
                PortNumber   = "33333";
            }
            else
            {
                var i = 0;
                while (true)
                {
                    InstanceName = $"Particular.ServiceControl.{++i}";
                    if (!serviceControlInstances.Any(p => p.Name.Equals(InstanceName, StringComparison.OrdinalIgnoreCase)))
                    {
                        break;
                    }
                }
            }

            AuditRetention           = SettingConstants.AuditRetentionPeriodDefaultInHoursForUI;
            ErrorRetention           = SettingConstants.ErrorRetentionPeriodDefaultInDaysForUI;
            Description              = "A ServiceControl Instance";
            HostName                 = "localhost";
            AuditQueueName           = "audit";
            AuditForwardingQueueName = "audit.log";
            ErrorQueueName           = "error";
            ErrorForwardingQueueName = "error.log";
            ErrorForwarding          = ErrorForwardingOptions.First(p => !p.Value); //Default to Off.
            UseSystemAccount         = true;
        }
        private void RefreshInstances()
        {
            var currentInstances = ServiceControlInstance.Instances();

            var addedInstances   = currentInstances.Where(i => Instances.All(i2 => i2.Name != i.Name)).ToList();
            var removedInstances = Instances.Where(i => currentInstances.All(i2 => i2.Name != i.Name)).ToList();

            foreach (var item in addedInstances)
            {
                Instances.Add(instanceDetailsFunc(item));
            }

            foreach (var item in removedInstances)
            {
                Instances.Remove(item);
            }

            foreach (var instance in Instances)
            {
                instance.ServiceControlInstance.Reload();
            }
            // Existing instances are updated in the InstanceDetailsViewModel
        }
示例#10
0
        public static PsServiceControl FromInstance(ServiceControlInstance instance)
        {
            var result = new PsServiceControl
            {
                Name     = instance.Name,
                Url      = instance.Url,
                HostName = instance.HostName,
                Port     = instance.Port,
                DatabaseMaintenancePort = instance.DatabaseMaintenancePort,
                InstallPath             = instance.InstallPath,
                LogPath = instance.LogPath,
                DBPath  = instance.DBPath,
                TransportPackageName = instance.TransportPackage.Name,
                ConnectionString     = instance.ConnectionString,
                ErrorQueue           = instance.ErrorQueue,
                ErrorLogQueue        = instance.ErrorLogQueue,
                ServiceAccount       = instance.ServiceAccount,
                Version = instance.Version,
                //TODO: Do we need the version check here?
                ForwardErrorMessages = instance.Version < ServiceControlSettings.ForwardErrorMessages.SupportedFrom || instance.ForwardErrorMessages,
                AuditQueue           = instance.AuditQueue,
                AuditLogQueue        = instance.AuditLogQueue,
                ForwardAuditMessages = instance.ForwardAuditMessages,
                AuditRetentionPeriod = instance.AuditRetentionPeriod,
                ErrorRetentionPeriod = instance.ErrorRetentionPeriod,
                RemoteInstances      = instance.RemoteInstances.Select <RemoteInstanceSetting, object>(i =>
                {
                    if (string.IsNullOrEmpty(i.QueueAddress))
                    {
                        return(new { ApiUri = i.ApiUri });
                    }
                    return(new { ApiUri = i.ApiUri, QueueAddress = i.QueueAddress });
                }).ToArray()
            };

            return(result);
        }
示例#11
0
        internal ReportCard Update(ServiceControlInstance instance, bool startService)
        {
            try
            {
                instance.ReportCard = new ReportCard();
                instance.ValidateChanges();
                if (instance.ReportCard.HasErrors)
                {
                    instance.ReportCard.Status = Status.FailedValidation;
                    return(instance.ReportCard);
                }

                if (!instance.TryStopService())
                {
                    instance.ReportCard.Errors.Add("Service failed to stop");
                    instance.ReportCard.Status = Status.Failed;
                    return(instance.ReportCard);
                }

                instance.ApplyConfigChange();
                if (!instance.ReportCard.HasErrors)
                {
                    if (startService && !instance.TryStartService())
                    {
                        instance.ReportCard.Warnings.Add($"Service did not start after changes - please check configuration for {instance.Name}");
                    }
                }

                instance.ReportCard.SetStatus();
                return(instance.ReportCard);
            }
            finally
            {
                instance.Reload();
            }
        }
        public AdvanceOptionsViewModel(ServiceControlInstance instance, IEventAggregator eventAggregator, StartServiceInMaintenanceModeCommand maintenanceModeCommand, DeleteInstanceCommand deleteInstanceCommand)
        {
            ServiceControlInstance = instance;
            DisplayName            = "ADVANCED OPTIONS";

            StartServiceInMaintenanceModeCommand = new ReactiveCommand().DoAsync(async _ =>
            {
                await maintenanceModeCommand.ExecuteAsync(this);
                eventAggregator.PublishOnUIThread(new RefreshInstances());
            });
            DeleteCommand              = deleteInstanceCommand;
            OpenUrl                    = new OpenURLCommand();
            CopyToClipboard            = new CopyToClipboardCommand();
            StopMaintenanceModeCommand = new ReactiveCommand().DoAsync(async _ =>
            {
                await StopService();
                eventAggregator.PublishOnUIThread(new RefreshInstances());
            });
            Cancel = Command.Create(() =>
            {
                TryClose(false);
                eventAggregator.PublishOnUIThread(new RefreshInstances());
            }, () => !InProgress);
        }
        static void UpgradeInstances(Session session, ServiceControlZipInfo zipInfo, MSILogger logger, UnattendInstaller unattendedInstaller)
        {
            var options = new InstanceUpgradeOptions();

            var upgradeInstancesPropertyValue = session["UPGRADEINSTANCES"];

            if (string.IsNullOrWhiteSpace(upgradeInstancesPropertyValue))
            {
                return;
            }
            upgradeInstancesPropertyValue = upgradeInstancesPropertyValue.Trim();

            var forwardErrorMessagesPropertyValue = session["FORWARDERRORMESSAGES"];

            try
            {
                options.OverrideEnableErrorForwarding = bool.Parse(forwardErrorMessagesPropertyValue);
            }
            catch
            {
                options.OverrideEnableErrorForwarding = null;
            }

            var auditRetentionPeriodPropertyValue = session["AUDITRETENTIONPERIOD"];

            try
            {
                options.AuditRetentionPeriod = TimeSpan.Parse(auditRetentionPeriodPropertyValue);
            }
            catch
            {
                options.AuditRetentionPeriod = null;
            }

            var errorRetentionPeriodPropertyValue = session["ERRORRETENTIONPERIOD"];

            try
            {
                options.ErrorRetentionPeriod = TimeSpan.Parse(errorRetentionPeriodPropertyValue);
            }
            catch
            {
                options.ErrorRetentionPeriod = null;
            }

            //determine what to upgrade
            var instancesToUpgrade = new List <ServiceControlInstance>();

            if (upgradeInstancesPropertyValue.Equals("*", StringComparison.OrdinalIgnoreCase) || upgradeInstancesPropertyValue.Equals("ALL", StringComparison.OrdinalIgnoreCase))
            {
                instancesToUpgrade.AddRange(ServiceControlInstance.Instances());
            }
            else
            {
                var candidates = upgradeInstancesPropertyValue.Replace(" ", String.Empty).Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                instancesToUpgrade.AddRange(ServiceControlInstance.Instances().Where(instance => candidates.Contains(instance.Name, StringComparer.OrdinalIgnoreCase)));
            }

            // do upgrades
            foreach (var instance in instancesToUpgrade)
            {
                if (zipInfo.Version > instance.Version)
                {
                    if (!instance.AppSettingExists(SettingsList.ForwardErrorMessages.Name) & !options.OverrideEnableErrorForwarding.Value)
                    {
                        logger.Warn($"Unattend upgrade {instance.Name} to {zipInfo.Version} not attempted. FORWARDERRORMESSAGES MSI parameter was required because appsettings needed a value for '{SettingsList.ForwardErrorMessages.Name}'");
                        continue;
                    }


                    if (!options.AuditRetentionPeriod.HasValue)
                    {
                        if (!instance.AppSettingExists(SettingsList.AuditRetentionPeriod.Name))
                        {
                            //Try migration first
                            if (instance.AppSettingExists(SettingsList.HoursToKeepMessagesBeforeExpiring.Name))
                            {
                                var i = instance.ReadAppSetting(SettingsList.HoursToKeepMessagesBeforeExpiring.Name, -1);
                                if (i > 0)
                                {
                                    options.AuditRetentionPeriod = TimeSpan.FromHours(i);
                                }
                            }
                            else
                            {
                                logger.Warn($"Unattend upgrade {instance.Name} to {zipInfo.Version} not attempted. AUDITRETENTIONPERIOD MSI parameter was required because appsettings needed a value for '{SettingsList.AuditRetentionPeriod.Name}'");
                                continue;
                            }
                        }
                    }

                    if (!instance.AppSettingExists(SettingsList.ErrorRetentionPeriod.Name) & !options.ErrorRetentionPeriod.HasValue)
                    {
                        logger.Warn($"Unattend upgrade {instance.Name} to {zipInfo.Version} not attempted. ERRORRETENTIONPERIOD MSI parameter was required because appsettings needed a value for '{SettingsList.ErrorRetentionPeriod.Name}'");
                        continue;
                    }

                    if (!unattendedInstaller.Upgrade(instance, options))
                    {
                        logger.Warn($"Failed to upgrade {instance.Name} to {zipInfo.Version}");
                    }
                }
            }
        }
示例#14
0
        async Task <bool> InstallServiceControlAudit(InstanceDetailsViewModel detailsViewModel, AddNewAuditInstanceViewModel viewModel, ServiceControlInstance instance)
        {
            var auditNewInstance = new ServiceControlAuditNewInstance
            {
                //Read from user configured values
                DisplayName             = viewModel.ServiceControlAudit.InstanceName,
                Name                    = viewModel.ServiceControlAudit.InstanceName.Replace(' ', '.'),
                ServiceDescription      = viewModel.ServiceControlAudit.Description,
                DBPath                  = viewModel.ServiceControlAudit.DatabasePath,
                LogPath                 = viewModel.ServiceControlAudit.LogPath,
                InstallPath             = viewModel.ServiceControlAudit.DestinationPath,
                HostName                = viewModel.ServiceControlAudit.HostName,
                Port                    = Convert.ToInt32(viewModel.ServiceControlAudit.PortNumber),
                DatabaseMaintenancePort = Convert.ToInt32(viewModel.ServiceControlAudit.DatabaseMaintenancePortNumber),
                ServiceAccount          = viewModel.ServiceControlAudit.ServiceAccount,
                ServiceAccountPwd       = viewModel.ServiceControlAudit.Password,

                //Copy from existing ServiceControl instance
                AuditLogQueue        = instance.AuditLogQueue,
                AuditQueue           = instance.AuditQueue,
                ForwardAuditMessages = instance.ForwardAuditMessages,
                // ReSharper disable once PossibleInvalidOperationException
                AuditRetentionPeriod       = instance.AuditRetentionPeriod.Value,
                TransportPackage           = instance.TransportPackage,
                ConnectionString           = instance.ConnectionString,
                ServiceControlQueueAddress = instance.Name
            };

            using (var progress = detailsViewModel.GetProgressObject("ADDING AUDIT INSTANCE"))
            {
                var installationCancelled = await InstallInstance(auditNewInstance, progress);

                if (installationCancelled)
                {
                    return(false);
                }
            }

            return(true);
        }
示例#15
0
 protected override void ProcessRecord()
 {
     WriteObject(ServiceControlInstance.Instances().Select(PsServiceControl.FromInstance), true);
 }
        public bool Upgrade(ServiceControlInstance instance, ServiceControlUpgradeOptions options)
        {
            if (instance.Version < options.UpgradeInfo.CurrentMinimumVersion)
            {
                logger.Error($"Upgrade aborted. An interim upgrade to version {options.UpgradeInfo.RecommendedUpgradeVersion} is required before upgrading to version {ZipInfo.Version}. Download available at https://github.com/Particular/ServiceControl/releases/tag/{options.UpgradeInfo.RecommendedUpgradeVersion}");
                return(false);
            }

            ZipInfo.ValidateZip();

            var checkLicenseResult = CheckLicenseIsValid();

            if (!checkLicenseResult.Valid)
            {
                logger.Error($"Upgrade aborted - {checkLicenseResult.Message}");
                return(false);
            }

            instance.ReportCard = new ReportCard();

            var restartService = instance.Service.Status == ServiceControllerStatus.Running;

            if (!instance.TryStopService())
            {
                logger.Error("Service failed to stop or service stop timed out");
            }

            try
            {
                var backupFile = instance.BackupAppConfig();
                try
                {
                    instance.UpgradeFiles(ZipInfo.FilePath);
                }
                finally
                {
                    instance.RestoreAppConfig(backupFile);
                }

                options.ApplyChangesToInstance(instance);

                if (options.UpgradeInfo.DeleteIndexes)
                {
                    instance.RemoveDatabaseIndexes();
                }

                if (options.UpgradeInfo.DataBaseUpdate)
                {
                    instance.UpdateDatabase(msg => { });
                }

                instance.SetupInstance();

                if (instance.ReportCard.HasErrors)
                {
                    foreach (var error in instance.ReportCard.Errors)
                    {
                        logger.Error(error);
                    }

                    return(false);
                }

                if (restartService && !instance.TryStartService())
                {
                    logger.Error("Service failed to start after update - please check configuration for {0}", instance.Name);
                    return(false);
                }
            }
            catch (Exception ex)
            {
                logger.Error("Upgrade Failed: {0}", ex.Message);
                return(false);
            }

            return(true);
        }
        public override async Task ExecuteAsync(InstanceDetailsViewModel model)
        {
            var licenseCheckResult = installer.CheckLicenseIsValid();

            if (!licenseCheckResult.Valid)
            {
                windowManager.ShowMessage("LICENSE ERROR", $"Upgrade could not continue due to an issue with the current license. {licenseCheckResult.Message}.  Contact [email protected]", hideCancel: true);
                return;
            }

            var instance = ServiceControlInstance.FindByName(model.Name);

            instance.Service.Refresh();

            var upgradeOptions = new InstanceUpgradeOptions();

            if (!instance.AppSettingExists(SettingsList.ForwardErrorMessages.Name))
            {
                var result = windowManager.ShowYesNoCancelDialog("UPGRADE QUESTION - DISABLE ERROR FORWARDING", "Error messages can be forwarded to a secondary error queue known as the Error Forwarding Queue. This queue exists to allow external tools to receive error messages. If you do not have a tool processing messages from the Error Forwarding Queue this setting should be disabled.", "So what do you want to do ?", "Do NOT forward", "Yes I want to forward");
                if (!result.HasValue)
                {
                    //Dialog was cancelled
                    eventAggregator.PublishOnUIThread(new RefreshInstances());
                    return;
                }
                upgradeOptions.OverrideEnableErrorForwarding = !result.Value;
            }

            //Grab old setting if it exists
            if (!instance.AppSettingExists(SettingsList.AuditRetentionPeriod.Name))
            {
                if (instance.AppSettingExists(SettingsList.HoursToKeepMessagesBeforeExpiring.Name))
                {
                    var i = instance.ReadAppSetting(SettingsList.HoursToKeepMessagesBeforeExpiring.Name, -1);
                    if (i != -1)
                    {
                        upgradeOptions.AuditRetentionPeriod = TimeSpan.FromHours(i);
                    }
                }

                // No setting to migrate so display dialog
                if (!upgradeOptions.AuditRetentionPeriod.HasValue)
                {
                    var viewModel = new SliderDialogViewModel("UPGRADE QUESTION - DATABASE RETENTION",
                                                              "Service Control periodically purges audit messages from the database.",
                                                              "AUDIT RETENTION PERIOD",
                                                              "Please specify the age at which these records should be removed",
                                                              TimeSpanUnits.Hours,
                                                              SettingConstants.AuditRetentionPeriodMinInHours,
                                                              SettingConstants.AuditRetentionPeriodMaxInHours,
                                                              1,
                                                              24,
                                                              SettingConstants.AuditRetentionPeriodDefaultInHoursForUI);

                    if (windowManager.ShowSliderDialog(viewModel))
                    {
                        upgradeOptions.AuditRetentionPeriod = viewModel.Period;
                    }
                    else
                    {
                        //Dialog was cancelled
                        eventAggregator.PublishOnUIThread(new RefreshInstances());
                        return;
                    }
                }
            }

            if (!instance.AppSettingExists(SettingsList.ErrorRetentionPeriod.Name))
            {
                var viewModel = new SliderDialogViewModel("UPGRADE QUESTION - DATABASE RETENTION",
                                                          "Service Control periodically purges resolved and archived error messages from the database.",
                                                          "ERROR RETENTION PERIOD",
                                                          "Please specify the age at which these records should be removed",
                                                          TimeSpanUnits.Days,
                                                          SettingConstants.ErrorRetentionPeriodMinInDays,
                                                          SettingConstants.ErrorRetentionPeriodMaxInDays,
                                                          1,
                                                          1,
                                                          SettingConstants.ErrorRetentionPeriodDefaultInDaysForUI);

                if (windowManager.ShowSliderDialog(viewModel))
                {
                    upgradeOptions.ErrorRetentionPeriod = viewModel.Period;
                }
                else
                {
                    //Dialog was cancelled
                    eventAggregator.PublishOnUIThread(new RefreshInstances());
                    return;
                }
            }

            var confirm = instance.Service.Status == ServiceControllerStatus.Stopped ||
                          windowManager.ShowYesNoDialog($"STOP INSTANCE AND UPGRADE TO {installer.ZipInfo.Version}", $"{model.Name} needs to be stopped in order to upgrade to version {installer.ZipInfo.Version}.", "Do you want to proceed?", "Yes I want to proceed", "No");

            if (confirm)
            {
                using (var progress = model.GetProgressObject($"UPGRADING {model.Name}"))
                {
                    var reportCard   = new ReportCard();
                    var restartAgain = model.IsRunning;

                    var stopped = await model.StopService(progress);

                    if (!stopped)
                    {
                        eventAggregator.PublishOnUIThread(new RefreshInstances());

                        reportCard.Errors.Add("Failed to stop the service");
                        reportCard.SetStatus();
                        windowManager.ShowActionReport(reportCard, "ISSUES UPGRADING INSTANCE", "Could not upgrade instance because of the following errors:");

                        return;
                    }

                    reportCard = await Task.Run(() => installer.Upgrade(model.Name, upgradeOptions, progress));

                    if (reportCard.HasErrors || reportCard.HasWarnings)
                    {
                        windowManager.ShowActionReport(reportCard, "ISSUES UPGRADING INSTANCE", "Could not upgrade instance because of the following errors:", "There were some warnings while upgrading the instance:");
                    }
                    else
                    {
                        if (restartAgain)
                        {
                            var serviceStarted = await model.StartService(progress);

                            if (!serviceStarted)
                            {
                                reportCard.Errors.Add("The Service failed to start. Please consult the service control logs for this instance");
                                windowManager.ShowActionReport(reportCard, "UPGRADE FAILURE", "Instance reported this error after upgrade:");
                            }
                        }
                    }
                }
                eventAggregator.PublishOnUIThread(new RefreshInstances());
            }
        }
示例#18
0
        public bool Add(ServiceControlInstanceMetadata details, Func <PathInfo, bool> promptToProceed)
        {
            ZipInfo.ValidateZip();

            var checkLicenseResult = CheckLicenseIsValid();

            if (!checkLicenseResult.Valid)
            {
                logger.Error($"Install aborted - {checkLicenseResult.Message}");
                return(false);
            }

            var instanceInstaller = details;

            instanceInstaller.ReportCard = new ReportCard();

            //Validation
            instanceInstaller.Validate(promptToProceed);
            if (instanceInstaller.ReportCard.HasErrors)
            {
                foreach (var error in instanceInstaller.ReportCard.Errors)
                {
                    logger.Error(error);
                }
                return(false);
            }

            try
            {
                instanceInstaller.CopyFiles(ZipInfo.FilePath);
                instanceInstaller.WriteConfigurationFile();
                instanceInstaller.RegisterUrlAcl();
                instanceInstaller.SetupInstance();
                instanceInstaller.RegisterService();
                foreach (var warning in instanceInstaller.ReportCard.Warnings)
                {
                    logger.Warn(warning);
                }

                if (instanceInstaller.ReportCard.HasErrors)
                {
                    foreach (var error in instanceInstaller.ReportCard.Errors)
                    {
                        logger.Error(error);
                    }
                    return(false);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message);
                return(false);
            }

            //Post Installation
            var instance = ServiceControlInstance.FindByName(instanceInstaller.Name);

            if (!instance.TryStartService())
            {
                logger.Warn("The service failed to start");
            }
            return(true);
        }