public HttpResponseMessage Get()
        {
            HttpResponseMessage httpResponse = new HttpResponseMessage();

            //Get the subdomain (if exists) for the api call
            string subdomain = Common.GetSubDomain(Request.RequestUri);

            var deployment = new DeploymentModel
            {
                Subdomain   = subdomain,
                Environment = new EnvironmentModel
                {
                    Local        = EnvironmentSettings.CurrentEnvironment.Site,
                    CoreServices = EnvironmentSettings.CurrentEnvironment.CoreServices
                }
            };

            //var json = LowercaseJsonSerializer.SerializeObject(deployment);

            /*
             * var json = JsonConvert.SerializeObject(deployment,
             *  Formatting.Indented,
             *  new JsonSerializerSettings {
             *          ContractResolver = new CamelCasePropertyNamesContractResolver()
             *      }
             *  );*/

            httpResponse = Request.CreateResponse(HttpStatusCode.OK, deployment);

            return(httpResponse);
        }
Beispiel #2
0
        public void ToDeploymentModel_WithoutDependencies_Returns_Correctly()
        {
            var aFeature = new Feature(new FeatureIdentifier("a"), "a", new[]
            {
                new Property(new PropertyIdentifier("p1"), "p1")
            }
                                       );

            var bFeature = new Feature(new FeatureIdentifier("b"), "b", new[]
            {
                new Property(new PropertyIdentifier("p2"), "p2")
            }
                                       );

            var featureModel = new FeatureModel(new[] { aFeature, bFeature }, Enumerable.Empty <PropertyRelation>());

            var genes = new[]
            {
                new DeploymentGene(new FeatureIdentifier("a"), new MicroserviceIdentifier("a")),
                new DeploymentGene(new FeatureIdentifier("b"), new MicroserviceIdentifier("b"))
            };
            var sot = new DeploymentChromosome(featureModel, genes);

            var deploymentModel = new DeploymentModel(featureModel, new[]
            {
                new Microservice(new[] { new FeatureInstance(aFeature, new[] { new PropertyIdentifier("p1") }) }),
                new Microservice(new[] { new FeatureInstance(bFeature, new[] { new PropertyIdentifier("p2") }) }),
            });

            Assert.AreEqual(deploymentModel, sot.ToDeploymentModel());
        }
        /// <summary>
        ///		Obtiene los proveedores de datos
        /// </summary>
        private DataProviderCollection GetDataProviders(DeploymentModel deployment)
        {
            DataProviderCollection providers = new DataProviderCollection();

            // Obtiene los proveedores
            foreach (KeyValuePair <string, DatabaseConnectionModel> connection in deployment.Connections)
            {
                switch (connection.Value.Type)
                {
                case DatabaseConnectionModel.DataBaseType.SqLite:
                    providers.Add(GetSqLiteProvider(connection.Key, connection.Value));
                    break;

                case DatabaseConnectionModel.DataBaseType.SqlServer:
                    providers.Add(GetSqlServerProvider(connection.Key, connection.Value));
                    break;

                default:
                    System.Diagnostics.Debug.WriteLine("Esto hay que controlarlo");
                    break;
                }
            }
            // Devuelve los proveedores
            return(providers);
        }
Beispiel #4
0
        private void CloneFromPublishLocation(DeploymentModel model)
        {
            Logger.Debug(model.GitDeployment ? "Git deployment" : "Non Git Deployment");

            publishGitPath = repoPath + "\\" + "Website";

            DeleteRepoPathContents(publishGitPath);

            if (model.GitDeployment)
            {
                fullPublishGitPath = publishGitPath + "\\.git";

                var token = githubUserRepository.GetToken(model.Username);
                if (token == string.Empty)
                {
                    throw new Exception("No auth token found for user " + model.Username);
                }

                token = token + "@";

                //Clone via https
                model.GitRepo = model.GitRepo.Insert(8, token);

                CloneFromPublishGitRepository(model.GitRepo, publishGitPath);
            }
        }
Beispiel #5
0
        public async Task <IActionResult> CreateAzureADApplication([FromBody] DeploymentModel deployApp)
        {
            try
            {
                logger.LogInformation("Create Azure AD Application: {application}", deployApp.ApplicationName);
                var appUri = String.Format("https://{0}/{1}", tokenServices.TenantId, deployApp.ApplicationName);

                var app = await _servicePrincipalRepo.CreateAppAndServicePrincipal(deployApp.ApplicationName, appUri, "msiot123",
                                                                                   tokenServices.TenantId);

                ServicePrincipalResponseModel spm = new ServicePrincipalResponseModel()
                {
                    ApplicationName = app.App.DisplayName,
                    AppObjectId     = app.App.ObjectId,
                    AppIdUrl        = app.App.IdentifierUris.First(),
                    ClientId        = app.App.AppId,
                    ClientSecret    = app.AppClientSecret,
                    TenantId        = tokenServices.TenantId
                };

                logger.LogInformation("Create Azure AD Application Completed: App clientid{application}", spm.ClientId);
                return(Ok(spm));
            }
            catch (Exception e)
            {
                logger.LogError(e, "Create Azure AD Application: - Exception {message}", e.Message);
                throw;
            }
        }
