Esempio n. 1
0
        public static bool LoadConfigurationIntoContext(DeploymentContext context)
        {
            try
            {
                string expectedConfigFile = Path.Combine(context.ConfigurationDirectory, context.Job.Branch + ".json");
                string configFileContents = File.ReadAllText(expectedConfigFile);

                DeploymentConfiguration config = JsonConvert.DeserializeObject <DeploymentConfiguration>(configFileContents);

                context.TaskParameters.InitialiseParametersFromConfiguration(config);

                // set web directory
                string webDirectory     = config.GlobalParameters != null && config.GlobalParameters.ContainsKey("webDirectory") ? config.GlobalParameters["webDirectory"] : "WWW";
                string fullWebDirectory = Path.Combine(context.GitDirectory, webDirectory);
                context.WebSiteDirectory = fullWebDirectory;

                context.Configuration = config;
            }
            catch (Exception exception)
            {
                context.CurrentLogger.Fatal("Cannot load configuration file ({0}). Ensure the file exists and is valid JSON.", context.Branch);
                context.CurrentLogger.Fatal(exception);
                return(false);
            }

            return(true);
        }
Esempio n. 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Endpoint routing breaks most of our links because it doesn't include "ambient" route parameters
            // like eventId and eventRole in links -- they'd have to be manually specified everywhere
            services.AddMvc(options =>
            {
                options.EnableEndpointRouting = false;
            });

            services.AddRazorPages()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Pages");
                options.Conventions.AuthorizeFolder("/ModelBases");
            });

            DeploymentConfiguration.ConfigureDatabase(Configuration, services, _hostEnv);
            FileManager.ConnectionString = Configuration.GetConnectionString("AzureStorageConnectionString");

            services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
            {
                microsoftOptions.ClientId     = Configuration["Authentication-Microsoft-ApplicationId"];
                microsoftOptions.ClientSecret = Configuration["Authentication-Microsoft-Password"];
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("IsEventAuthor", policy => policy.Requirements.Add(new IsAuthorInEventRequirement()));
                options.AddPolicy("IsEventAdmin", policy => policy.Requirements.Add(new IsAdminInEventRequirement()));
                options.AddPolicy("IsGlobalAdmin", policy => policy.Requirements.Add(new IsGlobalAdminRequirement()));
                options.AddPolicy("IsPlayer", policy => policy.Requirements.Add(new IsPlayerInEventRequirement()));
                options.AddPolicy("PlayerCanSeePuzzle", policy => policy.Requirements.Add(new PlayerCanSeePuzzleRequirement()));
                options.AddPolicy("PlayerIsOnTeam", policy => policy.Requirements.Add(new PlayerIsOnTeamRequirement()));
                options.AddPolicy("IsAuthorOfPuzzle", policy => policy.Requirements.Add(new IsAuthorOfPuzzleRequirement()));
                options.AddPolicy("IsEventAdminOrEventAuthor", policy => policy.Requirements.Add(new IsEventAdminOrEventAuthorRequirement()));
                options.AddPolicy("IsEventAdminOrPlayerOnTeam", policy => policy.Requirements.Add(new IsEventAdminOrPlayerOnTeamRequirement()));
                options.AddPolicy("IsEventAdminOrAuthorOfPuzzle", policy => policy.Requirements.Add(new IsEventAdminOrAuthorOfPuzzleRequirement()));
                options.AddPolicy("IsRegisteredForEvent", policy => policy.Requirements.Add(new IsRegisteredForEventRequirement()));
            });

            services.AddScoped <IAuthorizationHandler, IsAuthorInEventHandler>();
            services.AddScoped <IAuthorizationHandler, IsAdminInEventHandler>();
            services.AddScoped <IAuthorizationHandler, IsGlobalAdminHandler>();
            services.AddScoped <IAuthorizationHandler, IsPlayerInEventHandler>();
            services.AddScoped <IAuthorizationHandler, PlayerCanSeePuzzleHandler>();
            services.AddScoped <IAuthorizationHandler, PlayerIsOnTeamHandler>();
            services.AddScoped <IAuthorizationHandler, IsAuthorOfPuzzleHandler>();

            services.AddScoped <IAuthorizationHandler, IsEventAdminOrAuthorOfPuzzleHandler_Admin>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrAuthorOfPuzzleHandler_Author>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrEventAuthorHandler_Admin>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrEventAuthorHandler_Author>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrPlayerOnTeamHandler_Admin>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrPlayerOnTeamHandler_Play>();
            services.AddScoped <IAuthorizationHandler, IsRegisteredForEventHandler_Admin>();
            services.AddScoped <IAuthorizationHandler, IsRegisteredForEventHandler_Author>();
            services.AddScoped <IAuthorizationHandler, IsRegisteredForEventHandler_Player>();
            services.AddScoped <BackgroundFileUploader>();
            services.AddScoped <AuthorizationHelper>();
        }
Esempio n. 3
0
        private static void DownloadPackages(ILogger logger, Arguments arguments)
        {
            var obsoleteFolders = new string[] { Path.Combine(Paths.RhetosServerRootPath, "DslScripts"), Path.Combine(Paths.RhetosServerRootPath, "DataMigration") };
            var obsoleteFolder  = obsoleteFolders.FirstOrDefault(folder => Directory.Exists(folder));

            if (obsoleteFolder != null)
            {
                throw new UserException("Backup all Rhetos server folders and delete obsolete folder '" + obsoleteFolder + "'. It is no longer used.");
            }

            if (!arguments.DeployDatabaseOnly)
            {
                logger.Trace("Getting packages.");
                var config = new DeploymentConfiguration(DeploymentUtility.InitializationLogProvider);
                var packageDownloaderOptions = new PackageDownloaderOptions {
                    IgnorePackageDependencies = arguments.IgnorePackageDependencies
                };
                var packageDownloader = new PackageDownloader(config, DeploymentUtility.InitializationLogProvider, packageDownloaderOptions);
                var packages          = packageDownloader.GetPackages();

                InstalledPackages.Save(packages);
            }
            else
            {
                logger.Info("Skipped download packages (DeployDatabaseOnly).");
            }
        }
