-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
/
ExtensionList.java
468 lines (420 loc) · 15.6 KB
/
ExtensionList.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
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, 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;
import com.google.common.collect.Lists;
import hudson.init.InitMilestone;
import hudson.model.Hudson;
import jenkins.ExtensionComponentSet;
import jenkins.model.Jenkins;
import hudson.util.AdaptedIterator;
import hudson.util.DescriptorList;
import hudson.util.Iterators;
import hudson.ExtensionPoint.LegacyInstancesAreScopedToHudson;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import jenkins.util.io.OnMaster;
/**
* Retains the known extension instances for the given type 'T'.
*
* <p>
* Extensions are loaded lazily on demand and automatically by using {@link ExtensionFinder}, but this
* class also provides a mechanism to provide compatibility with the older {@link DescriptorList}-based
* manual registration,
*
* <p>
* All {@link ExtensionList} instances should be owned by {@link jenkins.model.Jenkins}, even though
* extension points can be defined by anyone on any type. Use {@link jenkins.model.Jenkins#getExtensionList(Class)}
* and {@link jenkins.model.Jenkins#getDescriptorList(Class)} to obtain the instances.
*
* @param <T>
* Type of the extension point. This class holds instances of the subtypes of 'T'.
*
* @author Kohsuke Kawaguchi
* @since 1.286
* @see jenkins.model.Jenkins#getExtensionList(Class)
* @see jenkins.model.Jenkins#getDescriptorList(Class)
*/
public class ExtensionList<T> extends AbstractList<T> implements OnMaster {
/**
* @deprecated as of 1.417
* Use {@link #jenkins}
*/
@Deprecated
public final Hudson hudson;
public final @CheckForNull Jenkins jenkins;
public final Class<T> extensionType;
/**
* Once discovered, extensions are retained here.
*/
@CopyOnWrite
private volatile List<ExtensionComponent<T>> extensions;
private final List<ExtensionListListener> listeners = new CopyOnWriteArrayList<>();
/**
* Place to store manually registered instances with the per-Hudson scope.
* {@link CopyOnWriteArrayList} is used here to support concurrent iterations and mutation.
*/
private final CopyOnWriteArrayList<ExtensionComponent<T>> legacyInstances;
/**
* @deprecated as of 1.416
* Use {@link #ExtensionList(Jenkins, Class)}
*/
@Deprecated
protected ExtensionList(Hudson hudson, Class<T> extensionType) {
this((Jenkins)hudson,extensionType);
}
protected ExtensionList(Jenkins jenkins, Class<T> extensionType) {
this(jenkins,extensionType, new CopyOnWriteArrayList<>());
}
/**
* @deprecated as of 1.416
* Use {@link #ExtensionList(Jenkins, Class, CopyOnWriteArrayList)}
*/
@Deprecated
protected ExtensionList(Hudson hudson, Class<T> extensionType, CopyOnWriteArrayList<ExtensionComponent<T>> legacyStore) {
this((Jenkins)hudson,extensionType,legacyStore);
}
/**
*
* @param legacyStore
* Place to store manually registered instances. The version of the constructor that
* omits this uses a new {@link Vector}, making the storage lifespan tied to the life of {@link ExtensionList}.
* If the manually registered instances are scoped to VM level, the caller should pass in a static list.
*/
protected ExtensionList(Jenkins jenkins, Class<T> extensionType, CopyOnWriteArrayList<ExtensionComponent<T>> legacyStore) {
this.hudson = (Hudson)jenkins;
this.jenkins = jenkins;
this.extensionType = extensionType;
this.legacyInstances = legacyStore;
if (jenkins == null) {
extensions = Collections.emptyList();
}
}
/**
* Add a listener to the extension list.
* @param listener The listener.
*/
public void addListener(@Nonnull ExtensionListListener listener) {
listeners.add(listener);
}
/**
* Looks for the extension instance of the given type (subclasses excluded),
* or return null.
*/
public @CheckForNull <U extends T> U get(@Nonnull Class<U> type) {
for (T ext : this)
if(ext.getClass()==type)
return type.cast(ext);
return null;
}
/**
* Looks for the extension instance of the given type (subclasses excluded),
* or throws an IllegalStateException.
*
* Meant to simplify call inside @Extension annotated class to retrieve their own instance.
*/
public @Nonnull <U extends T> U getInstance(@Nonnull Class<U> type) throws IllegalStateException {
for (T ext : this)
if(ext.getClass()==type)
return type.cast(ext);
throw new IllegalStateException("The class " + type.getName() + " was not found, potentially not yet loaded");
}
@Override
public @Nonnull Iterator<T> iterator() {
// we need to intercept mutation, so for now don't allow Iterator.remove
return new AdaptedIterator<ExtensionComponent<T>,T>(Iterators.readOnly(ensureLoaded().iterator())) {
protected T adapt(ExtensionComponent<T> item) {
return item.getInstance();
}
};
}
/**
* Gets the same thing as the 'this' list represents, except as {@link ExtensionComponent}s.
*/
public List<ExtensionComponent<T>> getComponents() {
return Collections.unmodifiableList(ensureLoaded());
}
public T get(int index) {
return ensureLoaded().get(index).getInstance();
}
public int size() {
return ensureLoaded().size();
}
/**
* Gets the read-only view of this {@link ExtensionList} where components are reversed.
*/
public List<T> reverseView() {
return new AbstractList<T>() {
@Override
public T get(int index) {
return ExtensionList.this.get(size()-index-1);
}
@Override
public int size() {
return ExtensionList.this.size();
}
};
}
@Override
public boolean remove(Object o) {
try {
return removeSync(o);
} finally {
if(extensions!=null) {
fireOnChangeListeners();
}
}
}
@Override
public boolean removeAll(Collection<?> c) {
boolean removed = false;
try {
for (Object o : c) {
removed |= removeSync(o);
}
return removed;
} finally {
if (extensions != null && removed) {
fireOnChangeListeners();
}
}
}
private synchronized boolean removeSync(Object o) {
boolean removed = removeComponent(legacyInstances, o);
if(extensions!=null) {
List<ExtensionComponent<T>> r = new ArrayList<>(extensions);
removed |= removeComponent(r,o);
extensions = sort(r);
}
return removed;
}
private <T> boolean removeComponent(Collection<ExtensionComponent<T>> collection, Object t) {
for (ExtensionComponent<T> c : collection) {
if (c.getInstance().equals(t)) {
return collection.remove(c);
}
}
return false;
}
@Override
public final synchronized T remove(int index) {
T t = get(index);
remove(t);
return t;
}
/**
* Write access will put the instance into a legacy store.
*
* @deprecated since 2009-02-23.
* Prefer automatic registration.
*/
@Override
@Deprecated
public boolean add(T t) {
try {
return addSync(t);
} finally {
if(extensions!=null) {
fireOnChangeListeners();
}
}
}
private synchronized boolean addSync(T t) {
legacyInstances.add(new ExtensionComponent<>(t));
// if we've already filled extensions, add it
if(extensions!=null) {
List<ExtensionComponent<T>> r = new ArrayList<>(extensions);
r.add(new ExtensionComponent<>(t));
extensions = sort(r);
}
return true;
}
@Override
public void add(int index, T element) {
add(element);
}
/**
* Used to bind extension to URLs by their class names.
*
* @since 1.349
*/
public T getDynamic(String className) {
for (T t : this)
if (t.getClass().getName().equals(className))
return t;
return null;
}
private List<ExtensionComponent<T>> ensureLoaded() {
if(extensions!=null)
return extensions; // already loaded
if (jenkins.getInitLevel().compareTo(InitMilestone.PLUGINS_PREPARED)<0)
return legacyInstances; // can't perform the auto discovery until all plugins are loaded, so just make the legacy instances visible
synchronized (getLoadLock()) {
if(extensions==null) {
List<ExtensionComponent<T>> r = load();
r.addAll(legacyInstances);
extensions = sort(r);
}
return extensions;
}
}
/**
* Chooses the object that locks the loading of the extension instances.
*/
protected Object getLoadLock() {
return jenkins.lookup.setIfNull(Lock.class,new Lock());
}
/**
* Used during {@link Jenkins#refreshExtensions()} to add new components into existing {@link ExtensionList}s.
* Do not call from anywhere else.
*/
public void refresh(ExtensionComponentSet delta) {
boolean fireOnChangeListeners = false;
synchronized (getLoadLock()) {
if (extensions==null)
return; // not yet loaded. when we load it, we'll load everything visible by then, so no work needed
Collection<ExtensionComponent<T>> found = load(delta);
if (!found.isEmpty()) {
List<ExtensionComponent<T>> l = Lists.newArrayList(extensions);
l.addAll(found);
extensions = sort(l);
fireOnChangeListeners = true;
}
}
if (fireOnChangeListeners) {
fireOnChangeListeners();
}
}
private void fireOnChangeListeners() {
for (ExtensionListListener listener : listeners) {
try {
listener.onChange();
} catch (Exception e) {
LOGGER.log(Level.SEVERE, "Error firing ExtensionListListener.onChange().", e);
}
}
}
/**
* Loading an {@link ExtensionList} can result in a nested loading of another {@link ExtensionList}.
* What that means is that we need a single lock that spans across all the {@link ExtensionList}s,
* or else we can end up in a dead lock.
*/
private static final class Lock {}
/**
* Loads all the extensions.
*/
protected List<ExtensionComponent<T>> load() {
if (LOGGER.isLoggable(Level.FINE))
LOGGER.log(Level.FINE,"Loading ExtensionList: "+extensionType, new Throwable());
return jenkins.getPluginManager().getPluginStrategy().findComponents(extensionType, hudson);
}
/**
* Picks up extensions that we care from the given list.
*/
protected Collection<ExtensionComponent<T>> load(ExtensionComponentSet delta) {
return delta.find(extensionType);
}
/**
* If the {@link ExtensionList} implementation requires sorting extensions,
* override this method to do so.
*
* <p>
* The implementation should copy a list, do a sort, and return the new instance.
*/
protected List<ExtensionComponent<T>> sort(List<ExtensionComponent<T>> r) {
r = new ArrayList<>(r);
Collections.sort(r);
return r;
}
/**
* @deprecated as of 1.416
* Use {@link #create(Jenkins, Class)}
*/
@Deprecated
public static <T> ExtensionList<T> create(Hudson hudson, Class<T> type) {
return create((Jenkins)hudson,type);
}
@SuppressWarnings({"unchecked", "rawtypes"})
public static <T> ExtensionList<T> create(Jenkins jenkins, Class<T> type) {
if(type.getAnnotation(LegacyInstancesAreScopedToHudson.class)!=null)
return new ExtensionList<>(jenkins, type);
else {
return new ExtensionList(jenkins, type, staticLegacyInstances.computeIfAbsent(type, key -> new CopyOnWriteArrayList()));
}
}
/**
* Gets the extension list for a given type.
* Normally calls {@link Jenkins#getExtensionList(Class)} but falls back to an empty list
* in case {@link Jenkins#getInstanceOrNull()} is null.
* Thus it is useful to call from {@code all()} methods which need to behave gracefully during startup or shutdown.
* @param type the extension point type
* @return some list
* @since 1.572
*/
public static @Nonnull <T> ExtensionList<T> lookup(Class<T> type) {
Jenkins j = Jenkins.getInstanceOrNull();
return j == null ? create((Jenkins) null, type) : j.getExtensionList(type);
}
/**
* Convenience method allowing lookup of the only instance of a given type.
* Equivalent to {@code ExtensionList.lookup(Class).get(Class)} if there is one instance,
* and throws an {@code IllegalStateException} otherwise.
*
* @param type The type to look up.
* @return the singleton instance of the given type in its list.
* @throws IllegalStateException if there are no instances, or more than one
*
* @since 2.87
*/
public static @Nonnull <U> U lookupSingleton(Class<U> type) {
ExtensionList<U> all = lookup(type);
if (all.size() != 1) {
throw new IllegalStateException("Expected 1 instance of " + type.getName() + " but got " + all.size());
}
return all.get(0);
}
/**
* Places to store static-scope legacy instances.
*/
@SuppressWarnings("rawtypes")
private static final Map<Class, CopyOnWriteArrayList> staticLegacyInstances = new ConcurrentHashMap<>();
/**
* Exposed for the test harness to clear all legacy extension instances.
*/
public static void clearLegacyInstances() {
staticLegacyInstances.clear();
}
private static final Logger LOGGER = Logger.getLogger(ExtensionList.class.getName());
}