public System.Threading.Tasks.Task SavePackageAsync(Package package, CancellationToken cancellationToken)
        {
            if (package.Id > 0)
            {
                throw new InvalidOperationException("Only new package can be saved.");
            }
            var collection = GetPackages();
            var newId      = collection.Count == 0 ? 1 : collection.Max(t => t.Id) + 1;

            var packageDoc = new PackageDoc
            {
                Id               = newId,
                Description      = package.Description,
                ComponentId      = package.ComponentId,
                PackageType      = package.PackageType,
                ReleaseDate      = package.ReleaseDate,
                ExecutionDate    = package.ExecutionDate,
                ExecutionResult  = package.ExecutionResult,
                ComponentVersion = package.ComponentVersion,
                ExecutionError   = package.ExecutionError,
                Manifest         = package.Manifest,
            };

            package.Id = newId;
            collection.Insert(packageDoc);

            RepositoryVersionInfo.Reset();

            return(System.Threading.Tasks.Task.CompletedTask);
        }
Beispiel #2
0
        private static void SavePackage(Manifest manifest, ExecutionContext executionContext, bool successful, Exception execError)
        {
            var executionResult = successful ? ExecutionResult.Successful : ExecutionResult.Faulty;
            var isAppPack       = manifest.Type == PackageType.Application;

            RepositoryVersionInfo.Reset();
            var oldPacks = isAppPack
                ? RepositoryVersionInfo.Instance.InstalledPackages
                           .Where(p => p.AppId == manifest.AppId && p.ApplicationVersion == manifest.VersionControl.Target)
                           .OrderBy(p => p.ExecutionDate).ToList()
                : RepositoryVersionInfo.Instance.InstalledPackages
                           .Where(p => p.AppId == manifest.AppId && p.SenseNetVersion == manifest.VersionControl.Target)
                           .OrderBy(p => p.ExecutionDate).ToList();

            var oldPack = oldPacks.LastOrDefault();

            if (oldPack == null)
            {
                var newPack = CreatePackage(manifest, executionResult, execError);
                DataProvider.Current.SavePackage(newPack);
            }
            else
            {
                UpdatePackage(oldPack, manifest, executionResult, execError);
                DataProvider.Current.UpdatePackage(oldPack);
            }
        }
Beispiel #3
0
        internal static void SavePackage(Manifest manifest, ExecutionResult executionResult, Exception execError)
        {
            RepositoryVersionInfo.Reset();
            var oldPacks = RepositoryVersionInfo.Instance.InstalledPackages;

            if (manifest.PackageType == PackageType.Tool)
            {
                oldPacks = oldPacks
                           .Where(p => p.ComponentId == manifest.ComponentId && p.PackageType == PackageType.Tool &&
                                  p.ExecutionResult == ExecutionResult.Unfinished);
            }
            else
            {
                oldPacks = oldPacks
                           .Where(p => p.ComponentId == manifest.ComponentId && p.ComponentVersion == manifest.Version);
            }
            oldPacks = oldPacks.OrderBy(p => p.ExecutionDate).ToArray();

            var oldPack = oldPacks.LastOrDefault();

            if (oldPack == null)
            {
                var newPack = CreatePackage(manifest, executionResult, execError);
                Storage.SavePackageAsync(newPack, CancellationToken.None).GetAwaiter().GetResult();
            }
            else
            {
                UpdatePackage(oldPack, manifest, executionResult, execError);
                Storage.UpdatePackageAsync(oldPack, CancellationToken.None).GetAwaiter().GetResult();
            }
        }
