public Task Invoke(string channel, string[] args)
        {
            var id          = args[0];
            var application = _applicationService.GetApplication(id);
            var result      = _applicationImageInstanceService.GetAllCurrentTagsForPrimary(application)
                              .ToDictionary(
                x => x.Key.TagProperty.Path,
                x => x.Key.TagProperty.ValueFormat == TagPropertyValueFormat.TagOnly ? $"{x.Key.Repository}:{x.Value}" : $"{x.Value}"
                );

            var builder = new SlackMessageBuilder($"The services for application '{id}' have the following tags:")
                          .AddDivider();

            var allFields  = result.Select(x => $"*{x.Key}*\n {x.Value}").ToList();
            var startIndex = 0;

            do
            {
                var fields = allFields.Skip(startIndex).Take(10).ToList();
                builder.AddSection(fields: fields);
                startIndex += fields.Count;
            } while (startIndex < allFields.Count);

            var message = builder.Build();

            return(_slackClient.PostMessageAsync(channel, message));
        }
Ejemplo n.º 2
0
        public async Task <bool> CreateNotification(Deployment deployment)
        {
            var application = _applicationService.GetApplication(deployment.ApplicationId);
            var channel     = application.Notifications.Channels.FirstOrDefault();

            var applicationImage = application.Images.FirstOrDefault(
                x => x.Repository == deployment.ImageRepository &&
                x.TagProperty.Path == deployment.UpdatePath
                );

            if (applicationImage == null)
            {
                _log.LogCritical("Received a deployment for '{Image}' on '{TagPath}' but we could not find it in the application manifest",
                                 deployment.ImageRepository,
                                 deployment.UpdatePath
                                 );

                return(false);
            }

            if (channel != null)
            {
                _log.LogInformation(
                    "Sending notification about image tag update operation for '{Repository}' with {Tag} for application {Application} with new tag {NewTag}",
                    deployment.ImageRepository,
                    deployment.CurrentTag,
                    deployment.ApplicationId,
                    deployment.TargetTag
                    );
                try
                {
                    var notification =
                        _deploymentNotificationBuilder.BuildNotification(
                            deployment
                            );

                    // send notification to slack
                    var handle = await _slackClient.PostMessageAsync(channel, notification);

                    await _deploymentNotificationRepository.Add(new DeploymentNoficationDao()
                    {
                        Id             = Guid.NewGuid(),
                        DeploymentId   = deployment.Id,
                        SlackMessageId = handle.Id
                    });

                    await _deploymentNotificationRepository.Save();
                }
                catch (Exception e)
                {
                    _log.LogError(e, "Failed to send deployment update notification to slack");
                    return(false);
                }
            }

            // check if this is a preview release and send a notification to the github pr
            if (deployment.Type == DeploymentType.PreviewRelease)
            {
                if (applicationImage.SourceCode.IsAvailable)
                {
                    var pullRequests = await _gitHubClient.PullRequest.GetAllForRepository(
                        applicationImage.SourceCode.Github.Owner,
                        applicationImage.SourceCode.Github.Repository,
                        new PullRequestRequest()
                    {
                        State = ItemStateFilter.Open
                    });

                    var pullRequestMap = pullRequests.Select(x => (
                                                                 prObj: x,
                                                                 branch: x.Head.Label,
                                                                 number: x.Number,
                                                                 isOpen: x.State.Value == ItemState.Open,
                                                                 id: x.Id,
                                                                 title: x.Title,
                                                                 creator: x.User.Email ?? x.User.Name
                                                                 )
                                                             )
                                         .ToList();

                    deployment.Parameters.TryGetValue(DeploymentParameterConstants.PreviewReleaseBranch, out var branch);

                    var matchingPullrequests = pullRequestMap
                                               .Where(x => x.branch.Contains(branch, StringComparison.OrdinalIgnoreCase))
                                               .ToList();

                    if (matchingPullrequests.Count != 1)
                    {
                        _log.LogCritical(
                            "Multiple, or no open pull requests or branches with the base name ('{Branch}') were detected (count: {Count})",
                            branch,
                            matchingPullrequests.Count);
                    }
                    else
                    {
                        var relevantPullRequest = matchingPullrequests[0];

                        if (deployment.CurrentTag == string.Empty)
                        {
                            // this is a first deployment of a pr
                            var pullRequestNotificationTemplate = _shipbotConfiguration.Value.NotificationTemplates
                                                                  .Deployment.PullRequestNotification;

                            if (!string.IsNullOrWhiteSpace(pullRequestNotificationTemplate))
                            {
                                var template = Template.Parse(pullRequestNotificationTemplate);

                                var message = await template.RenderAsync(deployment.Parameters);

                                _log.LogTrace("Submitting new preview release deployment to github pr");
                                // we are created a new preview release, let's notify the devs on the PR.
                                var result = await _gitHubClient.Issue.Comment.Create(
                                    applicationImage.SourceCode.Github.Owner,
                                    applicationImage.SourceCode.Github.Repository,
                                    relevantPullRequest.number,
                                    message
                                    );
                            }
                            else
                            {
                                _log.LogError("Failed to acquire a template for a message to a GitHub PR");
                            }
                        }
                        else
                        {
                            _log.LogTrace("Submitting preview release deployment update to github pr");
                            // we are created a new preview release, let's notify the devs on the PR.
                            // var result = await _gitHubClient.Issue.Comment.Create(
                            //     applicationImage.SourceCode.Github.Owner,
                            //     applicationImage.SourceCode.Github.Repository,
                            //     relevantPullRequest.number,
                            //     "A new image was detected for this preview release. A new deployment is underway and will be available shortly."
                            // );
                        }
                    }
                }
                else
                {
                    _log.LogError("Could not set deployment notification to Github Pull Request");
                }
            }

            return(true);
        }