-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
LoadStatistics.java
651 lines (580 loc) · 23.5 KB
/
LoadStatistics.java
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
651
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Seiji Sogabe
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.model;
import hudson.Extension;
import hudson.model.MultiStageTimeSeries.TimeScale;
import hudson.model.MultiStageTimeSeries.TrendChart;
import hudson.model.queue.SubTask;
import hudson.util.ColorPalette;
import hudson.util.NoOverlapCategoryAxis;
import jenkins.model.Jenkins;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.ui.RectangleInsets;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.export.Exported;
import java.awt.*;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.List;
import javax.annotation.CheckForNull;
/**
* Utilization statistics for a node or a set of nodes.
*
* <h2>Implementation Note</h2>
* <p>
* Instances of this class is not capable of updating the statistics itself
* — instead, it's done by the {@link LoadStatisticsUpdater} timer.
* This is more efficient (as it allows us a single pass to update all stats),
* but it's not clear to me if the loss of autonomy is worth it.
*
* @author Kohsuke Kawaguchi
* @see Label#loadStatistics
* @see Jenkins#overallLoad
* @see Jenkins#unlabeledLoad
*/
@ExportedBean
public abstract class LoadStatistics {
/**
* {@code true} if and only if the new way of building statistics has been implemented by this class.
* @since 1.607
*/
private final boolean modern;
/**
* Number of executors defined for Jenkins and how it changes over time.
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries definedExecutors;
/**
* Number of executors on-line and how it changes over time. Replaces {@link #totalExecutors}
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries onlineExecutors;
/**
* Number of executors in the process of coming on-line and how it changes over time.
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries connectingExecutors;
/**
* Number of busy executors and how it changes over time.
*/
@Exported
public final MultiStageTimeSeries busyExecutors;
/**
* Number of executors not executing and how it changes over time. Note the these executors may not be able to
* take work, see {@link #availableExecutors}.
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries idleExecutors;
/**
* Number of executors not executing and available to take work and how it changes over time.
* @since 1.607
*/
@Exported
public final MultiStageTimeSeries availableExecutors;
/**
* Number of total executors and how it changes over time.
* @deprecated use {@link #onlineExecutors}. Note {@code totalExecutors==onlineExecutors} for backward
* compatibility support.
*/
@Exported
@Deprecated
public final MultiStageTimeSeries totalExecutors;
/**
* Number of {@link hudson.model.Queue.BuildableItem}s that can run on any node in this node set but blocked.
*/
@Exported
public final MultiStageTimeSeries queueLength;
protected LoadStatistics(int initialOnlineExecutors, int initialBusyExecutors) {
this.definedExecutors = new MultiStageTimeSeries(Messages._LoadStatistics_Legends_DefinedExecutors(),
ColorPalette.YELLOW, initialOnlineExecutors, DECAY);
this.onlineExecutors = new MultiStageTimeSeries(
Messages._LoadStatistics_Legends_OnlineExecutors(), ColorPalette.BLUE, initialOnlineExecutors,DECAY);
this.connectingExecutors = new MultiStageTimeSeries(Messages._LoadStatistics_Legends_ConnectingExecutors(),
ColorPalette.YELLOW, 0, DECAY);
this.busyExecutors = new MultiStageTimeSeries(
Messages._LoadStatistics_Legends_BusyExecutors(), ColorPalette.RED, initialBusyExecutors,DECAY);
this.idleExecutors = new MultiStageTimeSeries(Messages._LoadStatistics_Legends_IdleExecutors(),
ColorPalette.YELLOW, initialOnlineExecutors - initialBusyExecutors, DECAY);
this.availableExecutors = new MultiStageTimeSeries(Messages._LoadStatistics_Legends_AvailableExecutors(),
ColorPalette.YELLOW, initialOnlineExecutors - initialBusyExecutors, DECAY);
this.queueLength = new MultiStageTimeSeries(
Messages._LoadStatistics_Legends_QueueLength(),ColorPalette.GREY, 0, DECAY);
this.totalExecutors = onlineExecutors;
modern = isModern(getClass());
}
/*package*/ static boolean isModern(Class<? extends LoadStatistics> clazz) {
// cannot use Util.isOverridden as these are protected methods.
boolean hasGetNodes = false;
boolean hasMatches = false;
while (clazz != LoadStatistics.class && clazz != null && !(hasGetNodes && hasMatches)) {
if (!hasGetNodes) {
try {
final Method getNodes = clazz.getDeclaredMethod("getNodes");
hasGetNodes = !Modifier.isAbstract(getNodes.getModifiers());
} catch (NoSuchMethodException e) {
// ignore
}
}
if (!hasMatches) {
try {
final Method getNodes = clazz.getDeclaredMethod("matches", Queue.Item.class, SubTask.class);
hasMatches = !Modifier.isAbstract(getNodes.getModifiers());
} catch (NoSuchMethodException e) {
// ignore
}
}
if (!(hasGetNodes && hasMatches) && LoadStatistics.class.isAssignableFrom(clazz.getSuperclass())) {
clazz = (Class<? extends LoadStatistics>) clazz.getSuperclass();
}
}
return hasGetNodes && hasMatches;
}
/**
* @deprecated use {@link #idleExecutors} directly.
*/
@Deprecated
public float getLatestIdleExecutors(TimeScale timeScale) {
return idleExecutors.pick(timeScale).getLatest();
}
/**
* Computes the # of idle executors right now and obtains the snapshot value.
* @deprecated use {@link #computeSnapshot()} and then {@link LoadStatisticsSnapshot#getIdleExecutors()}
*/
@Deprecated
public abstract int computeIdleExecutors();
/**
* Computes the # of total executors right now and obtains the snapshot value.
* @deprecated use {@link #computeSnapshot()} and then {@link LoadStatisticsSnapshot#getOnlineExecutors()}
*/
@Deprecated
public abstract int computeTotalExecutors();
/**
* Computes the # of queue length right now and obtains the snapshot value.
* @deprecated use {@link #computeSnapshot()} and then {@link LoadStatisticsSnapshot#getQueueLength()}
*/
@Deprecated
public abstract int computeQueueLength();
/**
* Creates a trend chart.
*/
public JFreeChart createChart(CategoryDataset ds) {
final JFreeChart chart = ChartFactory.createLineChart(null, // chart title
null, // unused
null, // range axis label
ds, // data
PlotOrientation.VERTICAL, // orientation
true, // include legend
true, // tooltips
false // urls
);
chart.setBackgroundPaint(Color.white);
final CategoryPlot plot = chart.getCategoryPlot();
plot.setBackgroundPaint(Color.WHITE);
plot.setOutlinePaint(null);
plot.setRangeGridlinesVisible(true);
plot.setRangeGridlinePaint(Color.black);
final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
renderer.setBaseStroke(new BasicStroke(3));
configureRenderer(renderer);
final CategoryAxis domainAxis = new NoOverlapCategoryAxis(null);
plot.setDomainAxis(domainAxis);
domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
domainAxis.setLowerMargin(0.0);
domainAxis.setUpperMargin(0.0);
domainAxis.setCategoryMargin(0.0);
final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
// crop extra space around the graph
plot.setInsets(new RectangleInsets(0, 0, 0, 5.0));
return chart;
}
protected void configureRenderer(LineAndShapeRenderer renderer) {
renderer.setSeriesPaint(0, ColorPalette.BLUE); // online
renderer.setSeriesPaint(1, ColorPalette.RED); // busy
renderer.setSeriesPaint(2, ColorPalette.GREY); // queue
renderer.setSeriesPaint(3, ColorPalette.YELLOW);// available
}
/**
* Creates {@link CategoryDataset} which then becomes the basis
* of the load statistics graph.
*/
public TrendChart createTrendChart(TimeScale timeScale) {
return MultiStageTimeSeries.createTrendChart(timeScale,onlineExecutors,busyExecutors,queueLength,availableExecutors);
}
/**
* Generates the load statistics graph.
*/
public TrendChart doGraph(@QueryParameter String type) throws IOException {
return createTrendChart(TimeScale.parse(type));
}
public Api getApi() {
return new Api(this);
}
/**
* @deprecated use {@link #updateCounts(LoadStatisticsSnapshot)}
*/
@Deprecated
protected void updateExecutorCounts() {
updateCounts(computeSnapshot());
}
/**
* Updates all the series from the current snapshot.
* @param current the current snapshot.
* @since 1.607
*/
protected void updateCounts(LoadStatisticsSnapshot current) {
definedExecutors.update(current.getDefinedExecutors());
onlineExecutors.update(current.getOnlineExecutors());
connectingExecutors.update(current.getConnectingExecutors());
busyExecutors.update(current.getBusyExecutors());
idleExecutors.update(current.getIdleExecutors());
availableExecutors.update(current.getAvailableExecutors());
queueLength.update(current.getQueueLength());
}
/**
* Returns the {@link Node} instances that this statistic counts.
* @return the {@link Node}
* @since 1.607
*/
protected abstract Iterable<Node> getNodes();
/**
* Returns {@code true} is the specified {@link SubTask} from the {@link Queue} should be counted.
* @param item the {@link Queue.Item} that the {@link SubTask belongs to}
* @param subTask the {@link SubTask}
* @return {@code true} IFF the specified {@link SubTask} from the {@link Queue} should be counted.
* @since 1.607
*/
protected abstract boolean matches(Queue.Item item, SubTask subTask);
/**
* Computes a self-consistent snapshot of the load statistics.
*
* Note: The original method of computing load statistics would compute the total and idle counts independently
* which could lead to counting errors while jobs started in between the different state counting operations.
* By returning a {@link LoadStatisticsSnapshot} we get a single consistent view of the counts which was valid
* for at least one point in time during the execution of this method.
*
* @return a self-consistent snapshot of the load statistics.
* @since 1.607
*/
public LoadStatisticsSnapshot computeSnapshot() {
if (modern) {
return computeSnapshot(Jenkins.getInstance().getQueue().getBuildableItems());
} else {
int t = computeTotalExecutors();
int i = computeIdleExecutors();
return new LoadStatisticsSnapshot(t, t, Math.max(i-t,0), Math.max(t-i,0), i, i, computeQueueLength());
}
}
/**
* Computes the self-consistent snapshot with the specified queue items.
* @param queue the queue items.
* @return a self-consistent snapshot of the load statistics.
* @since 1.607
*/
protected LoadStatisticsSnapshot computeSnapshot(Iterable<Queue.BuildableItem> queue) {
final LoadStatisticsSnapshot.Builder builder = LoadStatisticsSnapshot.builder();
final Iterable<Node> nodes = getNodes();
if (nodes != null) {
for (Node node : nodes) {
builder.with(node);
}
}
int q = 0;
if (queue != null) {
for (Queue.BuildableItem item : queue) {
for (SubTask st : item.task.getSubTasks()) {
if (matches(item, st))
q++;
}
}
}
return builder.withQueueLength(q).build();
}
/**
* With 0.90 decay ratio for every 10sec, half reduction is about 1 min.
*
* Put differently, the half reduction time is {@code CLOCK*log(0.5)/log(DECAY)}
*/
public static final float DECAY = Float.parseFloat(System.getProperty(LoadStatistics.class.getName()+".decay","0.9"));
/**
* Load statistics clock cycle in milliseconds. Specify a small value for quickly debugging this feature and node provisioning through cloud.
*/
public static int CLOCK = Integer.getInteger(LoadStatistics.class.getName() + ".clock", 10 * 1000);
/**
* Periodically update the load statistics average.
*/
@Extension
public static class LoadStatisticsUpdater extends PeriodicWork {
public long getRecurrencePeriod() {
return CLOCK;
}
protected void doRun() {
Jenkins j = Jenkins.getInstance();
List<Queue.BuildableItem> bis = j.getQueue().getBuildableItems();
// update statistics on slaves
for( Label l : j.getLabels() ) {
l.loadStatistics.updateCounts(l.loadStatistics.computeSnapshot(bis));
}
// update statistics of the entire system
j.unlabeledLoad.updateCounts(j.unlabeledLoad.computeSnapshot(bis));
j.overallLoad.updateCounts(j.overallLoad.computeSnapshot(bis));
}
}
/**
* Holds a snapshot of the current statistics.
* @since 1.607
*/
@ExportedBean
public static class LoadStatisticsSnapshot implements Serializable {
private static final long serialVersionUID = 1L;
/**
* The total number of executors that Jenkins currently knows, this includes all off-line slaves.
*/
private final int definedExecutors;
/**
* The total number of executors that are currently on-line.
*/
private final int onlineExecutors;
/**
* The total number of executors that are currently in the process of connecting to Jenkins.
*/
private final int connectingExecutors;
/**
* The total number of executors that are currently busy running jobs.
*/
private final int busyExecutors;
/**
* The total number of executors that are currently on-line and idle. This includes executors that are
* not accepting tasks.
*/
private final int idleExecutors;
/**
* The total number of executors that are currently on-line, idle and accepting tasks.
*/
private final int availableExecutors;
/**
* The number of items in the queue.
*/
private final int queueLength;
private LoadStatisticsSnapshot(
int definedExecutors, int onlineExecutors, int connectingExecutors,
int busyExecutors, int idleExecutors, int availableExecutors,
int queueLength) {
this.definedExecutors = definedExecutors;
this.onlineExecutors = onlineExecutors;
this.connectingExecutors = connectingExecutors;
// assert definedExecutors == onlineExecutors + connectingExecutors;
this.busyExecutors = busyExecutors;
this.idleExecutors = idleExecutors;
// assert onlineExecutors == busyExecutors + idleExecutors;
this.availableExecutors = availableExecutors;
// assert availableExecutors <= idleExecutors;
this.queueLength = queueLength;
}
/**
* The total number of executors that Jenkins currently knows, this includes all off-line slaves.
*/
@Exported
public int getDefinedExecutors() {
return definedExecutors;
}
/**
* The total number of executors that are currently on-line.
*/
@Exported
public int getOnlineExecutors() {
return onlineExecutors;
}
/**
* The total number of executors that are currently in the process of connecting to Jenkins.
*/
@Exported
public int getConnectingExecutors() {
return connectingExecutors;
}
/**
* The total number of executors that are currently busy running jobs.
*/
@Exported
public int getBusyExecutors() {
return busyExecutors;
}
/**
* The total number of executors that are currently on-line and idle. This includes executors that are
* not accepting tasks.
*/
@Exported
public int getIdleExecutors() {
return idleExecutors;
}
/**
* The total number of executors that are currently on-line, idle and accepting tasks.
*/
@Exported
public int getAvailableExecutors() {
return availableExecutors;
}
/**
* The number of items in the queue.
*/
@Exported
public int getQueueLength() {
return queueLength;
}
/** {@inheritDoc} */
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
LoadStatisticsSnapshot that = (LoadStatisticsSnapshot) o;
if (availableExecutors != that.availableExecutors) {
return false;
}
if (busyExecutors != that.busyExecutors) {
return false;
}
if (connectingExecutors != that.connectingExecutors) {
return false;
}
if (definedExecutors != that.definedExecutors) {
return false;
}
if (idleExecutors != that.idleExecutors) {
return false;
}
if (onlineExecutors != that.onlineExecutors) {
return false;
}
if (queueLength != that.queueLength) {
return false;
}
return true;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int result = definedExecutors;
result = 31 * result + onlineExecutors;
result = 31 * result + connectingExecutors;
result = 31 * result + busyExecutors;
result = 31 * result + idleExecutors;
result = 31 * result + availableExecutors;
result = 31 * result + queueLength;
return result;
}
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("LoadStatisticsSnapshot{");
sb.append("definedExecutors=").append(definedExecutors);
sb.append(", onlineExecutors=").append(onlineExecutors);
sb.append(", connectingExecutors=").append(connectingExecutors);
sb.append(", busyExecutors=").append(busyExecutors);
sb.append(", idleExecutors=").append(idleExecutors);
sb.append(", availableExecutors=").append(availableExecutors);
sb.append(", queueLength=").append(queueLength);
sb.append('}');
return sb.toString();
}
/**
* Use a builder so we can add more stats if needed.
* Not thread safe
* @since 1.607
*/
public static class Builder {
private int definedExecutors;
private int onlineExecutors;
private int connectingExecutors;
private int busyExecutors;
private int idleExecutors;
private int availableExecutors;
private int queueLength;
public LoadStatisticsSnapshot build() {
return new LoadStatisticsSnapshot(
definedExecutors, onlineExecutors, connectingExecutors,
busyExecutors, idleExecutors, availableExecutors,
queueLength
);
}
public Builder withQueueLength(int queueLength) {
this.queueLength = queueLength;
return this;
}
public Builder with(@CheckForNull Node node) {
if (node != null) {
return with(node.toComputer());
}
return this;
}
public Builder with(@CheckForNull Computer computer) {
if (computer == null) {
return this;
}
if (computer.isOnline()) {
final List<Executor> executors = computer.getExecutors();
final boolean acceptingTasks = computer.isAcceptingTasks();
for (Executor e : executors) {
definedExecutors++;
onlineExecutors++;
if (e.getCurrentWorkUnit() != null) {
busyExecutors++;
} else {
idleExecutors++;
if (acceptingTasks) availableExecutors++;
}
}
} else {
final int numExecutors = computer.getNumExecutors();
definedExecutors += numExecutors;
if (computer.isConnecting()) {
connectingExecutors += numExecutors;
}
}
return this;
}
}
public static Builder builder() {
return new Builder();
}
}
}