-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathJobOutputWindow.xaml.cs
435 lines (408 loc) · 20.8 KB
/
JobOutputWindow.xaml.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
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using System.Diagnostics;
using System.Net;
using System.Timers;
using Microsoft.Azure.Management.Automation.Models;
using AutomationISE.Model;
namespace AutomationISE
{
/// <summary>
/// Interaction logic for TestJobOutputWindow.xaml
/// </summary>
public partial class JobOutputWindow : Window
{
private JobCreateResponse jobCreateResponse = null;
private AutomationISEClient iseClient;
private String runbookName;
private String runbookType;
private System.Timers.Timer refreshTimer;
private static int TIMEOUT_MS = 30000;
private JobStreamListParameters jobParams = new JobStreamListParameters();
private bool cancelOutput = false;
private List<String> processedStreamIDs = new List<String>();
/* These values are the defaults for the settings visible using PS>(Get-Host).PrivateData */
public static String ErrorForegroundColorCode = "#FFFF0000";
public static String ErrorBackgroundColorCode = "#00FFFFFF";
public static String WarningForegroundColorCode = "#FFFF8C00";
public static String WarningBackgroundColorCode = "#00FFFFFF";
public static String VerboseForegroundColorCode = "#FF00FFFF";
public static String VerboseBackgroundColorCode = "#00FFFFFF";
public JobOutputWindow(AutomationRunbook runbook, AutomationISEClient client, int refreshTimerValue)
{
InitializeComponent();
StartJobButton.IsEnabled = true;
StopJobButton.IsEnabled = false;
this.Title = runbook.Name + " Test Job";
AdditionalInformation.Text = "Tip: not seeing Verbose output? Add the line \"$VerbosePreference='Continue'\" to your runbook.";
runbookName = runbook.Name;
runbookType = runbook.RunbookType;
iseClient = client;
jobParams.Time = DateTime.UtcNow.AddDays(-30).ToString("o");
Task t = checkTestJob(true);
refreshTimer = new System.Timers.Timer();
refreshTimer.Interval = refreshTimerValue;
refreshTimer.Elapsed += new ElapsedEventHandler(refresh);
}
//TODO: refactor this to a different class with some inheritance structure
public JobOutputWindow(String name, JobCreateResponse response, AutomationISEClient client, int refreshTimerValue)
{
InitializeComponent();
StartJobButton.IsEnabled = true;
StopJobButton.IsEnabled = false;
this.Title = "Job: " + name;
AdditionalInformation.Text = "This is a Global Runbook responsible for syncing your GitHub repo with your Automation Account. Neato!";
runbookName = name;
jobCreateResponse = response;
iseClient = client;
jobParams.Time = DateTime.UtcNow.AddDays(-30).ToString("o");
Task t = checkJob();
refreshTimer = new System.Timers.Timer();
refreshTimer.Interval = refreshTimerValue;
refreshTimer.Elapsed += new ElapsedEventHandler(refresh);
}
private async Task checkTestJob(bool showWarning = false)
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
TestJobGetResponse response = await iseClient.automationManagementClient.TestJobs.GetAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, runbookName, cts.Token);
// Set cancel output to false so we show the output of this job
cancelOutput = false;
if (showWarning)
{
JobDetails.FontWeight = FontWeights.Bold;
JobDetails.Content = "This is a past test job for " + runbookName + " created at " + response.TestJob.CreationTime.LocalDateTime;
}
else
{
JobDetails.FontWeight = FontWeights.Normal;
JobDetails.Content = runbookName + " test job created at " + response.TestJob.CreationTime.LocalDateTime;
}
JobDetails.Content += "\r\nLast refreshed at " + DateTime.Now;
JobStatus.Content = response.TestJob.Status;
if (response.TestJob.Status == "Failed")
{
updateJobOutputTextBlockWithException(response.TestJob.Exception);
StartJobButton.IsEnabled = true;
StopJobButton.IsEnabled = false;
}
else
{
cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
JobStreamListResponse jslResponse = await iseClient.automationManagementClient.JobStreams.ListTestJobStreamsAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, runbookName, jobParams, cts.Token);
if (jslResponse.JobStreams.Count > 0)
{
jobParams.Time = jslResponse.JobStreams.Last().Properties.Time.UtcDateTime.ToString("o");
}
/* Write out each stream's output */
foreach (JobStream stream in jslResponse.JobStreams)
{
// If cancelOutput is set to true, then we should break out and stop writing output
if (cancelOutput) break;
cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
var jslStream = await iseClient.automationManagementClient.JobStreams.GetTestJobStreamAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, runbookName, stream.Properties.JobStreamId, cts.Token);
// Current issue sending back previous streams so ensuring we have not already processed the job before outputing
if ((processedStreamIDs.IndexOf(stream.Properties.JobStreamId) == -1))
{
processedStreamIDs.Add(stream.Properties.JobStreamId);
updateJobOutputTextBlock(jslStream);
}
}
if (response.TestJob.Status == "Suspended")
{
updateJobOutputTextBlockWithException(response.TestJob.Exception);
StartJobButton.IsEnabled = false;
StopJobButton.IsEnabled = true;
}
else if (response.TestJob.Status == "Completed")
{
StartJobButton.IsEnabled = true;
StopJobButton.IsEnabled = false;
}
else if (response.TestJob.Status == "Stopped")
{
StartJobButton.IsEnabled = true;
StopJobButton.IsEnabled = false;
}
else if (!IsRetryStatusCode(response.StatusCode))
{
StartJobButton.IsEnabled = true;
StopJobButton.IsEnabled = false;
}
else
{
StartJobButton.IsEnabled = false;
StopJobButton.IsEnabled = true;
refreshTimer.Enabled = true;
}
}
}
private async Task checkJob()
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
JobGetResponse response = await iseClient.automationManagementClient.Jobs.GetAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, jobCreateResponse.Job.Properties.JobId, cts.Token);
JobDetails.Content = runbookName + " test job created at " + response.Job.Properties.CreationTime.LocalDateTime;
JobDetails.Content += "\r\nLast refreshed at " + DateTime.Now;
JobStatus.Content = response.Job.Properties.Status;
cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
JobStreamListResponse jslResponse = await iseClient.automationManagementClient.JobStreams.ListAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, jobCreateResponse.Job.Properties.JobId, jobParams, cts.Token);
foreach (JobStream stream in jslResponse.JobStreams)
{
cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
var jslStream = await iseClient.automationManagementClient.JobStreams.GetAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, jobCreateResponse.Job.Properties.JobId, stream.Properties.JobStreamId, cts.Token);
if (jslStream.JobStream.Properties.Time.DateTime > Convert.ToDateTime(jobParams.Time))
{
jobParams.Time = stream.Properties.Time.ToString("o");
updateJobOutputTextBlock(jslStream);
}
}
refreshTimer.Enabled = true;
}
private void updateJobOutputTextBlock(JobStreamGetResponse stream)
{
String streamText = stream.JobStream.Properties.StreamText;
OutputTextBlockParagraph.Inlines.Add("\r\n");
if (stream.JobStream.Properties.StreamType == "Output")
{
OutputTextBlockParagraph.Inlines.Add(streamText);
}
else if (stream.JobStream.Properties.StreamType == "Verbose")
{
streamText = "VERBOSE: " + streamText;
OutputTextBlockParagraph.Inlines.Add(new Run(streamText)
{
Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom(VerboseForegroundColorCode)),
Background = (SolidColorBrush)(new BrushConverter().ConvertFrom(VerboseBackgroundColorCode))
});
}
else if (stream.JobStream.Properties.StreamType == "Error")
{
streamText = "ERROR: " + streamText;
OutputTextBlockParagraph.Inlines.Add(new Run(streamText)
{
Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom(ErrorForegroundColorCode)),
Background = (SolidColorBrush)(new BrushConverter().ConvertFrom(ErrorBackgroundColorCode))
});
}
else if (stream.JobStream.Properties.StreamType == "Warning")
{
streamText = "WARNING: " + streamText;
OutputTextBlockParagraph.Inlines.Add(new Run(streamText)
{
Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom(WarningForegroundColorCode)),
Background = (SolidColorBrush)(new BrushConverter().ConvertFrom(WarningBackgroundColorCode))
});
}
else
{
Debug.WriteLine("Unknown stream type couldn't be colored properly: " + stream.JobStream.Properties.StreamType);
OutputTextBlockParagraph.Inlines.Add(stream.JobStream.Properties.StreamType.ToUpper() + ": " + streamText);
}
OutputTextBlock.ScrollToEnd();
}
private void updateJobOutputTextBlockWithException(string exceptionMessage)
{
OutputTextBlockParagraph.Inlines.Add("\r\n");
OutputTextBlockParagraph.Inlines.Add(new Run(exceptionMessage)
{
Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom(ErrorForegroundColorCode)),
Background = (SolidColorBrush)(new BrushConverter().ConvertFrom(ErrorBackgroundColorCode))
});
}
private void refresh(object source, ElapsedEventArgs e)
{
try
{
refreshTimer.Enabled = false;
this.Dispatcher.Invoke(() =>
{
Task t;
if (jobCreateResponse != null)
t = checkJob();
else
t = checkTestJob();
});
}
catch (Exception exception)
{
System.Windows.Forms.MessageBox.Show(exception.Message, "Refresh Failure", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
refreshTimer.Enabled = true;
}
}
private async void StopJobButton_Click(object sender, RoutedEventArgs e)
{
try
{
StopJobButton.IsEnabled = false;
StopJobButton.Content = "Stopping...";
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
Microsoft.Azure.AzureOperationResponse response = await iseClient.automationManagementClient.TestJobs.StopAsync(
iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, runbookName, cts.Token);
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception("The job couldn't be stopped.\r\nReceived status code: " + response.StatusCode);
JobStatus.Content = "Submitted job stop request";
}
catch (Exception exception)
{
System.Windows.Forms.MessageBox.Show(exception.Message, "Job Stop Failure", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
finally
{
StopJobButton.IsEnabled = true;
StopJobButton.Content = "Stop Job";
}
}
private async Task<IDictionary<string, string>> GetLastTestJobParams()
{
try {
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
TestJobGetResponse response = await iseClient.automationManagementClient.TestJobs.GetAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, runbookName, cts.Token);
IDictionary<string, string> jobParams = response.TestJob.Parameters;
return jobParams;
}
catch
{
// return null if test job not found.
return null;
}
}
private async Task<TestJobGetResponse> GetLastTestJob()
{
try
{
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
return await iseClient.automationManagementClient.TestJobs.GetAsync(iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, runbookName, cts.Token);
}
catch
{
// return null if test job not found.
return null;
}
}
private async void StartJobButton_Click(object sender, RoutedEventArgs e)
{
try
{
StartJobButton.IsEnabled = false;
processedStreamIDs.Clear();
cancelOutput = true;
refreshTimer.Stop();
jobParams.Time = DateTime.UtcNow.AddDays(-30).ToString("o");
TestJobCreateResponse response = await createTestJob();
if (response != null)
{
OutputTextBlockParagraph.Inlines.Clear();
JobDetails.FontWeight = FontWeights.Regular;
JobDetails.Content = runbookName + " test job created at " + response.TestJob.CreationTime.LocalDateTime;
JobStatus.Content = response.TestJob.Status;
StopJobButton.IsEnabled = true;
}
else
{
StartJobButton.IsEnabled = true;
}
}
catch (Exception exception)
{
System.Windows.Forms.MessageBox.Show(exception.Message, "Job Start Failure", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
}
finally
{
refreshTimer.Start();
}
}
private async Task<TestJobCreateResponse> createTestJob()
{
RunbookDraft draft = await AutomationRunbookManager.GetRunbookDraft(runbookName, iseClient.automationManagementClient,
iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name);
if (draft.InEdit == false)
throw new Exception("This runbook has no draft to test because it is in a 'Published' state.");
HybridRunbookWorkerGroupsListResponse hybridGroupResponse = await iseClient.automationManagementClient.HybridRunbookWorkerGroups.ListAsync(
iseClient.accountResourceGroups[iseClient.currAccount].Name, iseClient.currAccount.Name,
new CancellationToken());
TestJobCreateParameters jobCreationParams = new TestJobCreateParameters();
jobCreationParams.RunbookName = runbookName;
if (draft.Parameters.Count > 0 || hybridGroupResponse.HybridRunbookWorkerGroups.Count > 0)
{
/* User needs to specify some things */
// var existingParams = await GetLastTestJobParams();
IDictionary<string, string> existingParams = null;
String lastRunOn = null;
var lastJob = await GetLastTestJob();
if (lastJob != null)
{
existingParams = lastJob.TestJob.Parameters;
lastRunOn = lastJob.TestJob.RunOn;
}
// IDictionary<string, string> jobParams = response.TestJob.Parameters;
RunbookParamDialog paramDialog = new RunbookParamDialog(draft.Parameters, existingParams, lastRunOn, hybridGroupResponse.HybridRunbookWorkerGroups,runbookType);
if (paramDialog.ShowDialog() == true)
{
if (runbookType == "Python2")
jobCreationParams.Parameters = paramDialog.paramValues;
else
{
if (draft.Parameters.Count > 0)
jobCreationParams.Parameters = paramDialog.paramValues;
}
if (!String.IsNullOrEmpty(paramDialog.runOnSelection) && !paramDialog.runOnSelection.Equals("Azure"))
jobCreationParams.RunOn = paramDialog.runOnSelection;
}
else
{
return null;
}
}
/* start the test job */
CancellationTokenSource cts = new CancellationTokenSource();
cts.CancelAfter(TIMEOUT_MS);
TestJobCreateResponse jobResponse = await iseClient.automationManagementClient.TestJobs.CreateAsync(
iseClient.accountResourceGroups[iseClient.currAccount].Name,
iseClient.currAccount.Name, jobCreationParams, cts.Token);
if (jobResponse == null || jobResponse.StatusCode != System.Net.HttpStatusCode.Created)
throw new Exception("The test job could not be created: received HTTP status code " + jobResponse.StatusCode);
return jobResponse;
}
private static bool IsRetryStatusCode(HttpStatusCode statusCode)
{
switch (statusCode)
{
case HttpStatusCode.OK:
case HttpStatusCode.Accepted:
case HttpStatusCode.NoContent:
return true;
case HttpStatusCode.BadRequest:
case HttpStatusCode.Unauthorized:
case HttpStatusCode.Forbidden:
case HttpStatusCode.NotFound:
case HttpStatusCode.InternalServerError:
return false;
default:
return true;
}
}
}
}