Beispiel #6
0
        /// <summary>
        ///		Exporta los archivos
        /// </summary>
        internal void Export(DeploymentModel deployment)
        {
            using (BlockLogModel block = Manager.Logger.Default.CreateBlock(LogModel.LogType.Info, $"Start deployment '{deployment.Name}'"))
            {
                (NormalizedDictionary <object> constants, string error) = GetParameters(deployment.JsonParameters);

                if (!string.IsNullOrWhiteSpace(error))
                {
                    block.Error(error);
                }
                else
                {
                    ExporterOptions options = new ExporterOptions(deployment.SourcePath, deployment.TargetPath);

                    // Asigna las propiedades
                    options.WriteComments    = deployment.WriteComments;
                    options.LowcaseFileNames = deployment.LowcaseFileNames;
                    options.ReplaceArguments = deployment.ReplaceArguments;
                    // Añade los parámetros
                    foreach ((string key, object value) in constants.Enumerate())
                    {
                        options.AddParameter(key, value);
                    }
                    // Exporta los archivos
                    new DatabrickExporter(Manager.Logger, options).Export();
                }
            }
        }
        public async Task <IActionResult> Deploy4x4IoTSolution([FromBody] DeploymentModel depMod)
        {
            try
            {
                logger.LogInformation("Deploy application: {application}", depMod.ApplicationName);
                DeploymentRequest deployReq = new DeploymentRequest()
                {
                    ApplicationName = depMod.ApplicationName,
                    ClientId        = depMod.ClientId,
                    ClientSecret    = depMod.ClientSecret,
                    SubscriptionId  = depMod.SubscriptionId,
                    TenantId        = depMod.TenantId,
                    Location        = depMod.Location,
                    DataPacketDesignerPackageWebZipUri     = urlOptions.Value.DataPacketDesignerPackage,
                    DeviceManagementPortalPackageWebZipUri = urlOptions.Value.DeviceManagementPortalPackage
                };
                await _resourceManagerRepo.CreateResoureGroup(depMod.SubscriptionId, depMod.Location, depMod.ApplicationName);

                var deployment = await _resourceManagerRepo.Deploy4x4MSIoTSolutionUsingAzureRMTemplate(deployReq);

                logger.LogInformation("Deploy application Begin-Accepted");
                return(Ok(deployment));
            }
            catch (Exception e)
            {
                logger.LogError(e, "Deploy application - Exception {message}", e.Message);
                throw;
            }
        }
        /// <inheritdoc/>
        public async Task <DeploymentEntity> CreateAsync(DeploymentModel deployment)
        {
            DeploymentEntity deploymentEntity = new DeploymentEntity();

            deploymentEntity.PopulateBaseProperties(_org, _app, _httpContext);
            deploymentEntity.TagName         = deployment.TagName;
            deploymentEntity.EnvironmentName = deployment.Environment.Name;

            ReleaseEntity release = await _releaseRepository.GetSucceededReleaseFromDb(
                deploymentEntity.Org,
                deploymentEntity.App,
                deploymentEntity.TagName);

            await _applicationInformationService
            .UpdateApplicationInformationAsync(_org, _app, release.TargetCommitish, deployment.Environment);

            Build queuedBuild = await QueueDeploymentBuild(release, deploymentEntity, deployment.Environment.Hostname);

            deploymentEntity.Build = new BuildEntity
            {
                Id      = queuedBuild.Id.ToString(),
                Status  = queuedBuild.Status,
                Started = queuedBuild.StartTime
            };

            return(await _deploymentRepository.CreateAsync(deploymentEntity));
        }