Esempio n. 4
0
        public DeploymentConfiguration GetConfiguration(string path)
        {
            var content = LoadConfiguration(path);
            DeploymentConfiguration configuration = ParseConfiguration(content);

            return(configuration);
        }
        public void TestConfigurationXmlShouldConfigureDeployerCorrectly()
        {
            var connections = new[]
            {
                new DatabaseEndpoint()
                {
                    DatabaseName = "Db1", ServerName = "Server1"
                },
            };

            var arguments = new Arguments()
            {
                Database = new DatabaseEndpoints()
                {
                    Endpoints = connections
                },
                DeployedAssemblyOverridePath     = @"c:\some dir\some other dir\MyAssembly1.dll",
                TargetAssemblyPath               = @".\MyAssembly1.dll",
                RunServerMigrationsInTransaction = false,
                Mode = DeploymentMode.MigrationOnly
            };

            var expectedConfig = new DeploymentConfiguration()
            {
                MigrationConfigurationInfo = new MigrationConfigurationInfo
                {
                    Type = "Galen.Enterprise.Security.Core.Data.Migrations.SecurityDbContext.Configuration"
                },

                InitializerConfigurationInfo = new InitializerConfigurationInfo
                {
                    Type = "Galen.Enterprise.Security.Core.Data.Initializers.SecurityDbContextCreateIfNotExistsWithTestData",
                    DisableForcedSeeding = true,
                    ServiceAccount       = new ServiceAccountInfo()
                    {
                        Name                 = "EnterpriseServiceAccount",
                        AccountType          = "Sql",
                        DatabaseUser         = "******",
                        DatabaseUserPassword = "******",
                    }
                }
            };

            var sut = new ConfigurationArgumentMapper(new DeploymentConfigurationXmlStore(ResourceHelper.ReadStream(
                                                                                              "Galen.Ci.EntityFramework.Deployer.Tests.Data.TestConfiguration.xml")));
            var actualConfig = sut.FromArguments(arguments);

            Assert.IsNotNull(actualConfig);
            Assert.IsNotNull(actualConfig.InitializationConfig);

            Assert.IsNotNull(actualConfig.MigrationConfig);
            Assert.AreEqual(expectedConfig.MigrationConfigurationInfo.Type, actualConfig.MigrationConfig.Type);
            Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.Type, actualConfig.InitializationConfig.Type);
            Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.DisableForcedSeeding, actualConfig.InitializationConfig.DisableForcedSeeding);
            Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.Name, actualConfig.InitializationConfig.ServiceAccount.Name);
            Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.Domain, actualConfig.InitializationConfig.ServiceAccount.Domain);
            Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.DatabaseUser, actualConfig.InitializationConfig.ServiceAccount.DatabaseUser);
            Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.AccountType, actualConfig.InitializationConfig.ServiceAccount.AccountType);
            Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.DatabaseUserPassword, actualConfig.InitializationConfig.ServiceAccount.DatabaseUserPassword);
        }
Esempio n. 6
0
        public static DeploymentConfiguration LoadDeploymentConfiguration()
        {
            DeploymentConfiguration config = new DeploymentConfiguration();
            config.AwsAccessKeyId = Microsoft.Win32.Registry.GetValue(STR_CONFIG_REGISTRY_KEY_NAME, "AwsAccessKeyId", null) as string;
            config.AwsSecretAccessKey = Microsoft.Win32.Registry.GetValue(STR_CONFIG_REGISTRY_KEY_NAME, "AwsSecretAccessKey", null) as string;
            config.BucketName = Microsoft.Win32.Registry.GetValue(STR_CONFIG_REGISTRY_KEY_NAME, "BucketName", null) as string;
            config.DeploymentDirectory = Microsoft.Win32.Registry.GetValue(STR_CONFIG_REGISTRY_KEY_NAME, "DeploymentDirectory", null) as string;

            Guid targetKey;
            if (Guid.TryParseExact(Microsoft.Win32.Registry.GetValue(STR_CONFIG_REGISTRY_KEY_NAME, "TargetKey", null) as string, "N", out targetKey))
                config.TargetKey = targetKey;

            TimeSpan checkFrequency;
            if (TimeSpan.TryParse(Microsoft.Win32.Registry.GetValue(STR_CONFIG_REGISTRY_KEY_NAME, "CheckFrequency", null) as string, out checkFrequency))
                config.CheckFrequency = checkFrequency;

            Guid instanceKey;
            if (Guid.TryParseExact(Microsoft.Win32.Registry.GetValue(STR_CONFIG_REGISTRY_KEY_NAME, "InstanceKey", null) as string, "N", out instanceKey))
                config.InstanceKey = instanceKey;

            if (config.AwsAccessKeyId != null)
            {
                return config;
            }
            else
            {
                // Fail over to old style config.
                var serialised = Microsoft.Win32.Registry.GetValue(STR_CONFIG_REGISTRY_KEY_NAME, STR_DEPLOYMENT_CONFIG_NAME, null) as string;
                if (serialised != null)
                {
                    return Utils.Serialisation.ParsePullConfiguration(serialised);
                }
            }
            return null;
        }