Beispiel #4
0
        private static void SavePackage(Manifest manifest, ExecutionContext executionContext, bool successful, Exception execError)
        {
            var executionResult = successful ? ExecutionResult.Successful : ExecutionResult.Faulty;

            RepositoryVersionInfo.Reset();
            var oldPacks = RepositoryVersionInfo.Instance.InstalledPackages;

            if (manifest.PackageType == PackageType.Tool)
            {
                oldPacks = oldPacks
                           .Where(p => p.ComponentId == manifest.ComponentId && p.PackageType == PackageType.Tool &&
                                  p.ExecutionResult == ExecutionResult.Unfinished);
            }
            else
            {
                oldPacks = oldPacks
                           .Where(p => p.ComponentId == manifest.ComponentId && p.ComponentVersion == manifest.Version);
            }
            oldPacks = oldPacks.OrderBy(p => p.ExecutionDate).ToArray();

            var oldPack = oldPacks.LastOrDefault();

            if (oldPack == null)
            {
                var newPack = CreatePackage(manifest, executionResult, execError);
                Storage.SavePackage(newPack);
            }
            else
            {
                UpdatePackage(oldPack, manifest, executionResult, execError);
                Storage.UpdatePackage(oldPack);
            }
        }
        /* ==================================================================================== Package deletion */

        public async Task Packaging_DeleteOne()
        {
            await PackagingTestAsync(async() =>
            {
                await SavePackage("C1", "1.0", "00:00", "2016-01-01", PackageType.Install, ExecutionResult.Unfinished);
                await SavePackage("C1", "1.0", "01:00", "2016-01-01", PackageType.Install, ExecutionResult.Faulty);
                await SavePackage("C1", "1.0", "02:00", "2016-01-01", PackageType.Install, ExecutionResult.Successful);
                await SavePackage("C1", "1.1", "03:00", "2016-01-03", PackageType.Patch, ExecutionResult.Faulty);
                await SavePackage("C1", "1.1", "04:00", "2016-01-03", PackageType.Patch, ExecutionResult.Faulty);
                await SavePackage("C1", "1.1", "05:00", "2016-01-06", PackageType.Patch, ExecutionResult.Successful);
                await SavePackage("C1", "1.2", "06:00", "2016-01-07", PackageType.Patch, ExecutionResult.Unfinished);
                await SavePackage("C1", "1.2", "07:00", "2016-01-08", PackageType.Patch, ExecutionResult.Unfinished);
                await SavePackage("C1", "1.2", "08:00", "2016-01-09", PackageType.Patch, ExecutionResult.Faulty);
                await SavePackage("C1", "1.2", "09:00", "2016-01-09", PackageType.Patch, ExecutionResult.Faulty);
                await SavePackage("C1", "1.2", "10:00", "2016-01-09", PackageType.Patch, ExecutionResult.Successful);

                // action: delete all faulty and unfinished
                var packs = RepositoryVersionInfo.Instance.InstalledPackages
                            .Where(p => p.ExecutionResult != ExecutionResult.Successful);
                foreach (var package in packs)
                {
                    await PackageManager.Storage.DeletePackageAsync(package, CancellationToken.None);
                }

                RepositoryVersionInfo.Reset();

                // check
                var actual = string.Join(" | ", RepositoryVersionInfo.Instance.InstalledPackages
                                         .OrderBy(p => p.ComponentVersion)
                                         .Select(p => $"{p.PackageType.ToString()[0]}:{p.ComponentVersion}-{p.ExecutionDate.Hour}")
                                         .ToArray());
                var expected = "I:1.0-2 | P:1.1-5 | P:1.2-10";
                Assert.AreEqual(expected, actual);
            }).ConfigureAwait(false);
        }
