Example #1
0
        /// <inheritdoc/>
        public async Task <Build> QueueAsync(
            QueueBuildParameters queueBuildParameters,
            int buildDefinitionId)
        {
            queueBuildParameters.GiteaEnvironment = $"{_generalSettings.HostName}/repos";
            queueBuildParameters.AppDeployToken   = _sourceControl.GetDeployToken();

            QueueBuildRequest queueBuildRequest = CreateBuildRequest(queueBuildParameters, buildDefinitionId);

            return(await SendRequest(queueBuildRequest));
        }
Example #2
0
 /// <inheritdoc/>
 public Task <string> GetDeployToken()
 {
     try
     {
         return(_decoratedService.GetDeployToken());
     }
     catch (Exception ex)
     {
         LogError(ex, "GetDeployToken");
         throw;
     }
 }
Example #3
0
        public async Task <IActionResult> StartDeployment(string org, string service)
        {
            if (org == null || service == null)
            {
                return(BadRequest(new DeploymentStatus
                {
                    Success = false,
                    Message = "Org or service not supplied",
                }));
            }

            if (_configuration["AccessTokenDevOps"] == null)
            {
                ViewBag.ServiceUnavailable = true;
                return(BadRequest(new DeploymentStatus
                {
                    Success = false,
                    Message = "Deployment failed: no access token",
                }));
            }

            string credentials = _configuration["AccessTokenDevOps"];

            string result       = string.Empty;
            Branch masterBranch = _giteaAPI.GetBranch(org, service, "master").Result;

            if (masterBranch == null)
            {
                _logger.LogWarning($"Unable to fetch branch information for app owner {org} and app {service}");
                return(StatusCode(500, new DeploymentResponse
                {
                    Success = false,
                    Message = "Deployment failed: unable to find latest commit",
                }));
            }

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
                    string giteaEnvironment = Environment.GetEnvironmentVariable("GiteaEndpoint") ?? _settings.ApiEndPointHost;
                    object buildContent     = new
                    {
                        definition = new
                        {
                            id = 5,
                        },
                        parameters = $"{{\"APP_OWNER\":\"{org}\",\"APP_REPO\":\"{service}\",\"APP_DEPLOY_TOKEN\":\"{_sourceControl.GetDeployToken()}\",\"GITEA_ENVIRONMENT\":\"{giteaEnvironment}\", \"APP_COMMIT_ID\":\"{masterBranch.Commit.Id}\",\"should_deploy\":\"{true}\"}}\"",
                    };

                    string        buildjson   = JsonConvert.SerializeObject(buildContent);
                    StringContent httpContent = new StringContent(buildjson, Encoding.UTF8, "application/json");
                    using (HttpResponseMessage response = await client.PostAsync("https://dev.azure.com/brreg/altinn-studio/_apis/build/builds?api-version=5.0-preview.4", httpContent))
                    {
                        response.EnsureSuccessStatusCode();
                        BuildModel responseBody = await response.Content.ReadAsAsync <BuildModel>();

                        result = responseBody.Id;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Unable deploy app {service} for {org} because {ex}");
                return(StatusCode(500, new DeploymentResponse
                {
                    Success = false,
                    Message = "Deployment failed " + ex,
                }));
            }

            return(Ok(new DeploymentResponse
            {
                Success = true,
                BuildId = result,
                Message = "Deployment status: " + result,
            }));
        }
        public async Task <IActionResult> StartDeployment(string applicationOwnerId, string applicationCode)
        {
            _logger.LogInformation("applicationOwnerId -{0}", applicationOwnerId);
            _logger.LogInformation("applicationCode -{0}", applicationCode);
            if (applicationOwnerId == null || applicationCode == null)
            {
                _logger.LogInformation("failed in owner and app code -bad request");
                return(BadRequest(new DeploymentStatus
                {
                    Success = false,
                    Message = "ApplicationOwnerId and applicationCode must be supplied",
                }));
            }

            _logger.LogInformation("access token {0}", _configuration["AccessTokenDevOps"]);
            if (_configuration["AccessTokenDevOps"] == null)
            {
                _logger.LogInformation("failed in access token -bad request");
                ViewBag.ServiceUnavailable = true;
                return(BadRequest(new DeploymentStatus
                {
                    Success = false,
                    Message = "Deployment failed: no access token",
                }));
            }

            Repository repository = _giteaAPI.GetRepository(applicationOwnerId, applicationCode).Result;

            _logger.LogInformation("repository -{0}", repository);
            _logger.LogInformation("repository permission -{0}", repository.Permissions);
            _logger.LogInformation("repository permission push -{0}", repository.Permissions.Push);
            if (repository != null && repository.Permissions != null && repository.Permissions.Push != true)
            {
                _logger.LogInformation("failed in repository -bad request");
                ViewBag.ServiceUnavailable = true;
                return(BadRequest(new DeploymentStatus
                {
                    Success = false,
                    Message = "Deployment failed: not authorized",
                }));
            }

            string credentials = _configuration["AccessTokenDevOps"];

            string result       = string.Empty;
            Branch masterBranch = _giteaAPI.GetBranch(applicationOwnerId, applicationCode, "master").Result;

            if (masterBranch == null)
            {
                _logger.LogWarning($"Unable to fetch branch information for app owner {applicationOwnerId} and app {applicationCode}");
                return(StatusCode(500, new DeploymentResponse
                {
                    Success = false,
                    Message = "Deployment failed: unable to find latest commit",
                }));
            }

            // register application in platform storage
            bool applicationInStorage = await RegisterApplicationInStorage(applicationOwnerId, applicationCode, masterBranch.Commit.Id);

            if (!applicationInStorage)
            {
                _logger.LogWarning($"Unable to deploy app {applicationCode} for {applicationOwnerId} to Platform Storage");
                return(StatusCode(500, new DeploymentResponse
                {
                    Success = false,
                    Message = $"Deployment of Application Metadata to Platform Storage failed",
                }));
            }

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
                    string giteaEnvironment = Environment.GetEnvironmentVariable("GiteaEndpoint") ?? _settings.ApiEndPointHost;
                    object buildContent     = new
                    {
                        definition = new
                        {
                            id = 5,
                        },
                        parameters = $"{{\"APP_OWNER\":\"{applicationOwnerId}\",\"APP_REPO\":\"{applicationCode}\",\"APP_DEPLOY_TOKEN\":\"{_sourceControl.GetDeployToken()}\",\"GITEA_ENVIRONMENT\":\"{giteaEnvironment}\", \"APP_COMMIT_ID\":\"{masterBranch.Commit.Id}\",\"should_deploy\":\"{true}\"}}\"",
                    };

                    string        buildjson   = JsonConvert.SerializeObject(buildContent);
                    StringContent httpContent = new StringContent(buildjson, Encoding.UTF8, "application/json");

                    _logger.LogInformation("buildjson {0}", buildjson);

                    using (HttpResponseMessage response = await client.PostAsync("https://dev.azure.com/brreg/altinn-studio/_apis/build/builds?api-version=5.0-preview.4", httpContent))
                    {
                        response.EnsureSuccessStatusCode();
                        _logger.LogInformation("response content type - {0}", response.Content.Headers.ContentType);
                        _logger.LogInformation("response content - {0}", response.Content.ReadAsStringAsync().Result);
                        BuildModel responseBody = await response.Content.ReadAsAsync <BuildModel>();

                        result = responseBody.Id;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogWarning($"Unable deploy app {applicationCode} for {applicationOwnerId} because {ex}");
                return(StatusCode(500, new DeploymentResponse
                {
                    Success = false,
                    Message = "Deployment failed " + ex,
                }));
            }

            return(Ok(new DeploymentResponse
            {
                Success = true,
                BuildId = result,
                Message = "Deployment status: " + result,
            }));
        }