Esempio n. 7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(config =>
            {
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .Build();
                config.Filters.Add(new AuthorizeFilter(policy));
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddMvc()
            .AddRazorPagesOptions(options =>
            {
                options.Conventions.AuthorizeFolder("/Pages");
                options.Conventions.AuthorizeFolder("/ModelBases");
            });

            DeploymentConfiguration.ConfigureDatabase(Configuration, services, hostingEnvironment);
            FileManager.ConnectionString = Configuration.GetConnectionString("AzureStorageConnectionString");

            services.AddAuthentication().AddMicrosoftAccount(microsoftOptions =>
            {
                microsoftOptions.ClientId     = Configuration["Authentication-Microsoft-ApplicationId"];
                microsoftOptions.ClientSecret = Configuration["Authentication-Microsoft-Password"];
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("IsEventAuthor", policy => policy.Requirements.Add(new IsAuthorInEventRequirement()));
                options.AddPolicy("IsEventAdmin", policy => policy.Requirements.Add(new IsAdminInEventRequirement()));
                options.AddPolicy("IsGlobalAdmin", policy => policy.Requirements.Add(new IsGlobalAdminRequirement()));
                options.AddPolicy("IsPlayer", policy => policy.Requirements.Add(new IsPlayerInEventRequirement()));
                options.AddPolicy("PlayerCanSeePuzzle", policy => policy.Requirements.Add(new PlayerCanSeePuzzleRequirement()));
                options.AddPolicy("PlayerIsOnTeam", policy => policy.Requirements.Add(new PlayerIsOnTeamRequirement()));
                options.AddPolicy("IsAuthorOfPuzzle", policy => policy.Requirements.Add(new IsAuthorOfPuzzleRequirement()));
                options.AddPolicy("IsEventAdminOrEventAuthor", policy => policy.Requirements.Add(new IsEventAdminOrEventAuthorRequirement()));
                options.AddPolicy("IsEventAdminOrPlayerOnTeam", policy => policy.Requirements.Add(new IsEventAdminOrPlayerOnTeamRequirement()));
                options.AddPolicy("IsEventAdminOrAuthorOfPuzzle", policy => policy.Requirements.Add(new IsEventAdminOrAuthorOfPuzzleRequirement()));
                options.AddPolicy("IsRegisteredForEvent", policy => policy.Requirements.Add(new IsRegisteredForEventRequirement()));
            });

            services.AddScoped <IAuthorizationHandler, IsAuthorInEventHandler>();
            services.AddScoped <IAuthorizationHandler, IsAdminInEventHandler>();
            services.AddScoped <IAuthorizationHandler, IsGlobalAdminHandler>();
            services.AddScoped <IAuthorizationHandler, IsPlayerInEventHandler>();
            services.AddScoped <IAuthorizationHandler, PlayerCanSeePuzzleHandler>();
            services.AddScoped <IAuthorizationHandler, PlayerIsOnTeamHandler>();
            services.AddScoped <IAuthorizationHandler, IsAuthorOfPuzzleHandler>();

            services.AddScoped <IAuthorizationHandler, IsEventAdminOrAuthorOfPuzzleHandler_Admin>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrAuthorOfPuzzleHandler_Author>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrEventAuthorHandler_Admin>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrEventAuthorHandler_Author>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrPlayerOnTeamHandler_Admin>();
            services.AddScoped <IAuthorizationHandler, IsEventAdminOrPlayerOnTeamHandler_Play>();
            services.AddScoped <IAuthorizationHandler, IsRegisteredForEventHandler_Admin>();
            services.AddScoped <IAuthorizationHandler, IsRegisteredForEventHandler_Author>();
            services.AddScoped <IAuthorizationHandler, IsRegisteredForEventHandler_Player>();
        }
        public async Task <IActionResult> DeployTemplate([FromBody] DeploymentConfiguration model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Template template = Templates.Load(TemplateManifestFile).FirstOrDefault(
                deploymentTemplate => deploymentTemplate.Id == model.TemplateId
                );

            if (template == null)
            {
                return(NotFound(new
                {
                    ErrorCode = "TemplateNotFound",
                    Message = $"Template {model.TemplateId} not found."
                }));
            }

            string deploymentId = HttpContext.TraceIdentifier;
            bool   started      = await _deployer.DeployAsync(deploymentId, template.ImageName, model.Parameters);

            return(Ok(new
            {
                Action = "Deploy",
                Started = started,
                DeploymentId = deploymentId
            }));
        }
Esempio n. 9
0
        public bool GetDeploymentConfiguration(out DeploymentConfiguration deploymentConfiguration)
        {
            if (!_deploymentConfigurationPathProvider.TryGetDeploymentConfigurationRoot(out var configurationRoot))
            {
                deploymentConfiguration = DeploymentConfiguration.Empty;
                return(false);
            }

            // load deployment configuration from target location
            var rendererConfigurationBuilder = new ConfigurationBuilder();

            var paths = new[]
            {
                Constants.PREPROCESSOR_FILENAME,
                "values.yaml",
                Constants.APP_VERSIONS_FILENAME,
            };

            foreach (var path in paths)
            {
                var fi = new FileInfo(Path.Combine(configurationRoot.FullName, path));
                if (fi.Exists)
                {
                    rendererConfigurationBuilder.AddYamlFile(fi.FullName);
                }
            }
            var renderConfiguration = rendererConfigurationBuilder.Build();

            //
            deploymentConfiguration = new DeploymentConfiguration();
            renderConfiguration.Bind(deploymentConfiguration);

            return(true);
        }
Esempio n. 10
0
 public DeploymentService(DeploymentConfiguration configuration, DeploymentPipelineFactory pipelineFactory,
                          FileUploadHandlerFactory fileUploadHandler)
 {
     this.configuration     = configuration;
     this.pipeline          = pipelineFactory.Create(configuration.SSHLogin);
     this.fileUploadHandler = fileUploadHandler;
     powershellClient       = new PowershellClient();
 }
Esempio n. 11
0
        public DeploymentService(IOptions <DeploymentConfiguration> config, IGithubClient github, INotificationService notifications)
        {
            _config        = config.Value;
            _notifications = notifications;
            _github        = github;

            github.Configure(_config.Repository, _config.ApiKey);
        }
Esempio n. 12
0
 public static void Save(DeploymentConfiguration config)
 {
     Microsoft.Win32.Registry.SetValue(STR_CONFIG_REGISTRY_KEY_NAME, "AwsAccessKeyId", config.AwsAccessKeyId, Microsoft.Win32.RegistryValueKind.String);
     Microsoft.Win32.Registry.SetValue(STR_CONFIG_REGISTRY_KEY_NAME, "AwsSecretAccessKey", config.AwsSecretAccessKey, Microsoft.Win32.RegistryValueKind.String);
     Microsoft.Win32.Registry.SetValue(STR_CONFIG_REGISTRY_KEY_NAME, "BucketName", config.BucketName, Microsoft.Win32.RegistryValueKind.String);
     Microsoft.Win32.Registry.SetValue(STR_CONFIG_REGISTRY_KEY_NAME, "CheckFrequency", config.CheckFrequency.ToString(), Microsoft.Win32.RegistryValueKind.String);
     Microsoft.Win32.Registry.SetValue(STR_CONFIG_REGISTRY_KEY_NAME, "DeploymentDirectory", config.DeploymentDirectory, Microsoft.Win32.RegistryValueKind.String);
     Microsoft.Win32.Registry.SetValue(STR_CONFIG_REGISTRY_KEY_NAME, "TargetKey", config.TargetKey.ToString("N"), Microsoft.Win32.RegistryValueKind.String);
     if (config.InstanceKey.HasValue)
         Microsoft.Win32.Registry.SetValue(STR_CONFIG_REGISTRY_KEY_NAME, "InstanceKey", config.InstanceKey.Value.ToString("N"), Microsoft.Win32.RegistryValueKind.String);
 }
Esempio n. 13
0
        public DeploymentConfiguration ParseConfiguration(string content)
        {
            if (string.IsNullOrEmpty(content))
            {
                throw new Exception("Unable to parse empty content");
            }

            DeploymentConfiguration config = JsonSerializer.Deserialize <DeploymentConfiguration>(content);

            return(config);
        }
 public static string Describe(DeploymentConfiguration Deployment)
 {
     if (Deployment is PositionalDeploymentConfiguration)
     {
         return(Describe((PositionalDeploymentConfiguration)Deployment));
     }
     if (Deployment is ConvoyDeploymentConfiguration)
     {
         return(Describe((ConvoyDeploymentConfiguration)Deployment));
     }
     return(string.Empty);
 }
Esempio n. 15
0
        public static InstalledPackages DownloadPackages(bool ignoreDependencies, ILogProvider logProvider, ILogger logger)
        {
            logger.Info("Getting packages.");
            var config = new DeploymentConfiguration(logProvider);
            var packageDownloaderOptions = new PackageDownloaderOptions {
                IgnorePackageDependencies = ignoreDependencies
            };
            var packageDownloader = new PackageDownloader(config, logProvider, packageDownloaderOptions);
            var installedPackages = packageDownloader.GetPackages();

            return(installedPackages);
        }
Esempio n. 16
0
        public void DeserializationShouldResultInCorrectConfiguration()
        {
            byte[] sourceData = ResourceHelper.ReadBytes("Galen.Ci.EntityFramework.Deployer.Tests.Data.DeserializationShouldResultInCorrectConfiguration_Source.xml");
            DeploymentConfiguration actualConfig;
            var expectedConfig = new DeploymentConfiguration()
            {
                MigrationConfigurationInfo = new MigrationConfigurationInfo
                {
                    Type = "Galen.Enterprise.Data.Migrations.SomeContext.Configuration"
                },

                InitializerConfigurationInfo = new InitializerConfigurationInfo
                {
                    Type           = "Galen.Enterprise.Data.Initializers.SomeContextCreateDatabaseIfNotExists",
                    ServiceAccount = new ServiceAccountInfo()
                    {
                        Name         = "SomeWindowsAccountName",
                        Domain       = "SomeDomainName",
                        DatabaseUser = "******",
                        AccountType  = "Windows"
                    }
                }
            };

            using (var stream = new MemoryStream(sourceData))
            {
                var sut = new DeploymentConfigurationXmlStore(stream);
                actualConfig = sut.Load();
            }

            Assert.IsNotNull(actualConfig);
            Assert.IsNotNull(actualConfig.InitializerConfigurationInfo);

            Assert.IsNotNull(actualConfig.MigrationConfigurationInfo);
            Assert.AreEqual(expectedConfig.MigrationConfigurationInfo.Type, actualConfig.MigrationConfigurationInfo.Type);

            Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.Type, actualConfig.InitializerConfigurationInfo.Type);

            Assert.IsTrue((actualConfig.InitializerConfigurationInfo.ServiceAccount != null &&
                           expectedConfig.InitializerConfigurationInfo.ServiceAccount != null) ||
                          (actualConfig.InitializerConfigurationInfo.ServiceAccount == null &&
                           expectedConfig.InitializerConfigurationInfo.ServiceAccount == null), "Service account info mismatch");

            if (actualConfig.InitializerConfigurationInfo.ServiceAccount != null)
            {
                Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.Name, actualConfig.InitializerConfigurationInfo.ServiceAccount.Name);
                Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.Domain, actualConfig.InitializerConfigurationInfo.ServiceAccount.Domain);
                Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.DatabaseUser, actualConfig.InitializerConfigurationInfo.ServiceAccount.DatabaseUser);
                Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.AccountType, actualConfig.InitializerConfigurationInfo.ServiceAccount.AccountType);
                Assert.AreEqual(expectedConfig.InitializerConfigurationInfo.ServiceAccount.DatabaseUserPassword, actualConfig.InitializerConfigurationInfo.ServiceAccount.DatabaseUserPassword);
            }
        }