Beispiel #6
0
        private void CheckPrerequisits(PackageParameter[] packageParameters, bool forcedReinstall, bool log, bool editConnectionString)
        {
            if (log)
            {
                Logger.LogMessage("ComponentId: {0}", this.ComponentId);
                Logger.LogMessage("PackageType:   " + this.PackageType);
                Logger.LogMessage("Package version: " + this.Version);
                if (SystemInstall)
                {
                    Logger.LogMessage(forcedReinstall ? "FORCED REINSTALL" : "SYSTEM INSTALL");
                }
            }

            if (SystemInstall && editConnectionString)
            {
                EditConnectionString(this.Parameters, packageParameters);
                RepositoryVersionInfo.Reset();
            }

            var versionInfo           = RepositoryVersionInfo.Instance;
            var existingComponentInfo = versionInfo.Components.FirstOrDefault(a => a.ComponentId == ComponentId);

            if (PackageType == PackageType.Install)
            {
                if (!(forcedReinstall && SystemInstall) && existingComponentInfo != null)
                {
                    // Install packages can be executed multiple times only if it is
                    // allowed in the package AND the version in the manifest is the
                    // same as in the db.
                    if (!this.MultipleExecutionAllowed || existingComponentInfo.Version != this.Version)
                    {
                        throw new PackagePreconditionException(
                                  string.Format(SR.Errors.Precondition.CannotInstallExistingComponent1, this.ComponentId),
                                  PackagingExceptionType.CannotInstallExistingComponent);
                    }
                }
            }
            else if (PackageType != PackageType.Tool)
            {
                if (existingComponentInfo == null)
                {
                    throw new PackagePreconditionException(string.Format(SR.Errors.Precondition.CannotUpdateMissingComponent1, this.ComponentId),
                                                           PackagingExceptionType.CannotUpdateMissingComponent);
                }
                if (existingComponentInfo.Version >= this.Version)
                {
                    throw new PackagePreconditionException(string.Format(SR.Errors.Precondition.TargetVersionTooSmall2, this.Version, existingComponentInfo.Version),
                                                           PackagingExceptionType.TargetVersionTooSmall);
                }
            }

            if (log && this.Dependencies.Any())
            {
                Logger.LogMessage("Dependencies:");
            }
            foreach (var dependency in this.Dependencies)
            {
                CheckDependency(dependency, versionInfo, log);
            }
        }
        internal static PackagingResult ExecutePhase(XmlDocument manifestXml, int phase, RepositoryStartSettings settings = null)
        {
            var manifest = Manifest.Parse(manifestXml, phase, true, new PackageParameter[0]);

            // Fill context with indexing folder, repo start settings, providers and other
            // parameters necessary for on-the-fly steps to run.
            var executionContext = ExecutionContext.Create("packagePath", "targetPath",
                                                           new string[0], "sandboxPath", manifest, phase, manifest.CountOfPhases,
                                                           null, null, settings);

            PackagingResult result;

            try
            {
                result = ExecuteCurrentPhase(manifest, executionContext);
            }
            finally
            {
                if (Repository.Started())
                {
                    SnTrace.System.Write("PackageManager: stopping repository ... ");
                    Repository.Shutdown();
                }
            }

            RepositoryVersionInfo.Reset();

            return(result);
        }
        protected PackagingResult ExecutePhase(XmlDocument manifestXml, int phase, TextWriter console = null)
        {
            var manifest         = Manifest.Parse(manifestXml, phase, true, new PackageParameter[0]);
            var executionContext = ExecutionContext.CreateForTest("packagePath", "targetPath", new string[0], "sandboxPath", manifest, phase, manifest.CountOfPhases, null, console);
            var result           = PackageManager.ExecuteCurrentPhase(manifest, executionContext);

            RepositoryVersionInfo.Reset();
            return(result);
        }
Beispiel #9
0
        private void InitializePackagingTest(RepositoryBuilder builder)
        {
            _log = new StringBuilder();
            var loggers   = new[] { new PackagingTestLogger(_log) };
            var loggerAcc = new TypeAccessor(typeof(SenseNet.Packaging.Logger));

            loggerAcc.SetStaticField("_loggers", loggers);

            RepositoryVersionInfo.Reset();
        }
 private async Task PackagingTestAsync(Func <Task> callback)
 {
     await NoRepoIntegrationTestAsync(async() =>
     {
         await Providers.Instance.DataProvider
         .GetExtension <IPackagingDataProviderExtension>()
         .DeleteAllPackagesAsync(CancellationToken.None)
         .ConfigureAwait(false);
         RepositoryVersionInfo.Reset();
         await callback().ConfigureAwait(false);
     }).ConfigureAwait(false);
 }
        /* ==================================================================================== TOOLS */

        private void PackagingTest(Action callback)
        {
            NoRepoIntegrationTest(() =>
            {
                Providers.Instance.DataProvider
                .GetExtension <IPackagingDataProviderExtension>()
                .DeleteAllPackagesAsync(CancellationToken.None)
                .ConfigureAwait(false).GetAwaiter().GetResult();
                RepositoryVersionInfo.Reset();
                callback();
            });
        }
