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
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.AppService.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.RecoveryServices.Backup;
using Microsoft.Azure.Management.Sql.Fluent.Models;
using Microsoft.WindowsAzure.Storage;
using Tango.AzureUtils.ActiveDirectory;
using Tango.AzureUtils.Deployment;
using Tango.BL;
using Tango.Core;
using Tango.Core.DB;
namespace Tango.AzureUtils.Environment
{
public class EnvironmentManager : AzureUtilsComponentBase
{
private ActiveDirectoryManager _adManager;
private DeploymentManager _deploymentManager;
public EnvironmentManager(IAzure azure) : base(azure)
{
_adManager = new ActiveDirectoryManager(azure, AzureUtilsAuthenticationFactory.GetCredentials());
_adManager.ConfirmationRequired += (x, e) => OnRequestConfirmation(e);
_adManager.Progress += (x, e) => OnProgress(e);
_deploymentManager = new DeploymentManager(azure);
_deploymentManager.ConfirmationRequired += (x, e) => OnRequestConfirmation(e);
_deploymentManager.Progress += (x, e) => OnProgress(e);
}
#region Deployment Slots
public async Task<IDeploymentSlot> CreateDeploymentSlot(IWebApp app, IDeploymentSlot sourceSlot, String name, String adEmail, String adPassword)
{
String dbCatalog = $"Tango_{name}";
String machineStudioContainerName = $"machine-studio-versions-{name.ToLower()}";
String ppcContainerName = $"tango-versions-{name.ToLower()}";
String machineServiceBackupsContainerName = $"machine-service-backups-{name.ToLower()}";
String machineServiceLogsContainerName = $"machine-service-logs-{name.ToLower()}";
String environmentGroupName = $"Tango {name}";
String slotName = app.Name + "-" + name;
OnProgress(AzureUtilsStage.Initializing, $"Retrieving '{sourceSlot.Name}' settings...");
var settings = await sourceSlot.GetMachineServiceSettingsAsync();
OnProgress(AzureUtilsStage.EnvironmentGroup, $"Authenticating with active directory graph...");
await _adManager.Authenticate(adEmail, adPassword);
if (!await _adManager.IsGroupExists(environmentGroupName))
{
OnProgress(AzureUtilsStage.EnvironmentGroup, $"Creating environment group '{environmentGroupName}'...");
await _adManager.AddGroup(environmentGroupName);
OnProgress(AzureUtilsStage.EnvironmentGroup, $"Adding environment group user '{adEmail}'...");
await _adManager.AddUserToGroup(environmentGroupName, adEmail);
}
else
{
await RequestConfirmation($"Environment group '{environmentGroupName}' already exists. Do you wish to continue?");
}
OnProgress(AzureUtilsStage.DeploymentSlot, $"Checking '{app.Name}' deployment slots...");
IDeploymentSlot slot = (await app.DeploymentSlots.ListAsync()).ToList().SingleOrDefault(x => x.Name == slotName);
if (slot == null)
{
//Add Slot
OnProgress(AzureUtilsStage.DeploymentSlot, $"Creating new deployment slot '{slotName}'...");
var dictionary = new Dictionary<string, string>();
dictionary.Add(nameof(MachineServiceSettings.DB_ADDRESS), settings.DB_ADDRESS);
dictionary.Add(nameof(MachineServiceSettings.DB_CATALOG), dbCatalog);
dictionary.Add(nameof(MachineServiceSettings.DB_PASSWORD), settings.DB_PASSWORD);
dictionary.Add(nameof(MachineServiceSettings.DB_USER_NAME), settings.DB_USER_NAME);
dictionary.Add(nameof(MachineServiceSettings.DEPLOYMENT_SLOT), name);
dictionary.Add(nameof(MachineServiceSettings.ENFORCE_MACHINE_STUDIO_VERSION), settings.ENFORCE_MACHINE_STUDIO_VERSION);
dictionary.Add(nameof(MachineServiceSettings.ENVIRONMENT_GROUP), environmentGroupName);
dictionary.Add(nameof(MachineServiceSettings.STORAGE_ACCOUNT), settings.STORAGE_ACCOUNT);
dictionary.Add(nameof(MachineServiceSettings.MACHINE_STUDIO_VERSIONS_CONTAINER), machineStudioContainerName);
dictionary.Add(nameof(MachineServiceSettings.TANGO_VERSIONS_CONTAINER), ppcContainerName);
slot = await app.DeploymentSlots
.Define(slotName)
.WithBrandNewConfiguration()
.WithWebAppAlwaysOn(true)
.WithWebSocketsEnabled(true)
.WithStickyAppSettings(dictionary)
.WithStickyConnectionString(dbCatalog, $"Server=tcp:twine.database.windows.net,1433;Initial Catalog={dbCatalog};Persist Security Info=False;User ID=BackupUser;Password=Aa123456;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Connection Timeout=30;", Microsoft.Azure.Management.AppService.Fluent.Models.ConnectionStringType.SQLAzure)
.CreateAsync();
}
else
{
await RequestConfirmation($"Deployment slot '{slotName}' already exists. Do you wish to continue.");
}
//Add Database
OnProgress(AzureUtilsStage.Database, $"Checking twine database server...");
var sqlServer = (await Azure.SqlServers.ListAsync()).SingleOrDefault(x => x.Name == "twine");
var existingDatabase = (await sqlServer.Databases.ListAsync()).SingleOrDefault(x => x.Name == dbCatalog);
if (existingDatabase == null)
{
OnProgress(AzureUtilsStage.Database, $"Creating new database '{dbCatalog}'...");
var database = await sqlServer.Databases.Define(dbCatalog).WithEdition(DatabaseEdition.Standard).CreateAsync();
}
else
{
await RequestConfirmation($"Database '{dbCatalog}' already exists. Do you wish to continue?");
}
//Add permissions for environment group on database
OnProgress(AzureUtilsStage.Database, $"Adding environment group permissions on '{dbCatalog}'...");
using (DbManager db = DbManager.FromDataSource(new DataSource()
{
Type = DataSourceType.Azure,
Address = settings.DB_ADDRESS,
Catalog = dbCatalog,
UserName = adEmail,
Password = adPassword,
IntegratedSecurity = false
}))
{
try
{
await db.ExecuteCommandAsync($"CREATE USER [{environmentGroupName}] FROM EXTERNAL PROVIDER");
await db.ExecuteCommandAsync($"ALTER ROLE db_datareader ADD MEMBER [{environmentGroupName}];");
await db.ExecuteCommandAsync($"ALTER ROLE db_datawriter ADD MEMBER [{environmentGroupName}];");
}
catch (Exception ex)
{
await RequestConfirmation($"Error creating/adding permissions for environment group '{environmentGroupName}' on database.\n{ex.FlattenMessage()}\n\nDo you wish to continue?");
}
}
OnProgress(AzureUtilsStage.Database, $"Adding BackupUser permissions on '{dbCatalog}'...");
//Create backup user
using (DbManager db = DbManager.FromCredentials(settings.DB_ADDRESS, dbCatalog, settings.DB_USER_NAME, settings.DB_PASSWORD))
{
try
{
await db.ExecuteCommandAsync("CREATE USER [BackupUser] FOR LOGIN [BackupUser] WITH DEFAULT_SCHEMA=[dbo]");
await db.ExecuteCommandAsync("EXEC sp_addrolemember N'db_owner', N'BackupUser'");
await db.ExecuteCommandAsync("EXEC sp_addrolemember N'db_accessadmin', N'BackupUser'");
await db.ExecuteCommandAsync("EXEC sp_addrolemember N'db_securityadmin', N'BackupUser'");
await db.ExecuteCommandAsync("EXEC sp_addrolemember N'db_backupoperator', N'BackupUser'");
await db.ExecuteCommandAsync("EXEC sp_addrolemember N'db_datareader', N'BackupUser'");
await db.ExecuteCommandAsync("EXEC sp_addrolemember N'db_datawriter', N'BackupUser'");
}
catch (Exception ex)
{
await RequestConfirmation($"Error creating/adding permissions for BackupUser on database.\n{ex.FlattenMessage()}\n\nDo you wish to continue?");
}
}
//Synchronize Schema
//await _deploymentManager.OpenSQLExaminerSchema(sourceSlot, slot);
//await RequestConfirmation($"Please synchronize the database schema between '{settings.DB_CATALOG}' and '{dbCatalog}'.\nPlease confirm in order to continue.");
//OnProgress(AzureUtilsStage.Database, $"Waiting for database schema synchronization...");
//await _deploymentManager.OpenSQLExaminerData(sourceSlot, slot, true);
//await RequestConfirmation($"Please synchronize the database static collections between '{settings.DB_CATALOG}' and '{dbCatalog}'.\nPlease confirm in order to continue.");
//OnProgress(AzureUtilsStage.Database, $"Waiting for database static collections synchronization...");
//OnProgress(AzureUtilsStage.Database, $"Retrieving latest Machine Studio version...");
//var latestMsVersion = await _deploymentManager.GetLatestMachineStudioVersion(sourceSlot);
//OnProgress(AzureUtilsStage.Database, $"Retrieving latest PPC version...");
//var latestPPCVersion = await _deploymentManager.GetLatestPPCVersion(sourceSlot);
//var targetSettings = await slot.GetMachineServiceSettingsAsync();
//using (ObservablesContext db = ObservablesContext.CreateDefault(targetSettings.ToDataSource()))
//{
// db.MachineStudioVersions.Add(latestMsVersion);
// db.TangoVersions.Add(latestPPCVersion);
//}
//Add Storage Containers
OnProgress(AzureUtilsStage.Storage, $"Connecting to storage account...");
var targetAccount = CloudStorageAccount.Parse(settings.STORAGE_ACCOUNT);
var targetClient = targetAccount.CreateCloudBlobClient();
OnProgress(AzureUtilsStage.Storage, $"Creating storage container '{machineStudioContainerName}'...");
var machineStudioContainer = targetClient.GetContainerReference(machineStudioContainerName);
await machineStudioContainer.CreateIfNotExistsAsync();
OnProgress(AzureUtilsStage.Storage, $"Creating storage container '{ppcContainerName}'...");
var ppcContainer = targetClient.GetContainerReference(ppcContainerName);
await ppcContainer.CreateIfNotExistsAsync();
OnProgress(AzureUtilsStage.Storage, $"Creating storage container '{machineServiceBackupsContainerName}'...");
var machineServiceBackupsContainer = targetClient.GetContainerReference(machineServiceBackupsContainerName);
await machineServiceBackupsContainer.CreateIfNotExistsAsync();
OnProgress(AzureUtilsStage.Storage, $"Creating storage container '{machineServiceLogsContainerName}'...");
var machineServiceLogsContainer = targetClient.GetContainerReference(machineServiceLogsContainerName);
await machineServiceLogsContainer.CreateIfNotExistsAsync();
_deploymentManager.UpgradeConfiguration.UpgradeMachineService = true;
_deploymentManager.UpgradeConfiguration.UpgradeMachineStudio = true;
_deploymentManager.UpgradeConfiguration.UpgradePPC = true;
await _deploymentManager.PerformFullUpgrade(sourceSlot, slot);
OnProgress(AzureUtilsStage.Ready, "Deployment slot created successfully.", 0, 100, false);
return slot;
}
#endregion
}
}
|