Beispiel #9
0
        public void ToDeploymentModel_WithRecursiveDependenciesInSingleMicroservice_Returns_Correctly()
        {
            var aFeature = new Feature(new FeatureIdentifier("a"), "a", new[]
            {
                new Property(new PropertyIdentifier("p1"), "p1"),
                new Property(new PropertyIdentifier("p2"), "p2")
            }
                                       );

            var bFeature = new Feature(new FeatureIdentifier("b"), "b", new[]
            {
                new Property(new PropertyIdentifier("p3"), "p3"),
                new Property(new PropertyIdentifier("p4"), "p4")
            }
                                       );

            var cFeature = new Feature(new FeatureIdentifier("c"), "c", new[]
            {
                new Property(new PropertyIdentifier("p5"), "p5"),
                new Property(new PropertyIdentifier("p6"), "p6"),
                new Property(new PropertyIdentifier("p7"), "p7")
            }
                                       );

            var featureModel = new FeatureModel(new[] { aFeature, bFeature, cFeature }, new[]
            {
                new PropertyRelation(new PropertyIdentifier("p6"), new PropertyIdentifier("p4")),
                new PropertyRelation(new PropertyIdentifier("p4"), new PropertyIdentifier("p2"))
            });

            var genes = new[]
            {
                new DeploymentGene(new FeatureIdentifier("a"), new MicroserviceIdentifier("a")),
                new DeploymentGene(new FeatureIdentifier("b"), new MicroserviceIdentifier("b")),
                new DeploymentGene(new FeatureIdentifier("c"), new MicroserviceIdentifier("c"))
            };

            var sot = new DeploymentChromosome(featureModel, genes);

            var deploymentModel = new DeploymentModel(featureModel, new[]
            {
                new Microservice(new[]
                {
                    new FeatureInstance(aFeature, new[] { new PropertyIdentifier("p1"), new PropertyIdentifier("p2") }),
                }),
                new Microservice(new []
                {
                    new FeatureInstance(aFeature, new[] { new PropertyIdentifier("p2") }, true),
                    new FeatureInstance(bFeature, new[] { new PropertyIdentifier("p3"), new PropertyIdentifier("p4") })
                }),
                new Microservice(new []
                {
                    new FeatureInstance(cFeature, new[] { new PropertyIdentifier("p5"), new PropertyIdentifier("p6"), new PropertyIdentifier("p7") }),
                    new FeatureInstance(bFeature, new[] { new PropertyIdentifier("p4") }, true),
                    new FeatureInstance(aFeature, new[] { new PropertyIdentifier("p2") }, true)
                }),
            });

            Assert.AreEqual(deploymentModel, sot.ToDeploymentModel());
        }
Beispiel #10
0
 /// <summary>
 ///		Carga los elementos
 /// </summary>
 internal void LoadItems(DeploymentModel deployment)
 {
     foreach (KeyValuePair <string, DatabaseConnectionModel> item in deployment.Connections)
     {
         Add(new DeploymentConnectionViewModel(Project, item.Key, item.Value), false);
     }
 }
Beispiel #11
0
        public async Task CreateAsync_OK()
        {
            // Arrange
            DeploymentModel deploymentModel = new DeploymentModel
            {
                TagName = "1",
            };

            deploymentModel.Environment = new EnvironmentModel
            {
                Name     = "at23",
                Hostname = "hostname"
            };

            _releaseRepository.Setup(r => r.GetSucceededReleaseFromDb(
                                         It.IsAny <string>(),
                                         It.IsAny <string>(),
                                         It.IsAny <string>())).ReturnsAsync(GetReleases("updatedRelease.json").First());

            _applicationInformationService.Setup(ais => ais.UpdateApplicationInformationAsync(
                                                     It.IsAny <string>(),
                                                     It.IsAny <string>(),
                                                     It.IsAny <string>(),
                                                     It.IsAny <EnvironmentModel>())).Returns(Task.CompletedTask);

            Mock <IAzureDevOpsBuildClient> azureDevOpsBuildClient = new Mock <IAzureDevOpsBuildClient>();

            azureDevOpsBuildClient.Setup(b => b.QueueAsync(
                                             It.IsAny <QueueBuildParameters>(),
                                             It.IsAny <int>())).ReturnsAsync(GetBuild());

            _deploymentRepository.Setup(r => r.Create(
                                            It.IsAny <DeploymentEntity>())).ReturnsAsync(GetDeployments("createdDeployment.json").First());

            DeploymentService deploymentService = new DeploymentService(
                new TestOptionsMonitor <AzureDevOpsSettings>(GetAzureDevOpsSettings()),
                azureDevOpsBuildClient.Object,
                _httpContextAccessor.Object,
                _deploymentRepository.Object,
                _releaseRepository.Object,
                _applicationInformationService.Object);

            // Act
            DeploymentEntity deploymentEntity = await deploymentService.CreateAsync(deploymentModel);

            // Assert
            Assert.NotNull(deploymentEntity);
            _releaseRepository.Verify(
                r => r.GetSucceededReleaseFromDb(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()), Times.Once);
            _applicationInformationService.Verify(
                ais => ais.UpdateApplicationInformationAsync(
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <EnvironmentModel>()),
                Times.Once);
            azureDevOpsBuildClient.Verify(
                b => b.QueueAsync(It.IsAny <QueueBuildParameters>(), It.IsAny <int>()), Times.Once);
            _deploymentRepository.Verify(r => r.Create(It.IsAny <DeploymentEntity>()), Times.Once);
        }