Beispiel #12
0
        public void SavePackage(Package package)
        {
            if (package.Id > 0)
            {
                throw new InvalidOperationException("Only new package can be saved.");
            }

            package.Id = ++_id;
            Storage.Add(ClonePackage(package, true));

            RepositoryVersionInfo.Reset();
        }
Beispiel #13
0
        public void PrepareTest()
        {
            // preparing logger
            _log = new StringBuilder();
            var loggers   = new[] { new PackagingTestLogger(_log) };
            var loggerAcc = new PrivateType(typeof(Logger));

            loggerAcc.SetStaticField("_loggers", loggers);

            var unused = CreateRepositoryBuilderForTestInstance();

            RepositoryVersionInfo.Reset();
        }
        public Task SavePackageAsync(Package package, CancellationToken cancellationToken)
        {
            if (package.Id > 0)
            {
                throw new InvalidOperationException("Only new package can be saved.");
            }

            package.Id = ++_id;
            Storage.Add(ClonePackage(package, true));

            RepositoryVersionInfo.Reset();

            return(Task.CompletedTask);
        }
Beispiel #15
0
        public void PrepareTest()
        {
            // preparing logger
            _log = new StringBuilder();
            var loggers   = new[] { new PackagingTestLogger(_log) };
            var loggerAcc = new TypeAccessor(typeof(Logger));

            loggerAcc.SetStaticField("_loggers", loggers);

            var builder = CreateRepositoryBuilderForTest();

            builder.UsePackagingDataProviderExtension(new InMemoryPackageStorageProvider());

            RepositoryVersionInfo.Reset();
        }
Beispiel #16
0
        public void PrepareTest()
        {
            // preparing logger
            _log = new StringBuilder();
            var loggers   = new[] { new PackagingTestLogger(_log) };
            var loggerAcc = new PrivateType(typeof(Logger));

            loggerAcc.SetStaticField("_loggers", loggers);

            var storage = new TestPackageStorageProvider();

            _packageStorageProviderFactoryBackup = PackageManager.StorageFactory;
            PackageManager.StorageFactory        = new TestPackageStorageProviderFactory(storage);

            RepositoryVersionInfo.Reset();
        }
Beispiel #17
0
        public void PrepareTest()
        {
            // preparing logger
            _log = new StringBuilder();
            var loggers   = new[] { new PackagingTestLogger(_log) };
            var loggerAcc = new TypeAccessor(typeof(Logger));

            loggerAcc.SetStaticField("_loggers", loggers);

            var builder = CreateRepositoryBuilderForTest(TestContext, services =>
            {
                services.AddSingleton <IPackagingDataProvider, InMemoryPackageStorageProvider>();
            });

            RepositoryVersionInfo.Reset();
        }
Beispiel #18
0
        private void InitializePackagingTest(RepositoryBuilder builder)
        {
            _log = new StringBuilder();
            var loggers   = new[] { new PackagingTestLogger(_log) };
            var loggerAcc = new TypeAccessor(typeof(SenseNet.Packaging.Logger));

            loggerAcc.SetStaticField("_loggers", loggers);

            using (var ctx = new MsSqlDataContext(ConnectionStrings.ConnectionString, DataOptions.GetLegacyConfiguration(), CancellationToken.None))
            {
                DropPackagesTable(ctx);
                InstallPackagesTable(ctx);
            }

            RepositoryVersionInfo.Reset();
        }
Beispiel #19
0
        /*================================================= tools */

        protected async Task SavePackage(string id, string version, string execTime, string releaseDate, PackageType packageType, ExecutionResult result)
        {
            var package = new Package
            {
                ComponentId      = id,
                ComponentVersion = Version.Parse(version),
                Description      = $"{id}-Description",
                ExecutionDate    = DateTime.Parse($"2017-03-30 {execTime}"),
                ReleaseDate      = DateTime.Parse(releaseDate),
                ExecutionError   = null,
                ExecutionResult  = result,
                PackageType      = packageType,
            };

            await PackageManager.Storage.SavePackageAsync(package, CancellationToken.None);

            RepositoryVersionInfo.Reset();
        }
