-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathJenkinsJobRunner.cs
More file actions
321 lines (251 loc) · 12.5 KB
/
JenkinsJobRunner.cs
File metadata and controls
321 lines (251 loc) · 12.5 KB
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
using JenkinsNET.Exceptions;
using JenkinsNET.Models;
using System;
using System.Collections.Generic;
using System.Threading;
#if NET_ASYNC
using System.Threading.Tasks;
#endif
namespace JenkinsNET.Utilities
{
/// <summary>
/// Represents the method that will handle an
/// event when the job status has changed.
/// </summary>
public delegate void StatusChangedEventHandler();
/// <summary>
/// Represents a method that will handle an
/// event when the job console output has changed.
/// </summary>
public delegate void ConsoleOutputChangedEventHandler(string newText);
/// <summary>
/// Begins building a Jenkins Job, and polls the status
/// until the job has completed.
/// </summary>
public class JenkinsJobRunner
{
public JenkinsClient Client {get;}
protected ProgressiveTextReader textReader;
protected bool isJobStarted;
/// <summary>
/// Occurs when the status of the running Jenkins Job changes.
/// </summary>
public event StatusChangedEventHandler StatusChanged;
/// <summary>
/// Occurs when the Console Output of the
/// running Jenkins Job has changed.
/// </summary>
public event ConsoleOutputChangedEventHandler ConsoleOutputChanged;
/// <summary>
/// Gets the status of the running Jenkins Job.
/// </summary>
public JenkinsJobStatus Status {get; protected set;}
/// <summary>
/// Gets or sets whether the Jobs Console Output
/// should be monitored. Default value is false.
/// </summary>
public bool MonitorConsoleOutput {get; set;}
/// <summary>
/// Time in milliseconds to wait between requests.
/// Default value is 500.
/// </summary>
public int PollInterval {get; set;} = 500;
/// <summary>
/// Maximum time in seconds to wait for job to be queued.
/// Default value is 60 (one minute).
/// </summary>
public int QueueTimeout {get; set;} = 60;
/// <summary>
/// Maximum time in seconds to wait for job to complete.
/// Default value is 600 (10 minutes).
/// </summary>
public int BuildTimeout {get; set;} = 600;
/// <summary>
/// Returns the Console Output of the currently running Jenkins Job.
/// </summary>
public string ConsoleOutput => textReader?.Text;
/// <summary>
/// Gets the number of the current Queue item.
/// </summary>
public int? QueueItemNumber {get; protected set;}
/// <summary>
/// Gets the number of the current Build.
/// </summary>
public int? BuildNumber {get; protected set;}
/// <summary>
/// Creates a new JobRunner using the provided Jenkins-Client.
/// </summary>
public JenkinsJobRunner(JenkinsClient client)
{
this.Client = client ?? throw new ArgumentNullException(nameof(client));
}
/// <summary>
/// Run the Job.
/// </summary>
/// <param name="jobName">The name of the Job to run.</param>
/// <exception cref="JenkinsNetException"></exception>
/// <exception cref="JenkinsJobBuildException"></exception>
/// <exception cref="JenkinsJobGetBuildException"></exception>
public JenkinsBuildBase Run(string jobName)
{
if (isJobStarted) throw new JenkinsNetException("This JobRunner instance has already been started! Separate JenkinsJobRunner instances are required to run multiple jobs.");
isJobStarted = true;
SetStatus(JenkinsJobStatus.Pending);
var queueStartTime = DateTime.Now;
var buildResult = Client.Jobs.Build(jobName);
if (buildResult == null)
throw new JenkinsJobBuildException("An empty build response was returned!");
return Process(jobName, buildResult, queueStartTime);
}
#if NET_ASYNC
/// <summary>
/// Run the Job asynchronously.
/// </summary>
/// <param name="jobName">The name of the Job to run.</param>
/// <exception cref="JenkinsNetException"></exception>
/// <exception cref="JenkinsJobBuildException"></exception>
/// <exception cref="JenkinsJobGetBuildException"></exception>
public async Task<JenkinsBuildBase> RunAsync(string jobName)
{
if (isJobStarted) throw new JenkinsNetException("This JobRunner instance has already been started! Separate JenkinsJobRunner instances are required to run multiple jobs.");
isJobStarted = true;
SetStatus(JenkinsJobStatus.Pending);
var queueStartTime = DateTime.Now;
var buildResult = await Client.Jobs.BuildAsync(jobName);
if (buildResult == null)
throw new JenkinsJobBuildException("An empty build response was returned!");
return await ProcessAsync(jobName, buildResult, queueStartTime);
}
#endif
/// <summary>
/// Run the Job with parameters.
/// </summary>
/// <param name="jobName">The name of the Job to run.</param>
/// <param name="jobParameters">The parameters used to start the Job.</param>
/// <exception cref="JenkinsNetException"></exception>
/// <exception cref="JenkinsJobBuildException"></exception>
/// <exception cref="JenkinsJobGetBuildException"></exception>
public JenkinsBuildBase RunWithParameters(string jobName, IDictionary<string, string> jobParameters)
{
if (isJobStarted) throw new JenkinsNetException("This JobRunner instance has already been started! Separate JenkinsJobRunner instances are required to run multiple jobs.");
isJobStarted = true;
SetStatus(JenkinsJobStatus.Pending);
var queueStartTime = DateTime.Now;
var buildResult = Client.Jobs.BuildWithParameters(jobName, jobParameters);
if (buildResult == null)
throw new JenkinsJobBuildException("An empty build response was returned!");
return Process(jobName, buildResult, queueStartTime);
}
#if NET_ASYNC
/// <summary>
/// Run the Job asynchronously with parameters.
/// </summary>
/// <param name="jobName">The name of the Job to run.</param>
/// <param name="jobParameters">The parameters used to start the Job.</param>
/// <exception cref="JenkinsNetException"></exception>
/// <exception cref="JenkinsJobBuildException"></exception>
/// <exception cref="JenkinsJobGetBuildException"></exception>
public async Task<JenkinsBuildBase> RunWithParametersAsync(string jobName, IDictionary<string, string> jobParameters)
{
if (isJobStarted) throw new JenkinsNetException("This JobRunner instance has already been started! Separate JenkinsJobRunner instances are required to run multiple jobs.");
isJobStarted = true;
SetStatus(JenkinsJobStatus.Pending);
var queueStartTime = DateTime.Now;
var buildResult = await Client.Jobs.BuildWithParametersAsync(jobName, jobParameters);
if (buildResult == null)
throw new JenkinsJobBuildException("An empty build response was returned!");
return await ProcessAsync(jobName, buildResult, queueStartTime);
}
#endif
/// <exception cref="JenkinsNetException"></exception>
/// <exception cref="JenkinsJobBuildException"></exception>
/// <exception cref="JenkinsJobGetBuildException"></exception>
private JenkinsBuildBase Process(string jobName, JenkinsBuildResult buildResult, DateTime queueStartTime)
{
QueueItemNumber = buildResult.GetQueueItemNumber();
if (!QueueItemNumber.HasValue) throw new JenkinsNetException("Queue-Item number not found!");
SetStatus(JenkinsJobStatus.Queued);
while (true) {
if (!QueueItemNumber.HasValue) throw new JenkinsNetException("Queue-Item number not found!");
var queueItem = Client.Queue.GetItem(QueueItemNumber.Value);
BuildNumber = queueItem?.Executable?.Number;
if (BuildNumber.HasValue) break;
if (QueueTimeout > 0 && DateTime.Now.Subtract(queueStartTime).TotalSeconds > QueueTimeout)
throw new JenkinsNetException("Timeout occurred while waiting for build to start!");
Thread.Sleep(PollInterval);
}
if (!BuildNumber.HasValue) throw new JenkinsNetException("Build number not found!");
SetStatus(JenkinsJobStatus.Building);
var buildStartTime = DateTime.Now;
textReader = new ProgressiveTextReader(Client, jobName, BuildNumber.ToString());
textReader.TextChanged += TextReader_TextChanged;
JenkinsBuildBase buildItem = null;
do
{
Thread.Sleep(PollInterval);
if (BuildTimeout > 0 && DateTime.Now.Subtract(buildStartTime).TotalSeconds > BuildTimeout)
throw new JenkinsNetException("Timeout occurred while waiting for build to complete!");
if (MonitorConsoleOutput && !textReader.IsComplete)
textReader.Update();
buildItem = Client.Builds.Get<JenkinsBuildBase>(jobName, BuildNumber.Value.ToString());
} while (buildItem.Building == null || (bool) buildItem.Building);
while (MonitorConsoleOutput && !textReader.IsComplete) {
textReader.Update();
}
SetStatus(JenkinsJobStatus.Complete);
return buildItem;
}
#if NET_ASYNC
/// <exception cref="JenkinsNetException"></exception>
/// <exception cref="JenkinsJobBuildException"></exception>
/// <exception cref="JenkinsJobGetBuildException"></exception>
private async Task<JenkinsBuildBase> ProcessAsync(string jobName, JenkinsBuildResult buildResult, DateTime queueStartTime)
{
QueueItemNumber = buildResult.GetQueueItemNumber();
if (!QueueItemNumber.HasValue) throw new JenkinsNetException("Queue-Item number not found!");
SetStatus(JenkinsJobStatus.Queued);
while (true) {
if (!QueueItemNumber.HasValue) throw new JenkinsNetException("Queue-Item number not found!");
var queueItem = await Client.Queue.GetItemAsync(QueueItemNumber.Value);
BuildNumber = queueItem?.Executable?.Number;
if (BuildNumber.HasValue) break;
if (QueueTimeout > 0 && DateTime.Now.Subtract(queueStartTime).TotalSeconds > QueueTimeout)
throw new JenkinsNetException("Timeout occurred while waiting for build to start!");
await Task.Delay(PollInterval);
}
SetStatus(JenkinsJobStatus.Building);
var buildStartTime = DateTime.Now;
textReader = new ProgressiveTextReader(Client, jobName, BuildNumber.ToString());
textReader.TextChanged += TextReader_TextChanged;
JenkinsBuildBase buildItem = null;
while (string.IsNullOrEmpty(buildItem?.Result)) {
if (!BuildNumber.HasValue) throw new JenkinsNetException("Build number not found!");
buildItem = await Client.Builds.GetAsync<JenkinsBuildBase>(jobName, BuildNumber.Value.ToString());
if (!string.IsNullOrEmpty(buildItem?.Result)) break;
if (BuildTimeout > 0 && DateTime.Now.Subtract(buildStartTime).TotalSeconds > BuildTimeout)
throw new JenkinsNetException("Timeout occurred while waiting for build to complete!");
if (MonitorConsoleOutput && !textReader.IsComplete)
await textReader.UpdateAsync();
await Task.Delay(PollInterval);
}
while (MonitorConsoleOutput && !textReader.IsComplete) {
await textReader.UpdateAsync();
}
SetStatus(JenkinsJobStatus.Complete);
return buildItem;
}
#endif
private void TextReader_TextChanged(string newText)
{
ConsoleOutputChanged?.Invoke(newText);
}
private void SetStatus(JenkinsJobStatus newStatus)
{
Status = newStatus;
try {
StatusChanged?.Invoke();
}
catch {}
}
}
}