Skip to content
This repository was archived by the owner on Jul 30, 2024. It is now read-only.

Commit 624d0ec

Browse files
author
Christy Henriksson
authored
Migrate Stats.AggregateCdnDownloads to JsonConfig (#523)
1 parent 5aae40c commit 624d0ec

12 files changed

Lines changed: 120 additions & 45 deletions

File tree

src/NuGet.Jobs.Common/Extensions/DapperExtensions.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
33

44
using System.Collections.Generic;
5-
using System.Linq;
65
using System.Threading.Tasks;
76
using Dapper;
87

src/Stats.AggregateCdnDownloadsInGallery/Job.cs renamed to src/Stats.AggregateCdnDownloadsInGallery/AggregateCdnDownloadsJob.cs

Lines changed: 35 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -9,16 +9,18 @@
99
using System.Diagnostics;
1010
using System.Linq;
1111
using System.Threading.Tasks;
12+
using Autofac;
13+
using Microsoft.Extensions.Configuration;
14+
using Microsoft.Extensions.DependencyInjection;
1215
using Microsoft.Extensions.Logging;
16+
using Microsoft.Extensions.Options;
1317
using NuGet.Jobs;
14-
using NuGet.Services.KeyVault;
15-
using NuGet.Services.Sql;
18+
using NuGet.Jobs.Configuration;
1619
using IPackageIdGroup = System.Linq.IGrouping<string, Stats.AggregateCdnDownloadsInGallery.DownloadCountData>;
1720

1821
namespace Stats.AggregateCdnDownloadsInGallery
1922
{
20-
public class Job
21-
: JobBase
23+
public class AggregateCdnDownloadsJob : JsonConfigurationJob
2224
{
2325
private const int _defaultBatchSize = 5000;
2426
private const int _defaultBatchSleepSeconds = 10;
@@ -55,40 +57,35 @@ GROUP BY Stats.[PackageRegistrationKey]
5557
DROP TABLE #AggregateCdnDownloadsInGallery";
5658

5759
private const string _storedProcedureName = "[dbo].[SelectTotalDownloadCountsPerPackageVersion]";
58-
private ISqlConnectionFactory _statisticsDbConnectionFactory;
59-
private ISqlConnectionFactory _galleryDbConnectionFactory;
60-
private int _batchSize;
61-
private int _batchSleepSeconds;
60+
61+
private AggregateCdnDownloadsConfiguration _configuration;
6262

6363
public override void Init(IServiceContainer serviceContainer, IDictionary<string, string> jobArgsDictionary)
6464
{
65-
var secretInjector = (ISecretInjector)serviceContainer.GetService(typeof(ISecretInjector));
66-
67-
var statisticsDbConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.StatisticsDatabase);
68-
_statisticsDbConnectionFactory = new AzureSqlConnectionFactory(statisticsDbConnectionString, secretInjector);
69-
70-
var galleryDbConnectionString = JobConfigurationManager.GetArgument(jobArgsDictionary, JobArgumentNames.DestinationDatabase);
71-
_galleryDbConnectionFactory = new AzureSqlConnectionFactory(galleryDbConnectionString, secretInjector);
65+
base.Init(serviceContainer, jobArgsDictionary);
7266

73-
_batchSize = JobConfigurationManager.TryGetIntArgument(jobArgsDictionary, JobArgumentNames.BatchSize) ?? _defaultBatchSize;
74-
_batchSleepSeconds = JobConfigurationManager.TryGetIntArgument(jobArgsDictionary, JobArgumentNames.BatchSleepSeconds) ?? _defaultBatchSleepSeconds;
67+
_configuration = _serviceProvider.GetRequiredService<IOptionsSnapshot<AggregateCdnDownloadsConfiguration>>().Value;
7568
}
7669

7770
public override async Task Run()
7871
{
7972
// Gather download counts data from statistics warehouse
8073
IReadOnlyList<DownloadCountData> downloadData;
81-
Logger.LogInformation("Using batch size {BatchSize} and batch sleep seconds {BatchSleepSeconds}.", _batchSize, _batchSleepSeconds);
82-
Logger.LogInformation("Gathering Download Counts from {DataSource}/{InitialCatalog}...", _statisticsDbConnectionFactory.DataSource, _statisticsDbConnectionFactory.InitialCatalog);
74+
Logger.LogInformation("Using batch size {BatchSize} and batch sleep seconds {BatchSleepSeconds}.",
75+
_configuration.BatchSize,
76+
_configuration.BatchSleepSeconds);
77+
8378
var stopwatch = Stopwatch.StartNew();
8479

85-
using (var statisticsDatabase = await _statisticsDbConnectionFactory.CreateAsync())
86-
using (var statisticsDatabaseTransaction = statisticsDatabase.BeginTransaction(IsolationLevel.Snapshot))
80+
using (var connection = await OpenSqlConnectionAsync<StatisticsDbConfiguration>())
81+
using (var transaction = connection.BeginTransaction(IsolationLevel.Snapshot))
8782
{
83+
Logger.LogInformation("Gathering Download Counts from {DataSource}/{InitialCatalog}...", connection.DataSource, connection.Database);
84+
8885
downloadData = (
89-
await statisticsDatabase.QueryWithRetryAsync<DownloadCountData>(
86+
await connection.QueryWithRetryAsync<DownloadCountData>(
9087
_storedProcedureName,
91-
transaction: statisticsDatabaseTransaction,
88+
transaction: transaction,
9289
commandType: CommandType.StoredProcedure,
9390
commandTimeout: TimeSpan.FromMinutes(15),
9491
maxRetries: 3))
@@ -106,10 +103,10 @@ await statisticsDatabase.QueryWithRetryAsync<DownloadCountData>(
106103
return;
107104
}
108105

109-
using (var destinationDatabase = await _galleryDbConnectionFactory.CreateAsync())
106+
using (var connection = await OpenSqlConnectionAsync<GalleryDbConfiguration>())
110107
{
111108
// Fetch package registrations so we can match package ID to package registration key.
112-
var packageRegistrationLookup = await GetPackageRegistrations(destinationDatabase);
109+
var packageRegistrationLookup = await GetPackageRegistrations(connection);
113110

114111
// Group based on package ID and store in a stack for easy incremental processing.
115112
var allGroups = downloadData.GroupBy(p => p.PackageId).ToList();
@@ -126,18 +123,18 @@ await statisticsDatabase.QueryWithRetryAsync<DownloadCountData>(
126123
while (remainingGroups.Any())
127124
{
128125
// Create a batch of one or more package registrations to update.
129-
var batch = PopGroupBatch(remainingGroups, _batchSize);
126+
var batch = PopGroupBatch(remainingGroups, _configuration.BatchSize);
130127

131-
await ProcessBatch(batch, destinationDatabase, packageRegistrationLookup);
128+
await ProcessBatch(batch, connection, packageRegistrationLookup);
132129

133130
Logger.LogInformation(
134131
"There are {GroupCount} package registration groups remaining.",
135132
remainingGroups.Count);
136133

137134
if (remainingGroups.Any())
138135
{
139-
Logger.LogInformation("Sleeping for {BatchSleepSeconds} seconds before continuing.", _batchSleepSeconds);
140-
await Task.Delay(TimeSpan.FromSeconds(_batchSleepSeconds));
136+
Logger.LogInformation("Sleeping for {BatchSleepSeconds} seconds before continuing.", _configuration.BatchSleepSeconds);
137+
await Task.Delay(TimeSpan.FromSeconds(_configuration.BatchSleepSeconds));
141138
}
142139
}
143140

@@ -305,5 +302,14 @@ private async Task<IDictionary<string, string>> GetPackageRegistrations(SqlConne
305302

306303
return packageRegistrationDictionary;
307304
}
305+
306+
protected override void ConfigureAutofacServices(ContainerBuilder containerBuilder)
307+
{
308+
}
309+
310+
protected override void ConfigureJobServices(IServiceCollection services, IConfigurationRoot configurationRoot)
311+
{
312+
ConfigureInitializationSection<AggregateCdnDownloadsConfiguration>(services, configurationRoot);
313+
}
308314
}
309315
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Copyright (c) .NET Foundation. All rights reserved.
2+
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
3+
4+
namespace Stats.AggregateCdnDownloadsInGallery
5+
{
6+
public class AggregateCdnDownloadsConfiguration
7+
{
8+
public int BatchSize { get; set; }
9+
10+
public int BatchSleepSeconds { get; set; }
11+
}
12+
}

src/Stats.AggregateCdnDownloadsInGallery/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ public class Program
99
{
1010
public static void Main(string[] args)
1111
{
12-
var job = new Job();
12+
var job = new AggregateCdnDownloadsJob();
1313
JobRunner.Run(job, args).Wait();
1414
}
1515
}

src/Stats.AggregateCdnDownloadsInGallery/Scripts/Stats.AggregateCdnDownloadsInGallery.cmd

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,8 @@ echo "Starting job - #{Jobs.stats.aggregatecdndownloadsingallery.Title}"
88
title #{Jobs.stats.aggregatecdndownloadsingallery.Title}
99

1010
start /w stats.aggregatecdndownloadsingallery.exe ^
11-
-VaultName "#{Deployment.Azure.KeyVault.VaultName}" ^
12-
-ClientId "#{Deployment.Azure.KeyVault.ClientId}" ^
13-
-CertificateThumbprint "#{Deployment.Azure.KeyVault.CertificateThumbprint}" ^
14-
-StatisticsDatabase "#{Jobs.stats.aggregatecdndownloadsingallery.StatisticsDatabase}" ^
15-
-DestinationDatabase "#{Jobs.stats.aggregatecdndownloadsingallery.DestinationDatabase}" ^
11+
-Configuration "#{Jobs.stats.aggregatecdndownloadsingallery.Configuration}" ^
1612
-InstrumentationKey "#{Jobs.stats.aggregatecdndownloadsingallery.InstrumentationKey}" ^
17-
-BatchSize "#{Jobs.stats.aggregatecdndownloadsingallery.BatchSize}" ^
18-
-BatchSleepSeconds "#{Jobs.stats.aggregatecdndownloadsingallery.BatchSleepSeconds}" ^
1913
-verbose true ^
2014
-Interval #{Jobs.stats.aggregatecdndownloadsingallery.Interval}
2115

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"Initialization": {
3+
"BatchSize": 5000,
4+
"BatchSleepSeconds": 10
5+
},
6+
7+
"GalleryDb": {
8+
"ConnectionString": "Data Source=tcp:#{Deployment.Azure.Sql.GalleryDatabaseAddress};Initial Catalog=nuget-dev-0-v2gallery;User ID=$$Dev-GalleryDBWriter-UserName$$;Password=$$Dev-GalleryDBWriter-Password$$;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
9+
},
10+
11+
"StatisticsDb": {
12+
"ConnectionString": "Data Source=tcp:#{Deployment.Azure.Sql.StatisticsDatabaseAddress};Initial Catalog=nuget-dev-statistics;User ID=$$Dev-StatisticsDBWriter-UserName$$;Password=$$Dev-StatisticsDBWriter-Password$$;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
13+
},
14+
15+
"KeyVault_VaultName": "#{Deployment.Azure.KeyVault.VaultName}",
16+
"KeyVault_ClientId": "#{Deployment.Azure.KeyVault.ClientId}",
17+
"KeyVault_CertificateThumbprint": "#{Deployment.Azure.KeyVault.CertificateThumbprint}",
18+
"KeyVault_ValidateCertificate": true,
19+
"KeyVault_StoreName": "My",
20+
"KeyVault_StoreLocation": "LocalMachine"
21+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"Initialization": {
3+
"BatchSize": 5000,
4+
"BatchSleepSeconds": 10
5+
},
6+
7+
"GalleryDb": {
8+
"ConnectionString": "Data Source=tcp:#{Deployment.Azure.Sql.GalleryDatabaseAddress};Initial Catalog=nuget-int-0-v2gallery;User ID=$$Int-GalleryDBWriter-UserName$$;Password=$$Int-GalleryDBWriter-Password$$;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
9+
},
10+
11+
"StatisticsDb": {
12+
"ConnectionString": "Data Source=tcp:#{Deployment.Azure.Sql.StatisticsDatabaseAddress};Initial Catalog=nuget-int-statistics;User ID=$$Int-StatisticsDBWriter-UserName$$;Password=$$Int-StatisticsDBWriter-Password$$;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
13+
},
14+
15+
"KeyVault_VaultName": "#{Deployment.Azure.KeyVault.VaultName}",
16+
"KeyVault_ClientId": "#{Deployment.Azure.KeyVault.ClientId}",
17+
"KeyVault_CertificateThumbprint": "#{Deployment.Azure.KeyVault.CertificateThumbprint}",
18+
"KeyVault_ValidateCertificate": true,
19+
"KeyVault_StoreName": "My",
20+
"KeyVault_StoreLocation": "LocalMachine"
21+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"Initialization": {
3+
"BatchSize": 5000,
4+
"BatchSleepSeconds": 10
5+
},
6+
7+
"GalleryDb": {
8+
"ConnectionString": "Data Source=tcp:#{Deployment.Azure.Sql.GalleryDatabaseAddress};Initial Catalog=NuGetGallery;User ID=$$Prod-GalleryDBWriter-UserName$$;Password=$$Prod-GalleryDBWriter-Password$$;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
9+
},
10+
11+
"StatisticsDb": {
12+
"ConnectionString": "Data Source=tcp:#{Deployment.Azure.Sql.StatisticsDatabaseAddress};Initial Catalog=nuget-prod-statistics;User ID=$$Prod-StatisticsDBWriter-UserName$$;Password=$$Prod-StatisticsDBWriter-Password$$;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;"
13+
},
14+
15+
"KeyVault_VaultName": "#{Deployment.Azure.KeyVault.VaultName}",
16+
"KeyVault_ClientId": "#{Deployment.Azure.KeyVault.ClientId}",
17+
"KeyVault_CertificateThumbprint": "#{Deployment.Azure.KeyVault.CertificateThumbprint}",
18+
"KeyVault_ValidateCertificate": true,
19+
"KeyVault_StoreName": "My",
20+
"KeyVault_StoreLocation": "LocalMachine"
21+
}

src/Stats.AggregateCdnDownloadsInGallery/Stats.AggregateCdnDownloadsInGallery.csproj

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,17 @@
4242
<Reference Include="Microsoft.CSharp" />
4343
</ItemGroup>
4444
<ItemGroup>
45+
<Compile Include="Configuration\AggregateCdnDownloadsConfiguration.cs" />
4546
<Compile Include="DownloadCountData.cs" />
46-
<Compile Include="Job.cs" />
47+
<Compile Include="AggregateCdnDownloadsJob.cs" />
4748
<Compile Include="PackageRegistrationData.cs" />
4849
<Compile Include="Program.cs" />
4950
<Compile Include="Properties\AssemblyInfo.cs" />
5051
</ItemGroup>
5152
<ItemGroup>
5253
<None Include="App.config" />
5354
<None Include="Scripts\*" />
55+
<None Include="Settings\*" />
5456
<None Include="Stats.AggregateCdnDownloadsInGallery.nuspec" />
5557
</ItemGroup>
5658
<ItemGroup>
@@ -75,9 +77,6 @@
7577
<PackageReference Include="Newtonsoft.Json">
7678
<Version>9.0.1</Version>
7779
</PackageReference>
78-
<PackageReference Include="NuGet.Services.Sql">
79-
<Version>2.27.0</Version>
80-
</PackageReference>
8180
</ItemGroup>
8281
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
8382
<Import Project="..\..\build\sign.targets" Condition="Exists('..\..\build\sign.targets')" />

src/Stats.AggregateCdnDownloadsInGallery/Stats.AggregateCdnDownloadsInGallery.nuspec

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,7 @@
1818
<file src="Scripts\PreDeploy.ps1" />
1919
<file src="Scripts\PostDeploy.ps1" />
2020
<file src="Scripts\nssm.exe" />
21+
22+
<file src="Settings\*.json" target="bin" />
2123
</files>
2224
</package>

0 commit comments

Comments
 (0)