Esempio n. 17
0
 public DeploymentRow(DeploymentConfiguration Deployment, Faction Faction, UnitConfigurationRenderer Renderer)
     : base("scenario-deployment-row")
 {
     Add(new Button("scenario-deployment-header")
     {
         DisplayedString = Deployment.UnitGroup.Name
     });
     Add(new Button("scenario-deployment")
     {
         DisplayedString = DeploymentDescriber.Describe(Deployment)
     });
     Add(new UnitGroupView(Deployment.UnitGroup, Faction, Renderer));
 }
Esempio n. 18
0
 public HelmRendererContext(
     DeploymentConfiguration configuration,
     string name,
     string ns,
     DirectoryInfo workingDirectory,
     HelmChart?chart    = null,
     string?cluster     = null,
     string?environment = null,
     string?vertical    = null,
     string?subVertical = null
     )
     : base(configuration, name, ns, workingDirectory, cluster, environment, vertical, subVertical)
 {
     Chart = chart;
 }
Esempio n. 19
0
        private static void DownloadPackages(ILogger logger, DeployArguments arguments)
        {
            if (!arguments.DeployDatabaseOnly)
            {
                logger.Trace("Getting packages.");
                var config = new DeploymentConfiguration(DeploymentUtility.InitializationLogProvider);
                var packageDownloaderOptions = new PackageDownloaderOptions { IgnorePackageDependencies = arguments.IgnorePackageDependencies };
                var packageDownloader = new PackageDownloader(config, DeploymentUtility.InitializationLogProvider, packageDownloaderOptions);
                var packages = packageDownloader.GetPackages();

                InstalledPackages.Save(packages);
            }
            else
                logger.Info("Skipped download packages (DeployDatabaseOnly).");
        }
Esempio n. 20
0
        public override bool TryGetNodeDetail(out NodeDetail nodeDetail)
        {
            NodeDetail    thisNodeDetail;
            bool          sucess;
            List <object> childernNaames = new List <object>();

            string[] childPathChunks = new string[this.PathChunks.Length - 1];
            Array.Copy(this.PathChunks, 1, childPathChunks, 0, this.PathChunks.Length - 1);

            switch (PathChunks[0].ToLower())
            {
            case ProviderUtil.SHARDS:
                DeploymentConfiguration deployment = ((ClusterConfiguration)Configuration).Deployment;

                thisNodeDetail = new ShardsDetail(PathChunks[0], deployment, childPathChunks);

                sucess = true;
                break;

            case ProviderUtil.DATABASES:
                DatabaseConfigurations databasees = ((ClusterConfiguration)Configuration).Databases;

                thisNodeDetail = new DatabasesDetail(PathChunks[0], databasees, childPathChunks);

                sucess = true;
                break;

            case ProviderUtil.CONFIGCLUSTER:

                thisNodeDetail = new ConfigurationNodesDetail(PathChunks[0], true, true,
                                                              new ConfigClusterInfo(ConfigurationConnection.ConfigCluster), childPathChunks);

                sucess = true;
                break;

            default:
                thisNodeDetail = null;
                sucess         = false;
                break;
            }

            if (PathChunks.Length == 1)
            {
                nodeDetail = thisNodeDetail;
                return(sucess);
            }
            return(thisNodeDetail.TryGetNodeDetail(out nodeDetail));
        }