Beispiel #20
0
        public void InitializeTest()
        {
            // preparing logger
            _log = new StringBuilder();
            var loggers   = new[] { new PackagingTestLogger(_log) };
            var loggerAcc = new PrivateType(typeof(Logger));

            loggerAcc.SetStaticField("_loggers", loggers);

            // preparing database
            ConnectionStrings.ConnectionString = ConnectionString;
            var proc = DataProvider.CreateDataProcedure("DELETE FROM [Packages]");

            proc.CommandType = CommandType.Text;
            proc.ExecuteNonQuery();
            proc             = DataProvider.CreateDataProcedure("DBCC CHECKIDENT ('[Packages]', RESEED, 1)");
            proc.CommandType = CommandType.Text;
            proc.ExecuteNonQuery();

            RepositoryVersionInfo.Reset();
        }
Beispiel #21
0
        internal static void SavePackage(Manifest manifest, ExecutionResult executionResult, Exception execError, bool insertOnly = false)
        {
            // Ensure consistency of local version-info before determining the installed packages.
            RepositoryVersionInfo.Reset(true);

            var oldPacks = RepositoryVersionInfo.Instance.InstalledPackages;

            if (manifest.PackageType == PackageType.Tool)
            {
                oldPacks = oldPacks
                           .Where(p => p.ComponentId == manifest.ComponentId && p.PackageType == PackageType.Tool &&
                                  p.ExecutionResult == ExecutionResult.Unfinished);
            }
            else
            {
                oldPacks = oldPacks
                           .Where(p => p.ComponentId == manifest.ComponentId && p.ComponentVersion == manifest.Version);
            }
            oldPacks = oldPacks.OrderBy(p => p.ExecutionDate).ToArray();

            var oldPack = oldPacks.LastOrDefault();

            if (oldPack == null || insertOnly)
            {
                var newPack = CreatePackage(manifest, executionResult, execError);
                Storage.SavePackageAsync(newPack, CancellationToken.None).GetAwaiter().GetResult();
            }
            else
            {
                UpdatePackage(oldPack, manifest, executionResult, execError);
                Storage.UpdatePackageAsync(oldPack, CancellationToken.None).GetAwaiter().GetResult();
            }

            // Ensure consistency of local version-info after persisting every executed package.
            RepositoryVersionInfo.Reset(true);
        }
        private static void PatchAndCheck(string componentId,
                                          Version[] packageVersions,
                                          Version[] successfulPatchVersions,
                                          Version[] failedPatchVersions,
                                          Version expectedVersion)
        {
            Version initialVersion = null;

            // install mock packages
            if (packageVersions?.Any() ?? false)
            {
                // the first should be an install package, Patch packages will follow
                var install = true;

                foreach (var packageVersion in packageVersions)
                {
                    PackageManager.Storage.SavePackage(new Package
                    {
                        ComponentId      = componentId,
                        ComponentVersion = packageVersion,
                        ExecutionResult  = ExecutionResult.Successful,
                        PackageType      = install ? PackageType.Install : PackageType.Patch
                    });

                    install = false;
                }

                RepositoryVersionInfo.Reset();

                initialVersion = packageVersions.Last();
            }

            var installedComponent = RepositoryVersionInfo.Instance.Components.Single(c => c.ComponentId == componentId);

            if (installedComponent != null)
            {
                Assert.AreEqual(initialVersion, installedComponent.Version);
            }

            var assemblyComponent = RepositoryVersionInfo.GetAssemblyComponents()
                                    .Single(c => c.ComponentId == componentId);

            // ACTION
            var results = PackageManager.ExecuteAssemblyPatches(assemblyComponent);

            // reload version info
            installedComponent = RepositoryVersionInfo.Instance.Components.Single(c => c.ComponentId == componentId);

            if (successfulPatchVersions?.Any() ?? false)
            {
                // the component was successfully upgraded
                foreach (var patchVersion in successfulPatchVersions)
                {
                    Assert.IsTrue(results[patchVersion].Successful);
                }
            }
            if (failedPatchVersions?.Any() ?? false)
            {
                // there should be failed patch results
                foreach (var patchVersion in failedPatchVersions)
                {
                    Assert.IsFalse(results[patchVersion].Successful);
                }
            }

            if (!(successfulPatchVersions?.Any() ?? false) && !(failedPatchVersions?.Any() ?? false))
            {
                // no patch is expected
                Assert.IsFalse(results?.Keys.Any() ?? false);
            }

            if (installedComponent != null)
            {
                Assert.AreEqual(expectedVersion, installedComponent.Version);
            }
        }