Beispiel #12
0
 public DeployedRelease(ReleaseModel release, DeploymentModel deployment)
 {
     ReleaseId    = release.Id;
     DeploymentId = deployment.Id;
     Version      = release.Version;
     Created      = release.Created;
     DeployedAt   = deployment.DeployedAt;
 }
Beispiel #13
0
        public void GetHashCode_Returns_Same_ForReversedDeploymentModel()
        {
            var featureModel    = CreateFeatureModel();
            var microservices   = CreateMicroservices(featureModel);
            var deploymentModel = new DeploymentModel(featureModel, microservices);

            Assert.AreEqual(deploymentModel, new DeploymentModel(featureModel, microservices.Reverse()));
        }
Beispiel #14
0
 public DeploymentViewModel(SolutionViewModel solutionViewModel, DeploymentModel deployment)
 {
     // Inicializa las propiedades
     SolutionViewModel = solutionViewModel;
     IsNew             = deployment == null;
     Deployment        = deployment ?? new DeploymentModel(solutionViewModel.Solution);
     // Inicializa el viewModel
     InitViewModel();
 }
Beispiel #15
0
        public void Constructor_Sets_Fields_Correctly()
        {
            var featureModel    = CreateFeatureModel();
            var microservices   = CreateMicroservices(featureModel);
            var deploymentModel = new DeploymentModel(featureModel, microservices);

            Assert.AreEqual(deploymentModel.FeatureModel, featureModel);
            CollectionAssert.AreEquivalent(microservices, deploymentModel.Microservices);
        }
        public void Write(DeploymentModel deploymentModel)
        {
            var root = new JObject(
                new JProperty("version", new JValue(2)),
                new JProperty("microservices", new JArray(deploymentModel.Microservices.Select(WriteMicroservice))),
                new JProperty("relations", new JArray(deploymentModel.FeatureModel.Relations.Select(WriteRelation)))
                );

            File.WriteAllText(_filePath, root.ToString());
        }
Beispiel #17
0
        public static async Task Run([QueueTrigger("tenantstosync", Connection = "AzureStorageConnectionString")] string myQueueItem, ILogger log)
        {
            log.LogInformation($"C# Queue trigger function processed: {myQueueItem}");

            if (!string.IsNullOrEmpty(myQueueItem))
            {
                TenantQueueItem tenant = JsonConvert.DeserializeObject <TenantQueueItem>(myQueueItem);

                if (tenant != null && !string.IsNullOrWhiteSpace(tenant.TenantId))
                {
                    List <DeploymentServiceModel> deploymentsToSync  = new List <DeploymentServiceModel>();
                    IEnumerable <Configuration>   deploymentsFromHub = null;
                    try
                    {
                        deploymentsFromHub = await TenantConnectionHelper.GetRegistry(tenant.TenantId).GetConfigurationsAsync(100);

                        DeploymentSyncService service = new DeploymentSyncService();

                        deploymentsToSync.AddRange(await service.GetDeploymentsToSync(tenant.TenantId, deploymentsFromHub));
                    }
                    catch (Exception)
                    {
                        log.LogError($"Error occurrred while fetching deployments");
                        throw;
                    }

                    if (deploymentsToSync != null && deploymentsToSync.Count > 0)
                    {
                        // Get the connection string from app settings
                        string connectionString = Environment.GetEnvironmentVariable("AzureStorageConnectionString", EnvironmentVariableTarget.Process);

                        // Instantiate a QueueClient which will be used to create and manipulate the queue
                        QueueClient queueClient = new QueueClient(connectionString, "deploymentstosync");

                        await queueClient.CreateIfNotExistsAsync();

                        if (queueClient.Exists())
                        {
                            foreach (var deploymentToSync in deploymentsToSync)
                            {
                                DeploymentModel deployment = new DeploymentModel();
                                deployment.TenantId      = tenant.TenantId;
                                deployment.Deployment    = deploymentToSync;
                                deployment.Configuration = deploymentsFromHub.FirstOrDefault(d => d.Id == deploymentToSync.Id);

                                var deploymentToSyncString = JsonConvert.SerializeObject(deployment);

                                queueClient.SendMessage(Base64Encode(deploymentToSyncString));
                            }
                        }
                    }
                }
            }
        }
Beispiel #18
0
        private void DeployBlog(DeploymentModel model)
        {
            CloneFromGithub(model.CloneUrl, model.Username);

            LetItSnow();

            PushToGithub();

            PublishToGitFTP(model);

            DeleteRepoPathContents(repoPath);
        }
Beispiel #19
0
        public void GetHashCode_Returns_Same_ForIdenticalDeploymentModel()
        {
            var featureModel    = CreateFeatureModel();
            var microservices   = CreateMicroservices(featureModel);
            var deploymentModel = new DeploymentModel(featureModel, microservices);

            var featureModel2    = CreateFeatureModel();
            var microservices2   = CreateMicroservices(featureModel);
            var deploymentModel2 = new DeploymentModel(featureModel2, microservices2);

            Assert.AreEqual(deploymentModel.GetHashCode(), deploymentModel2.GetHashCode());
        }