Esempio n. 21
0
        private static int Main(string[] args)
        {
            var connectionString = ConfigurationManager.ConnectionStrings["MasterDb"];
            var fileDestination  = ConfigurationManager.AppSettings["FileDestination"];

            var jobConfiguration = JobConfiguration.Create()
                                   .WithName("Ssis Up - Sample Data Load")
                                   .WithDescription("This is a sample data load")
                                   .WithSsisOwner("sa")
                                   .WithSsisServer(Environment.MachineName)
                                   .WithSchedule(
                ScheduleConfiguration.Create()
                .WithName("Saturday Load")
                .RunOn(FrequencyDay.Saturday)
                .StartingAt(new TimeSpan(10, 0, 0))
                .ActivatedFrom(DateTime.Parse("1 Jan 2010"))
                .ActivatedUntil(DateTime.Parse("31 Dec 2020")))
                                   .WithStep(
                StepConfiguration.Create()
                .WithId(1)
                .WithName("Load Movie Data")
                .WithSubSystem(SsisSubSystem.IntegrationServices)
                .WithDtsxFile(@".\Packages\SampleJob.dtsx")
                .WithDtsConfigurationFile(@".\Packages\SampleJob.dtsConfig")
                .WithDtsxFileDestination(fileDestination)
                .ExecuteCommand(
                    string.Format(
                        @"/FILE ""{0}\SampleJob.dtsx"" /CONFIGFILE ""{0}\SampleJob.dtsConfig"" /CHECKPOINTING OFF /REPORTING E /X86",
                        fileDestination))
                .OnSuccess(JobAction.QuitWithSuccess)
                .OnFailure(JobAction.QuitWithFailure));


            var result = DeploymentConfiguration
                         .Create()
                         .ToDatabase(connectionString.ConnectionString)
                         .WithJobConfiguration(jobConfiguration)
                         .Deploy();


            if (!result.Successful)
            {
                return(-1);
            }

            return(0);
        }
Esempio n. 22
0
        public DeploymentResult Execute(DeploymentConfiguration configuration)
        {
            _jobConfigurationParser.Parse(configuration.JobConfiguration);

            var scripts = _sqlScriptProvider.Build(configuration.JobConfiguration);

            var sqlResult = _sqlExecutionService.Execute(configuration.ConnectionString, scripts, configuration.Debug);

            if (!sqlResult.Successful)
            {
                return(sqlResult);
            }

            var fileDeployResult = _fileService.Execute(configuration.JobConfiguration);

            return(fileDeployResult);
        }
Esempio n. 23
0
        public ShardsDetail(string nodeName, DeploymentConfiguration configuration, string[] pathChunks)
        {
            NodeName       = nodeName;
            NodeType       = PathType.Shards;
            IsContainer    = true;
            IsValid        = true;
            Configuration  = configuration;
            ChilderanTable = new PrintableTable();
            PathChunks     = pathChunks;
            ChilderanName  = new List <string>();
            ChilderanTable.AddHeader("Shard Name", "Node(s)", "Status", "Shard Port");
            ClusterInfo clusterInfo = ConfigurationConnection.ClusterInfo;

            foreach (ShardConfiguration shard in configuration.Shards.Values)
            {
                List <string> status    = new List <string>();
                ShardInfo     shardInfo = clusterInfo.GetShard(shard.Name);
                if (shardInfo != null)
                {
                    foreach (String node in shard.Servers.Nodes.Keys)
                    {
                        string statusString = "";
                        if (shardInfo.RunningNodes.Values.ToList().Exists(k => k.Address.IpAddress.ToString().Equals(node)))
                        {
                            statusString = ProviderUtil.STARTED;

                            if (shardInfo.Primary != null)
                            {
                                if (shardInfo.Primary.Address.IpAddress.ToString().Equals(node))
                                {
                                    statusString += ProviderUtil.PRIMARY_STATUS;
                                }
                            }
                        }
                        else
                        {
                            statusString = ProviderUtil.STOPPED;
                        }
                        status.Add(statusString);
                    }
                }

                ChilderanTable.AddMultiLineRow(new string[] { shard.Name }, shard.Servers.Nodes.Keys.ToArray(), status.ToArray(), new string[] { shard.Port.ToString() });
                ChilderanName.Add(shard.Name);
            }
        }
Esempio n. 24
0
        public void Configure(IWebHostBuilder builder)
        {
            builder.ConfigureServices((context, services) =>
            {
                // Set up to use Azure settings
                IWebHostEnvironment env             = context.HostingEnvironment;
                IConfigurationBuilder configBuilder = new ConfigurationBuilder()
                                                      .SetBasePath(env.ContentRootPath)
                                                      .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                                      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                                                      .AddEnvironmentVariables();
                context.Configuration = configBuilder.Build();

                DeploymentConfiguration.ConfigureDatabase(context.Configuration, services, env);

                services.AddDefaultIdentity <IdentityUser>()
                .AddEntityFrameworkStores <PuzzleServerContext>();
            });
        }
        public async Task <ActionResult> Deploy(int?id)
        {
            string token_header = null;

            if (Session["token_header"] != null)
            {
                token_header = Session["token_header"].ToString();
            }
            if (id == null)
            {
                return(View());
            }

            long modelid = (long)id;
            CustomTranslatorAPIClient clientapp = new CustomTranslatorAPIClient();


            DeploymentConfiguration regionaldeployment1 = new DeploymentConfiguration();

            regionaldeployment1.region     = 1;    // North America = 1
            regionaldeployment1.isDeployed = true; // true = deployment ; false = undeployment

            DeploymentConfiguration regionaldeployment2 = new DeploymentConfiguration();

            regionaldeployment2.region     = 2;    // Europe = 2
            regionaldeployment2.isDeployed = true; // true = deployment ; false = undeployment

            DeploymentConfiguration regionaldeployment3 = new DeploymentConfiguration();

            regionaldeployment3.region     = 3;    // Asia Pacific
            regionaldeployment3.isDeployed = true; // true = deployment ; false = undeployment

            List <DeploymentConfiguration> deploymentconfig = new List <DeploymentConfiguration>();

            deploymentconfig.Add(regionaldeployment1);
            deploymentconfig.Add(regionaldeployment2);
            deploymentconfig.Add(regionaldeployment3);

            string result = await clientapp.CreateModelDeploymentRequest(modelid, deploymentconfig, token_header);

            Response.Write(result);
            return(View());
        }
Esempio n. 26
0
        public void SerializationShouldGenerateCorrectXml()
        {
            string expectedXml =
                ResourceHelper.ReadString(
                    "Galen.Ci.EntityFramework.Deployer.Tests.Data.SerializationShouldGenerateCorrectXml_Expected.xml");

            string actualXml;

            var config = new DeploymentConfiguration()
            {
                MigrationConfigurationInfo = new MigrationConfigurationInfo
                {
                    Type = "Galen.Enterprise.Data.Migrations.SomeContext.Configuration"
                },

                InitializerConfigurationInfo = new InitializerConfigurationInfo
                {
                    Type           = "Galen.Enterprise.Data.Initializers.SomeContextCreateDatabaseIfNotExists",
                    ServiceAccount = new ServiceAccountInfo()
                    {
                        Name         = "SomeWindowsAccountName",
                        Domain       = "SomeDomainName",
                        DatabaseUser = "******",
                        AccountType  = "Windows"
                    }
                }
            };

            using (var memoryStream = new MemoryStream())
            {
                var sut = new DeploymentConfigurationXmlStore(memoryStream);
                sut.Save(config);

                memoryStream.Position = 0;
                using (var sr = new StreamReader(memoryStream))
                {
                    actualXml = sr.ReadToEnd();
                }
            }

            Assert.AreEqual(expectedXml, actualXml);
        }
