Exemplo n.º 1
0
        static void Install()
        {
            LogFile.WriteMessage("*** Installing " + IbnConst.ProductName + " ***");
            try
            {
                IIisManager iisManager = IisManager.Create(Settings.InstallDirWeb);

                InstallMmc30();
                InstallServices();
                RegisterIMServer(true, Settings.InstallDirWeb, iisManager.Is64Bit());
                StartServices();
                UpdateRegistry();
                RegisterAspNet(iisManager);
                //throw new Exception();

                LogFile.WriteMessage("*** OK ***");
            }
            catch
            {
                LogFile.WriteMessage("*** Failed ***");
                if (_actions.Count > 0)
                {
                    LogFile.WriteMessage("");
                    LogFile.WriteMessage("Rollback started");
                    try
                    {
                        RollBack();
                    }
                    catch {}
                    LogFile.WriteMessage("Rollback finished");
                }
                throw;
            }
        }
Exemplo n.º 2
0
        public static async Task <DeployerApp> BuildAppAsync([NotNull] string[] inputArgs,
                                                             ILogger?logger = null,
                                                             CancellationToken cancellationToken = default)
        {
            if (inputArgs is null)
            {
                throw new ArgumentNullException(nameof(inputArgs));
            }

            var args = inputArgs.ToImmutableArray();

            bool hasDefinedLogger = logger is {};

            string outputTemplate = GetOutputTemplate(args);

            var levelSwitch = new LoggingLevelSwitch();

            logger ??= new LoggerConfiguration()
            .WriteTo.Console(outputTemplate: outputTemplate, standardErrorFromLevel: LogEventLevel.Error)
            .MinimumLevel.ControlledBy(levelSwitch)
            .CreateLogger();

            logger.Verbose("Using output template {Template}", outputTemplate);

            try
            {
                string?machineSettings =
                    GetMachineSettingsFile(new DirectoryInfo(Path.Combine(
                                                                 Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "tools", "Milou.Deployer")));

                AppSettingsBuilder appSettingsBuilder;

                try
                {
                    appSettingsBuilder = KeyValueConfigurationManager
                                         .Add(new ReflectionKeyValueConfiguration(typeof(AppBuilder).Assembly))
                                         .Add(new ReflectionKeyValueConfiguration(typeof(ConfigurationKeys).Assembly));
                }
                catch (Exception ex) when(!ex.IsFatal())
                {
                    logger.Error(ex, "Could note create settings");
                    throw;
                }

                if (!string.IsNullOrWhiteSpace(machineSettings))
                {
                    logger.Information("Using machine specific configuration file '{Settings}'", machineSettings);
                    appSettingsBuilder =
                        appSettingsBuilder.Add(new JsonKeyValueConfiguration(machineSettings, false));
                }

                string?configurationFile =
                    Environment.GetEnvironmentVariable(ConfigurationKeys.KeyValueConfigurationFile);

                if (!string.IsNullOrWhiteSpace(configurationFile) && File.Exists(configurationFile))
                {
                    logger.Information("Using configuration values from file '{ConfigurationFile}'", configurationFile);
                    appSettingsBuilder =
                        appSettingsBuilder.Add(new JsonKeyValueConfiguration(configurationFile, false));
                }

                var argsAsParameters = args
                                       .Where(arg => arg.StartsWith("-", StringComparison.OrdinalIgnoreCase))
                                       .Select(arg => arg.TrimStart('-'))
                                       .ToImmutableArray();

                MultiSourceKeyValueConfiguration configuration = appSettingsBuilder
                                                                 .Add(new EnvironmentVariableKeyValueConfigurationSource())
                                                                 .AddCommandLineArgsSettings(argsAsParameters)
                                                                 .Add(new UserJsonConfiguration())
                                                                 .Build();

                logger.Debug("Using configuration: {Configuration}", configuration.SourceChain);

                string logPath = configuration[ConsoleConfigurationKeys.LoggingFilePath];

                string environmentLogLevel =
                    configuration[ConfigurationKeys.LogLevelEnvironmentVariable];

                string configurationLogLevel = configuration[ConfigurationKeys.LogLevel];

                var logLevel =
                    Arbor.App.Extensions.Logging.LogEventLevelExtensions.ParseOrDefault(
                        environmentLogLevel.WithDefault(configurationLogLevel));

                levelSwitch.MinimumLevel = logLevel;

                LoggerConfiguration loggerConfiguration = new LoggerConfiguration()
                                                          .WriteTo.Console(outputTemplate: outputTemplate);

                if (!string.IsNullOrWhiteSpace(logPath))
                {
                    loggerConfiguration = loggerConfiguration.WriteTo.File(logPath);
                }

                if (!hasDefinedLogger)
                {
                    if (logger is IDisposable disposable)
                    {
                        disposable.Dispose();
                    }

                    logger = loggerConfiguration
                             .MinimumLevel.ControlledBy(levelSwitch)
                             .CreateLogger();
                }

                if (!string.IsNullOrWhiteSpace(machineSettings))
                {
                    logger.Information("Using machine specific configuration file '{Settings}'", machineSettings);
                }

                string?nugetSource = args.GetArgumentValueOrDefault("nuget-source");
                string?nugetConfig = args.GetArgumentValueOrDefault("nuget-config");

                var webDeployConfig = new WebDeployConfig(new WebDeployRulesConfig(
                                                              true,
                                                              true,
                                                              false,
                                                              true,
                                                              true));

                bool allowPreReleaseEnabled =
                    configuration[ConfigurationKeys.AllowPreReleaseEnvironmentVariable]
                    .ParseAsBooleanOrDefault() ||
                    (Debugger.IsAttached &&
                     configuration[ConfigurationKeys.ForceAllowPreRelease]
                     .ParseAsBooleanOrDefault());

                string?nuGetExePath = configuration[ConfigurationKeys.NuGetExePath];

                if (string.IsNullOrWhiteSpace(nuGetExePath))
                {
                    logger.Debug("nuget.exe is not specified, downloading with {Tool}", nameof(NuGetDownloadClient));

                    using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30)))
                    {
                        var nuGetDownloadClient = new NuGetDownloadClient();
                        NuGetDownloadResult nuGetDownloadResult;

                        using (var httpClient = new HttpClient())
                        {
                            nuGetDownloadResult = await nuGetDownloadClient
                                                  .DownloadNuGetAsync(NuGetDownloadSettings.Default, logger, httpClient, cts.Token)
                                                  .ConfigureAwait(false);
                        }

                        if (!nuGetDownloadResult.Succeeded)
                        {
                            throw new InvalidOperationException(
                                      Resources.NuGetExeCouldNotBeDownloaded);
                        }

                        nuGetExePath = nuGetDownloadResult.NuGetExePath;
                    }

                    logger.Debug("Successfully downloaded nuget.exe to '{DownloadedPath}'", nuGetExePath);
                }

                var deployerConfiguration = new DeployerConfiguration(webDeployConfig)
                {
                    NuGetExePath               = nuGetExePath,
                    NuGetConfig                = nugetConfig.WithDefault(configuration[ConfigurationKeys.NuGetConfig]),
                    NuGetSource                = nugetSource.WithDefault(configuration[ConfigurationKeys.NuGetSource]),
                    AllowPreReleaseEnabled     = allowPreReleaseEnabled,
                    StopStartIisWebSiteEnabled = configuration[ConfigurationKeys.StopStartIisWebSiteEnabled]
                                                 .ParseAsBooleanOrDefault(true)
                };

                var nuGetCliSettings = new NuGetCliSettings(
                    deployerConfiguration.NuGetSource,
                    nuGetExePath: deployerConfiguration.NuGetExePath,
                    nugetConfigFile: deployerConfiguration.NuGetConfig);

                var nuGetPackageInstaller =
                    new NuGetPackageInstaller(logger: logger, nugetCliSettings: nuGetCliSettings);

                var deploymentService = new DeploymentService(
                    deployerConfiguration,
                    logger,
                    configuration,
                    new WebDeployHelper(logger),
                    deploymentExecutionDefinition =>
                    IisManager.Create(deployerConfiguration, logger, deploymentExecutionDefinition),
                    nuGetPackageInstaller,
                    new FtpHandlerFactory());

                string temp = configuration[ConfigurationKeys.TempDirectory];

                const string tempEnvironmentVariableName = "temp";

                if (!string.IsNullOrWhiteSpace(temp) && Directory.Exists(temp))
                {
                    Environment.SetEnvironmentVariable(tempEnvironmentVariableName, temp);
                    Environment.SetEnvironmentVariable("tmp", temp);
                }

                var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
                return(new DeployerApp(logger, deploymentService, configuration, levelSwitch, cancellationTokenSource));
            }
            catch (Exception ex) when(!ex.IsFatal())
            {
                logger.Error("Could not build application");
                throw;
            }
        }