Beispiel #20
0
        private void CloneFromPublishLocation(DeploymentModel model)
        {
            Logger.Debug(model.GitDeployment ? "Git deployment" : "Non Git Deployment");

            publishGitPath = repoPath + "\\" + "Website";

            if (model.GitDeployment)
            {
                fullPublishGitPath = publishGitPath + "\\.git";

                CloneFromPublishGitRepository(model.GitRepo, publishGitPath);
            }
        }
Beispiel #21
0
        private static void PrintModel(TestScriptExecutionContext context, DeploymentModel model)
        {
            context.Log.LogInformation($"> Deployment Model of Test Script");

            foreach (var hub in model.Hubs)
            {
                context.Log.LogInformation($" > Hub: {hub.HubType}");

                foreach (var device in hub.Devices)
                {
                    context.Log.LogInformation($"  > Device: {device.DeviceType} @ {device.PortId}");
                }
            }
        }
Beispiel #22
0
        public IDeploymentChromosome Create(DeploymentModel deploymentModel)
        {
            var featureModel = deploymentModel.FeatureModel;
            var genes        = new List <IDeploymentGene>();

            foreach (var microservice in deploymentModel.Microservices)
            {
                foreach (var feature in microservice.Where(f => !f.IsInternal))
                {
                    genes.Add(new DeploymentGene(feature.FeatureId, microservice.Id));
                }
            }
            return(new DeploymentChromosome(featureModel, genes));
        }
Beispiel #23
0
        public void Create_WithDependencies_Creates_CorrectChromosome()
        {
            var aFeature = new Feature(new FeatureIdentifier("a"), "a", new[]
            {
                new Property(new PropertyIdentifier("p1"), "p1"),
                new Property(new PropertyIdentifier("p2"), "p2")
            }
                                       );

            var bFeature = new Feature(new FeatureIdentifier("b"), "b", new[]
            {
                new Property(new PropertyIdentifier("p3"), "p3"),
                new Property(new PropertyIdentifier("p4"), "p4")
            }
                                       );

            var cFeature = new Feature(new FeatureIdentifier("c"), "c", new[]
            {
                new Property(new PropertyIdentifier("p5"), "p5"),
                new Property(new PropertyIdentifier("p6"), "p6"),
                new Property(new PropertyIdentifier("p7"), "p7")
            }
                                       );

            var featureModel = new FeatureModel(new[] { aFeature, bFeature, cFeature }, new[]
            {
                new PropertyRelation(new PropertyIdentifier("p6"), new PropertyIdentifier("p2")),
                new PropertyRelation(new PropertyIdentifier("p7"), new PropertyIdentifier("p4"))
            });

            var microservices = new[]
            {
                new Microservice(new[] { new FeatureInstance(aFeature, new[] { new PropertyIdentifier("p1"), new PropertyIdentifier("p2") }) }),
                new Microservice(new[] { new FeatureInstance(bFeature, new[] { new PropertyIdentifier("p3"), new PropertyIdentifier("p4") }) }),
                new Microservice(new[]
                {
                    new FeatureInstance(cFeature, new[] { new PropertyIdentifier("p5"), new PropertyIdentifier("p6"), new PropertyIdentifier("p7") }),
                    new FeatureInstance(bFeature, new[] { new PropertyIdentifier("p4") }, true),
                    new FeatureInstance(aFeature, new[] { new PropertyIdentifier("p2") }, true)
                }),
            };

            var deploymentModel = new DeploymentModel(featureModel, microservices);

            var sot        = new DeploymentChromosomeFactory();
            var chromosome = sot.Create(deploymentModel);

            Assert.AreEqual(deploymentModel, chromosome.ToDeploymentModel());
        }
Beispiel #24
0
        private void DeployBlog(DeploymentModel model)
        {
            CloneFromGithub(model.CloneUrl, model.Username);

            CloneFromPublishLocation(model);

            LetItSnow();

            PublishToGitFTP(model);

            Logger.Debug("Deleting content from " + repoPath);
            DeleteRepoPathContents(repoPath);
            Directory.Delete(repoPath);
            Logger.Debug("Deleted files/folders");
        }
