BatchActivity.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. using Microsoft.Azure.Batch;
  2. using Microsoft.Azure.Batch.Auth;
  3. using Microsoft.Azure.Batch.Common;
  4. using Microsoft.Azure.Services.AppAuthentication;
  5. using Microsoft.Azure.WebJobs;
  6. using Microsoft.Azure.WebJobs.Extensions.DurableTask;
  7. using Microsoft.Extensions.Logging;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Threading.Tasks;
  11. using static ADPControl.HttpSurface;
  12. namespace ADPControl
  13. {
  14. public static class BatchActivity
  15. {
  16. // Batch resource settings
  17. private const string PoolVMSize = "Standard_D8s_v3";
  18. private const string PoolId = PoolVMSize;
  19. private const int PoolNodeCount = 2;
  20. private const string AppPackageName = "SqlPackageWrapper";
  21. public const string AppPackageVersion = "1";
  22. [FunctionName(nameof(CreateBatchPoolAndExportJob))]
  23. public static async Task<string> CreateBatchPoolAndExportJob([ActivityTrigger] ExportRequest request, ILogger log)
  24. {
  25. var azureServiceTokenProvider = new AzureServiceTokenProvider();
  26. // Get a Batch client using function identity
  27. BatchTokenCredentials batchCred = new BatchTokenCredentials(request.BatchAccountUrl, await azureServiceTokenProvider.GetAccessTokenAsync("https://batch.core.windows.net/"));
  28. string jobId = request.SourceSqlServerName + "-Export-" + DateTime.UtcNow.ToString("MMddHHmmss");
  29. using (BatchClient batchClient = BatchClient.Open(batchCred))
  30. {
  31. ImageReference imageReference = CreateImageReference();
  32. VirtualMachineConfiguration vmConfiguration = CreateVirtualMachineConfiguration(imageReference);
  33. await CreateBatchPoolIfNotExist(batchClient, vmConfiguration, request.VNetSubnetId);
  34. await CreateBatchJob(batchClient, jobId, log);
  35. }
  36. return jobId;
  37. }
  38. [FunctionName(nameof(CreateBatchPoolAndImportJob))]
  39. public static async Task<string> CreateBatchPoolAndImportJob([ActivityTrigger] ImportRequest request, ILogger log)
  40. {
  41. var azureServiceTokenProvider = new AzureServiceTokenProvider();
  42. // Get a Batch client using function identity
  43. BatchTokenCredentials batchCred = new BatchTokenCredentials(request.BatchAccountUrl, await azureServiceTokenProvider.GetAccessTokenAsync("https://batch.core.windows.net/"));
  44. string jobId = request.TargetSqlServerName + "-Import-" + DateTime.UtcNow.ToString("MMddHHmmss");
  45. using (BatchClient batchClient = BatchClient.Open(batchCred))
  46. {
  47. ImageReference imageReference = CreateImageReference();
  48. VirtualMachineConfiguration vmConfiguration = CreateVirtualMachineConfiguration(imageReference);
  49. await CreateBatchPoolIfNotExist(batchClient, vmConfiguration, request.VNetSubnetId);
  50. await CreateBatchJob(batchClient, jobId, log);
  51. }
  52. return jobId;
  53. }
  54. public static async Task<CloudJob> CreateBatchJob(BatchClient batchClient, string jobId, ILogger log)
  55. {
  56. // Create a Batch job
  57. log.LogInformation("Creating job [{0}]...", jobId);
  58. CloudJob job = null;
  59. try
  60. {
  61. job = batchClient.JobOperations.CreateJob(jobId, new PoolInformation { PoolId = PoolId });
  62. job.OnAllTasksComplete = OnAllTasksComplete.TerminateJob;
  63. // Commit the job to the Batch service
  64. await job.CommitAsync();
  65. log.LogInformation($"Created job {jobId}");
  66. // Obtain the bound job from the Batch service
  67. await job.RefreshAsync();
  68. }
  69. catch (BatchException be)
  70. {
  71. // Accept the specific error code JobExists as that is expected if the job already exists
  72. if (be.RequestInformation?.BatchError?.Code == BatchErrorCodeStrings.JobExists)
  73. {
  74. log.LogWarning("The job {0} already existed when we tried to create it", jobId);
  75. }
  76. else
  77. {
  78. log.LogError("Exception creating job: {0}", be.Message);
  79. throw be; // Any other exception is unexpected
  80. }
  81. }
  82. return job;
  83. }
  84. // Create the Compute Pool of the Batch Account
  85. public static async Task CreateBatchPoolIfNotExist(BatchClient batchClient, VirtualMachineConfiguration vmConfiguration, string vnetSubnetId)
  86. {
  87. Console.WriteLine("Creating pool [{0}]...", PoolId);
  88. try
  89. {
  90. CloudPool pool = batchClient.PoolOperations.CreatePool(
  91. poolId: PoolId,
  92. targetDedicatedComputeNodes: PoolNodeCount,
  93. virtualMachineSize: PoolVMSize,
  94. virtualMachineConfiguration: vmConfiguration);
  95. // Specify the application and version to install on the compute nodes
  96. pool.ApplicationPackageReferences = new List<ApplicationPackageReference>
  97. {
  98. new ApplicationPackageReference {
  99. ApplicationId = AppPackageName,
  100. Version = AppPackageVersion }
  101. };
  102. // Initial the first data disk for each VM in the pool
  103. StartTask startTask = new StartTask("cmd /c Powershell -command \"Get-Disk | Where partitionstyle -eq 'raw' | sort number | Select-Object -first 1 |" +
  104. " Initialize-Disk -PartitionStyle MBR -PassThru | New-Partition -UseMaximumSize -DriveLetter F |" +
  105. " Format-Volume -FileSystem NTFS -NewFileSystemLabel data1 -Confirm:$false -Force\"");
  106. startTask.MaxTaskRetryCount = 1;
  107. startTask.UserIdentity = new UserIdentity(new AutoUserSpecification(AutoUserScope.Pool, ElevationLevel.Admin));
  108. startTask.WaitForSuccess = true;
  109. pool.StartTask = startTask;
  110. // Create the Pool within the vnet subnet if it's specified.
  111. if (vnetSubnetId != null)
  112. {
  113. pool.NetworkConfiguration = new NetworkConfiguration();
  114. pool.NetworkConfiguration.SubnetId = vnetSubnetId;
  115. }
  116. await pool.CommitAsync();
  117. await pool.RefreshAsync();
  118. }
  119. catch (BatchException be)
  120. {
  121. // Accept the specific error code PoolExists as that is expected if the pool already exists
  122. if (be.RequestInformation?.BatchError?.Code == BatchErrorCodeStrings.PoolExists)
  123. {
  124. Console.WriteLine("The pool {0} already existed when we tried to create it", PoolId);
  125. }
  126. else
  127. {
  128. throw; // Any other exception is unexpected
  129. }
  130. }
  131. }
  132. public static VirtualMachineConfiguration CreateVirtualMachineConfiguration(ImageReference imageReference)
  133. {
  134. VirtualMachineConfiguration config = new VirtualMachineConfiguration(
  135. imageReference: imageReference,
  136. nodeAgentSkuId: "batch.node.windows amd64");
  137. config.DataDisks = new List<DataDisk>();
  138. config.DataDisks.Add(new DataDisk(0, 2048, CachingType.ReadOnly, StorageAccountType.PremiumLrs));
  139. return config;
  140. }
  141. public static ImageReference CreateImageReference()
  142. {
  143. return new ImageReference(
  144. publisher: "MicrosoftWindowsServer",
  145. offer: "WindowsServer",
  146. sku: "2019-datacenter-smalldisk",
  147. version: "latest");
  148. }
  149. public static void CreateBatchTasks(string action, string jobId, string containerUrl, string batchAccountUrl, string sqlServerName, string accessToken, dynamic databases, ILogger log)
  150. {
  151. // Get a Batch client using function identity
  152. log.LogInformation("CreateBatchTasks: entering");
  153. var azureServiceTokenProvider = new AzureServiceTokenProvider();
  154. BatchTokenCredentials batchCred = new BatchTokenCredentials(batchAccountUrl, azureServiceTokenProvider.GetAccessTokenAsync("https://batch.core.windows.net/").Result);
  155. using (BatchClient batchClient = BatchClient.Open(batchCred))
  156. {
  157. // For each database, submit the Exporting job to Azure Batch Compute Pool.
  158. log.LogInformation("CreateBatchTasks: enumerating databases");
  159. List<CloudTask> tasks = new List<CloudTask>();
  160. foreach (var db in databases)
  161. {
  162. string serverDatabaseName = db.name.ToString();
  163. string logicalDatabase = serverDatabaseName.Remove(0, sqlServerName.Length + 1);
  164. log.LogInformation("CreateBatchTasks: creating task for database {0}", logicalDatabase);
  165. string taskId = sqlServerName + "_" + logicalDatabase;
  166. string command = string.Format("cmd /c %AZ_BATCH_APP_PACKAGE_{0}#{1}%\\BatchWrapper {2}", AppPackageName.ToUpper(), AppPackageVersion, action);
  167. command += string.Format(" {0} {1} {2} {3} {4}", sqlServerName, logicalDatabase, accessToken, AppPackageName.ToUpper(), AppPackageVersion);
  168. string taskCommandLine = string.Format(command);
  169. CloudTask singleTask = new CloudTask(taskId, taskCommandLine);
  170. singleTask.EnvironmentSettings = new[] { new EnvironmentSetting("JOB_CONTAINER_URL", containerUrl) };
  171. Console.WriteLine(string.Format("Adding task {0} to job ...", taskId));
  172. tasks.Add(singleTask);
  173. }
  174. // Add all tasks to the job.
  175. batchClient.JobOperations.AddTask(jobId, tasks);
  176. }
  177. log.LogInformation("CreateBatchTasks: exiting");
  178. }
  179. }
  180. }