Esempio n. 27
0
        public DeploymentRendererContext(
            DeploymentConfiguration configuration,
            string name,
            string ns,
            DirectoryInfo workingDirectory,
            string?cluster,
            string?environment,
            string?vertical,
            string?subVertical
            )
        {
            Configuration    = configuration;
            Name             = name;
            Namespace        = ns;
            WorkingDirectory = workingDirectory;

            Cluster     = cluster;
            Environment = environment;
            Vertical    = vertical;
            SubVertical = subVertical;
        }
Esempio n. 28
0
        public Task <IWorkflow> Start()
        {
            string ip = "";

            if (baseSteps.site == "staging")
            {
                ip = "40.113.145.68";
            }
            if (baseSteps.site == "bcn")
            {
                ip = "13.94.168.16";
            }
            if (baseSteps.site == "demo")
            {
                ip = "40.68.203.169";
            }

            var configuration = new DeploymentConfiguration()
            {
                //QueueName = "notificationwf",
                //TenantPrefix = "NotificationWf",

                QueueName    = "Tester",
                TenantPrefix = "Tester",

                ServiceBus         = new Uri("rabbitmq://" + ip + "/hivmonitor"),
                ServiceBusUsername = "******",
                ServiceBusPassword = "******",
                Services           = new Dictionary <Regex, Uri>()
            };

            workflow = Workflow.From(configuration)
                       .DefinedIn(typeof(BarcodeProcesedEventHandler).Assembly)
                       .UsingMassTransitOverRabbitMq()
                       .CreateWorkflow();

            return(workflow.Start());
        }
Esempio n. 29
0
        public override bool TryGetNodeDetail(out NodeDetail nodeDetail)
        {
            NodeDetail              thisNode       = new EndNodeDetail();
            List <string>           childernNaames = new List <string>();
            DeploymentConfiguration config         = (DeploymentConfiguration)this.Configuration;

            foreach (ShardConfiguration singleShard in config.Shards.Values)
            {
                if (singleShard.Name.ToLower().Equals(PathChunks[0].ToLower()))
                {
                    string[] childPathChunks = new string[this.PathChunks.Length - 1];
                    Array.Copy(this.PathChunks, 1, childPathChunks, 0, this.PathChunks.Length - 1);
                    thisNode = new ShardValueDetail(PathChunks[0], singleShard, childPathChunks);
                }
            }
            if (PathChunks.Length == 1)
            {
                nodeDetail = thisNode;
                return(true);
            }

            return(thisNode.TryGetNodeDetail(out nodeDetail));
        }
Esempio n. 30
0
        protected override void OnStart(string[] args)
        {
            try
            {
                stopping = false;
                // Load configuration from registry.
                config = Utils.Registry.LoadDeploymentConfiguration();
                // Update config.
                UpdateConfig();
                // Register instance under target.
                Register();

                if (worker == null)
                {
                    worker = new System.Threading.Thread(new System.Threading.ThreadStart(ThreadProc));
                    worker.Start();
                }
            }
            catch (Exception ex)
            {
                this.EventLog.WriteEntry(string.Format("Failed starting service : ", ex.ToString()), EventLogEntryType.Error);
            }
        }
Esempio n. 31
0
        static void Main(string[] args)
        {
            configurationBuilder = new DeploymentConfigurationBuilder(deploymentConfigLogger);
            DeploymentPipelineFactory pipelineFactory = new DeploymentPipelineFactory(deploymentFactoryLogger, pipelineLogger);
            string settingsFilePath = string.Empty;

            if (args.Length == 0)
            {
                //settingsFilePath = "sample_deployment_config.json";
                settingsFilePath = "E:\\Tempfiles\\deployment-central\\omniscraper-deployment.json";
            }
            else
            {
                settingsFilePath = args[0];
            }


            DeploymentConfiguration deploymentConfiguration = configurationBuilder.GetConfiguration(settingsFilePath);

            DeploymentService deploymentService =
                new DeploymentService(deploymentConfiguration, pipelineFactory, fileUploadHandlerFactory);

            deploymentService.Deploy();
        }
Esempio n. 32
0
 public AppDeployment(DeploymentConfiguration config, TextWriter logWriter = null)
 {
     this.config = config;
     this.logWriter = logWriter;
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ProductConfigurationOptions"/> class.
 /// </summary>
 /// <param name="configuration">The configuration.</param>
 public ProductConfigurationOptions(DeploymentConfiguration configuration)
 {
     _configuration = configuration;
 }
Esempio n. 34
0
        public static string Serialise(DeploymentConfiguration config)
        {
            if (config == null)
                throw new ArgumentNullException("config", "Configuration cannot be null.");

            var values = new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string,string>("CheckFrequency", config.CheckFrequency.ToString()),
                new KeyValuePair<string,string>("AwsAccessKeyId", config.AwsAccessKeyId),
                new KeyValuePair<string,string>("AwsSecretAccessKey", config.AwsSecretAccessKey),
                new KeyValuePair<string,string>("BucketName", config.BucketName),
                new KeyValuePair<string,string>("DeploymentDirectory", config.DeploymentDirectory),
                new KeyValuePair<string,string>("TargetKey", config.TargetKey.ToString("N")),
            };
            if (config.InstanceKey.HasValue)
                values.Add(new KeyValuePair<string,string>("InstanceKey", config.InstanceKey.Value.ToString("N")));

            using (var reader = new StreamReader(Utils.Serialisation.Serialise(values)))
            {
                return reader.ReadToEnd();
            }
        }
 public void Save(DeploymentConfiguration configuration)
 {
     m_Config = configuration;
 }
 public DeploymentConfigurationInMemoryStore(DeploymentConfiguration config)
 {
     m_Config = config;
 }
