Пример #1
0
        /// <summary>
        /// Runs the all specified package migration plans and publishes a <see cref="MigrationPlansExecutedNotification"/>
        /// if all are successful.
        /// </summary>
        /// <param name="plansToRun"></param>
        /// <returns></returns>
        /// <exception cref="Exception">If any plan fails it will throw an exception.</exception>
        public IEnumerable <ExecutedMigrationPlan> RunPackagePlans(IEnumerable <string> plansToRun)
        {
            var results = new List <ExecutedMigrationPlan>();

            // Create an explicit scope around all package migrations so they are
            // all executed in a single transaction. If one package migration fails,
            // none of them will be committed. This is intended behavior so we can
            // ensure when we publish the success notification that is is done when they all succeed.
            using (ICoreScope scope = _scopeProvider.CreateCoreScope(autoComplete: true))
            {
                foreach (var migrationName in plansToRun)
                {
                    if (!_packageMigrationPlans.TryGetValue(migrationName, out PackageMigrationPlan? plan))
                    {
                        throw new InvalidOperationException("Cannot find package migration plan " + migrationName);
                    }

                    using (_profilingLogger.TraceDuration <PackageMigrationRunner>(
                               "Starting unattended package migration for " + migrationName,
                               "Unattended upgrade completed for " + migrationName))
                    {
                        var upgrader = new Upgrader(plan);
                        // This may throw, if so the transaction will be rolled back
                        results.Add(upgrader.Execute(_migrationPlanExecutor, _scopeProvider, _keyValueService));
                    }
                }
            }

            var executedPlansNotification = new MigrationPlansExecutedNotification(results);

            _eventAggregator.Publish(executedPlansNotification);

            return(results);
        }
Пример #2
0
        // executes the step
        internal async Task <InstallSetupResult> ExecuteStepAsync(InstallSetupStep step, object instruction)
        {
            using (_proflog.TraceDuration <InstallApiController>($"Executing installation step: '{step.Name}'.",
                                                                 "Step completed"))
            {
                var modelAttempt = instruction.TryConvertTo(step.StepType);
                if (!modelAttempt.Success)
                {
                    throw new InvalidCastException(
                              $"Cannot cast/convert {step.GetType().FullName} into {step.StepType.FullName}");
                }

                var    model           = modelAttempt.Result;
                var    genericStepType = typeof(InstallSetupStep <>);
                Type[] typeArgs        = { step.StepType };
                var    typedStepType   = genericStepType.MakeGenericType(typeArgs);
                try
                {
                    var method = typedStepType.GetMethods().Single(x => x.Name == "ExecuteAsync");
                    var task   = (Task <InstallSetupResult>)method.Invoke(step, new[] { model });
                    return(await task);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Installation step {Step} failed.", step.Name);
                    throw;
                }
            }
        }
Пример #3
0
        /// <summary>
        /// Used to lazily check if Examine Index handling is enabled
        /// </summary>
        /// <returns></returns>
        private bool IsEnabled()
        {
            //let's deal with shutting down Examine with MainDom
            var examineShutdownRegistered = _mainDom.Register(release: () =>
            {
                using (_profilingLogger.TraceDuration <ExamineUmbracoIndexingHandler>("Examine shutting down"))
                {
                    _examineManager.Dispose();
                }
            });

            if (!examineShutdownRegistered)
            {
                _logger.LogInformation("Examine shutdown not registered, this AppDomain is not the MainDom, Examine will be disabled");

                //if we could not register the shutdown examine ourselves, it means we are not maindom! in this case all of examine should be disabled!
                Suspendable.ExamineEvents.SuspendIndexers(_logger);
                return(false); //exit, do not continue
            }

            _logger.LogDebug("Examine shutdown registered with MainDom");

            var registeredIndexers = _examineManager.Indexes.OfType <IUmbracoIndex>().Count(x => x.EnableDefaultEventHandler);

            _logger.LogInformation("Adding examine event handlers for {RegisteredIndexers} index providers.", registeredIndexers);

            // don't bind event handlers if we're not suppose to listen
            if (registeredIndexers == 0)
            {
                return(false);
            }

            return(true);
        }
Пример #4
0
        public override bool PerformRun()
        {
            // Do not run the code on replicas nor unknown role servers
            // ONLY run for Master server or Single
            switch (_runtime.ServerRole)
            {
            case ServerRole.Replica:
                _logger.Debug <CleanRoom>("Does not run on replica servers.");
                return(true);    // We return true to try again as the server role may change!

            case ServerRole.Unknown:
                _logger.Debug <CleanRoom>("Does not run on servers with unknown role.");
                return(true);    // We return true to try again as the server role may change!
            }

            if (_contentService.RecycleBinSmells())
            {
                // Take out the trash
                using (_logger.TraceDuration <CleanRoom>("Mum, I am emptying out the bin", "Its all clean now!"))
                {
                    _contentService.EmptyRecycleBin(userId: -1);
                }
            }

            // If we want to keep repeating - we need to return true
            // But if we run into a problem/error & want to stop repeating - return false
            return(true);
        }
Пример #5
0
        private void RebuildDatabaseCacheIfSerializerChanged()
        {
            var serializer        = ConfigurationManager.AppSettings[Nucache_Serializer_Key];
            var currentSerializer = _keyValueService.GetValue(Nucache_Serializer_Key);

            if (currentSerializer == null)
            {
                currentSerializer = JSON_SERIALIZER_VALUE;
            }
            if (serializer == null)
            {
                serializer = JSON_SERIALIZER_VALUE;
            }

            if (serializer != currentSerializer)
            {
                _profilingLogger.Warn <NuCacheSerializerComponent>($"Database NuCache was serialized using {currentSerializer}. Currently configured NuCache serializer {serializer}. Rebuilding Nucache");

                using (_profilingLogger.TraceDuration <NuCacheSerializerComponent>($"Rebuilding NuCache database with {currentSerializer} serializer"))
                {
                    _service.Value.Rebuild();
                    _keyValueService.SetValue(Nucache_Serializer_Key, serializer);
                }
            }
        }
