forked from jenkinsci/remoting
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Engine.java
1142 lines (1044 loc) · 48.7 KB
/
Engine.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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* 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.remoting;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.remoting.Channel.Mode;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URI;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import java.security.AccessController;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPublicKey;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import jakarta.websocket.ClientEndpointConfig;
import jakarta.websocket.CloseReason;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.Endpoint;
import jakarta.websocket.EndpointConfig;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.Session;
import net.jcip.annotations.NotThreadSafe;
import org.jenkinsci.remoting.engine.Jnlp4ConnectionState;
import org.jenkinsci.remoting.engine.JnlpAgentEndpoint;
import org.jenkinsci.remoting.engine.JnlpAgentEndpointConfigurator;
import org.jenkinsci.remoting.engine.JnlpAgentEndpointResolver;
import org.jenkinsci.remoting.engine.JnlpConnectionState;
import org.jenkinsci.remoting.engine.JnlpConnectionStateListener;
import org.jenkinsci.remoting.engine.JnlpEndpointResolver;
import org.jenkinsci.remoting.engine.JnlpProtocolHandler;
import org.jenkinsci.remoting.engine.JnlpProtocolHandlerFactory;
import org.jenkinsci.remoting.engine.WorkDirManager;
import org.jenkinsci.remoting.protocol.IOHub;
import org.jenkinsci.remoting.protocol.cert.BlindTrustX509ExtendedTrustManager;
import org.jenkinsci.remoting.protocol.cert.DelegatingX509ExtendedTrustManager;
import org.jenkinsci.remoting.protocol.cert.PublicKeyMatchingX509ExtendedTrustManager;
import org.jenkinsci.remoting.protocol.impl.ConnectionRefusalException;
import org.jenkinsci.remoting.util.KeyUtils;
import org.jenkinsci.remoting.util.VersionNumber;
/**
* Agent engine that proactively connects to Jenkins controller.
*
* @author Kohsuke Kawaguchi
*/
@NotThreadSafe // the fields in this class should not be modified by multiple threads concurrently
public class Engine extends Thread {
/**
* HTTP header sent by Jenkins to indicate the earliest version of Remoting it is prepared to accept connections from.
*/
public static final String REMOTING_MINIMUM_VERSION_HEADER = "X-Remoting-Minimum-Version";
/**
* The header name to be used for the connection cookie when using websockets.
*/
public static final String WEBSOCKET_COOKIE_HEADER = "Connection-Cookie";
/**
* Thread pool that sets {@link #CURRENT}.
*/
private final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
private final ThreadFactory defaultFactory = Executors.defaultThreadFactory();
@Override
public Thread newThread(@NonNull final Runnable r) {
Thread thread = defaultFactory.newThread(() -> {
CURRENT.set(Engine.this);
r.run();
});
thread.setDaemon(true);
thread.setUncaughtExceptionHandler((t, e) -> LOGGER.log(Level.SEVERE, e, () -> "Uncaught exception in thread " + t));
return thread;
}
});
/**
* @deprecated
* Use {@link #events}.
*/
@Deprecated
public final EngineListener listener;
private final EngineListenerSplitter events = new EngineListenerSplitter();
/**
* To make Jenkins more graceful against user error,
* JNLP agent can try to connect to multiple possible Jenkins URLs.
* This field specifies those candidate URLs, such as
* "http://foo.bar/jenkins/".
*/
private final List<URL> candidateUrls;
/**
* The list of {@link X509Certificate} instances to trust when connecting to any of the {@link #candidateUrls}
* or {@code null} to use the JVM default trust store.
*/
private List<X509Certificate> candidateCertificates;
/**
* URL that points to Jenkins's tcp agent listener, like {@code http://myhost/hudson/}
*
* <p>
* This value is determined from {@link #candidateUrls} after a successful connection.
* Note that this URL <b>DOES NOT</b> have "tcpSlaveAgentListener" in it.
*/
@CheckForNull
private URL hudsonUrl;
private final String secretKey;
private final String agentName;
private boolean webSocket;
private Map<String, String> webSocketHeaders;
private String credentials;
private String protocolName;
private String proxyCredentials = System.getProperty("proxyCredentials");
/**
* See {@link hudson.remoting.jnlp.Main#tunnel} for the documentation.
*/
@CheckForNull
private String tunnel;
private boolean disableHttpsCertValidation = false;
private boolean noReconnect = false;
/**
* Determines whether the socket will have {@link Socket#setKeepAlive(boolean)} set or not.
*
* @since 2.62.1
*/
private boolean keepAlive = true;
@CheckForNull
private JarCache jarCache = null;
/**
* Specifies a destination for the agent log.
* If specified, this option overrides the default destination within {@link #workDir}.
* If both this options and {@link #workDir} is not set, the log will not be generated.
* @since 3.8
*/
@CheckForNull
private Path agentLog;
/**
* Specified location of the property file with JUL settings.
* @since 3.8
*/
@CheckForNull
private Path loggingConfigFilePath = null;
/**
* Specifies a default working directory of the remoting instance.
* If specified, this directory will be used to store logs, JAR cache, etc.
* <p>
* In order to retain compatibility, the option is disabled by default.
* <p>
* Jenkins specifics: This working directory is expected to be equal to the agent root specified in Jenkins configuration.
* @since 3.8
*/
@CheckForNull
public Path workDir = null;
/**
* Specifies a directory within {@link #workDir}, which stores all the remoting-internal files.
* <p>
* This option is not expected to be used frequently, but it allows remoting users to specify a custom
* storage directory if the default {@code remoting} directory is consumed by other stuff.
* @since 3.8
*/
@NonNull
public String internalDir = WorkDirManager.DirType.INTERNAL_DIR.getDefaultLocation();
/**
* Fail the initialization if the workDir or internalDir are missing.
* This option presumes that the workspace structure gets initialized previously in order to ensure that we do not start up with a borked instance
* (e.g. if a filesystem mount gets disconnected).
* @since 3.8
*/
public boolean failIfWorkDirIsMissing = WorkDirManager.DEFAULT_FAIL_IF_WORKDIR_IS_MISSING;
private final DelegatingX509ExtendedTrustManager agentTrustManager = new DelegatingX509ExtendedTrustManager(new BlindTrustX509ExtendedTrustManager());
private final String directConnection;
private final String instanceIdentity;
private final Set<String> protocols;
public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String agentName) {
this(listener, hudsonUrls, secretKey, agentName, null, null, null);
}
public Engine(EngineListener listener, List<URL> hudsonUrls, String secretKey, String agentName, String directConnection, String instanceIdentity,
Set<String> protocols) {
this.listener = listener;
this.directConnection = directConnection;
this.events.add(listener);
this.candidateUrls = hudsonUrls.stream().map(Engine::ensureTrailingSlash).collect(Collectors.toList());
this.secretKey = secretKey;
this.agentName = agentName;
this.instanceIdentity = instanceIdentity;
this.protocols = protocols;
if(candidateUrls.isEmpty() && instanceIdentity == null) {
throw new IllegalArgumentException("No URLs given");
}
setUncaughtExceptionHandler((t, e) -> {
LOGGER.log(Level.SEVERE, e, () -> "Uncaught exception in Engine thread " + t);
interrupt();
});
}
private static URL ensureTrailingSlash(URL u) {
if (u.toString().endsWith("/")) {
return u;
} else {
try {
return new URL(u + "/");
} catch (MalformedURLException x) {
throw new IllegalArgumentException(x);
}
}
}
/**
* Starts the engine.
* The procedure initializes the working directory and all the required environment
* @throws IOException Initialization error
* @since 3.9
*/
public synchronized void startEngine() throws IOException {
startEngine(false);
}
/**
* Starts engine.
* @param dryRun If {@code true}, do not actually start the engine.
* This method can be used for testing startup logic.
*/
/*package*/ void startEngine(boolean dryRun) throws IOException {
LOGGER.log(Level.INFO, "Using Remoting version: {0}", Launcher.VERSION);
@CheckForNull File jarCacheDirectory = null;
// Prepare the working directory if required
if (workDir != null) {
final WorkDirManager workDirManager = WorkDirManager.getInstance();
if (jarCache != null) {
// Somebody has already specificed Jar Cache, hence we do not need it in the workspace.
workDirManager.disable(WorkDirManager.DirType.JAR_CACHE_DIR);
}
if (loggingConfigFilePath != null) {
workDirManager.setLoggingConfig(loggingConfigFilePath.toFile());
}
final Path path = workDirManager.initializeWorkDir(workDir.toFile(), internalDir, failIfWorkDirIsMissing);
jarCacheDirectory = workDirManager.getLocation(WorkDirManager.DirType.JAR_CACHE_DIR);
workDirManager.setupLogging(path, agentLog);
} else if (jarCache == null) {
LOGGER.log(Level.WARNING, "No Working Directory. Using the legacy JAR Cache location: {0}", JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION);
jarCacheDirectory = JarCache.DEFAULT_NOWS_JAR_CACHE_LOCATION;
}
if (jarCache == null){
if (jarCacheDirectory == null) {
// Should never happen in the current code
throw new IOException("Cannot find the JAR Cache location");
}
LOGGER.log(Level.FINE, "Using standard File System JAR Cache. Root Directory is {0}", jarCacheDirectory);
try {
jarCache = new FileSystemJarCache(jarCacheDirectory, true);
} catch (IllegalArgumentException ex) {
throw new IOException("Failed to initialize FileSystem JAR Cache in " + jarCacheDirectory, ex);
}
} else {
LOGGER.log(Level.INFO, "Using custom JAR Cache: {0}", jarCache);
}
// Start the engine thread
if (!dryRun) {
this.start();
}
}
/**
* Configures custom JAR Cache location.
* This option disables JAR Caching in the working directory.
* @param jarCache JAR Cache to be used
* @since 2.24
*/
public void setJarCache(@NonNull JarCache jarCache) {
this.jarCache = jarCache;
}
/**
* Sets path to the property file with JUL settings.
* @param filePath JAR Cache to be used
* @since 3.8
*/
public void setLoggingConfigFile(@NonNull Path filePath) {
this.loggingConfigFilePath = filePath;
}
/**
* Provides Jenkins URL if available.
* @return Jenkins URL. May return {@code null} if the connection is not established or if the URL cannot be determined
* in the {@link JnlpAgentEndpointResolver}.
*/
@CheckForNull
public URL getHudsonUrl() {
return hudsonUrl;
}
public void setWebSocket(boolean webSocket) {
this.webSocket = webSocket;
}
/**
* Sets map of custom websocket headers. These headers will be applied to the websocket connection to Jenkins.
*
* @param webSocketHeaders a map of the headers to apply to the websocket connection
*/
public void setWebSocketHeaders(@NonNull Map<String, String> webSocketHeaders) {
this.webSocketHeaders = webSocketHeaders;
}
/**
* If set, connect to the specified host and port instead of connecting directly to Jenkins.
* @param tunnel Value. {@code null} to disable tunneling
*/
public void setTunnel(@CheckForNull String tunnel) {
this.tunnel = tunnel;
}
public void setCredentials(String creds) {
this.credentials = creds;
}
public void setProxyCredentials(String proxyCredentials) {
this.proxyCredentials = proxyCredentials;
}
public void setNoReconnect(boolean noReconnect) {
this.noReconnect = noReconnect;
}
/**
* Determines if JNLPAgentEndpointResolver will not perform certificate validation in the HTTPs mode.
*
* @return {@code true} if the certificate validation is disabled.
*/
public boolean isDisableHttpsCertValidation() {
return disableHttpsCertValidation;
}
/**
* Sets if JNLPAgentEndpointResolver will not perform certificate validation in the HTTPs mode.
*
* @param disableHttpsCertValidation {@code true} if the certificate validation is disabled.
*/
public void setDisableHttpsCertValidation(boolean disableHttpsCertValidation) {
this.disableHttpsCertValidation = disableHttpsCertValidation;
}
/**
* Sets the destination for agent logs.
* @param agentLog Path to the agent log.
* If {@code null}, the engine will pick the default behavior depending on the {@link #workDir} value
* @since 3.8
*/
public void setAgentLog(@CheckForNull Path agentLog) {
this.agentLog = agentLog;
}
/**
* Specified a path to the work directory.
* @param workDir Path to the working directory of the remoting instance.
* {@code null} Disables the working directory.
* @since 3.8
*/
public void setWorkDir(@CheckForNull Path workDir) {
this.workDir = workDir;
}
/**
* Specifies name of the internal data directory within {@link #workDir}.
* @param internalDir Directory name
* @since 3.8
*/
public void setInternalDir(@NonNull String internalDir) {
this.internalDir = internalDir;
}
/**
* Sets up behavior if the workDir or internalDir are missing during the startup.
* This option presumes that the workspace structure gets initialized previously in order to ensure that we do not start up with a borked instance
* (e.g. if a filesystem mount gets disconnected).
* @param failIfWorkDirIsMissing Flag
* @since 3.8
*/
public void setFailIfWorkDirIsMissing(boolean failIfWorkDirIsMissing) { this.failIfWorkDirIsMissing = failIfWorkDirIsMissing; }
/**
* Returns {@code true} if and only if the socket to the controller will have {@link Socket#setKeepAlive(boolean)} set.
*
* @return {@code true} if and only if the socket to the controller will have {@link Socket#setKeepAlive(boolean)} set.
*/
public boolean isKeepAlive() {
return keepAlive;
}
/**
* Sets the {@link Socket#setKeepAlive(boolean)} to use for the connection to the controller.
*
* @param keepAlive the {@link Socket#setKeepAlive(boolean)} to use for the connection to the controller.
*/
public void setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
}
public void setCandidateCertificates(List<X509Certificate> candidateCertificates) {
this.candidateCertificates = candidateCertificates == null
? null
: new ArrayList<>(candidateCertificates);
}
public void addCandidateCertificate(X509Certificate certificate) {
if (candidateCertificates == null) {
candidateCertificates = new ArrayList<>();
}
candidateCertificates.add(certificate);
}
public void addListener(EngineListener el) {
events.add(el);
}
public void removeListener(EngineListener el) {
events.remove(el);
}
@Override
@SuppressFBWarnings(value = "HARD_CODE_PASSWORD", justification = "Password doesn't need to be protected.")
public void run() {
if (webSocket) {
runWebSocket();
return;
}
// Create the engine
try {
try (IOHub hub = IOHub.create(executor)) {
SSLContext context;
// prepare our SSLContext
try {
context = SSLContext.getInstance("TLS");
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Java runtime specification requires support for TLS algorithm", e);
}
char[] password = "password".toCharArray();
KeyStore store;
try {
store = KeyStore.getInstance(KeyStore.getDefaultType());
} catch (KeyStoreException e) {
throw new IllegalStateException("Java runtime specification requires support for JKS key store", e);
}
try {
store.load(null, password);
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Java runtime specification requires support for JKS key store", e);
} catch (CertificateException e) {
throw new IllegalStateException("Empty keystore", e);
}
KeyManagerFactory kmf;
try {
kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("Java runtime specification requires support for default key manager", e);
}
try {
kmf.init(store, password);
} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
throw new IllegalStateException(e);
}
try {
context.init(kmf.getKeyManagers(), new TrustManager[]{agentTrustManager}, null);
} catch (KeyManagementException e) {
events.error(e);
return;
}
innerRun(hub, context, executor);
}
} catch (IOException e) {
events.error(e);
}
}
@SuppressFBWarnings(value = {"REC_CATCH_EXCEPTION", "URLCONNECTION_SSRF_FD"}, justification = "checked exceptions were a mistake to begin with; connecting to Jenkins from agent")
private void runWebSocket() {
try {
String localCap = new Capability().toASCII();
final Map<String, List<String>> addedHeaders = new HashMap<>();
addedHeaders.put(JnlpConnectionState.CLIENT_NAME_KEY, List.of(agentName));
addedHeaders.put(JnlpConnectionState.SECRET_KEY, List.of(secretKey));
addedHeaders.put(Capability.KEY, List.of(localCap));
if (webSocketHeaders != null) {
for (Map.Entry<String, String> entry : webSocketHeaders.entrySet()) {
addedHeaders.put(entry.getKey(), List.of(entry.getValue()));
}
}
while (true) {
AtomicReference<Channel> ch = new AtomicReference<>();
class HeaderHandler extends ClientEndpointConfig.Configurator {
Capability remoteCapability = new Capability();
@Override
public void beforeRequest(Map<String, List<String>> headers) {
headers.putAll(addedHeaders);
LOGGER.fine(() -> "Sending: " + headers);
}
@Override
public void afterResponse(HandshakeResponse hr) {
LOGGER.fine(() -> "Receiving: " + hr.getHeaders());
List<String> remotingMinimumVersion = hr.getHeaders().get(REMOTING_MINIMUM_VERSION_HEADER);
if (remotingMinimumVersion != null && !remotingMinimumVersion.isEmpty()) {
VersionNumber minimumSupportedVersion = new VersionNumber(remotingMinimumVersion.get(0));
VersionNumber currentVersion = new VersionNumber(Launcher.VERSION);
if (currentVersion.isOlderThan(minimumSupportedVersion)) {
events.error(new IOException("Agent version " + minimumSupportedVersion + " or newer is required."));
}
}
try {
List<String> cookies = hr.getHeaders().get(Engine.WEBSOCKET_COOKIE_HEADER);
if (cookies != null && !cookies.isEmpty()) {
addedHeaders.put(Engine.WEBSOCKET_COOKIE_HEADER, List.of(cookies.get(0)));
} else {
addedHeaders.remove(Engine.WEBSOCKET_COOKIE_HEADER);
}
List<String> advertisedCapability = hr.getHeaders().get(Capability.KEY);
if (advertisedCapability == null) {
LOGGER.warning("Did not receive " + Capability.KEY + " header");
} else {
remoteCapability = Capability.fromASCII(advertisedCapability.get(0));
LOGGER.fine(() -> "received " + remoteCapability);
}
} catch (IOException x) {
events.error(x);
}
}
}
HeaderHandler headerHandler = new HeaderHandler();
class AgentEndpoint extends Endpoint {
@SuppressFBWarnings(value = "UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR", justification = "just trust me here")
AgentEndpoint.Transport transport;
@Override
public void onOpen(Session session, EndpointConfig config) {
events.status("WebSocket connection open");
session.addMessageHandler(ByteBuffer.class, this::onMessage);
try {
transport = new Transport(session);
ch.set(new ChannelBuilder(agentName, executor).
withJarCacheOrDefault(jarCache). // unless EngineJnlpConnectionStateListener can be used for this purpose
build(transport));
} catch (IOException x) {
events.error(x);
}
}
private void onMessage(ByteBuffer message) {
try {
transport.receive(message);
} catch (IOException x) {
events.error(x);
} catch (InterruptedException x) {
events.error(x);
Thread.currentThread().interrupt();
}
}
@Override
@SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE",
justification = "We want the transport.terminate method to run asynchronously and don't want to wait for its status.")
public void onClose(Session session, CloseReason closeReason) {
LOGGER.fine(() -> "onClose: " + closeReason);
// making this call async to avoid potential deadlocks when some thread is holding a lock on the
// channel object while this thread is trying to acquire it to call Transport#terminate
ch.get().executor.submit(() -> transport.terminate(new ChannelClosedException(ch.get(), null)));
}
@Override
@SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE",
justification = "We want the transport.terminate method to run asynchronously and don't want to wait for its status.")
public void onError(Session session, Throwable x) {
// TODO or would events.error(x) be better?
LOGGER.log(Level.FINE, null, x);
// as above
ch.get().executor.submit(() -> transport.terminate(new ChannelClosedException(ch.get(), x)));
}
class Transport extends AbstractByteBufferCommandTransport {
final Session session;
Transport(Session session) {
super(true);
this.session = session;
}
@Override
protected void write(ByteBuffer headerAndData) throws IOException {
LOGGER.finest(() -> "sending message of length " + (headerAndData.remaining() - ChunkHeader.SIZE));
try {
session.getAsyncRemote().sendBinary(headerAndData).get(5, TimeUnit.MINUTES);
} catch (Exception x) {
throw new IOException(x);
}
}
@Override
public Capability getRemoteCapability() {
return headerHandler.remoteCapability;
}
@Override
public void closeWrite() throws IOException {
events.status("Write side closed");
session.close();
}
@Override
public void closeRead() throws IOException {
events.status("Read side closed");
session.close();
}
}
}
hudsonUrl = candidateUrls.get(0);
String wsUrl = hudsonUrl.toString().replaceFirst("^http", "ws");
ContainerProvider.getWebSocketContainer().connectToServer(new AgentEndpoint(),
ClientEndpointConfig.Builder.create().configurator(headerHandler).build(), URI.create(wsUrl + "wsagents/"));
while (ch.get() == null) {
Thread.sleep(100);
}
this.protocolName = "WebSocket";
events.status("Connected");
ch.get().join();
events.status("Terminated");
if (noReconnect) {
return;
}
events.onDisconnect();
while (true) {
// TODO refactor various sleep statements into a common method
TimeUnit.SECONDS.sleep(10);
// Unlike JnlpAgentEndpointResolver, we do not use $jenkins/tcpSlaveAgentListener/, as that will be a 404 if the TCP port is disabled.
URL ping = new URL(hudsonUrl, "login");
try {
HttpURLConnection conn = (HttpURLConnection) ping.openConnection();
int status = conn.getResponseCode();
conn.disconnect();
if (status == 200) {
break;
} else {
events.status(ping + " is not ready: " + status);
}
} catch (IOException x) {
events.status(ping + " is not ready", x);
}
}
reconnect();
}
} catch (Exception e) {
events.error(e);
}
}
private void reconnect() {
try {
events.status("Performing onReconnect operation.");
events.onReconnect();
events.status("onReconnect operation completed.");
} catch (NoClassDefFoundError e) {
events.status("onReconnect operation failed.");
LOGGER.log(Level.WARNING, "Reconnection error.", e);
}
}
private void innerRun(IOHub hub, SSLContext context, ExecutorService service) {
// Create the protocols that will be attempted to connect to the controller.
List<JnlpProtocolHandler<? extends JnlpConnectionState>> protocols = new JnlpProtocolHandlerFactory(service)
.withIOHub(hub)
.withSSLContext(context)
.withPreferNonBlockingIO(false) // we only have one connection, prefer blocking I/O
.handlers();
final Map<String,String> headers = new HashMap<>();
headers.put(JnlpConnectionState.CLIENT_NAME_KEY, agentName);
headers.put(JnlpConnectionState.SECRET_KEY, secretKey);
List<String> jenkinsUrls = new ArrayList<>();
for (URL url: candidateUrls) {
jenkinsUrls.add(url.toExternalForm());
}
JnlpEndpointResolver resolver = createEndpointResolver(jenkinsUrls);
try {
boolean first = true;
while(true) {
if(first) {
first = false;
} else {
if(noReconnect)
return; // exit
}
events.status("Locating server among " + candidateUrls);
final JnlpAgentEndpoint endpoint;
try {
endpoint = resolver.resolve();
} catch (IOException e) {
if (!noReconnect) {
events.status("Could not locate server among " + candidateUrls + "; waiting 10 seconds before retry", e);
// TODO refactor various sleep statements into a common method
TimeUnit.SECONDS.sleep(10);
continue;
} else {
if (Boolean.getBoolean(Engine.class.getName() + ".nonFatalJnlpAgentEndpointResolutionExceptions")) {
events.status("Could not resolve JNLP agent endpoint", e);
} else {
events.error(e);
}
}
return;
}
if (endpoint == null) {
events.status("Could not resolve server among " + candidateUrls);
return;
}
hudsonUrl = endpoint.getServiceUrl();
events.status(String.format("Agent discovery successful%n"
+ " Agent address: %s%n"
+ " Agent port: %d%n"
+ " Identity: %s",
endpoint.getHost(),
endpoint.getPort(),
KeyUtils.fingerprint(endpoint.getPublicKey()))
);
PublicKeyMatchingX509ExtendedTrustManager delegate = new PublicKeyMatchingX509ExtendedTrustManager();
RSAPublicKey publicKey = endpoint.getPublicKey();
if (publicKey != null) {
// This is so that JNLP4-connect will only connect if the public key matches
// if the public key is not published then JNLP4-connect will refuse to connect
delegate.add(publicKey);
}
agentTrustManager.setDelegate(delegate);
events.status("Handshaking");
Socket jnlpSocket = connectTcp(endpoint);
Channel channel = null;
try {
// Try available protocols.
boolean triedAtLeastOneProtocol = false;
for (JnlpProtocolHandler<? extends JnlpConnectionState> protocol : protocols) {
if (!protocol.isEnabled()) {
events.status("Protocol " + protocol.getName() + " is not enabled, skipping");
continue;
}
if (jnlpSocket == null) {
jnlpSocket = connectTcp(endpoint);
}
if (!endpoint.isProtocolSupported(protocol.getName())) {
events.status("Server reports protocol " + protocol.getName() + " not supported, skipping");
continue;
}
triedAtLeastOneProtocol = true;
events.status("Trying protocol: " + protocol.getName());
try {
channel = protocol.connect(jnlpSocket, headers, new EngineJnlpConnectionStateListener(endpoint.getPublicKey(), headers)).get();
} catch (IOException ioe) {
events.status("Protocol " + protocol.getName() + " failed to establish channel", ioe);
} catch (RuntimeException e) {
events.status("Protocol " + protocol.getName() + " encountered a runtime error", e);
} catch (Error e) {
events.status("Protocol " + protocol.getName() + " could not be completed due to an error",
e);
} catch (Throwable e) {
events.status("Protocol " + protocol.getName() + " encountered an unexpected exception", e);
}
// On success do not try other protocols.
if (channel != null) {
this.protocolName = protocol.getName();
break;
}
// On failure form a new connection.
jnlpSocket.close();
jnlpSocket = null;
}
// If no protocol worked.
if (channel == null) {
if (triedAtLeastOneProtocol) {
onConnectionRejected("None of the protocols were accepted");
} else {
onConnectionRejected("None of the protocols are enabled");
return; // exit
}
continue;
}
events.status("Connected");
channel.join();
events.status("Terminated");
} finally {
if (jnlpSocket != null) {
try {
jnlpSocket.close();
} catch (IOException e) {
events.status("Failed to close socket", e);
}
}
}
if(noReconnect)
return; // exit
events.onDisconnect();
// try to connect back to the server every 10 secs.
resolver.waitForReady();
reconnect();
}
} catch (Throwable e) {
events.error(e);
}
}
private JnlpEndpointResolver createEndpointResolver(List<String> jenkinsUrls) {
JnlpEndpointResolver resolver;
if (directConnection == null) {
SSLSocketFactory sslSocketFactory = null;
try {
sslSocketFactory = getSSLSocketFactory();
} catch (Exception e) {
events.error(e);
}
resolver = new JnlpAgentEndpointResolver(jenkinsUrls, credentials, proxyCredentials, tunnel,
sslSocketFactory, disableHttpsCertValidation);
} else {
resolver = new JnlpAgentEndpointConfigurator(directConnection, instanceIdentity, protocols);
}
return resolver;
}
private void onConnectionRejected(String greeting) throws InterruptedException {
events.status("reconnect rejected, sleeping 10s: ", new Exception("The server rejected the connection: " + greeting));
// TODO refactor various sleep statements into a common method
TimeUnit.SECONDS.sleep(10);
}
/**
* Connects to TCP agent host:port, with a few retries.
* @param endpoint Connection endpoint
* @throws IOException Connection failure or invalid parameter specification
*/
private Socket connectTcp(@NonNull JnlpAgentEndpoint endpoint) throws IOException, InterruptedException {
String msg = "Connecting to " + endpoint.getHost() + ':' + endpoint.getPort();
events.status(msg);
int retry = 1;
while(true) {
try {
final Socket s = endpoint.open(SOCKET_TIMEOUT); // default is 30 mins. See PingThread for the ping interval
s.setKeepAlive(keepAlive);
return s;
} catch (IOException e) {
if(retry++>10) {
throw e;
}
// TODO refactor various sleep statements into a common method
TimeUnit.SECONDS.sleep(10);
events.status(msg+" (retrying:"+retry+")",e);
}
}
}
/**
* When invoked from within remoted {@link Callable} (that is,
* from the thread that carries out the remote requests),
* this method returns the {@link Engine} in which the remote operations
* run.
*/
public static Engine current() {
return CURRENT.get();
}
private static final ThreadLocal<Engine> CURRENT = new ThreadLocal<>();
private static final Logger LOGGER = Logger.getLogger(Engine.class.getName());
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "File path is loaded from system properties.")
static KeyStore getCacertsKeyStore()
throws PrivilegedActionException, KeyStoreException, NoSuchProviderException, CertificateException,
NoSuchAlgorithmException, IOException {
Map<String, String> properties = AccessController.doPrivileged(
(PrivilegedExceptionAction<Map<String, String>>) () -> {
Map<String, String> result = new HashMap<>();
result.put("trustStore", System.getProperty("javax.net.ssl.trustStore"));
result.put("javaHome", System.getProperty("java.home"));
result.put("trustStoreType",
System.getProperty("javax.net.ssl.trustStoreType", KeyStore.getDefaultType()));
result.put("trustStoreProvider", System.getProperty("javax.net.ssl.trustStoreProvider", ""));
result.put("trustStorePasswd", System.getProperty("javax.net.ssl.trustStorePassword", ""));
return result;
});
KeyStore keystore = null;
FileInputStream trustStoreStream = null;
try {
String trustStore = properties.get("trustStore");
if (!"NONE".equals(trustStore)) {
File trustStoreFile;
if (trustStore != null) {
trustStoreFile = new File(trustStore);
trustStoreStream = getFileInputStream(trustStoreFile);
} else {
String javaHome = properties.get("javaHome");
trustStoreFile = new File(
javaHome + File.separator + "lib" + File.separator + "security" + File.separator
+ "jssecacerts");
if ((trustStoreStream = getFileInputStream(trustStoreFile)) == null) {
trustStoreFile = new File(
javaHome + File.separator + "lib" + File.separator + "security" + File.separator
+ "cacerts");
trustStoreStream = getFileInputStream(trustStoreFile);
}
}
if (trustStoreStream != null) {
trustStore = trustStoreFile.getPath();
} else {
trustStore = "No File Available, using empty keystore.";
}
}
String trustStoreType = properties.get("trustStoreType");
String trustStoreProvider = properties.get("trustStoreProvider");
LOGGER.log(Level.FINE, "trustStore is: {0}", trustStore);
LOGGER.log(Level.FINE, "trustStore type is: {0}", trustStoreType);
LOGGER.log(Level.FINE, "trustStore provider is: {0}", trustStoreProvider);
if (trustStoreType.length() != 0) {
LOGGER.log(Level.FINE, "init truststore");
if (trustStoreProvider.length() == 0) {