Beispiel #25
0
        public static void Write(int version, DeploymentModel deploymentModel, string filePath)
        {
            IDeploymentModelWriter writer;

            switch (version)
            {
            case 2:
                writer = new LegacyDeploymentModelJsonWriter(filePath);
                break;

            default:
                writer = new JsonDeploymentModelWriter(filePath);
                break;
            }
            writer.Write(deploymentModel);
        }
        /// <summary>
        ///		Carga los modos de distribución
        /// </summary>
        internal DeploymentModelCollection Load(ProjectModel project, MLNode rootML)
        {
            DeploymentModelCollection deployments = new DeploymentModelCollection();

            // Carga los datos
            foreach (MLNode nodeML in rootML.Nodes)
            {
                if (nodeML.Name == TagRoot)
                {
                    DeploymentModel deployment = new DeploymentModel();

                    // Carga los datos
                    LoadBase(nodeML, deployment);
                    deployment.PathScriptsTarget = nodeML.Nodes[TagPathScriptsTarget].Value;
                    deployment.PathFilesTarget   = nodeML.Nodes[TagPathFilesTarget].Value;
                    // Carga las conexiones y parámetros
                    foreach (MLNode childML in nodeML.Nodes)
                    {
                        switch (childML.Name)
                        {
                        case TagConnection:
                            if (!string.IsNullOrEmpty(childML.Attributes[TagKey].Value) &&
                                !string.IsNullOrEmpty(childML.Attributes[TagId].Value))
                            {
                                deployment.Connections.Add(childML.Attributes[TagKey].Value,
                                                           project.Connections.Search(childML.Attributes[TagId].Value) as DatabaseConnectionModel);
                            }
                            break;

                        case TagScript:
                            deployment.Scripts.Add(LoadScript(childML));
                            break;

                        case TagFormatReportType:
                            deployment.ReportFormatTypes.Add(childML.Value.GetEnum(DeploymentModel.ReportFormat.Xml));
                            break;
                        }
                    }
                    // Carga los parámetros
                    LoadParameters(nodeML, deployment.Parameters);
                    // Añade los datos de la distribución
                    deployments.Add(deployment);
                }
            }
            // Devuelve la colección de distribuciones
            return(deployments);
        }
        public async Task <ActionResult <PagedResult <DeploymentModel> > > Get([FromBody] DeploymentFilter filter)
        {
            var result = new PagedResult <DeploymentModel>();

            var query = this.deploymentManager.CreateDeploymentQuery();

            var list = await query.ListAsync(filter.Page, filter.PageSize);

            result.Count = await query.CountAsync();

            result.Page     = filter.Page;
            result.PageSize = filter.PageSize;
            result.Items    = list.Select(x => DeploymentModel.Create(x))
                              .ToList();

            return(this.Ok(result));
        }
        public DeploymentDetailsResponse Handle(DeploymentDetailsRequest message)
        {
            var deployment = _repository.Deployments.Load <Domain.Deployment>(message.Id);

            if (deployment == null)
            {
                return(DeploymentDetailsResponse.Empty);
            }

            NugetFeed[]           feeds    = _repository.Feeds.PerformQuery <NugetFeed>();
            NugetFeed             feed     = feeds.Single(x => x.Id == deployment.FeedId);
            IEnumerable <Version> versions = _board.GetPackageVersions(feed.Uri, deployment.PackageId);

            var model = new DeploymentModel(deployment, feeds, versions);

            return(new DeploymentDetailsResponse(model));
        }
Beispiel #29
0
    /// <summary>
    /// Verifies the deployment model and waits till it reaches zero deployment errors.
    /// </summary>
    /// <param name="self"></param>
    /// <param name="configure">Builder infrastructure for the deployment model</param>
    /// <returns></returns>
    public static async Task VerifyDeploymentModelAsync(this Hub self, DeploymentModel model)
    {
        var awaitable = self.VerifyObservable(model)
                        .Do(LogErrors(self))
                        .Where(x => x.Length == 0)
                        .FirstAsync()
                        .GetAwaiter();

        var firstErors = model.Verify(self.Protocol);

        if (firstErors.Length > 0)
        {
            LogErrors(self)(firstErors);

            await awaitable;
        }
    }