Esempio n. 37
0
        public ISiteBuilder CreateBuilder(ITracer tracer, ILogger logger)
        {
            string repositoryRoot = _environment.RepositoryPath;
            var configuration = new DeploymentConfiguration(repositoryRoot);

            // If there's a custom deployment file then let that take over.
            if (!String.IsNullOrEmpty(configuration.Command))
            {
                return new CustomBuilder(_environment, _settings, _propertyProvider, repositoryRoot, configuration.Command);
            }

            // If the repository has an explicit pointer to a project path to be deployed
            // then use it.
            string targetProjectPath = configuration.ProjectPath;
            if (!String.IsNullOrEmpty(targetProjectPath))
            {
                tracer.Trace("Found .deployment file in repository");

                // Try to resolve the project
                return ResolveProject(repositoryRoot,
                                      targetProjectPath,
                                      tryWebSiteProject: true,
                                      searchOption: SearchOption.TopDirectoryOnly);
            }

            // Get all solutions in the current repository path
            var solutions = VsHelper.GetSolutions(repositoryRoot).ToList();

            if (!solutions.Any())
            {
                return ResolveProject(repositoryRoot,
                                      searchOption: SearchOption.AllDirectories);
            }

            // More than one solution is ambiguous
            if (solutions.Count > 1)
            {
                // TODO: Show relative paths in error messages
                ThrowAmbiguousSolutionsError(solutions);
            }

            // We have a solution
            VsSolution solution = solutions[0];

            // We need to determine what project to deploy so get a list of all web projects and
            // figure out with some heuristic, which one to deploy.

            // TODO: Pick only 1 and throw if there's more than one
            VsSolutionProject project = solution.Projects.Where(p => p.IsWap || p.IsWebSite).FirstOrDefault();

            if (project == null)
            {
                logger.Log(Resources.Log_NoDeployableProjects, solution.Path);

                return ResolveNonAspProject(repositoryRoot, null);
            }

            if (project.IsWap)
            {
                return new WapBuilder(_environment,
                                      _settings,
                                      _propertyProvider,
                                      repositoryRoot,
                                      project.AbsolutePath,
                                      solution.Path);
            }

            return new WebSiteBuilder(_environment,
                                      _settings,
                                      _propertyProvider,
                                      repositoryRoot,
                                      project.AbsolutePath,
                                      solution.Path);
        }
Esempio n. 38
0
        public async Task CanCreateBatchAccountWithPool()
        {
            using (var context = FluentMockContext.Start(this.GetType().FullName))
            {
                var rgName             = TestUtilities.GenerateName("rgstg");
                var batchAccountName   = TestUtilities.GenerateName("batchaccount");
                var storageAccountName = TestUtilities.GenerateName("sa");
                try
                {
                    var poolId          = TestUtilities.GenerateName("testPool");
                    var poolDisplayName = TestUtilities.GenerateName("my-pool-name");
                    var vmSize          = "STANDARD_D4";
                    var maxTasksPerNode = 13;

                    //create task scheduling policy
                    var taskSchedulingPolicy = new TaskSchedulingPolicy();
                    taskSchedulingPolicy.NodeFillType = ComputeNodeFillType.Pack;

                    //create deployment configuration
                    var deploymentConfiguration = new DeploymentConfiguration();
                    deploymentConfiguration.CloudServiceConfiguration           = new CloudServiceConfiguration();
                    deploymentConfiguration.CloudServiceConfiguration.OsFamily  = "4";
                    deploymentConfiguration.CloudServiceConfiguration.OsVersion = "WA-GUEST-OS-4.45_201708-01";

                    //create scaling settings
                    var scalingSettings = new Microsoft.Azure.Management.Batch.Fluent.Models.ScaleSettings();
                    scalingSettings.FixedScale = new FixedScaleSettings();
                    scalingSettings.FixedScale.TargetDedicatedNodes   = 6;
                    scalingSettings.FixedScale.NodeDeallocationOption = ComputeNodeDeallocationOption.TaskCompletion;

                    //create metadata
                    var metadata = new List <MetadataItem>();
                    metadata.Add(new MetadataItem("metadata-1", "value-1"));
                    metadata.Add(new MetadataItem("metadata-2", "value-2"));

                    //create start task
                    var startTask         = new StartTask();
                    var cmdLine           = "cmd /c SET";
                    var maxTaskRetryCount = 6;
                    startTask.CommandLine         = cmdLine;
                    startTask.EnvironmentSettings = new List <EnvironmentSetting>();
                    startTask.EnvironmentSettings.Add(new EnvironmentSetting("MYSET", "1234"));
                    startTask.UserIdentity      = new UserIdentity(default(string), new AutoUserSpecification(AutoUserScope.Pool, ElevationLevel.Admin));
                    startTask.MaxTaskRetryCount = maxTaskRetryCount;
                    startTask.WaitForSuccess    = true;
                    startTask.ResourceFiles     = new List <ResourceFile>();
                    startTask.ResourceFiles.Add(new ResourceFile(default(string), default(string), "https://testaccount.blob.core.windows.net/example-blob-file", default(string), "c:\\\\temp\\\\gohere", "777"));

                    //create user accounts
                    var userAccounts = new List <UserAccount>();
                    userAccounts.Add(new UserAccount("username1", "examplepassword", ElevationLevel.Admin, new LinuxUserConfiguration(1234, 4567, "sshprivatekeyvalue"), default(WindowsUserConfiguration)));

                    var batchManager = TestHelper.CreateBatchManager();

                    // Create
                    var batchAccount = await batchManager.BatchAccounts
                                       .Define(batchAccountName)
                                       .WithRegion(Region.AsiaSouthEast)
                                       .WithNewResourceGroup(rgName)
                                       .WithNewStorageAccount(storageAccountName)
                                       .CreateAsync();

                    batchAccount.Update().DefineNewPool(poolId)
                    .WithDisplayName(poolDisplayName)
                    .WithVmSize(vmSize)
                    .WithInterNodeCommunication(InterNodeCommunicationState.Enabled)
                    .WithMaxTasksPerNode(maxTasksPerNode)
                    .WithTaskSchedulingPolicy(taskSchedulingPolicy)
                    .WithDeploymentConfiguration(deploymentConfiguration)
                    .WithScaleSettings(scalingSettings)
                    .WithMetadata(metadata)
                    .WithStartTask(startTask)
                    .WithUserAccount(userAccounts)
                    .Attach()
                    .Apply();

                    Assert.Equal(rgName, batchAccount.ResourceGroupName);
                    Assert.NotNull(batchAccount.AutoStorage);
                    Assert.Equal(ResourceUtils.NameFromResourceId(batchAccount.AutoStorage.StorageAccountId), storageAccountName);

                    // List
                    var accounts = batchManager.BatchAccounts.ListByResourceGroup(rgName);
                    Assert.Contains(accounts, account => StringComparer.OrdinalIgnoreCase.Equals(account.Name, batchAccountName));

                    // Get
                    batchAccount = batchManager.BatchAccounts.GetByResourceGroup(rgName, batchAccountName);
                    Assert.NotNull(batchAccount);

                    Assert.True(batchAccount.Pools.ContainsKey(poolId));
                    batchAccount.Refresh();

                    Assert.True(batchAccount.Pools.ContainsKey(poolId));
                    var pool = batchAccount.Pools[poolId];

                    Assert.NotNull(pool);
                    Assert.Equal(vmSize, pool.VmSize);
                    Assert.Null(pool.MountConfiguration);
                    Assert.NotNull(pool.StartTask);
                    Assert.Equal(cmdLine, pool.StartTask.CommandLine);
                    Assert.NotNull(pool.StartTask.MaxTaskRetryCount);
                    Assert.Equal(maxTaskRetryCount, pool.StartTask.MaxTaskRetryCount);
                    Assert.Equal(1, pool.UserAccounts.Count);

                    batchAccount.Update()
                    .WithoutPool(poolId)
                    .Apply();

                    Assert.False(batchAccount.Pools.ContainsKey(poolId));

                    try
                    {
                        await batchManager.BatchAccounts.DeleteByResourceGroupAsync(batchAccount.ResourceGroupName, batchAccountName);
                    }
                    catch
                    {
                    }
                    var batchAccounts = batchManager.BatchAccounts.ListByResourceGroup(rgName);

                    Assert.Empty(batchAccounts);
                }
                finally
                {
                    try
                    {
                        var resourceManager = TestHelper.CreateResourceManager();
                        resourceManager.ResourceGroups.DeleteByName(rgName);
                    }
                    catch { }
                }
            }
        }
