Example #1
0
 public PackageInstaller(
     ILogger logger,
     DeployerConfiguration deployerConfiguration,
     IKeyValueConfiguration keyValueConfiguration)
 {
     _logger = logger;
     _deployerConfiguration = deployerConfiguration;
     _keyValueConfiguration = keyValueConfiguration;
 }
Example #2
0
 private IisManager(
     ServerManager serverManager,
     DeployerConfiguration configuration,
     ILogger logger,
     DeploymentExecutionDefinition deploymentExecutionDefinition)
 {
     _serverManager = serverManager;
     _configuration = configuration;
     _logger        = logger;
     _deploymentExecutionDefinition = deploymentExecutionDefinition;
 }
Example #3
0
        public static IisManager Create(
            [NotNull] DeployerConfiguration configuration,
            [NotNull] ILogger logger,
            [NotNull] DeploymentExecutionDefinition deploymentExecutionDefinition)
        {
            if (configuration is null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            if (logger is null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (deploymentExecutionDefinition is null)
            {
                throw new ArgumentNullException(nameof(deploymentExecutionDefinition));
            }

            return(new IisManager(new ServerManager(), configuration, logger, deploymentExecutionDefinition));
        }
        public DeploymentService(
            DeployerConfiguration deployerConfiguration,
            ILogger logger,
            [NotNull] IKeyValueConfiguration keyValueConfiguration,
            IWebDeployHelper webDeployHelper,
            Func <DeploymentExecutionDefinition, IIisManager> iisManager,
            NuGetPackageInstaller nugetPackageInstaller,
            IFtpHandlerFactory ftpHandlerFactor)
        {
            if (logger is null)
            {
                throw new ArgumentNullException(nameof(logger));
            }

            if (keyValueConfiguration is null)
            {
                throw new ArgumentNullException(nameof(keyValueConfiguration));
            }

            DeployerConfiguration =
                deployerConfiguration ?? throw new ArgumentNullException(nameof(deployerConfiguration));

            _directoryCleaner = new DirectoryCleaner(logger);

            _packageInstaller = new PackageInstaller(logger, deployerConfiguration, keyValueConfiguration);

            _fileMatcher = new FileMatcher(logger);

            _xmlTransformer = new XmlTransformer(logger, _fileMatcher);

            _logger                = logger;
            _webDeployHelper       = webDeployHelper;
            _iisManager            = iisManager;
            _nugetPackageInstaller = nugetPackageInstaller;
            _ftpHandlerFactory     = ftpHandlerFactor;
        }
        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;
            }
        }
        public static RuleConfiguration Get(
            [NotNull] DeploymentExecutionDefinition deploymentExecutionDefinition,
            [NotNull] DeployerConfiguration deployerConfiguration,
            ILogger logger)
        {
            if (deploymentExecutionDefinition == null)
            {
                throw new ArgumentNullException(nameof(deploymentExecutionDefinition));
            }

            if (deployerConfiguration == null)
            {
                throw new ArgumentNullException(nameof(deployerConfiguration));
            }

            bool doNotDeleteEnabled = deploymentExecutionDefinition.DoNotDeleteEnabled(deployerConfiguration
                                                                                       .WebDeploy.Rules.DoNotDeleteRuleEnabled);

            bool useChecksumEnabled = deploymentExecutionDefinition.UseChecksumEnabled(deployerConfiguration
                                                                                       .WebDeploy.Rules.UseChecksumRuleEnabled);

            bool appDataSkipDirectiveEnabled = deploymentExecutionDefinition.AppDataSkipDirectiveEnabled(
                deployerConfiguration
                .WebDeploy.Rules.AppDataSkipDirectiveEnabled);

            bool applicationInsightsProfiler2SkipDirectiveEnabled =
                deploymentExecutionDefinition.ApplicationInsightsProfiler2SkipDirectiveEnabled(
                    deployerConfiguration
                    .WebDeploy.Rules.ApplicationInsightsProfiler2SkipDirectiveEnabled);

            bool appOfflineEnabled = deploymentExecutionDefinition.AppOfflineEnabled(deployerConfiguration
                                                                                     .WebDeploy.Rules.AppOfflineRuleEnabled);

            bool whatIfEnabled = deploymentExecutionDefinition.WhatIfEnabled();

            logger?.Debug(
                "{RuleName}: {DoNotDeleteEnabled}",
                nameof(deployerConfiguration.WebDeploy.Rules.DoNotDeleteRuleEnabled),
                doNotDeleteEnabled);
            logger?.Debug(
                "{RuleName}: {AppOfflineEnabled}",
                nameof(deployerConfiguration.WebDeploy.Rules.AppOfflineRuleEnabled),
                appOfflineEnabled);
            logger?.Debug(
                "{RuleName}: {UseChecksumEnabled}",
                nameof(deployerConfiguration.WebDeploy.Rules.UseChecksumRuleEnabled),
                useChecksumEnabled);
            logger?.Debug(
                "{RuleName}: {AppDataSkipDirectiveEnabled}",
                nameof(deployerConfiguration.WebDeploy.Rules.AppDataSkipDirectiveEnabled),
                appDataSkipDirectiveEnabled);
            logger?.Debug(
                "{RuleName}: {ApplicationInsightsProfiler2SkipDirectiveEnabled}",
                nameof(deployerConfiguration.WebDeploy.Rules.ApplicationInsightsProfiler2SkipDirectiveEnabled),
                applicationInsightsProfiler2SkipDirectiveEnabled);
            logger?.Debug(
                "{RuleName}: {WhatIfEnabled}",
                nameof(DeploymentExecutionDefinitionExtensions.WhatIfEnabled),
                whatIfEnabled);

            return(new RuleConfiguration
            {
                UseChecksumEnabled = useChecksumEnabled,
                AppDataSkipDirectiveEnabled = appDataSkipDirectiveEnabled,
                ApplicationInsightsProfiler2SkipDirectiveEnabled = applicationInsightsProfiler2SkipDirectiveEnabled,
                WhatIfEnabled = whatIfEnabled,
                DoNotDeleteEnabled = doNotDeleteEnabled,
                AppOfflineEnabled = appOfflineEnabled,
                Excludes = DefaultExcludes
            });
        }