Beispiel #30
0
        public void Create_WithoutDependencies_Creates_CorrectChromosome()
        {
            var aFeature = new Feature(new FeatureIdentifier("a"), "a", new[]
            {
                new Property(new PropertyIdentifier("p1"), "p1")
            });

            var bFeature = new Feature(new FeatureIdentifier("b"), "b", new []
            {
                new Property(new PropertyIdentifier("p2"), "p2")
            });
            var cFeature = new Feature(new FeatureIdentifier("c"), "c", new []
            {
                new Property(new PropertyIdentifier("p3"), "p3")
            });

            var featureModel = new FeatureModel(new []
            {
                aFeature,
                bFeature,
                cFeature
            }, Enumerable.Empty <PropertyRelation>());

            var microservices = new[]
            {
                new Microservice(new []
                {
                    new FeatureInstance(aFeature, aFeature.Properties.Select(p => p.Id))
                }),
                new Microservice(new []
                {
                    new FeatureInstance(bFeature, bFeature.Properties.Select(p => p.Id))
                }),
                new Microservice(new []
                {
                    new FeatureInstance(cFeature, cFeature.Properties.Select(p => p.Id))
                }),
            };
            var deploymentModel = new DeploymentModel(featureModel, microservices);

            var sot        = new DeploymentChromosomeFactory();
            var chromosome = sot.Create(deploymentModel);

            Assert.AreEqual(deploymentModel, chromosome.ToDeploymentModel());
        }
 public void Init()
 {
     XmlSerializer xmlSerializer = new XmlSerializer(typeof(DeploymentModel));
     using (FileStream configFileStream = new FileStream(_locationOfDeploymentModelXml, FileMode.Open, FileAccess.Read))
     {
         _model = xmlSerializer.Deserialize(configFileStream) as DeploymentModel;
         for (int i = 0; i < _model.Items.Length; i++)
         {
             if (_model.Items[i] is DeploymentModelParameters)
             {
                 _deploymentParams = (_model.Items[i] as DeploymentModelParameters).Parameter;
                 continue;
             }
             if (_model.Items[i] is DeploymentModelSteps)
             {
                 _steps = (_model.Items[i] as DeploymentModelSteps).Step;
             }
         }
     }
 }
Beispiel #32
0
        private void CloneFromPublishLocation(DeploymentModel model)
        {
            Logger.Debug(model.GitDeployment ? "Git deployment" : "Non Git Deployment");

            publishGitPath = repoPath + "\\" + "Website";

            DeleteRepoPathContents(publishGitPath);

            if (model.GitDeployment)
            {
                fullPublishGitPath = publishGitPath + "\\.git";

                var token = githubUserRepository.GetToken(model.Username);
                if (token == string.Empty)
                    throw new Exception("No auth token found for user " + model.Username);

                token = token + "@";

                //Clone via https
                model.GitRepo = model.GitRepo.Insert(8, token);

                CloneFromPublishGitRepository(model.GitRepo, publishGitPath);
            }
        }
Beispiel #33
0
        public void Init()
        {
            if (File.Exists(_xmlConfigPath))
            {
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(DeploymentModel));
                using (FileStream configFileStream = new FileStream(_xmlConfigPath, FileMode.Open, FileAccess.Read))
                {
                    _model = xmlSerializer.Deserialize(configFileStream) as DeploymentModel;
                    for (int i = 0; i < _model.Items.Length; i++)
                    {
                        if (_model.Items[i] is DeploymentModelParameters)
                        {
                            _deploymentParams = (_model.Items[i] as DeploymentModelParameters).Parameter.ToList();
                        }
                        else if (_model.Items[i] is DeploymentModelSteps)
                        {
                            _steps = (_model.Items[i] as DeploymentModelSteps).Step.ToList();
                        }
                    }
                }
            }
            else
            {
                _model = new DeploymentModel();
                _deploymentParams = new List<DeploymentModelParametersParameter>();
                _steps = new List<DeploymentModelStepsStep>();

                DeploymentModelParameters dmParams = new DeploymentModelParameters();
                dmParams.Parameter = _deploymentParams.ToArray();

                DeploymentModelSteps dmSteps = new DeploymentModelSteps();
                dmSteps.Step = _steps.ToArray();

                _model.Items = new object[2];
                _model.Items[0] = dmParams;
                _model.Items[1] = dmSteps;
            }
        }
Beispiel #34
0
        private void DeployBlog(DeploymentModel model)
        {
            CloneFromGithub(model.CloneUrl, model.Username);

            CloneFromPublishLocation(model);

            LetItSnow();

            PublishToGitFTP(model);

            Logger.Debug("Deleting content from " + repoPath);
            DeleteRepoPathContents(repoPath);
            Directory.Delete(repoPath);
            Logger.Debug("Deleted files/folders");
        }