Esempio n. 39
0
        private static void Download(string[] args)
        {
            var userData = UserData.Importer.LoadInstanceLatestUserData();
            if (!userData.Sections.Any(s => s.Name == "Plywood"))
            {
                Console.WriteLine("Error: Plywood section not found!");
                return;
            }
            var config = Utils.Registry.LoadDeploymentConfiguration();
            if (config == null) config = new DeploymentConfiguration();
            var section = userData["Plywood"];
            if (section.Keys.Contains("AwsAccessKeyId"))
                config.AwsAccessKeyId = section["AwsAccessKeyId"];
            if (section.Keys.Contains("AwsSecretAccessKey"))
                config.AwsSecretAccessKey = section["AwsSecretAccessKey"];
            if (section.Keys.Contains("BucketName"))
                config.BucketName = section["BucketName"];
            if (section.Keys.Contains("CheckFrequency"))
                config.CheckFrequency = TimeSpan.Parse(section["CheckFrequency"]);
            if (section.Keys.Contains("DeploymentDirectory"))
                config.DeploymentDirectory = section["DeploymentDirectory"];
            if (section.Keys.Contains("TargetKey"))
                config.TargetKey = Guid.Parse(section["TargetKey"]);

            Utils.Registry.Save(config);
        }
Esempio n. 40
0
        public static DeploymentConfiguration ParsePullConfiguration(TextReader source)
        {
            var properties = Utils.Serialisation.ReadProperties(source);

            if (!properties.ContainsKey("AwsAccessKeyId"))
                throw new DeserialisationException("Failed deserialising pull configuration: missing property \"AwsAccessKeyId\"");
            if (!properties.ContainsKey("AwsSecretAccessKey"))
                throw new DeserialisationException("Failed deserialising pull configuration: missing property \"AwsSecretAccessKey\"");
            if (!properties.ContainsKey("BucketName"))
                throw new DeserialisationException("Failed deserialising pull configuration: missing property \"BucketName\"");
            if (!properties.ContainsKey("CheckFrequency"))
                throw new DeserialisationException("Failed deserialising pull configuration: missing property \"CheckFrequency\"");
            if (!properties.ContainsKey("DeploymentDirectory"))
                throw new DeserialisationException("Failed deserialising pull configuration: missing property \"DeploymentDirectory\"");
            if (!properties.ContainsKey("TargetKey"))
                throw new DeserialisationException("Failed deserialising pull configuration: missing property \"TargetKey\"");

            TimeSpan checkFrequency;
            Guid targetKey;

            if (!TimeSpan.TryParse(properties["CheckFrequency"], out checkFrequency))
                throw new DeserialisationException("Failed deserialising pull configuration: invalid property value for \"CheckFrequency\"");
            if (!Guid.TryParseExact(properties["TargetKey"], "N", out targetKey))
                throw new DeserialisationException("Failed deserialising pull configuration: invalid property value for \"TargetKey\"");

            var config = new DeploymentConfiguration()
            {
                CheckFrequency = checkFrequency,
                AwsAccessKeyId = properties["AwsAccessKeyId"],
                AwsSecretAccessKey = properties["AwsSecretAccessKey"],
                BucketName = properties["BucketName"],
                DeploymentDirectory = properties["DeploymentDirectory"],
                TargetKey = targetKey,
            };

            Guid instanceKey;
            if (properties.ContainsKey("InstanceKey") && Guid.TryParseExact(properties["InstanceKey"], "N", out instanceKey))
                config.InstanceKey = instanceKey;

            return config;
        }
Esempio n. 41
0
        private void UpdateConfig()
        {
            try
            {
                var userData = UserData.Importer.LoadInstanceLatestUserData();
                if (userData.Sections.Any(s => s.Name == "Plywood"))
                {
                    if (config == null) config = new DeploymentConfiguration() { CheckFrequency = TimeSpan.FromSeconds(30) };
                    var section = userData["Plywood"];
                    if (section.Keys.Contains("AwsAccessKeyId"))
                        config.AwsAccessKeyId = section["AwsAccessKeyId"];
                    if (section.Keys.Contains("AwsSecretAccessKey"))
                        config.AwsSecretAccessKey = section["AwsSecretAccessKey"];
                    if (section.Keys.Contains("BucketName"))
                        config.BucketName = section["BucketName"];
                    if (section.Keys.Contains("CheckFrequency"))
                        config.CheckFrequency = TimeSpan.Parse(section["CheckFrequency"]);
                    if (section.Keys.Contains("DeploymentDirectory"))
                        config.DeploymentDirectory = section["DeploymentDirectory"];
                    if (section.Keys.Contains("TargetKey"))
                    {
                        Guid newTargetKey = Guid.Parse(section["TargetKey"]);
                        if (newTargetKey != config.TargetKey)
                        {
                            reregister = true;
                            config.TargetKey = Guid.Parse(section["TargetKey"]);
                        }
                    }
                    if (section.Keys.Contains("InstanceKey"))
                    {
                        Guid newInstanceKey = Guid.Parse(section["InstanceKey"]);
                        if (newInstanceKey != config.InstanceKey)
                        {
                            config.InstanceKey = Guid.Parse(section["InstanceKey"]);
                        }
                    }

                    Utils.Registry.Save(config);
                }
                else
                {
                    this.EventLog.WriteEntry("Failed updating instance plywood config from user data: Plywood section not found.", EventLogEntryType.Information);
                }
            }
            catch (Exception ex)
            {
                this.EventLog.WriteEntry("Failed updating instance plywood config from user data: " + ex.ToString(), EventLogEntryType.Warning);
            }
        }