-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
AbstractCIBase.java
281 lines (250 loc) · 11.5 KB
/
AbstractCIBase.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
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi,
* Erik Ramfelt, Koichi Fujikawa, Red Hat, Inc., Seiji Sogabe,
* Stephen Connolly, Tom Huybrechts, Yahoo! Inc., Alan Harder, CloudBees, Inc.
*
* 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 edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.security.AccessControlled;
import hudson.slaves.ComputerListener;
import hudson.slaves.RetentionStrategy;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import jenkins.model.Jenkins;
import jenkins.util.Listeners;
import jenkins.util.SystemProperties;
import org.kohsuke.stapler.StaplerFallback;
import org.kohsuke.stapler.StaplerProxy;
public abstract class AbstractCIBase extends Node implements ItemGroup<TopLevelItem>, StaplerProxy, StaplerFallback, ViewGroup, AccessControlled, DescriptorByNameOwner {
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for script console")
public static boolean LOG_STARTUP_PERFORMANCE = SystemProperties.getBoolean(Jenkins.class.getName() + "." + "logStartupPerformance", false);
private static final Logger LOGGER = Logger.getLogger(AbstractCIBase.class.getName());
/**
* If you are calling this on Hudson something is wrong.
*
* @deprecated
* Maybe you were trying to call {@link #getDisplayName()}.
*/
@NonNull
@Deprecated @Override
public String getNodeName() {
return "";
}
/**
* @deprecated
* Why are you calling a method that always returns ""?
* You probably want to call {@link Jenkins#getRootUrl()}
*/
@Override
@Deprecated
public String getUrl() {
return "";
}
/* =================================================================================================================
* Support functions that can only be accessed through package-protected
* ============================================================================================================== */
protected void resetLabel(Label l) {
l.reset();
}
protected void setViewOwner(View v) {
v.owner = this;
}
protected void interruptReloadThread() {
ViewJob.interruptReloadThread();
}
protected void killComputer(Computer c) {
c.kill();
}
private final Set<String> disabledAdministrativeMonitors = new HashSet<>();
/**
* Get the disabled administrative monitors
*
* @since 2.230
*/
public Set<String> getDisabledAdministrativeMonitors() {
synchronized (this.disabledAdministrativeMonitors) {
return new HashSet<>(disabledAdministrativeMonitors);
}
}
/**
* Set the disabled administrative monitors
*
* @since 2.230
*/
public void setDisabledAdministrativeMonitors(Set<String> disabledAdministrativeMonitors) {
synchronized (this.disabledAdministrativeMonitors) {
this.disabledAdministrativeMonitors.clear();
this.disabledAdministrativeMonitors.addAll(disabledAdministrativeMonitors);
}
}
/* =================================================================================================================
* Implementation provided
* ============================================================================================================== */
/**
* Returns all {@link Node}s in the system, excluding {@link jenkins.model.Jenkins} instance itself which
* represents the built-in node in this context.
*/
public abstract List<Node> getNodes();
public abstract Queue getQueue();
protected abstract ConcurrentMap<Node, Computer> getComputerMap();
/* =================================================================================================================
* Computer API uses package protection heavily
* ============================================================================================================== */
private void updateComputer(Node n, Map<String, Computer> byNameMap, Set<Computer> used, boolean automaticAgentLaunch) {
Computer c = byNameMap.get(n.getNodeName());
if (c != null) {
try {
c.setNode(n); // reuse
used.add(c);
} catch (RuntimeException e) {
LOGGER.log(Level.WARNING, "Error updating node " + n.getNodeName() + ", continuing", e);
}
} else {
c = createNewComputerForNode(n, automaticAgentLaunch);
if (c != null) {
used.add(c);
}
}
}
@CheckForNull
private Computer createNewComputerForNode(Node n, boolean automaticAgentLaunch) {
Computer c = null;
ConcurrentMap<Node, Computer> computers = getComputerMap();
// we always need Computer for the built-in node as a fallback in case there's no other Computer.
if (n.getNumExecutors() > 0 || n == Jenkins.get()) {
// The start/connect of a new computer is potentially costly, so we don't want to perform it inside
// computeIfAbsent. Instead, we use this creationWasAttempted flag to signal if start/connect is needed or
// not.
final AtomicBoolean creationWasAttempted = new AtomicBoolean(false);
try {
c = computers.computeIfAbsent(n, node -> {
creationWasAttempted.set(true);
return node.createComputer();
});
} catch (RuntimeException ex) { // Just in case there is a bogus extension
LOGGER.log(Level.WARNING, "Error retrieving computer for node " + n.getNodeName() + ", continuing", ex);
}
if (!creationWasAttempted.get()) {
LOGGER.log(Level.FINE, "Node {0} is not a new node skipping", n.getNodeName());
return null;
}
if (c == null) {
LOGGER.log(Level.WARNING, "Cannot create computer for node {0}, the {1}#createComputer() method returned null. Skipping this node",
new Object[]{n.getNodeName(), n.getClass().getName()});
return null;
}
if (!n.isHoldOffLaunchUntilSave() && automaticAgentLaunch) {
RetentionStrategy retentionStrategy = c.getRetentionStrategy();
if (retentionStrategy != null) {
// if there is a retention strategy, it is responsible for deciding to start the computer
retentionStrategy.start(c);
} else {
// we should never get here, but just in case, we'll fall back to the legacy behaviour
c.connect(true);
}
}
return c;
} else {
// TODO: Maybe it should be allowed, but we would just get NPE in the original logic before JENKINS-43496
LOGGER.log(Level.WARNING, "Node {0} has no executors. Cannot update the Computer instance of it", n.getNodeName());
return null;
}
}
/*package*/ void removeComputer(final Computer computer) {
ConcurrentMap<Node, Computer> computers = getComputerMap();
Queue.withLock(() -> {
if (computers.values().remove(computer)) {
computer.onRemoved();
}
});
}
/*package*/ @CheckForNull Computer getComputer(Node n) {
ConcurrentMap<Node, Computer> computers = getComputerMap();
return computers.get(n);
}
protected void updateNewComputer(final Node n, boolean automaticAgentLaunch) {
if (createNewComputerForNode(n, automaticAgentLaunch) == null) {
return;
}
getQueue().scheduleMaintenance();
Listeners.notify(ComputerListener.class, false, ComputerListener::onConfigurationChange);
}
/**
* Updates Computers.
*
* <p>
* This method tries to reuse existing {@link Computer} objects
* so that we won't upset {@link Executor}s running in it.
*/
protected void updateComputerList(final boolean automaticAgentLaunch) {
final ConcurrentMap<Node, Computer> computers = getComputerMap();
final Set<Computer> old = new HashSet<>(computers.size());
Queue.withLock(new Runnable() {
@Override
public void run() {
Map<String, Computer> byName = new HashMap<>();
for (Computer c : computers.values()) {
old.add(c);
Node node = c.getNode();
if (node == null)
continue; // this computer is gone
byName.put(node.getNodeName(), c);
}
Set<Computer> used = new HashSet<>(old.size());
updateComputer(AbstractCIBase.this, byName, used, automaticAgentLaunch);
for (Node s : getNodes()) {
long start = System.currentTimeMillis();
updateComputer(s, byName, used, automaticAgentLaunch);
if (LOG_STARTUP_PERFORMANCE && LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine(String.format("Took %dms to update node %s",
System.currentTimeMillis() - start, s.getNodeName()));
}
}
// find out what computers are removed, and kill off all executors.
// when all executors exit, it will be removed from the computers map.
// so don't remove too quickly
old.removeAll(used);
// we need to start the process of reducing the executors on all computers as distinct
// from the killing action which should not excessively use the Queue lock.
for (Computer c : old) {
c.inflictMortalWound();
}
}
});
for (Computer c : old) {
// when we get to here, the number of executors should be zero so this call should not need the Queue.lock
killComputer(c);
}
getQueue().scheduleMaintenance();
Listeners.notify(ComputerListener.class, false, ComputerListener::onConfigurationChange);
}
}