Beispiel #35
0
        public void PublishToGitFTP(DeploymentModel model)
        {
            if (model.AzureDeployment)
            {
                var remoteProcess =
                     Process.Start("\"" + gitLocation + "\"", " --git-dir=\"" + fullRepoPath + "\" remote add blog " + model.AzureRepo);
                if (remoteProcess != null)
                    remoteProcess.WaitForExit();

                var pushProcess = Process.Start("\"" + gitLocation + "\"", " --git-dir=\"" + fullRepoPath + "\" push -f blog master");
                if (pushProcess != null)
                    pushProcess.WaitForExit();

            }
            else
            {
                using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword))
                {
                    try
                    {
                        ftp.Open();
                        ftp.Login();

                        if (!string.IsNullOrWhiteSpace(model.FTPPath))
                        {
                            if (!ftp.DirectoryExists(model.FTPPath))
                            {
                                ftp.CreateDirectory(model.FTPPath);
                            }

                            ftp.SetCurrentDirectory(model.FTPPath);
                        }

                        FtpBlogFiles(snowPublishPath, model.FTPPath);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }
Beispiel #36
0
        private void DeployBlog(DeploymentModel model)
        {
            CloneFromGithub(model.CloneUrl, model.Username);

            LetItSnow();

            PushToGithub();

            PublishToGitFTP(model);

            DeleteRepoPathContents(repoPath);
        }
Beispiel #37
0
        public void PublishToGitFTP(DeploymentModel model)
        {
            if (model.GitDeployment)
            {
                Logger.Debug("Executing git add");

                var addProcess = new Process();
                var addProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                    {
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" add -A"

                    };
                addProcess.StartInfo = addProcessStartInfo;
                addProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                addProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data);
                addProcess.Start();
                addProcess.BeginOutputReadLine();
                addProcess.BeginErrorReadLine();
                addProcess.WaitForExit();

                Logger.Debug("git add process to exited");

                Logger.Debug("Executing git email config process");

                var emailProcess = new Process();
                var emailProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.email \"[email protected]\""

                };
                emailProcess.StartInfo = emailProcessStartInfo;
                emailProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                emailProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data);
                emailProcess.Start();
                emailProcess.BeginOutputReadLine();
                emailProcess.BeginErrorReadLine();
                emailProcess.WaitForExit();
                Logger.Debug("git email config process to exited");

                Logger.Debug("Executing git name config process");

                var userProcess = new Process();
                var userProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                {
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath + "\" config user.name \"barbato\""

                };
                userProcess.StartInfo = userProcessStartInfo;
                userProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                userProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data);
                userProcess.Start();
                userProcess.BeginOutputReadLine();
                userProcess.BeginErrorReadLine();
                userProcess.WaitForExit();

                Logger.Debug("git name config process to exited");

                Logger.Debug("Executing git commit");

                var commitProcess = new Process();
                var commitProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                    {
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        Arguments = " --git-dir=\"" + fullPublishGitPath + "\" --work-tree=\"" + publishGitPath +
                                    "\" commit -a -m \"Static Content Regenerated\""
                    };
                commitProcess.StartInfo = commitProcessStartInfo;
                commitProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                commitProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data);
                commitProcess.Start();
                commitProcess.BeginOutputReadLine();
                commitProcess.BeginErrorReadLine();
                commitProcess.WaitForExit();

                Logger.Debug("git commit process to exited");

                Logger.Debug("Executing git push");

                var pushProcess = new Process();
                var pushProcessStartInfo = new ProcessStartInfo("\"" + gitLocation + "\"")
                    {
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        Arguments = " --git-dir=\"" + fullPublishGitPath + "\" push -f origin master"
                    };
                pushProcess.OutputDataReceived += (sender, args) => Logger.Debug(args.Data);
                pushProcess.ErrorDataReceived += (sender, args) => Logger.Debug(args.Data);
                pushProcess.StartInfo = pushProcessStartInfo;
                pushProcess.Start();
                pushProcess.BeginOutputReadLine();
                pushProcess.BeginErrorReadLine();
                pushProcess.WaitForExit();

                Logger.Debug("git push process to exited");

            }
            else
            {
                using (ftp = new FtpConnection(model.FTPServer, model.FTPUsername, model.FTPPassword))
                {
                    try
                    {
                        ftp.Open();
                        ftp.Login();

                        if (!string.IsNullOrWhiteSpace(model.FTPPath))
                        {
                            var parrentDirectory = String.Format("/{0}", Path.GetDirectoryName(model.FTPPath).Replace(Path.DirectorySeparatorChar, '/'));
                            /* Get name of the directory */
                            var checkingDirectory = String.Format("{0}", Path.GetFileName(model.FTPPath)).ToLower();
                            /* Get all child directories info of the parent directory */
                            var ftpDirectories = ftp.GetDirectories(parrentDirectory);
                            /* check if the given directory exists in the returned result */
                            var exists = ftpDirectories.Any(d => d.Name.ToLower() == checkingDirectory);

                            if (!exists)
                            {
                                ftp.CreateDirectory(model.FTPPath);
                            }

                            ftp.SetCurrentDirectory(model.FTPPath);
                        }

                        FtpBlogFiles(publishGitPath, model.FTPPath);
                    }
                    catch (Exception ex)
                    {

                    }
                }
            }
        }
Beispiel #38
0
        private void CloneFromPublishLocation(DeploymentModel model)
        {
            Logger.Debug(model.GitDeployment ? "Git deployment" : "Non Git Deployment");

            publishGitPath = repoPath + "\\" + "Website";

            if (model.GitDeployment)
            {
                fullPublishGitPath = publishGitPath + "\\.git";

                CloneFromPublishGitRepository(model.GitRepo, publishGitPath);
            }
        }