Example #1
0
        public async static Task <Scorecard> CreateScorecardAsync(RolloutScorer rolloutScorer)
        {
            (int numHotfixes, int numRollbacks) = await rolloutScorer.CalculateNumHotfixesAndRollbacksFromAzdoAsync();

            List <Issue> githubIssues = await rolloutScorer.GetRolloutIssuesFromGithubAsync();

            string    repoLabel = rolloutScorer.RepoConfig.GithubIssueLabel;
            Scorecard scorecard = new Scorecard
            {
                Repo           = rolloutScorer.RepoConfig,
                Date           = rolloutScorer.RolloutStartDate,
                TimeToRollout  = await rolloutScorer.CalculateTimeToRolloutAsync(),
                CriticalIssues = githubIssues
                                 .Count(issue => Utilities.IssueContainsRelevantLabels(issue, GithubLabelNames.IssueLabel, repoLabel, rolloutScorer.Log)),
                Hotfixes = numHotfixes + githubIssues
                           .Count(issue => Utilities.IssueContainsRelevantLabels(issue, GithubLabelNames.HotfixLabel, repoLabel, rolloutScorer.Log)),
                Rollbacks = numRollbacks + githubIssues
                            .Count(issue => Utilities.IssueContainsRelevantLabels(issue, GithubLabelNames.RollbackLabel, repoLabel, rolloutScorer.Log)),
                Downtime            = await rolloutScorer.CalculateDowntimeAsync(githubIssues) + rolloutScorer.Downtime,
                Failure             = rolloutScorer.DetermineFailure() || rolloutScorer.Failed,
                BuildBreakdowns     = rolloutScorer.BuildBreakdowns,
                RolloutWeightConfig = rolloutScorer.RolloutWeightConfig,
                GithubIssues        = githubIssues,
            };

            // Critical issues and manual hotfixes/rollbacks need to be included in the build breakdowns, but it isn't possible to determine which
            // builds they belong to; so we'll just append the issues to the first build and the hotfixes/rollbacks to the last
            if (scorecard.BuildBreakdowns.Count > 0)
            {
                scorecard.BuildBreakdowns.Sort((x, y) => x.BuildSummary.BuildNumber.CompareTo(y.BuildSummary.BuildNumber));

                // Critical issues are assumed to have been caused by the first deployment
                ScorecardBuildBreakdown firstDeployment = scorecard.BuildBreakdowns.First();
                firstDeployment.Score.CriticalIssues += scorecard.CriticalIssues;
                firstDeployment.Score.GithubIssues.AddRange(scorecard.GithubIssues
                                                            .Where(issue => Utilities.IssueContainsRelevantLabels(issue, GithubLabelNames.IssueLabel, repoLabel, rolloutScorer.Log)));

                // Hotfixes & rollbacks are assumed to have taken place in the last deployment
                // This is likely incorrect given >2 deployments but can be manually adjusted if necessary
                ScorecardBuildBreakdown lastDeployment = scorecard.BuildBreakdowns.Last();
                lastDeployment.Score.Hotfixes  += rolloutScorer.ManualHotfixes;
                lastDeployment.Score.Rollbacks += rolloutScorer.ManualRollbacks;
                lastDeployment.Score.GithubIssues.AddRange(scorecard.GithubIssues
                                                           .Where(issue =>
                                                                  Utilities.IssueContainsRelevantLabels(issue, GithubLabelNames.HotfixLabel, repoLabel, rolloutScorer.Log) ||
                                                                  Utilities.IssueContainsRelevantLabels(issue, GithubLabelNames.RollbackLabel, repoLabel, rolloutScorer.Log)));
            }

            return(scorecard);
        }
        public static async Task Run([TimerTrigger("0 0 0 * * *")] TimerInfo myTimer, ILogger log)
        {
            AzureServiceTokenProvider tokenProvider = new AzureServiceTokenProvider();

            string deploymentEnvironment = Environment.GetEnvironmentVariable("DeploymentEnvironment") ?? "Staging";

            log.LogInformation($"INFO: Deployment Environment: {deploymentEnvironment}");

            log.LogInformation("INFO: Getting scorecard storage account key and deployment table's SAS URI from KeyVault...");
            SecretBundle scorecardsStorageAccountKey = await GetSecretBundleFromKeyVaultAsync(tokenProvider,
                                                                                              Utilities.KeyVaultUri, ScorecardsStorageAccount.KeySecretName);

            SecretBundle deploymentTableSasUriBundle = await GetSecretBundleFromKeyVaultAsync(tokenProvider,
                                                                                              "https://DotNetEng-Status-Prod.vault.azure.net", "deployment-table-sas-uri");

            log.LogInformation("INFO: Getting cloud tables...");
            CloudTable scorecardsTable  = Utilities.GetScorecardsCloudTable(scorecardsStorageAccountKey.Value);
            CloudTable deploymentsTable = new CloudTable(new Uri(deploymentTableSasUriBundle.Value));

            List <ScorecardEntity> scorecardEntries = await GetAllTableEntriesAsync <ScorecardEntity>(scorecardsTable);

            scorecardEntries.Sort((x, y) => x.Date.CompareTo(y.Date));
            List <AnnotationEntity> deploymentEntries =
                await GetAllTableEntriesAsync <AnnotationEntity>(deploymentsTable);

            deploymentEntries.Sort((x, y) => (x.Ended ?? DateTimeOffset.MaxValue).CompareTo(y.Ended ?? DateTimeOffset.MaxValue));
            log.LogInformation($"INFO: Found {scorecardEntries?.Count ?? -1} scorecard table entries and {deploymentEntries?.Count ?? -1} deployment table entries." +
                               $"(-1 indicates that null was returned.)");

            // The deployments we care about are ones that occurred after the last scorecard
            IEnumerable <AnnotationEntity> relevantDeployments =
                deploymentEntries.Where(d => (d.Ended ?? DateTimeOffset.MaxValue) > scorecardEntries.Last().Date.AddDays(ScoringBufferInDays));

            log.LogInformation($"INFO: Found {relevantDeployments?.Count() ?? -1} relevant deployments (deployments which occurred " +
                               $"after the last scorecard). (-1 indicates that null was returned.)");

            if (relevantDeployments.Count() > 0)
            {
                log.LogInformation("INFO: Checking to see if the most recent deployment occurred more than two days ago...");
                // We have only want to score if the buffer period has elapsed since the last deployment
                if ((relevantDeployments.Last().Ended ?? DateTimeOffset.MaxValue) < DateTimeOffset.UtcNow - TimeSpan.FromDays(ScoringBufferInDays))
                {
                    var scorecards = new List <Scorecard>();

                    log.LogInformation("INFO: Rollouts will be scored. Fetching GitHub PAT...");
                    SecretBundle githubPat;
                    using (KeyVaultClient kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback)))
                    {
                        githubPat = await kv.GetSecretAsync(Utilities.KeyVaultUri, Utilities.GitHubPatSecretName);
                    }

                    // We'll score the deployments by service
                    foreach (var deploymentGroup in relevantDeployments.GroupBy(d => d.Service))
                    {
                        log.LogInformation($"INFO: Scoring {deploymentGroup?.Count() ?? -1} rollouts for repo '{deploymentGroup.Key}'");
                        RolloutScorer.RolloutScorer rolloutScorer = new RolloutScorer.RolloutScorer
                        {
                            Repo                = deploymentGroup.Key,
                            RolloutStartDate    = deploymentGroup.First().Started.GetValueOrDefault().Date,
                            RolloutWeightConfig = StandardConfig.DefaultConfig.RolloutWeightConfig,
                            GithubConfig        = StandardConfig.DefaultConfig.GithubConfig,
                            Log = log,
                        };
                        log.LogInformation($"INFO: Finding repo config for {rolloutScorer.Repo}...");
                        rolloutScorer.RepoConfig = StandardConfig.DefaultConfig.RepoConfigs
                                                   .Find(r => r.Repo == rolloutScorer.Repo);
                        log.LogInformation($"INFO: Repo config: {rolloutScorer.RepoConfig.Repo}");
                        log.LogInformation($"INFO: Finding AzDO config for {rolloutScorer.RepoConfig.AzdoInstance}...");
                        rolloutScorer.AzdoConfig = StandardConfig.DefaultConfig.AzdoInstanceConfigs
                                                   .Find(a => a.Name == rolloutScorer.RepoConfig.AzdoInstance);

                        log.LogInformation($"INFO: Fetching AzDO PAT from KeyVault...");
                        using (KeyVaultClient kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback)))
                        {
                            rolloutScorer.SetupHttpClient(
                                (await kv.GetSecretAsync(rolloutScorer.AzdoConfig.KeyVaultUri, rolloutScorer.AzdoConfig.PatSecretName)).Value);
                        }
                        rolloutScorer.SetupGithubClient(githubPat.Value);

                        log.LogInformation($"INFO: Attempting to initialize RolloutScorer...");
                        try
                        {
                            await rolloutScorer.InitAsync();
                        }
                        catch (ArgumentException e)
                        {
                            log.LogError($"ERROR: Error while processing {rolloutScorer.RolloutStartDate} rollout of {rolloutScorer.Repo}.");
                            log.LogError($"ERROR: {e.Message}");
                            continue;
                        }

                        log.LogInformation($"INFO: Creating rollout scorecard...");
                        scorecards.Add(await Scorecard.CreateScorecardAsync(rolloutScorer));
                        log.LogInformation($"INFO: Successfully created scorecard for {rolloutScorer.RolloutStartDate.Date} rollout of {rolloutScorer.Repo}.");
                    }

                    log.LogInformation($"INFO: Uploading results for {string.Join(", ", scorecards.Select(s => s.Repo))}");
                    await RolloutUploader.UploadResultsAsync(scorecards, Utilities.GetGithubClient(githubPat.Value),
                                                             scorecardsStorageAccountKey.Value, StandardConfig.DefaultConfig.GithubConfig, skipPr : deploymentEnvironment != "Production");
                }
                else
                {
                    log.LogInformation(relevantDeployments.Last().Ended.HasValue ? $"INFO: Most recent rollout occurred less than two days ago " +
                                       $"({relevantDeployments.Last().Service} on {relevantDeployments.Last().Ended.Value}); waiting to score." :
                                       $"Most recent rollout ({relevantDeployments.Last().Service}) is still in progress.");
                }
            }
            else
            {
                log.LogInformation($"INFO: Found no rollouts which occurred after last recorded rollout " +
                                   $"({(scorecardEntries.Count > 0 ? $"date {scorecardEntries.Last().Date}" : "no rollouts in table")})");
            }
        }
        public static async Task Run([TimerTrigger("0 0 0 * * *")] TimerInfo myTimer, ILogger log)
        {
            AzureServiceTokenProvider tokenProvider = new AzureServiceTokenProvider();

            SecretBundle scorecardsStorageAccountKey = await GetStorageAccountKeyAsync(tokenProvider,
                                                                                       Utilities.KeyVaultUri, ScorecardsStorageAccount.KeySecretName);

            SecretBundle deploymentTableSasToken = await GetStorageAccountKeyAsync(tokenProvider,
                                                                                   "https://DotNetEng-Status-Prod.vault.azure.net", "deployment-table-sas-token");

            CloudTable scorecardsTable  = Utilities.GetScorecardsCloudTable(scorecardsStorageAccountKey.Value);
            CloudTable deploymentsTable = new CloudTable(
                new Uri($"https://dotnetengstatusprod.table.core.windows.net/deployments{deploymentTableSasToken.Value}"));

            List <ScorecardEntity> scorecardEntries =
                await GetAllTableEntriesAsync <ScorecardEntity>(scorecardsTable);

            scorecardEntries.Sort((x, y) => x.Date.CompareTo(y.Date));
            List <AnnotationEntity> deploymentEntries =
                await GetAllTableEntriesAsync <AnnotationEntity>(deploymentsTable);

            deploymentEntries.Sort((x, y) => (x.Ended ?? DateTimeOffset.MaxValue).CompareTo(y.Ended ?? DateTimeOffset.MaxValue));

            // The deployments we care about are ones that occurred after the last scorecard
            IEnumerable <AnnotationEntity> relevantDeployments =
                deploymentEntries.Where(d => (d.Ended ?? DateTimeOffset.MaxValue) > scorecardEntries.Last().Date);

            if (relevantDeployments.Count() > 0)
            {
                // We have only want to score if the buffer period has elapsed since the last deployment
                if ((relevantDeployments.Last().Ended ?? DateTimeOffset.MaxValue) < DateTimeOffset.UtcNow - TimeSpan.FromDays(ScoringBufferInDays))
                {
                    var scorecards = new List <Scorecard>();

                    SecretBundle githubPat;
                    using (KeyVaultClient kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback)))
                    {
                        githubPat = await kv.GetSecretAsync(Utilities.KeyVaultUri, Utilities.GitHubPatSecretName);
                    }

                    // We'll score the deployments by service
                    foreach (var deploymentGroup in relevantDeployments.GroupBy(d => d.Service))
                    {
                        RolloutScorer.RolloutScorer rolloutScorer = new RolloutScorer.RolloutScorer
                        {
                            Repo                = deploymentGroup.Key,
                            RolloutStartDate    = deploymentGroup.First().Started.GetValueOrDefault().Date,
                            RolloutWeightConfig = Configs.DefaultConfig.RolloutWeightConfig,
                            GithubConfig        = Configs.DefaultConfig.GithubConfig,
                            Log = log,
                        };
                        rolloutScorer.RepoConfig = Configs.DefaultConfig.RepoConfigs
                                                   .Find(r => r.Repo == rolloutScorer.Repo);
                        rolloutScorer.AzdoConfig = Configs.DefaultConfig.AzdoInstanceConfigs
                                                   .Find(a => a.Name == rolloutScorer.RepoConfig.AzdoInstance);

                        using (KeyVaultClient kv = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(tokenProvider.KeyVaultTokenCallback)))
                        {
                            rolloutScorer.SetupHttpClient(
                                (await kv.GetSecretAsync(rolloutScorer.AzdoConfig.KeyVaultUri, rolloutScorer.AzdoConfig.PatSecretName)).Value);
                        }
                        rolloutScorer.SetupGithubClient(githubPat.Value);

                        try
                        {
                            await rolloutScorer.InitAsync();
                        }
                        catch (ArgumentException e)
                        {
                            log.LogError($"Error while processing {rolloutScorer.RolloutStartDate} rollout of {rolloutScorer.Repo}.");
                            log.LogError(e.Message);
                            continue;
                        }

                        scorecards.Add(await Scorecard.CreateScorecardAsync(rolloutScorer));
                        log.LogInformation($"Successfully created scorecard for {rolloutScorer.RolloutStartDate.Date} rollout of {rolloutScorer.Repo}.");
                    }

                    log.LogInformation($"Uploading results for {string.Join(", ", scorecards.Select(s => s.Repo))}");
                    await RolloutUploader.UploadResultsAsync(scorecards,
                                                             Utilities.GetGithubClient(githubPat.Value), scorecardsStorageAccountKey.Value, Configs.DefaultConfig.GithubConfig);
                }
                else
                {
                    log.LogInformation(relevantDeployments.Last().Ended.HasValue ? $"Most recent rollout occurred less than two days ago " +
                                       $"({relevantDeployments.Last().Service} on {relevantDeployments.Last().Ended.Value}); waiting to score." :
                                       $"Most recent rollout ({relevantDeployments.Last().Service}) is still in progress.");
                }
            }
            else
            {
                log.LogInformation($"Found no rollouts which occurred after last recorded rollout (date {scorecardEntries.Last().Date})");
            }
        }