Exemplo n.º 1
0
        public override async Task <DeploymentResult> DeployAsync()
        {
            using (Logger.BeginScope("Deployment"))
            {
                StartTimer();

                var contentRoot = string.Empty;
                if (string.IsNullOrEmpty(DeploymentParameters.ServerConfigTemplateContent))
                {
                    DeploymentParameters.ServerConfigTemplateContent = File.ReadAllText("IIS.config");
                }

                _application = new IISApplication(IISDeploymentParameters, Logger);

                // For now, only support using published output
                DeploymentParameters.PublishApplicationBeforeDeployment = true;

                if (DeploymentParameters.ApplicationType == ApplicationType.Portable)
                {
                    DefaultWebConfigActions.Add(
                        WebConfigHelpers.AddOrModifyAspNetCoreSection(
                            "processPath",
                            DotNetCommands.GetDotNetExecutable(DeploymentParameters.RuntimeArchitecture)));
                }

                if (DeploymentParameters.PublishApplicationBeforeDeployment)
                {
                    DotnetPublish();
                    contentRoot = DeploymentParameters.PublishedApplicationRootPath;
                    // Do not override settings set on parameters
                    if (!IISDeploymentParameters.HandlerSettings.ContainsKey("debugLevel") &&
                        !IISDeploymentParameters.HandlerSettings.ContainsKey("debugFile"))
                    {
                        var logFile = Path.Combine(contentRoot, $"{_application.WebSiteName}.txt");
                        IISDeploymentParameters.HandlerSettings["debugLevel"] = "4";
                        IISDeploymentParameters.HandlerSettings["debugFile"]  = logFile;
                    }

                    DefaultWebConfigActions.Add(WebConfigHelpers.AddOrModifyHandlerSection(
                                                    key: "modules",
                                                    value: DeploymentParameters.AncmVersion.ToString()));
                    RunWebConfigActions(contentRoot);
                }

                var uri = TestUriHelper.BuildTestUri(ServerType.IIS, DeploymentParameters.ApplicationBaseUriHint);
                // To prevent modifying the IIS setup concurrently.
                await _application.StartIIS(uri, contentRoot);

                // Warm up time for IIS setup.
                Logger.LogInformation("Successfully finished IIS application directory setup.");
                return(new IISDeploymentResult(
                           LoggerFactory,
                           IISDeploymentParameters,
                           applicationBaseUri: uri.ToString(),
                           contentRoot: contentRoot,
                           hostShutdownToken: _hostShutdownToken.Token,
                           hostProcess: _application.HostProcess
                           ));
            }
        }
        /// <summary>
        /// Создание временной конфигурации для быстрого анализа.
        /// </summary>
        /// <param name="template">шаблон</param>
        /// <param name="product">приложение</param>
        /// <returns></returns>
        internal static Configuration CreateInstant(IISApplication product)
        {
            Template template    = null;
            string   productCode = null;

            foreach (var config in Directory.GetFiles(product.Path, "*.config"))
            {
                var appConfig = XDocument.Load(config);
                productCode = appConfig.Root.Element("NpoComputer.Product")?.Element("Code")?.Value;
                if (string.IsNullOrEmpty(productCode))
                {
                    continue;
                }
                template = TemplateManager.GetByProductCode(productCode, FilterMode.InstantOnly);
                if (template != null)
                {
                    break;
                }
            }

            if (template == null)
            {
                throw new FileNotFoundException("Не найдено подходящих шаблонов для данного приложения.");
            }

            Core.Application.Log(LogLevel.Informational, "Загрузка параметров для сайта \"{0}\"", product);

            var xml        = XDocument.Load(template.ConfigurationPath);
            var p          = xml.XPathSelectElements(@"Configuration/Parameters/Parameter");
            var parameters = new ParameterProvider(p.ToDictionary(k => k.Attribute("name").Value, v => v.Attribute("value").Value));

            parameters.AddParameter("ConfigurationPath", Path.Combine("Templates", template.Name));
            parameters.AddParameter("ReportsPath", Path.Combine(Core.Application.WorkingFolder, "Reports"));
            parameters.AddParameter("Title", product.ToString());
            parameters.AddParameter("SiteLogFile", product.IISLogPath);
            parameters.AddParameter("ApplicationPath", product.Path);

            if (productCode.Contains("NOMAD")) //TODO: Убрать костыль
            {
                var appPath     = product.Path;
                var logSettings = XDocument.Load(Path.Combine(appPath, "LogSettings.config"));
                var path        = ((IEnumerable)logSettings.XPathEvaluate("/*[name()='nlog']/*[name()='variable' and @name='logs-path']/@value")).Cast <XAttribute>().FirstOrDefault()?.Value;
                if (path != null && path.Contains("basedir"))
                {
                    path = Path.Combine(appPath, @"App_Data\Logs\");
                }
                parameters.AddParameter("ApplicationLogsPath", path);
                //TODO: Получать путь
                parameters.AddParameter("ClientsLogPath", Path.Combine(appPath, @"\App_Data\ClientLogs\"));
            }

            var taskNodes = xml.XPathSelectElements(@"Configuration/Tasks/Task");
            var tasks     = taskNodes.Select(t => Tasks.TaskFactory.Create(t)).ToList();

            return(new Configuration(template.Name, tasks, parameters, null));
        }
        private static IList <IISApplication> GroupAppPools(IEnumerable <IISAppPool> appPools)
        {
            var applications = new List <IISApplication>();
            var regexString  = ConfigurationManager.AppSettings["IISAppPoolRegex"];
            var regex        = new Regex(regexString);

            var appRoot = ConfigurationManager.AppSettings["AppRootUrl"].EnsureSlash();

            foreach (var appPool in appPools)
            {
                var matches = regex.Match(appPool.Name);
                if (matches.Success)
                {
                    var name = string.Empty;

                    for (var i = 1; i < matches.Groups.Count; i++)
                    {
                        name = matches.Groups[i].Value;
                        if (!string.IsNullOrEmpty(name))
                        {
                            break;
                        }
                    }

                    if (string.IsNullOrEmpty(name))
                    {
                        continue;
                    }

                    var application = applications.FirstOrDefault(a => a.Name == name);
                    if (application == null)
                    {
                        application = new IISApplication
                        {
                            Name = name,
                            Url  = $"{appRoot}{name}/",
                        };
                        applications.Add(application);
                    }

                    application.ApplicationPools.Add(appPool);
                }
            }

            return(applications);
        }
Exemplo n.º 4
0
        public override DeploymentResult Deploy()
        {
            // Start timer
            StartTimer();

            // Only supports publish and run on IIS.
            DeploymentParameters.PublishApplicationBeforeDeployment = true;

            _application = new IISApplication(DeploymentParameters, Logger);

            DeploymentParameters.DnxRuntime = PopulateChosenRuntimeInformation();

            // Publish to IIS root\application folder.
            DnuPublish(publishRoot: _application.WebSiteRootFolder);

            // Drop an ini file instead of setting environment variable.
            SetAspEnvironmentWithIni();

            // Setup the IIS Application.
            if (DeploymentParameters.ServerType == ServerType.IISNativeModule)
            {
                TurnRammFarOnNativeModule();
            }

            lock (_syncObject)
            {
                // To prevent modifying the IIS setup concurrently.
                _application.Deploy();
            }

            // Warm up time for IIS setup.
            Thread.Sleep(1 * 1000);
            Logger.LogInformation("Successfully finished IIS application directory setup.");

            return(new DeploymentResult
            {
                WebRootLocation = DeploymentParameters.ApplicationPath,
                DeploymentParameters = DeploymentParameters,
                // Accomodate the vdir name.
                ApplicationBaseUri = new UriBuilder(Uri.UriSchemeHttp, "localhost", IISApplication.Port, _application.VirtualDirectoryName).Uri.AbsoluteUri + "/",
                HostShutdownToken = _hostShutdownToken.Token
            });
        }
Exemplo n.º 5
0
        public override DeploymentResult Deploy()
        {
            // Start timer
            StartTimer();

            // Only supports publish and run on IIS.
            DeploymentParameters.PublishApplicationBeforeDeployment = true;

            _application = new IISApplication(DeploymentParameters, Logger);

            DeploymentParameters.DnxRuntime = PopulateChosenRuntimeInformation();

            // Publish to IIS root\application folder.
            DnuPublish(publishRoot: _application.WebSiteRootFolder);

            // Drop an ini file instead of setting environment variable.
            SetAspEnvironmentWithIni();

            // Setup the IIS Application.
            if (DeploymentParameters.ServerType == ServerType.IISNativeModule)
            {
                TurnRammFarOnNativeModule();
            }

            lock (_syncObject)
            {
                // To prevent modifying the IIS setup concurrently.
                _application.Deploy();
            }

            // Warm up time for IIS setup.
            Thread.Sleep(1 * 1000);
            Logger.LogInformation("Successfully finished IIS application directory setup.");

            return new DeploymentResult
            {
                WebRootLocation = DeploymentParameters.ApplicationPath,
                DeploymentParameters = DeploymentParameters,
                // Accomodate the vdir name.
                ApplicationBaseUri = new UriBuilder(Uri.UriSchemeHttp, "localhost", IISApplication.Port, _application.VirtualDirectoryName).Uri.AbsoluteUri + "/",
                HostShutdownToken = _hostShutdownToken.Token
            };
        }
Exemplo n.º 6
0
        public override async Task <DeploymentResult> DeployAsync()
        {
            using (Logger.BeginScope("Deployment"))
            {
                StartTimer();

                var contentRoot = string.Empty;
                if (string.IsNullOrEmpty(DeploymentParameters.ServerConfigTemplateContent))
                {
                    DeploymentParameters.ServerConfigTemplateContent = File.ReadAllText("IIS.config");
                }

                _application = new IISApplication(DeploymentParameters, Logger);

                // For now, only support using published output
                DeploymentParameters.PublishApplicationBeforeDeployment = true;
                if (DeploymentParameters.PublishApplicationBeforeDeployment)
                {
                    DotnetPublish();
                    contentRoot = DeploymentParameters.PublishedApplicationRootPath;
                }

                WebConfigHelpers.AddDebugLogToWebConfig(contentRoot, Path.Combine(contentRoot, $"{_application.WebSiteName}.txt"));

                var uri = TestUriHelper.BuildTestUri(ServerType.IIS, DeploymentParameters.ApplicationBaseUriHint);
                // To prevent modifying the IIS setup concurrently.
                await _application.StartIIS(uri, contentRoot);

                // Warm up time for IIS setup.
                Logger.LogInformation("Successfully finished IIS application directory setup.");

                return(new DeploymentResult(
                           LoggerFactory,
                           DeploymentParameters,
                           applicationBaseUri: uri.ToString(),
                           contentRoot: contentRoot,
                           hostShutdownToken: _hostShutdownToken.Token
                           ));
            }
        }
Exemplo n.º 7
0
        public override DeploymentResult Deploy()
        {
            // Start timer
            StartTimer();

            // Only supports publish and run on IIS.
            DeploymentParameters.PublishApplicationBeforeDeployment = true;

            _application = new IISApplication(DeploymentParameters, Logger);

            // Publish to IIS root\application folder.
            DotnetPublish(publishRoot: _application.WebSiteRootFolder);

            // Drop a json file instead of setting environment variable.
            SetAspEnvironmentWithJson();

            var uri = TestUriHelper.BuildTestUri();

            lock (_syncObject)
            {
                // To prevent modifying the IIS setup concurrently.
                _application.Deploy(uri);
            }

            // Warm up time for IIS setup.
            Thread.Sleep(1 * 1000);
            Logger.LogInformation("Successfully finished IIS application directory setup.");

            return(new DeploymentResult
            {
                WebRootLocation = DeploymentParameters.ApplicationPath,
                DeploymentParameters = DeploymentParameters,
                // Accomodate the vdir name.
                ApplicationBaseUri = uri.ToString(),
                HostShutdownToken = _hostShutdownToken.Token
            });
        }
Exemplo n.º 8
0
        public override DeploymentResult Deploy()
        {
            // Start timer
            StartTimer();

            // Only supports publish and run on IIS.
            DeploymentParameters.PublishApplicationBeforeDeployment = true;

            _application = new IISApplication(DeploymentParameters, Logger);

            // Publish to IIS root\application folder.
            DotnetPublish(publishRoot: _application.WebSiteRootFolder);

            // Drop a json file instead of setting environment variable.
            SetAspEnvironmentWithJson();

            var uri = TestUriHelper.BuildTestUri();

            lock (_syncObject)
            {
                // To prevent modifying the IIS setup concurrently.
                _application.Deploy(uri);
            }

            // Warm up time for IIS setup.
            Thread.Sleep(1 * 1000);
            Logger.LogInformation("Successfully finished IIS application directory setup.");

            return new DeploymentResult
            {
                ContentRoot = DeploymentParameters.PublishedApplicationRootPath,
                DeploymentParameters = DeploymentParameters,
                // Accomodate the vdir name.
                ApplicationBaseUri = uri.ToString(),
                HostShutdownToken = _hostShutdownToken.Token
            };
        }
Exemplo n.º 9
0
        private static IISApplication PopulateApplication(Application smApp)
        {
            var app = new IISApplication();

            app.AppPoolName = smApp.ApplicationPoolName;
            app.Path        = smApp.Path;
            var attributes = smApp.Attributes;

            if (attributes["preloadEnabled"] != null && attributes["preloadEnabled"].Value != null && attributes["preloadEnabled"].Value is bool)
            {
                app.EnablePreload = (bool)attributes["preloadEnabled"].Value;
            }
            app.EnabledProtocols = attributes["enabledProtocols"]?.Value as string;
            if (smApp.VirtualDirectories.Count >= 1)
            {
                app.PhysicalPath = Environment.ExpandEnvironmentVariables(smApp.VirtualDirectories[0].PhysicalPath);
                app.SpecificUser = smApp.VirtualDirectories[0].UserName;
                app.AuthenticationLogonMethod = Enum.GetName(typeof(AuthenticationLogonMethod), smApp.VirtualDirectories[0].LogonMethod);
            }
            app.Libraries = GetLibsForApp(app.PhysicalPath);
            app.Modules   = GetModulesForApp(app.PhysicalPath);

            return(app);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Создание конфигурации из шаблона
        /// </summary>
        /// <returns></returns>
        static public void CreateConfiguration(Template template)
        {
            Core.Application.Log(LogLevel.Informational, template.Description);
            Core.Application.Log(LogLevel.Informational, "Поиск подходящих продуктов для конфигурации \"{0}\"", template.Name);

            try
            {
                IISApplication currentApp = null;
                var            sites      = IISManager.GetProducts().Where(a => template.ProductCodes.Split(';').Contains(a.Code)).ToList();
                if (sites.Count == 0)
                {
                    Core.Application.Log(LogLevel.Informational, "Не найдены установленные продукты для данной конфигурации");
                }
                if (sites.Count == 1)
                {
                    currentApp = sites.First();
                }

                if (sites.Count > 1)
                {
                    Core.Application.Log(LogLevel.Informational, "Найдено несколько установок. Укажите соответствующий индекс продукта:");

                    while (currentApp == null)
                    {
                        for (var i = 0; i < sites.Count; i++)
                        {
                            Console.WriteLine("{0}: {1}", i, sites[i]);
                        }
                        try
                        {
                            var index = int.Parse(Console.ReadLine());
                            currentApp = sites[index];
                        }
                        catch
                        {
                            Core.Application.Log(LogLevel.Error, "Указан некорректный индекс, повторите попытку:");
                        }
                    }
                }
                if (currentApp != null)
                {
                    Core.Application.Log(LogLevel.Informational, "Загрузка параметров для сайта \"{0}\"", currentApp);
                    template.Parameters.First(x => x.Name == "ApplicationPath").Value = currentApp.Path;
                    template.Parameters.First(x => x.Name == "SiteLogFile").Value     = currentApp.IISLogPath;
                    template.Parameters.First(x => x.Name == "Title").Value           = currentApp.ToString();
                }
                else
                {
                    Core.Application.Log(LogLevel.Warning, "Некоторые параметры необходимо указать вручную.");
                }
            }
            catch (Exception e)
            {
                Core.Application.Log(LogLevel.Error, "Произошла ошибка: {0}", e.Message);
                Core.Application.Log(LogLevel.Warning, "Некоторые параметры необходимо указать вручную.");
            }

            foreach (var parameter in template.Parameters)
            {
                do
                {
                    Core.Application.Log(LogLevel.Informational, "{0}", parameter.Description);
                    Console.ForegroundColor = ConsoleColor.DarkGray;

                    foreach (var param in template.Parameters)
                    {
                        parameter.Value = parameter.Value.Replace(string.Format("%{0}%", param.Name), param.Value);
                    }

                    Console.Write("{0} ", parameter.Value);
                    Console.ResetColor();
                    Console.SetCursorPosition(0, Console.CursorTop);
                    var value = Console.ReadLine();

                    if (!string.IsNullOrEmpty(value))
                    {
                        parameter.Value = value;
                    }
                } while (parameter.Required && string.IsNullOrEmpty(parameter.Value));
            }

            var configName = template.Parameters.First(x => x.Name == "Title").Value;

            configName = configName?.Replace(" ", "_").Replace("/", "_");
            while (string.IsNullOrEmpty(configName) || ConfigurationManager.Get(configName) != null)
            {
                Core.Application.Log(LogLevel.Warning, "Конфигурация с именем \"{0}\" уже существует. Укажите другое имя", configName);
                configName = Console.ReadLine();
                configName = configName?.Replace(" ", "_").Replace("/", "_");
            }

            Core.Application.Log(LogLevel.Informational, "Создание конфигурации \"{0}\"", configName);
            new DirectoryInfo(Path.Combine(TemplatesPath, template.Name)).CopyTo(Path.Combine(ConfigurationManager.ConfigurationPath, configName), true);

            var doc                    = new XDocument();
            var serializer             = new XmlSerializer(typeof(Parameters.ParameterCollection));
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("", "");
            using (var writer = doc.CreateWriter())
                serializer.Serialize(writer, new Parameters.ParameterCollection()
                {
                    Parameters = template.Parameters.ToList()
                }, ns);

            var configPath = Path.Combine(ConfigurationManager.ConfigurationPath, configName, "application.config");
            var xml        = XDocument.Load(configPath);

            xml.XPathSelectElement(@"Configuration/Parameters").Remove();
            var p = xml.XPathSelectElement(@"Configuration");

            p.AddFirst(doc.Root);
            xml.Save(configPath);
            Core.Application.Log(LogLevel.Informational, "Конфигурация {0} успешно создана", configName);
        }