-
Notifications
You must be signed in to change notification settings - Fork 25
/
tosca_execution_client.ps1
650 lines (553 loc) · 23.5 KB
/
tosca_execution_client.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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
#Requires -Version 3.0
#####################################################################################
#
# Tosca Execution Client for PowerShell
# Version 1.0.0
# Triggers Tosca TestEvents via Tosca Server Execution API
#
#####################################################################################
######################################################################
# Global parameters/variables
######################################################################
param(
# Mandatory parameters
[string]$toscaServerUrl,
[string]$executionEnvironment = "Dex",
[string]$projectName,
[string]$events,
[string]$eventsConfigFilePath,
#Optional parameters
[string]$clientId,
[string]$clientSecret,
[int]$clientTimeout = 36000,
[string]$creator = "ToscaExecutionClient",
[Alias("d")]
[switch]$debug,
[Alias("h")]
[switch]$help,
[switch]$enqueueOnly,
[string]$executionId = "",
[string]$importResults = "true",
[switch]$fetchPartialResults,
[switch]$fetchResultsOnly,
[string]$logFolderPath = "logs",
[int]$pollingInterval = 60,
[int]$requestTimeout = 180,
[string]$resultsFileName = "",
[string]$resultsFolderPath = "results",
[Alias("s")]
[switch]$silent
)
[bool]$validationFailed = $true
# Variables for authentication
[string]$accessToken=""
[int]$tokenExpirationDate = 0
[bool]$authenticationEnabled = $false
# Variables for execution
[string]$executionStatus=""
[string]$executionResults=""
######################################################################
# Functions
######################################################################
#######################################
# Prints usage information for this script.
# Globals:
# None
# Arguments:
# None
# Returns:
# Nothing
#######################################
function displayHelp() {
Write-Output "`nUsage: $($PSCommandPath) -toscaServerUrl <toscaServerUrl> -projectName <projectName> -events <events> [Options]`n"
Write-Output "Mandatory parameters:"
Write-Output " toscaServerUrl URL of Tosca Server, e.g. https://myserver.tricentis.com or http://111.111.111.0:81."
Write-Output " projectName Project root name of the Tosca project where the event is located."
Write-Output " events Names or uniqueIds of the events that you want to execute, separated by comma. If you want to overwrite TCPs or Agent Characteristics for a specific event, use the ""eventsConfigFilePath"" parameter instead."
Write-Output " eventsConfigFilePath Path to the JSON file that contains the event configuration, including TCPs and Agent Characteristics. If you use this parameter, you don't need to use the ""events"" parameter."
Write-Output "`nOptions:"
Write-Output " clientId Client ID of the Tricentis User Administration access token. This parameter is mandatory if you use HTTPS."
Write-Output " clientSecret Client secret of the Tricentis User Administration access token. This parameter is mandatory if you use HTTPS."
Write-Output " clientTimeout Time in seconds that the ToscaExecutionClient waits for the execution to finish before it aborts (default: 36000)."
Write-Output " creator Name of who triggered the execution. The DEX Monitor UI displays this name (default: ToscaExecutionClient)."
Write-Output " debug Activates debug mode."
Write-Output " enqueueOnly Only enqueue the execution. ToscaExecutionClient doesn't fetch results."
Write-Output " executionEnvironment Environment in which you want to execute the event. Possible values are ""Dex"" or ""ElasticExecutionGrid"" (default: ""Dex"")."
Write-Output " executionId ID of the execution for which you want to get results. You only need this parameter if you choose ""fetchResultsOnly""."
Write-Output " fetchPartialResults Fetch partial execution results."
Write-Output " fetchResultsOnly Get the results of an currently running or already finished execution."
Write-Output " help Get usage information for the ToscaExecutionClient."
Write-Output " importResults Import results into your Tosca project. Possible values are ""true"" and ""false""."
Write-Output " logFolderPath Path to the folder where the ToscaExecutionClient saves log files (default: logs)."
Write-Output " pollingInterval Interval in seconds in which the ToscaExecutionClient requests results from the DEX Server (default: 60)."
Write-Output " resultsFileName Name of the file in which ToscaExecutionClient saves execution results (default: ""<executionId>_results.xml"")."
Write-Output " requestTimeout Time in seconds that the ToscaExecutionClient waits for a response from AOS (default: 180)."
Write-Output " resultsFolderPath Path to the folder where ToscaExecutionClient saves execution results (default: results)."
Write-Output " silent Deactivate logging to stdout (terminal)."
}
#######################################
# Prints log message
# Globals:
# logFolderPath
# Arguments:
# logLevel
# logMessage
# Returns:
# Nothing
#######################################
function log([string]$logLevel, [string]$logMessage) {
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss z"
$message = [string]::Format("{0} [{1}] {2}", $ts, $logLevel, $logMessage)
if( -not $silent ) {
if( $logLevel -eq "ERR" ) {
Write-Output $message | highlightInRed
} else {
Write-Output $message
}
}
$logFileName = "$(Get-Date -Format "yyyyMMdd")_ToscaExecutionClient.txt"
$logFilePath = "$logFolderPath\$logFileName"
try {
$message | Out-File $logFilePath -Append
} catch {
Write-Output "$ts [ERR] ToscaExecutionClient failed to write the log message in ""$path""."
Write-Output "$ts [ERR] $_"
Write-Output "$ts [INF] Stopping ToscaExecutionClient..."
exit 1
}
}
#######################################
# Creates directory if it does not exist
# Globals:
# None
# Arguments:
# path
# suppressLog
# Returns:
# Nothing
#######################################
function createDirectory([string]$path, [bool]$suppressLog=$false) {
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss z"
try {
if ( -not (Test-Path $path) ) {
if ( $suppressLog -eq $true ) {
Write-Output "$ts [INF] Directory ""$path"" does not exist. Try to create directory ""$path""..."
} else {
log "INF" "Directory ""$path"" does not exist. Try to create directory ""$path""..."
}
New-Item -Path "$path" -ItemType Directory | out-null
log "INF" "Successfully created directory ""$path""."
}
} catch {
if ( $suppressLog -eq $true ) {
Write-Output "$ts [ERR] ToscaExecutionClient failed to create directory ""$path""."
Write-Output "$ts [ERR] $_"
Write-Output "$ts [INF] Stopping ToscaExecutionClient..."
} else {
log "ERR" "ToscaExecutionClient failed to create directory ""$path""."
log "ERR" "$_"
log "INF" "Stopping ToscaExecutionClient..."
}
exit 1
}
}
#######################################
# Returns absolute path
# Globals:
# None
# Arguments:
# path
# suppressLog
# Returns:
# Resolved path to directory
#######################################
function getAbsolutePath([string]$path, [bool]$suppressLog=$false) {
$ts = Get-Date -Format "yyyy-MM-dd HH:mm:ss z"
try {
$isAbsolutePath = [System.IO.Path]::IsPathRooted($path)
if ( $isAbsolutePath -eq $false ) {
$path = [System.IO.Path]::Combine($PSScriptRoot, $path);
}
} catch {
if ( $suppressLog -eq $true ) {
Write-Output "$ts [ERR] ToscaExecutionClient failed to resolve path ""$path""."
Write-Output "$ts [ERR] $_"
Write-Output "$ts [INF] Stopping ToscaExecutionClient..."
} else {
log "ERR" "ToscaExecutionClient failed to resolve path ""$path""."
log "ERR" "$_"
log "INF" "Stopping ToscaExecutionClient..."
}
exit 1
}
return $path
}
#######################################
# Changes font color of terminal output to red
# Globals:
# None
# Arguments:
# None
# Returns:
# Nothing
#######################################
function highlightInRed {
process { Write-Host $_ -ForegroundColor Red }
}
#######################################
# Writes execution results
# Globals:
# executionId
# executionResults
# resultsFolderPath
# Arguments:
# writePartialResults
# Returns:
# Nothing
#######################################
function writeResults([bool]$writePartialResults = $false) {
$folderPath = $resultsFolderPath
$currentDate = Get-Date -Format "yyyyMMdd_HHmmss"
if( -not ([String]::IsNullOrEmpty($executionResults)) ) {
if ( $writePartialResults -eq $true ) {
$folderPath = "$folderPath\${executionId}_partial"
createDirectory $folderPath
$resultsFilePath= "$folderPath\${currentDate}_results.xml"
log "INF" "Writing partial results for execution with id ""$executionId"" to file ""$resultsFilePath""..."
} else {
if ( -not ([String]::IsNullOrEmpty($resultsFileName)) ) {
$resultsFilePath="$folderPath\${resultsFileName}"
} else {
$resultsFilePath="${folderPath}\${executionId}_results.xml"
}
log "INF" "Writing results for execution with id ""$executionId"" to file ""$resultsFilePath""..."
}
try {
$executionResults | Out-File $resultsFilePath
log "INF" "Finished writing execution results to file ""$resultsFilePath""."
} catch {
log "ERR" "ToscaExecutionClient failed to write results in directory ""$folderPath""."
log "ERR" "$_"
log "INF" "Stopping ToscaExecutionClient..."
exit 1
}
}
}
#######################################
# Generates header for API requests
# Globals:
# accessToken
# Arguments:
# None
# Returns:
# Nothing
#######################################
function generateHeader() {
$header = @{"X-Tricentis" = "OK" }
if( $accessToken ) {
$header.Authorization = "Bearer $accessToken"
}
return $header
}
#######################################
# Returns unix timestamp
# Globals:
# None
# Arguments:
# None
# Returns:
# Timestamp
#######################################
function getTimestamp() {
return [DateTimeOffset]::Now.ToUnixTimeSeconds()
}
#######################################
# Fetches access token from Tosca Server
# Globals:
# toscaServerUrl
# requestTimeout
# clientId
# clientSecret
# Arguments:
# None
# Returns:
# Nothing
#######################################
function fetchOrRefreshAccessToken() {
$now = getTimestamp
if ( $authenticationEnabled -eq $true -and $now -ge $script:tokenExpirationDate) {
log "INF" "Fetching access token with provided credentials..."
$accessTokenRequest = @{
grant_type = "client_credentials"
client_id = $clientId
client_secret = $clientSecret
}
$contentType = "application/x-www-form-urlencoded"
try {
$accessTokenResponse = Invoke-WebRequest `
-Uri "$toscaServerUrl/tua/connect/token" `
-body $accessTokenRequest `
-ContentType $contentType `
-Method Post `
-TimeoutSec $requestTimeout `
log "INF" "Sucessfully fetched access token"
$accessTokenResponseAsJson = ConvertFrom-Json($accessTokenResponse.Content)
$expiresIn = $accessTokenResponseAsJson.expires_in
$script:accessToken = $accessTokenResponseAsJson.access_token
$script:tokenExpirationDate = $now + ($expiresIn * 0.8)
}
catch {
log "ERR" "ToscaExecutionClient failed to fetch the access token."
log "ERR" $_
}
}
}
#######################################
# Enqueues execution request
# Globals:
# toscaServerUrl
# requestTimeout
# accessToken
# executionEnvironment
# projectName
# events
# importResults
# creator
# Arguments:
# None
# Returns:
# Nothing
#######################################
function enqueueExecution() {
$header = generateHeader
$body = "{""ProjectName"":""$projectName"",""ExecutionEnvironment"":""$executionEnvironment"",""Events"":$events,""ImportResult"":$($importResults.ToLower()),""Creator"":""$creator""}"
$contentType = "application/json"
log "INF" "Enqueue execution with provided parameters..."
if ( $debug -eq $true ) {
log "DBG" "Enqueue parameters:"
log "DBG" "$body"
log "DBG" "$header"
}
fetchOrRefreshAccessToken
try {
$enqueueResponse = Invoke-WebRequest `
-Uri "$toscaServerUrl/automationobjectservice/api/execution/enqueue" `
-body $body `
-Headers $header `
-ContentType $contentType `
-Method Post `
-TimeoutSec $requestTimeout `
$status = $enqueueResponse.StatusCode
$content = $enqueueResponse.Content
if ( $debug -eq $true ) {
log "DBG" "Status code of the response = HTTP code $status."
log "DBG" "Body of the response = $content"
}
$executionResponseAsJson = ConvertFrom-Json($content)
$script:executionId = $executionResponseAsJson.ExecutionId
if ( [string]::IsNullOrEmpty($executionId) ) {
log "ERR" "Enqueue response does not include executionId property."
log "ERR" "Status code of the response = HTTP code $status."
log "ERR" "Body of the response = $content"
exit 1
} else {
log "INF" "Successfully enqueued execution with id ""$executionId""."
}
}
catch {
log "ERR" "ToscaExecutionClient failed to enqueue the execution."
log "ERR" $_
exit 1
}
}
#######################################
# Fetches execution status
# Globals:
# toscaServerUrl
# requestTimeout
# accessToken
# executionId
# Arguments:
# None
# Returns:
# Nothing
#######################################
function fetchExecutionStatus () {
$header = generateHeader
log "INF" "Fetching status for execution with id ""$executionId""..."
fetchOrRefreshAccessToken
try {
$statusResponse = Invoke-WebRequest `
-Uri "$toscaServerUrl/automationobjectservice/api/execution/$executionId/status" `
-Headers $header `
-Method Get `
-TimeoutSec $requestTimeout `
$status = $statusResponse.StatusCode
$content = $statusResponse.Content
if ( $debug -eq $true ) {
log "DBG" "Status code of the response = HTTP code $status."
log "DBG" "Body of the response = $content"
}
$statusResponseAsJson = ConvertFrom-Json($content)
$script:executionStatus = $statusResponseAsJson.status
if ( [string]::IsNullOrEmpty($executionStatus) ) {
log "ERR" "Status response does not include status property."
log "ERR" "Status code of the response = HTTP code $status."
log "ERR" "Body of the response = $content"
}
}
catch {
log "ERR" "ToscaExecutionClient failed to fetch the status of execution with id ""$executionId""."
log "ERR" $_
}
}
#######################################
# Fetches execution results
# Globals:
# toscaServerUrl
# requestTimeout
# accessToken
# executionId
# Arguments:
# fetchPartialResults
# Returns:
# Nothing
#######################################
function fetchExecutionResults ([bool]$fetchPartialResults = $false) {
$queryParameters = ""
$header = generateHeader
log "INF" "Fetching results for execution with id ""$executionId""..."
if ( $fetchPartialResults -eq $true) {
$queryParameters="?partial=true"
}
try {
$resultsResponse = Invoke-WebRequest `
-Uri "$toscaServerUrl/automationobjectservice/api/execution/$executionId/results$queryParameters" `
-Headers $header `
-Method Get `
-TimeoutSec $requestTimeout `
$status = $resultsResponse.StatusCode
$content = $resultsResponse.Content
if ( $debug -eq $true ) {
log "DBG" "Status code of the response = HTTP code $status."
log "DBG" "Body of the response = $content"
}
# Reset execution results variable
$script:executionResults = ""
# All results available
if ( $status -eq 200 ) {
log "INF" "Sucessfully fetched results for execution with id ""$executionId""."
$script:executionResults=$content
}
# Not all results are available (E.g. cancelled events, configuration errors)
elseif ( $status -eq 206 ) {
log "WRN" "Not all execution results have been returned for execution with id ""$executionId"". Check AOS, DEX Server and DEX agent logs."
$script:executionResults="$responseBody"
}
# Handle non existing results when fetchPartialResults option is activated
elseif ( $fetchPartialResults -eq $true ) {
log "INF" "No results available yet for execution with id ""$executionId""."
}
else {
log "ERR" "No results available for execution with id ""$executionId"". Check AOS, DEX Server and DEX agent logs."
}
}
catch {
log "ERR" "ToscaExecutionClient failed to fetch the status of execution with id ""$executionId""."
log "ERR" $_
exit 1
}
}
######################################################################
# Main
######################################################################
# Print help and exit if help switch is enabled
if ( $help -eq $true ) {
displayHelp
exit 0
}
# Create directories for log and results folders
$logFolderPath = getAbsolutePath $logFolderPath $true
createDirectory $logFolderPath $true
$resultsFolderPath = getAbsolutePath $resultsFolderPath
createDirectory $resultsFolderPath
if ( [String]::IsNullOrEmpty($toscaServerUrl) ) {
log "ERR" "Mandatory parameter ""toscaServerUrl"" is not set"
} elseif ( [String]::IsNullOrEmpty($projectName) -and $fetchResultsOnly -eq $false ) {
log "ERR" "Mandatory parameter ""projectName"" is not set"
} elseif ( [String]::IsNullOrEmpty($events) -and [String]::IsNullOrEmpty($eventsConfigFilePath) -and $fetchResultsOnly -eq $false ) {
log "ERR" "Event configuration is missing. Define either ""events"" or ""eventsConfigFilePath""."
} elseif ( [String]::IsNullOrEmpty($projectName) ) {
log "ERR" "Mandatory parameter ""projectName"" is not set"
} else {
$validationFailed = $false
}
# Print help and exit if validation failed
if ( $validationFailed -eq $true ) {
displayHelp
exit 1
}
log "INF" "Starting ToscaExecutionClient..."
# Use value from events config file
if( -not ([String]::IsNullOrEmpty($eventsConfigFilePath)) ) {
log "INF" "Parameter ""eventsConfigFilePath"" defined. Using configuration from file."
$script:events = Get-Content -Path $eventsConfigFilePath -Raw
}
#Get access token if credentials are provided
if ( -not ([String]::IsNullOrEmpty($clientId)) -and -not ([String]::IsNullOrEmpty($clientSecret)) ) {
log "INF" "ClientId and clientSecret are provided. Authentication will be enabled. Fetch access token with provided credentials..."
$authenticationEnabled = $true
fetchOrRefreshAccessToken
} else {
log "WRN" "ClientId or clientSecret is not provided. Continue without authentication..."
}
# Skip enqueue call if fetchResultsOnlyOption is given
if ( $fetchResultsOnly -eq $true ) {
log "INF" "Option fetchResultsOnly is activated."
} else {
# Enqueue execution
enqueueExecution
# Skip fetching of execution results when enqueueOnlyOption is given
if ( $enqueueOnly -eq $true ) {
log "INF" "Option enqueueOnly is activated."
log "INF" "Enqueing execution has sucessfully finished"
log "INF" "Stopping ToscaExecutionClient..."
exit 0
}
}
# Handle missing execution id
if ( ([String]::IsNullOrEmpty($executionId)) ) {
log "ERR" "ExecutionId is missing or empty."
log "INF" "Stopping ToscaExecutionClient..."
exit 1
}
# Start status polling
log "INF" "Starting execution status polling with an interval of $pollingInterval seconds..."
$executionTimeout = $(getTimestamp) + $clientTimeout
while( ($(getTimestamp) -le $executionTimeout) -and -not ($executionStatus -like "*Completed*") -and -not ($executionStatus -eq "Error") -and -not ($executionStatus -eq "Cancelled") ) {
fetchExecutionStatus
log "INF" "Status of execution with id ""${executionId}"": ""${executionStatus}"""
if ( $fetchPartialResults -eq $true ) {
# Fetch partial results for the execution
log "INF" "Fetching partial results ..."
# Fetch partial results
fetchExecutionResults $true
# Write partial results
writeResults $true
}
log "INF" "Starting next polling cycle in $pollingInterval seconds..."
Start-Sleep -Seconds $pollingInterval
}
# Check for execution status after results polling
if ( ($executionStatus -like "*Completed*") -or ($executionStatus -eq "Error") -or ($executionStatus -eq "Cancelled") ) {
log "INF" "Execution with id ""${executionId}"" finished."
# Fetch results when execution is finished
fetchExecutionResults $false
# Write execution results
writeResults $false
log "INF" "Stopping ToscaExecutionClient..."
exit 0
} else {
log "ERR" "Execution exceeded clientTimeout of $clientTimeout seconds. Stopping ToscaExecutionClient..."
exit 1
}