-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathUpdateAdminDatabaseTask.cs
362 lines (308 loc) · 15.9 KB
/
UpdateAdminDatabaseTask.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
// SPDX-License-Identifier: Apache-2.0
// Licensed to the Ed-Fi Alliance under one or more agreements.
// The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
// See the LICENSE and NOTICES files in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Numerics;
using System.Xml;
using EdFi.Admin.DataAccess.Models;
using EdFi.Admin.DataAccess.Repositories;
using EdFi.Admin.DataAccess.Utils;
using EdFi.Common.Extensions;
using EdFi.Ods.Api.ExternalTasks;
using EdFi.Ods.Api.Middleware;
using EdFi.Ods.Common.Configuration;
using EdFi.Ods.Common.Constants;
using EdFi.Ods.Common.Context;
using EdFi.Ods.Common.Conventions;
using EdFi.Ods.Common.Database;
using EdFi.Ods.Common.Models;
using log4net;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using Formatting = Newtonsoft.Json.Formatting;
using TenantConfiguration = EdFi.Ods.Common.Configuration.TenantConfiguration;
namespace EdFi.Ods.Api.IntegrationTestHarness
{
public class UpdateAdminDatabaseTask : IExternalTask
{
private readonly ILog _logger = LogManager.GetLogger(typeof(UpdateAdminDatabaseTask));
private readonly IClientAppRepo _clientAppRepo;
private readonly IDefaultApplicationCreator _defaultApplicationCreator;
private readonly IConfiguration _configuration;
private readonly ApiSettings _apiSettings;
private readonly TestHarnessConfiguration _testHarnessConfiguration;
private readonly ITenantConfigurationMapProvider _tenantConfigurationMapProvider;
private readonly IContextProvider<TenantConfiguration> _tenantConfigurationContextProvider;
private readonly IDomainModelProvider _domainModelProvider;
private readonly Version _edfiDomainModelVersion;
private readonly long _maxSafeEducationOrganizationId;
public UpdateAdminDatabaseTask(IClientAppRepo clientAppRepo,
IDefaultApplicationCreator defaultApplicationCreator,
IConfiguration configuration,
ApiSettings apiSettings,
TestHarnessConfigurationProvider testHarnessConfigurationProvider,
IDomainModelProvider domainModelProvider)
{
_clientAppRepo = clientAppRepo;
_defaultApplicationCreator = defaultApplicationCreator;
_configuration = configuration;
_apiSettings = apiSettings;
_testHarnessConfiguration = testHarnessConfigurationProvider.GetTestHarnessConfiguration();
_domainModelProvider = domainModelProvider;
_edfiDomainModelVersion = Version.Parse(
_domainModelProvider
.GetDomainModel()
.Schemas
.Single(x => x.LogicalName.EqualsIgnoreCase(EdFiConventions.LogicalName))
.Version
);
// The biggest int64 value that can be stored in a double precision floating point format
// that can be used in Javascript for Postman tests. See Number.MAX_SAFE_INTEGER for reference.
const long maxSafeInt64 = 9007199254740991;
_maxSafeEducationOrganizationId = _edfiDomainModelVersion.Major < 5 ? int.MaxValue : maxSafeInt64;
}
public UpdateAdminDatabaseTask(IClientAppRepo clientAppRepo,
IDefaultApplicationCreator defaultApplicationCreator,
IConfiguration configuration,
ApiSettings apiSettings,
TestHarnessConfigurationProvider testHarnessConfigurationProvider,
IContextProvider<TenantConfiguration> tenantConfigurationContextProvider,
ITenantConfigurationMapProvider tenantConfigurationMapProvider,
IDomainModelProvider domainModelProvider)
: this (clientAppRepo, defaultApplicationCreator, configuration, apiSettings, testHarnessConfigurationProvider, domainModelProvider)
{
_tenantConfigurationMapProvider = tenantConfigurationMapProvider;
_tenantConfigurationContextProvider = tenantConfigurationContextProvider;
}
public void Execute()
{
PostmanEnvironment postmanEnvironment;
if (!_apiSettings.IsFeatureEnabled(ApiFeature.MultiTenancy.GetConfigKeyName()))
{
_logger.Debug($"Loading test data in Admin Database.");
postmanEnvironment = UpdateAdminDatabase();
}
else
{
postmanEnvironment = new PostmanEnvironment();
foreach (var tenantConfigurationMap in _tenantConfigurationMapProvider.GetMap())
{
_tenantConfigurationContextProvider.Set(tenantConfigurationMap.Value);
_logger.Debug($"Loading test data in Admin Database for tenant {tenantConfigurationMap.Key}.");
var ret = UpdateAdminDatabase(tenantConfigurationMap.Key);
postmanEnvironment.Values.AddRange(ret.Values);
_tenantConfigurationContextProvider.Set(null);
}
}
CreateEnvironmentFile();
void CreateEnvironmentFile()
{
// This checks if the Ed-Fi Data Standard in use has a Parent entity,
// which was renamed to Contact in Data Standard version 5.0.0.
var parentOrContactProperName = _edfiDomainModelVersion.Major < 5 ? "Parent" : "Contact";
var environmentFilePath = _configuration.GetValue<string>("environmentFilePath");
if (!string.IsNullOrEmpty(environmentFilePath) && new DirectoryInfo(environmentFilePath).Exists)
{
postmanEnvironment.Values.Add(
new ValueItem
{
Enabled = true,
Value = _configuration.GetValue<string>("Urls") ?? "http://localhost:8765/",
Key = "ApiBaseUrl"
});
postmanEnvironment.Values.Add(
new ValueItem
{
Enabled = true,
Value = _apiSettings.IsFeatureEnabled(ApiFeature.Composites.ToString()),
Key = "CompositesFeatureIsEnabled"
});
postmanEnvironment.Values.Add(
new ValueItem
{
Enabled = true,
Value = _apiSettings.IsFeatureEnabled(ApiFeature.Profiles.ToString()),
Key = "ProfilesFeatureIsEnabled"
});
// The following variable provides the Postman collections with the correct parent/
// contact related entity name for the Ed-Fi data standard currently in use.
postmanEnvironment.Values.Add(
new ValueItem
{
Enabled = true,
Value = parentOrContactProperName,
Key = "ParentOrContactProperName"
});
postmanEnvironment.Values.Add(
new ValueItem
{
Enabled = true,
Value = _maxSafeEducationOrganizationId,
Key = "MaxSafeEducationOrganizationId"
});
var jsonString = JsonConvert.SerializeObject(
postmanEnvironment,
Formatting.Indented,
new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
var fileName = Path.Combine(environmentFilePath, "environment.json");
File.WriteAllText(fileName, jsonString);
}
}
}
private PostmanEnvironment UpdateAdminDatabase(string tenantIdentifier = null)
{
var postmanEnvironment = new PostmanEnvironment();
_clientAppRepo.Reset();
// Add ODS instance
string odsConnectionString = string.Format(_configuration.GetConnectionString("EdFi_Ods"), tenantIdentifier);
var dbConnectionStringBuilderAdapterFactory =
new DbConnectionStringBuilderAdapterFactory(_apiSettings.GetDatabaseEngine());
var connectionStringBuilderAdapter = dbConnectionStringBuilderAdapterFactory.Get();
connectionStringBuilderAdapter.ConnectionString = odsConnectionString;
string odsDatabaseName = connectionStringBuilderAdapter.DatabaseName;
var odsInstance = _clientAppRepo.CreateOdsInstance(
new OdsInstance()
{
Name = odsDatabaseName,
InstanceType = "ODS",
ConnectionString = odsConnectionString,
});
// Add Profiles
string[] profileFilenames = Directory.GetFiles(Directory.GetParent(AppContext.BaseDirectory).FullName, $"*Profiles.xml");
if(!string.IsNullOrEmpty(tenantIdentifier))
{
profileFilenames = profileFilenames.Union(Directory.GetFiles(Directory.GetParent(AppContext.BaseDirectory).FullName, $"*Profiles{tenantIdentifier}.xml")).ToArray();
}
var profileDefinitionByName = new Dictionary<string, XmlNode>(StringComparer.OrdinalIgnoreCase);
foreach (var profileFilename in profileFilenames)
{
var _allDocs = new XmlDocument();
_allDocs.Load(profileFilename);
var profiles = new List<Profile>();
var profileDefinitions = _allDocs.SelectNodes("/Profiles/Profile");
foreach (XmlNode profileDefinition in profileDefinitions)
{
string profileName = profileDefinition.Attributes["name"].Value;
profiles.Add(
new Profile()
{
ProfileDefinition = profileDefinition.OuterXml,
ProfileName = profileName
});
profileDefinitionByName.Add(profileName, profileDefinition);
}
_clientAppRepo.CreateProfilesWithProfileDefinition(profiles);
}
foreach (var vendor in _testHarnessConfiguration.Vendors.Where(x =>
string.IsNullOrEmpty(tenantIdentifier) ||
x.TenantIdentifier.Equals(tenantIdentifier, StringComparison.InvariantCultureIgnoreCase)))
{
var user = _clientAppRepo.GetUser(vendor.Email) ??
_clientAppRepo.CreateUser(
new User
{
FullName = vendor.VendorName,
Email = vendor.Email,
Vendor = _clientAppRepo.CreateOrGetVendor(
vendor.Email, vendor.VendorName, vendor.NamespacePrefixes)
});
foreach (var app in vendor.Applications)
{
var application = _clientAppRepo.CreateApplicationForVendor(
user.Vendor.VendorId, app.ApplicationName, app.ClaimSetName);
var edOrgIds = app.ApiClients
.SelectMany(s => s.LocalEducationOrganizations)
.SelectMany(l => Range(l.Start, l.Count))
.Select(PreventEducationOrganizationIdOverflow)
.Distinct()
.ToList();
_defaultApplicationCreator.AddEdOrgIdsToApplication(edOrgIds, application.ApplicationId);
foreach (var client in app.ApiClients)
{
var key = !string.IsNullOrEmpty(client.Key)
? client.Key
: GetGuid();
var secret = !string.IsNullOrEmpty(client.Secret)
? client.Secret
: GetGuid();
var apiClient = _clientAppRepo.CreateApiClient(user.UserId, client.ApiClientName, key, secret);
postmanEnvironment.Values.Add(
new ValueItem
{
Enabled = true,
Value = key,
Key = "ApiKey_" + client.ApiClientName
});
postmanEnvironment.Values.Add(
new ValueItem
{
Enabled = true,
Value = secret,
Key = "ApiSecret_" + client.ApiClientName
});
var clientEdOrgIds = client.LocalEducationOrganizations
.SelectMany(l => Range(l.Start, l.Count))
.Select(PreventEducationOrganizationIdOverflow)
.Distinct()
.ToList();
_clientAppRepo.AddEdOrgIdsToApiClient(
user.UserId, apiClient.ApiClientId, clientEdOrgIds,
application.ApplicationId);
_clientAppRepo.AddOdsInstanceToApiClient(apiClient.ApiClientId, odsInstance.OdsInstanceId);
postmanEnvironment.Values.Add(
new ValueItem
{
Enabled = true,
Value = client.LocalEducationOrganizations,
Key = client.ApiClientName + "LeaId"
});
if (client.OwnershipToken != null)
{
_clientAppRepo.AddOwnershipTokensToApiClient(client.OwnershipToken, apiClient.ApiClientId);
}
if (client.ApiClientOwnershipTokens != null)
{
_clientAppRepo.AddApiClientOwnershipTokens(client.ApiClientOwnershipTokens, apiClient.ApiClientId);
}
}
if (app.Profiles != null)
{
var _profiles = new List<Profile>();
foreach (var profileName in app.Profiles)
{
var profileDefinition = profileDefinitionByName[profileName].OuterXml;
_profiles.Add(new Profile() { ProfileDefinition = profileDefinition, ProfileName = profileName });
}
_clientAppRepo.AddProfilesToApplication(_profiles, application.ApplicationId);
}
}
}
return postmanEnvironment;
string GetGuid()
{
return Guid.NewGuid().ToString("N").Substring(0, 20);
}
}
private long PreventEducationOrganizationIdOverflow(long educationOrganizationId)
{
return Math.Min(educationOrganizationId, _maxSafeEducationOrganizationId);
}
/// <summary>
/// Similar to Enumerable.Range().
/// Allows any numeric range (instead of only int32 ranges).
/// </summary>
private IEnumerable<T> Range<T>(T start, T count)
where T : INumber<T>
{
for (var i = start; i < start + count; i++)
{
yield return i;
}
}
}
}