forked from petehauge/DTL-VM-Generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Utils.ps1
357 lines (290 loc) · 12.3 KB
/
Utils.ps1
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
# This is included at the top of each script
# You would be tempted to include generic useful actions here
# i.e. setting ErrorPreference or checking that you are in the right folder
# but those won't be executed if you are executing the script from the wrong folder
# Instead setting $ActionPreference = "Stop" at the start of each script
# and the script won't start if it executed from wrong folder as it can't import this file.
Set-StrictMode -Version Latest
# Import a patched up version of this module because the standard release
# doesn't propagate Write-host messages to console
# see https://github.com/proxb/PoshRSJob/pull/158/commits/b64ad9f5fbe6fa85f860311f81ec0d6392d5fc01
if (Get-Module | Where-Object {$_.Name -eq "PoshRSJob"}) {
} else {
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
Import-Module "$PSScriptRoot\PoshRSJob\PoshRSJob.psm1"
}
# DTL Module dependency
$AzDtlModuleName = "Az.DevTestLabs2.psm1"
$AzDtlModuleSource = "https://raw.githubusercontent.com/Azure/azure-devtestlab/master/samples/DevTestLabs/Modules/Library/Az.DevTestLabs2.psm1"
# To be passed as 'ModulesToImport' param when starting a RSJob
$global:AzDtlModulePath = Join-Path -Path (Resolve-Path ./) -ChildPath $AzDtlModuleName
function Import-RemoteModule {
param(
[ValidateNotNullOrEmpty()]
[string] $Source,
[ValidateNotNullOrEmpty()]
[string] $ModuleName
)
$modulePath = Join-Path -Path (Resolve-Path ./) -ChildPath $ModuleName
if (Test-Path -Path $modulePath) {
# if the file exists, delete it - just in case there's a newer version, we always download the latest
Remove-Item -Path $modulePath
}
$WebClient = New-Object System.Net.WebClient
$WebClient.DownloadFile($Source, $modulePath)
Import-Module $modulePath
}
function Import-AzDtlModule {
Import-RemoteModule -Source $AzDtlModuleSource -ModuleName $AzDtlModuleName
}
function Set-LabAccessControl {
param(
$DevTestLabName,
$ResourceGroupName,
$customRole,
[string[]] $ownAr,
[string[]] $userAr
)
foreach ($owneremail in $ownAr) {
New-AzRoleAssignment -SignInName $owneremail -RoleDefinitionName 'Owner' -ResourceGroupName $ResourceGroupName -ResourceName $DevTestLabName -ResourceType 'Microsoft.DevTestLab/labs' | Out-Null
Write-Host "$owneremail added as Owner"
}
foreach ($useremail in $userAr) {
New-AzRoleAssignment -SignInName $useremail -RoleDefinitionName $customRole -ResourceGroupName $ResourceGroupName -ResourceName $DevTestLabName -ResourceType 'Microsoft.DevTestLab/labs' | Out-Null
Write-Host "$useremail added as $customRole"
}
}
function Select-VmSettings {
param (
$sourceImageInfos,
[Parameter(HelpMessage="String containing comma delimitated list of patterns. The script will (re)create just the VMs matching one of the patterns. The empty string (default) recreates all labs as well.")]
[string] $ImagePattern = ""
)
if($ImagePattern) {
$imgAr = $ImagePattern.Split(",").Trim()
# Severely in need of a linq query to do this ...
$newSources = @()
foreach($source in $sourceImageInfos) {
foreach($cond in $imgAr) {
if($source.imageName -like $cond) {
$newSources += $source
break
}
}
}
if(-not $newSources) {
throw "No source images selected by the image pattern chosen: $ImagePattern"
}
return $newSources
}
return $sourceImageInfos
}
function ManageExistingVM {
param($DevTestLabName, $VmSettings, $IfExist)
$newSettings = @()
$VmSettings | ForEach-Object {
$vmName = $_.imageName
$existingVms = Get-AzResource -ResourceType "Microsoft.DevTestLab/labs/virtualMachines" -Name "*$DevTestLabName*" | Where-Object { $_.Name -eq "$DevTestLabName/$vmName"}
if($existingVms) {
Write-Host "Found an existing VM $vmName in $DevTestLabName"
if($IfExist -eq "Delete") {
Write-Host "Deleting VM $vmName in $DevTestLabName"
$vmToDelete = $existingVms[0]
Remove-AzResource -ResourceId $vmToDelete.ResourceId -Force | Out-Null
$newSettings += $_
} elseif ($IfExist -eq "Leave") {
Write-Host "Leaving VM $vmName in $DevTestLabName be, not moving forward ..."
} elseif ($IfExist -eq "Error") {
throw "Found VM $vmName in $DevTestLabName. Error because passed the 'Error' parameter"
} else {
throw "Shouldn't get here in New-Vm. Parameter passed is $IfExist"
}
} else { # It is not an existing VM, we should continue creating it
Write-Host "$vmName doesn't exist in $DevTestLabName"
$newSettings += $_
}
}
return $newSettings
}
function Show-JobProgress {
[CmdletBinding()]
param(
[Parameter(Mandatory,ValueFromPipeline)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.Job[]]
$Job
)
Process {
$Job.ChildJobs | ForEach-Object {
if (-not $_.Progress) {
return
}
$_.Progress |Select-Object -Last 1 | ForEach-Object {
$ProgressParams = @{}
if ($_.Activity -and $null -ne $_.Activity) { $ProgressParams.Add('Activity', $_.Activity) }
if ($_.StatusDescription -and $null -ne $_.StatusDescription) { $ProgressParams.Add('Status', $_.StatusDescription) }
if ($_.CurrentOperation -and $null -ne $_.CurrentOperation) { $ProgressParams.Add('CurrentOperation', $_.CurrentOperation) }
if ($_.ActivityId -and $_.ActivityId -gt -1) { $ProgressParams.Add('Id', $_.ActivityId) }
if ($_.ParentActivityId -and $_.ParentActivityId -gt -1) { $ProgressParams.Add('ParentId', $_.ParentActivityId) }
if ($_.PercentComplete -and $_.PercentComplete -gt -1) { $ProgressParams.Add('PercentComplete', $_.PercentComplete) }
if ($_.SecondsRemaining -and $_.SecondsRemaining -gt -1) { $ProgressParams.Add('SecondsRemaining', $_.SecondsRemaining) }
Write-Progress @ProgressParams
}
}
}
}
function Wait-JobWithProgress {
param(
[ValidateNotNullOrEmpty()]
$jobs,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
$secTimeout
)
Write-Host "Waiting for results at most $secTimeout seconds, or $( [math]::Round($secTimeout / 60,1)) minutes, or $( [math]::Round($secTimeout / 60 / 60,1)) hours ..."
if(-not $jobs) {
Write-Host "No jobs to wait for"
return
}
# Control how often we show output and print out time passed info
# Change here to make it go faster or slower
$RetryIntervalSec = 7
$MaxPrintInterval = 7
$PrintInterval = 1
$timer = [Diagnostics.Stopwatch]::StartNew()
$runningJobs = $jobs | Where-Object { $_ -and ($_.State -eq "Running") }
while(($runningJobs) -and ($timer.Elapsed.TotalSeconds -lt $secTimeout)) {
$runningJobs | Receive-job -Keep -ErrorAction Continue # Show partial results
$runningJobs | Wait-Job -Timeout $RetryIntervalSec | Show-JobProgress # Show progress bar
if($PrintInterval -ge $MaxPrintInterval) {
$totalSecs = [math]::Round($timer.Elapsed.TotalSeconds,0)
Write-Host "Passed: $totalSecs seconds, or $( [math]::Round($totalSecs / 60,1)) minutes, or $( [math]::Round($totalSecs / 60 / 60,1)) hours ..." -ForegroundColor Yellow
$PrintInterval = 1
} else {
$PrintInterval += 1
}
$runningJobs = $jobs | Where-Object { $_ -and ($_.State -eq "Running") }
}
$timer.Stop()
$lasted = $timer.Elapsed.TotalSeconds
Write-Host ""
Write-Host "JOBS STATUS"
Write-Host "-------------------"
$jobs # Show overall status of all jobs
Write-Host ""
Write-Host "JOBS OUTPUT"
Write-Host "-------------------"
$jobs | Receive-Job -ErrorAction Continue # Show output for all jobs
$jobs | Remove-job -Force # -Force removes also the ones still running ...
if ($lasted -gt $secTimeout) {
throw "Jobs did not complete before timeout period. It lasted $lasted secs."
} else {
Write-Host "Jobs completed before timeout period. It lasted $lasted secs."
}
}
function Wait-RSJobWithProgress {
param(
[ValidateNotNullOrEmpty()]
$jobs,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
$secTimeout
)
Write-Host "Waiting for results at most $secTimeout seconds, or $( [math]::Round($secTimeout / 60,1)) minutes, or $( [math]::Round($secTimeout / 60 / 60,1)) hours ..."
if(-not $jobs) {
Write-Host "No jobs to wait for"
return
}
$timer = [Diagnostics.Stopwatch]::StartNew()
$jobs | Wait-RSJob -ShowProgress -Timeout $secTimeout | Out-Null
$timer.Stop()
$lasted = $timer.Elapsed.TotalSeconds
Write-Host ""
Write-Host "JOBS STATUS"
Write-Host "-------------------"
$jobs | Format-Table | Out-Host
$allJobs = $jobs | Select-Object -ExpandProperty 'Name'
$failedJobs = $jobs | Where-Object {$_.State -eq 'Failed'} | Select-Object -ExpandProperty 'Name'
$runningJobs = $jobs | Where-Object {$_.State -eq 'Running'} | Select-Object -ExpandProperty 'Name'
$completedJobs = $jobs | Where-Object {$_.State -eq 'Completed'} | Select-Object -ExpandProperty 'Name'
Write-Output "OUTPUT for ($allJobs)"
# These go to output to show errors and correct results
$jobs | Receive-RSJob -ErrorAction Continue
$jobs | Remove-RSjob -Force | Out-Null
$errorString = ""
if($failedJobs -or $runningJobs) {
$errorString += "Failed jobs: $failedJobs, Running jobs: $runningJobs. "
}
if ($lasted -gt $secTimeout) {
$errorString += "Jobs did not complete before timeout period. It lasted for $lasted secs."
}
if($errorString) {
throw "ERROR: $errorString"
}
Write-Output "These jobs ($completedJobs) completed before timeout period. They lasted for $lasted secs."
}
function Invoke-RSForEachLab {
param
(
[parameter(ValueFromPipeline)]
[string] $script,
[string] $ConfigFile = "config.csv",
[int] $SecondsBetweenLoops = 10,
[string] $customRole = "No VM Creation User",
[string] $ImagePattern = "",
[string] $IfExist = "Leave",
[int] $SecTimeout = 5 * 60 * 60,
[string] $MatchBy = "",
[string[]] $ModulesToImport
)
$config = Import-Csv $ConfigFile
$jobs = @()
$config | ForEach-Object {
$lab = $_
Write-Host "Starting operating on $($lab.DevTestLabName) ..."
# We are getting a string from the csv file, so we need to split it
if($lab.LabOwners) {
$ownAr = $lab.LabOwners.Split(",").Trim()
} else {
$ownAr = @()
}
if($lab.LabUsers) {
$userAr = $lab.LabUsers.Split(",").Trim()
} else {
$userAr = @()
}
# The scripts that operate over a single lab need to have an uniform number of parameters so that they can be invoked by Invoke-ForeachLab.
# The argumentList of star-job just allows passing arguments positionally, so it can't be used if the scripts have arguments in different positions.
# To workaround that, a string gets generated that embed the script as text and passes the parameters by name instead
# Also, a valueFromRemainingArguments=$true parameter needs to be added to the single lab script
# So we achieve the goal of reusing the Invoke-Foreach function for everything, while still keeping the single lab scripts clean for the caller
# The price we pay for the above is the crazy code below, which is likely quite bug prone ...
$formatOwners = $ownAr | ForEach-Object { "'$_'"}
$ownStr = $formatOwners -join ","
$formatUsers = $userAr | ForEach-Object { "'$_'"}
$userStr = $formatUsers -join ","
$params = "@{
DevTestLabName='$($lab.DevTestLabName)';
ResourceGroupName='$($lab.ResourceGroupName)';
SharedImageGalleryName='$($lab.SharedImageGalleryName)';
ShutDownTime='$($lab.ShutDownTime)';
TimezoneId='$($lab.TimezoneId)';
LabRegion='$($lab.LabRegion)';
LabOwners= @($ownStr);
LabUsers= @($userStr);
CustomRole='$($customRole)';
ImagePattern='$($ImagePattern)';
IfExist='$($IfExist)';
MatchBy='$($MatchBy)'
}"
$sb = [scriptblock]::create(
@"
`Set-Location `$Using:PWD
`$params=$params
.{$(get-content $script -Raw)} @params
"@)
$jobs += Start-RSJob -Name $lab.DevTestLabName -ScriptBlock $sb -ModulesToImport $ModulesToImport
Start-Sleep -Seconds $SecondsBetweenLoops
}
Wait-RSJobWithProgress -secTimeout $secTimeout -jobs $jobs
}