Beispiel #23
0
        internal static PackagingResult ExecuteCurrentPhase(Manifest manifest, ExecutionContext executionContext)
        {
            var sysInstall   = manifest.SystemInstall;
            var currentPhase = executionContext.CurrentPhase;

            if (0 == currentPhase - (sysInstall ? 1 : 0))
            {
                SaveInitialPackage(manifest);
            }

            var stepElements = manifest.GetPhase(executionContext.CurrentPhase);

            var stopper = Stopwatch.StartNew();

            Logger.LogMessage("Executing steps");

            Exception phaseException = null;
            var       successful     = false;

            try
            {
                var maxStepId = stepElements.Count;
                for (int i = 0; i < maxStepId; i++)
                {
                    var stepElement = stepElements[i];
                    var step        = Step.Parse(stepElement, i, executionContext);

                    var stepStopper = Stopwatch.StartNew();
                    Logger.LogStep(step, maxStepId);
                    step.Execute(executionContext);
                    stepStopper.Stop();
                    Logger.LogMessage("-------------------------------------------------------------");
                    Logger.LogMessage("Time: " + stepStopper.Elapsed);
                    if (executionContext.Terminated)
                    {
                        LogTermination(executionContext);
                        break;
                    }
                }
                stopper.Stop();
                Logger.LogMessage("=============================================================");
                Logger.LogMessage("All steps were executed.");
                Logger.LogMessage("Aggregated time: " + stopper.Elapsed);
                Logger.LogMessage("Errors: " + Logger.Errors);
                successful = true;
            }
            catch (Exception e)
            {
                phaseException = e;
            }

            var finished = executionContext.Terminated || (executionContext.CurrentPhase == manifest.CountOfPhases - 1);

            if (successful && !finished)
            {
                return new PackagingResult {
                           NeedRestart = true, Successful = true, Errors = Logger.Errors
                }
            }
            ;

            if (executionContext.Terminated && executionContext.TerminationReason == TerminationReason.Warning)
            {
                successful = false;

                phaseException = new PackageTerminatedException(executionContext.TerminationMessage);
            }

            try
            {
                SavePackage(manifest, executionContext, successful, phaseException);
            }
            catch (Exception e)
            {
                if (phaseException != null)
                {
                    Logger.LogException(phaseException);
                }
                throw new PackagingException("Cannot save the package.", e);
            }
            finally
            {
                RepositoryVersionInfo.Reset();

                // we need to shut down messaging, because the line above uses it
                if (!executionContext.Test)
                {
                    DistributedApplication.ClusterChannel.ShutDown();
                }
                else
                {
                    Diagnostics.SnTrace.Test.Write("DistributedApplication.ClusterChannel.ShutDown SKIPPED because it is a test context.");
                }
            }
            if (!successful && !executionContext.Terminated)
            {
                throw new ApplicationException(String.Format(SR.Errors.PhaseFinishedWithError_1, phaseException.Message), phaseException);
            }

            return(new PackagingResult {
                NeedRestart = false, Successful = successful, Terminated = executionContext.Terminated && !successful, Errors = Logger.Errors
            });
        }