Пример #6
0
        public Task HandleAsync(RuntimeUnattendedUpgradeNotification notification, CancellationToken cancellationToken)
        {
            if (_runtimeState.RunUnattendedBootLogic())
            {
                switch (_runtimeState.Reason)
                {
                case RuntimeLevelReason.UpgradeMigrations:
                {
                    var plan = new UmbracoPlan(_umbracoVersion);
                    using (_profilingLogger.TraceDuration <UnattendedUpgrader>(
                               "Starting unattended upgrade.",
                               "Unattended upgrade completed."))
                    {
                        DatabaseBuilder.Result result = _databaseBuilder.UpgradeSchemaAndData(plan);
                        if (result.Success == false)
                        {
                            var innerException = new UnattendedInstallException("An error occurred while running the unattended upgrade.\n" + result.Message);
                            _runtimeState.Configure(Core.RuntimeLevel.BootFailed, Core.RuntimeLevelReason.BootFailedOnException, innerException);
                        }

                        notification.UnattendedUpgradeResult = RuntimeUnattendedUpgradeNotification.UpgradeResult.CoreUpgradeComplete;
                    }
                }
                break;

                case RuntimeLevelReason.UpgradePackageMigrations:
                {
                    if (!_runtimeState.StartupState.TryGetValue(RuntimeState.PendingPacakgeMigrationsStateKey, out var pm) ||
                        pm is not IReadOnlyList <string> pendingMigrations)
                    {
                        throw new InvalidOperationException($"The required key {RuntimeState.PendingPacakgeMigrationsStateKey} does not exist in startup state");
                    }

                    if (pendingMigrations.Count == 0)
                    {
                        throw new InvalidOperationException("No pending migrations found but the runtime level reason is " + Core.RuntimeLevelReason.UpgradePackageMigrations);
                    }

                    try
                    {
                        IEnumerable <ExecutedMigrationPlan> result = _packageMigrationRunner.RunPackagePlans(pendingMigrations);
                        notification.UnattendedUpgradeResult = RuntimeUnattendedUpgradeNotification.UpgradeResult.PackageMigrationComplete;
                    }
                    catch (Exception ex)
                    {
                        SetRuntimeError(ex);
                        notification.UnattendedUpgradeResult = RuntimeUnattendedUpgradeNotification.UpgradeResult.HasErrors;
                    }
                }
                break;

                default:
                    throw new InvalidOperationException("Invalid reason " + _runtimeState.Reason);
                }
            }

            return(Task.CompletedTask);
        }
Пример #7
0
        private bool LoadContentFromDatabaseLocked(bool onStartup)
        {
            // locks:
            // contentStore is wlocked (1 thread)
            // content (and types) are read-locked

            var contentTypes = _serviceContext.ContentTypeService.GetAll().ToList();

            _contentStore.SetAllContentTypesLocked(contentTypes.Select(x => _publishedContentTypeFactory.CreateContentType(x)));

            using (_profilingLogger.TraceDuration <PublishedSnapshotService>("Loading content from database"))
            {
                // beware! at that point the cache is inconsistent,
                // assuming we are going to SetAll content items!

                _localContentDb?.Clear();

                // IMPORTANT GetAllContentSources sorts kits by level + parentId + sortOrder
                var kits = _publishedContentService.GetAllContentSources();
                return(onStartup ? _contentStore.SetAllFastSortedLocked(kits, true) : _contentStore.SetAllLocked(kits));
            }
        }
Пример #8
0
        public void RebuildDatabaseCacheIfSerializerChanged()
        {
            NuCacheSerializerType serializer = _nucacheSettings.Value.NuCacheSerializerType;
            var currentSerializerValue       = _keyValueService.GetValue(NuCacheSerializerKey);

            if (!Enum.TryParse(currentSerializerValue, out NuCacheSerializerType currentSerializer) ||
                serializer != currentSerializer)
            {
                _logger.LogWarning("Database NuCache was serialized using {CurrentSerializer}. Currently configured NuCache serializer {Serializer}. Rebuilding Nucache", currentSerializer, serializer);

                using (_profilingLogger.TraceDuration <NuCacheContentService>($"Rebuilding NuCache database with {serializer} serializer"))
                {
                    Rebuild();
                    _keyValueService.SetValue(NuCacheSerializerKey, serializer.ToString());
                }
            }
        }
Пример #9
0
 // executes the step
 internal InstallSetupResult ExecuteStep(InstallSetupStep step, JToken instruction)
 {
     using (_proflog.TraceDuration <InstallApiController>($"Executing installation step: '{step.Name}'.", "Step completed"))
     {
         var    model           = instruction?.ToObject(step.StepType);
         var    genericStepType = typeof(InstallSetupStep <>);
         Type[] typeArgs        = { step.StepType };
         var    typedStepType   = genericStepType.MakeGenericType(typeArgs);
         try
         {
             var method = typedStepType.GetMethods().Single(x => x.Name == "Execute");
             return((InstallSetupResult)method.Invoke(step, new[] { model }));
         }
         catch (Exception ex)
         {
             _logger.Error <InstallApiController>(ex, "Installation step {Step} failed.", step.Name);
             throw;
         }
     }
 }