Exemplo n.º 3
0
        static void Update()
        {
            LogFile.WriteMessageFormat("*** Updating Mediachase {0} ***", IbnConst.ProductName);

            //GlobalContext.Current = new GlobalContext(Settings.InstallDirWeb + @"portal\Apps");
            DBHelper2.Init(new DBHelper(string.Format(CultureInfo.InvariantCulture, "Data source={0};Initial catalog=master;User Id={1};Password={2};Connection Timeout=36000", Settings.SqlServer, Settings.SqlUser, Settings.SqlPassword)));
            DBHelper2.DBHelper.CommandTimeout = CommandTimeout;

            IConfigurator configurator  = Configurator.Create();
            IIisManager   oldIisManager = IisManager.Create(Settings.InstallDirWeb);
            bool          x64           = oldIisManager.Is64Bit();

            // Get copmanies
            CompanyInfo[] oldCompanies = CompanyInfo.ListCompanies(DBHelper2.DBHelper);
            bool          isAsp        = (oldCompanies.Length > 1);

            List <string> newCompanies = ListNewCompanies(configurator);
            bool          firstLaunch  = (newCompanies == null);

            List <CompanyInfo> companies = new List <CompanyInfo>();

            if (firstLaunch)
            {
                companies.AddRange(oldCompanies);
            }
            else
            {
                foreach (CompanyInfo oldCompany in oldCompanies)
                {
                    if (!newCompanies.Contains(oldCompany.Host))
                    {
                        companies.Add(oldCompany);
                    }
                }
            }

            string newAspPath = Path.Combine(Settings.InstallDir, "Asp");
            string codePath   = Path.Combine(Settings.InstallDir, "Code");
            string sourcePath = Path.Combine(codePath, "_Source");
            string newWebPath = Path.Combine(sourcePath, "Web");

            try
            {
                // Stop old web site
                oldIisManager.StopSite(Settings.SiteId);

                // Stop old services
                if (firstLaunch)
                {
                    StopService("AlertService" + IbnConst.VersionMajorMinor, false);
                    StopService("McOleDBService" + IbnConst.VersionMajorMinor, false);
                    StopService("ScheduleService" + IbnConst.VersionMajorMinor, false);

                    // Unregister old components
                    RegisterComponents(false, GetOldComponents());

                    // Unregister old IM Server
                    RegisterIMServer(false, Settings.InstallDirWeb, x64);

                    // TODO: ? Delete ISAPI extension
                    // TODO: ? Delete portal application pool
                    // TODO: ? Delete IM application pool

                    // Copy old files to new location: InstallPath\Code\_Source
                    LogFile.WriteLine("Copying old files to new location...");

                    CopyDirectory(Path.Combine(Settings.InstallDir, @"Web\Asp"), newAspPath);
                    CopyDirectory(Settings.InstallDir, sourcePath, "Tools");
                    CopyDirectory(Settings.InstallDir, sourcePath, @"Web\Download");
                    CopyDirectory(Settings.InstallDir, sourcePath, @"Web\instmsg");
                    CopyDirectory(Settings.InstallDir, sourcePath, @"Web\instmsg64");
                    CopyDirectory(Settings.InstallDir, sourcePath, @"Web\Portal");

                    LogWriteOk();

                    // Delete error logs
                    Directory.Delete(Path.Combine(sourcePath, @"Web\Portal\Admin\Log\Error"), true);

                    // Update files
                    UpdateFiles();

                    // Register new components
                    RegisterComponents(true, GetNewComponents());

                    // Register new IM Server
                    RegisterIMServer(true, newWebPath, x64);

                    // Start new services
                    StartNewServices();
                }
                firstLaunch = false;

                Pause("Restore clean databases.");

                for (int i = 0; i < companies.Count; i++)
                {
                    CompanyInfo company = companies[i];

                    LogFile.WriteMessageFormat("* Converting company {0} of {1}: '{2}' *", i + 1, companies.Count, company.Host);

                    try
                    {
                        ConvertCompany(configurator, isAsp, company);

                        // Delete binding from old web site
                        try
                        {
                            if (isAsp)
                            {
                                oldIisManager.DeleteBinding(Settings.SiteId, company.Host);
                            }
                        }
                        catch
                        {
                        }

                        LogFile.WriteLine("* OK *");
                    }
                    catch (Exception ex)
                    {
                        LogFile.WriteLine("* Failed *");
                        LogFile.WriteLine("");

                        if (isAsp)
                        {
                            LogFile.WriteLine(ex.ToString());
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                Settings.SaveVersion();

                Pause("Backup databases.");

                LogFile.WriteLine("*** OK ***");
            }
            catch (Exception ex)
            {
                LogFile.WriteLine("*** Failed ***");
                LogFile.WriteLine("");
                LogFile.WriteLine(ex.ToString());
                LogFile.WriteLine("");
                LogFile.WriteLine("Rollback started");

                #region Undo changes

                try
                {
                    if (!isAsp || firstLaunch)
                    {
                        // Unregister new components
                        try
                        {
                            RegisterComponents(false, GetNewComponents());
                        }
                        catch
                        {
                        }

                        // Unregister new IM server
                        try
                        {
                            RegisterIMServer(false, newWebPath, x64);
                        }
                        catch
                        {
                        }

                        // Recover files
                        try
                        {
                            RecoverFiles();
                        }
                        catch
                        {
                        }

                        // Delete [InstallDir]\Code
                        try
                        {
                            Directory.Delete(codePath, true);
                        }
                        catch
                        {
                        }

                        // Delete [InstallDir]\Asp
                        try
                        {
                            Directory.Delete(newAspPath, true);
                        }
                        catch
                        {
                        }

                        // Register old components
                        try
                        {
                            RegisterComponents(true, GetOldComponents());
                        }
                        catch
                        {
                        }

                        // Register old IM Server
                        try
                        {
                            RegisterIMServer(true, Settings.InstallDirWeb, x64);
                        }
                        catch
                        {
                        }

                        // Start old services
                        try
                        {
                            StartOldServices();
                        }
                        catch
                        {
                        }
                    }

                    // Start old web site
                    try
                    {
                        oldIisManager.StartSite(Settings.SiteId);
                    }
                    catch
                    {
                    }
                }
                catch
                {
                }

                #endregion

                LogFile.WriteLine("Rollback finished");
                throw;
            }
            finally
            {
                LogFile.WriteLine("");
                // Delete backup files
                DeleteBackupFiles();
            }
        }