Beispiel #24
0
        private static PackagingResult ExecuteCurrentPhase(Manifest manifest, ExecutionContext executionContext)
        {
            if (executionContext.CurrentPhase == 0)
            {
                SaveInitialPackage(manifest);
            }

            var steps = manifest.GetPhase(executionContext.CurrentPhase);

            var stopper = Stopwatch.StartNew();

            Logger.LogMessage("Executing steps");

            Exception phaseException = null;
            var       successful     = false;

            try
            {
                var maxStepId = steps.Count();
                foreach (var step in steps)
                {
                    var stepStopper = Stopwatch.StartNew();
                    Logger.LogStep(step, maxStepId);
                    step.Execute(executionContext);
                    stepStopper.Stop();
                    Logger.LogMessage("-------------------------------------------------------------");
                    Logger.LogMessage("Time: " + stepStopper.Elapsed);
                }
                stopper.Stop();
                Logger.LogMessage("=============================================================");
                Logger.LogMessage("All steps were executed.");
                Logger.LogMessage("Aggregated time: " + stopper.Elapsed);
                Logger.LogMessage("Errors: " + Logger.Errors);
                successful = true;
            }
            catch (Exception e)
            {
                phaseException = e;
            }

            if (successful && (executionContext.CurrentPhase < manifest.CountOfPhases - 1))
            {
                return new PackagingResult {
                           NeedRestart = true, Successful = true, Errors = Logger.Errors
                }
            }
            ;

            try
            {
                if (Logger.Level <= LogLevel.Default)
                {
                    SavePackage(manifest, executionContext, successful, phaseException);
                }
            }
            finally
            {
                RepositoryVersionInfo.Reset();

                //we need to shut down messaging, because the line above uses it
                DistributedApplication.ClusterChannel.ShutDown();
            }
            if (!successful)
            {
                throw new ApplicationException(String.Format(SR.Errors.PhaseFinishedWithError_1, phaseException.Message), phaseException);
            }

            return(new PackagingResult {
                NeedRestart = false, Successful = true, Errors = Logger.Errors
            });
        }
Beispiel #25
0
        private static PackagingResult ExecuteCurrentPhase(Manifest manifest, ExecutionContext executionContext)
        {
            if (manifest.Type == PackageType.Product && manifest.Level == PackageLevel.Install)
            {
                // In case of product install create initial entry at the beginning of the
                // second phase, after the new db was created in the first phase.
                if (executionContext.CurrentPhase == 1)
                {
                    SaveInitialPackage(manifest);
                }
            }
            else
            {
                if (executionContext.CurrentPhase == 0)
                {
                    SaveInitialPackage(manifest);
                }
            }

            var stepElements = manifest.GetPhase(executionContext.CurrentPhase);

            var stopper = Stopwatch.StartNew();

            Logger.LogMessage("Executing steps");

            Exception phaseException = null;
            var       successful     = false;

            try
            {
                var maxStepId = stepElements.Count();
                for (int i = 0; i < maxStepId; i++)
                {
                    var stepElement = stepElements[i];
                    var step        = Step.Parse(stepElement, i);
                    executionContext.SubstituteParameters(step);

                    var stepStopper = Stopwatch.StartNew();
                    Logger.LogStep(step, maxStepId);
                    step.Execute(executionContext);
                    stepStopper.Stop();
                    Logger.LogMessage("-------------------------------------------------------------");
                    Logger.LogMessage("Time: " + stepStopper.Elapsed);
                    if (executionContext.Terminated)
                    {
                        LogTermination(executionContext);
                        break;
                    }
                }
                stopper.Stop();
                Logger.LogMessage("=============================================================");
                Logger.LogMessage("All steps were executed.");
                Logger.LogMessage("Aggregated time: " + stopper.Elapsed);
                Logger.LogMessage("Errors: " + Logger.Errors);
                successful = true;
            }
            catch (Exception e)
            {
                phaseException = e;
            }

            var finished = executionContext.Terminated || (executionContext.CurrentPhase == manifest.CountOfPhases - 1);

            if (successful && !finished)
            {
                return new PackagingResult {
                           NeedRestart = true, Successful = true, Errors = Logger.Errors
                }
            }
            ;

            if (executionContext.Terminated && executionContext.TerminationReason == TerminationReason.Warning)
            {
                successful = false;

                phaseException = new PackageTerminatedException(executionContext.TerminationMessage);
            }

            try
            {
                SavePackage(manifest, executionContext, successful, phaseException);
            }
            finally
            {
                RepositoryVersionInfo.Reset();

                //we need to shut down messaging, because the line above uses it
                DistributedApplication.ClusterChannel.ShutDown();
            }
            if (!successful && !executionContext.Terminated)
            {
                throw new ApplicationException(String.Format(SR.Errors.PhaseFinishedWithError_1, phaseException.Message), phaseException);
            }

            return(new PackagingResult {
                NeedRestart = false, Successful = successful, Terminated = executionContext.Terminated && !successful, Errors = Logger.Errors
            });
        }