-
Notifications
You must be signed in to change notification settings - Fork 133
/
SSHLauncher.java
1396 lines (1230 loc) · 54.5 KB
/
SSHLauncher.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-, all the contributors
*
* 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.plugins.sshslaves;
import com.cloudbees.jenkins.plugins.sshcredentials.SSHAuthenticator;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials;
import com.cloudbees.plugins.credentials.domains.HostnamePortRequirement;
import com.cloudbees.plugins.credentials.domains.SchemeRequirement;
import com.cloudbees.plugins.credentials.common.StandardUsernameListBoxModel;
import com.trilead.ssh2.ChannelCondition;
import com.trilead.ssh2.Connection;
import com.trilead.ssh2.SCPClient;
import com.trilead.ssh2.SFTPv3FileAttributes;
import com.trilead.ssh2.ServerHostKeyVerifier;
import com.trilead.ssh2.Session;
import com.trilead.ssh2.jenkins.SFTPClient;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.AbortException;
import hudson.EnvVars;
import hudson.Extension;
import hudson.Util;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.model.ItemGroup;
import hudson.model.Node;
import hudson.model.Slave;
import hudson.model.TaskListener;
import hudson.plugins.sshslaves.verifiers.HostKey;
import hudson.plugins.sshslaves.verifiers.NonVerifyingKeyVerificationStrategy;
import hudson.plugins.sshslaves.verifiers.SshHostKeyVerificationStrategy;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.EnvironmentVariablesNodeProperty;
import hudson.slaves.NodeProperty;
import hudson.slaves.NodePropertyDescriptor;
import hudson.slaves.SlaveComputer;
import hudson.util.DescribableList;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.NamingThreadFactory;
import hudson.util.NullStream;
import java.util.Collections;
import jenkins.model.Jenkins;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.lang.InterruptedException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import static hudson.Util.fixEmpty;
import static java.util.logging.Level.WARNING;
/**
* A computer launcher that tries to start a linux agent by opening an SSH connection and trying to find java.
*/
public class SSHLauncher extends ComputerLauncher {
/**
* The scheme requirement.
*/
public static final SchemeRequirement SSH_SCHEME = new SchemeRequirement("ssh");
public static final Integer DEFAULT_MAX_NUM_RETRIES = 10;
public static final Integer DEFAULT_RETRY_WAIT_TIME = 15;
public static final Integer DEFAULT_LAUNCH_TIMEOUT_SECONDS = 60;
public static final String AGENT_JAR = "remoting.jar";
public static final String SLASH_AGENT_JAR = "/" + AGENT_JAR;
public static final String WORK_DIR_PARAM = " -workDir ";
public static final String JAR_CACHE_PARAM = " -jar-cache ";
public static final String JAR_CACHE_DIR = "/remoting/jarCache";
public static final int DEFAULT_SSH_PORT = 22;
/**
* Field host
*/
private String host;
/**
* Field port
*/
private int port;
/**
* The id of the credentials to use.
*/
private String credentialsId;
/**
* Transient stash of the credentials to use, mostly just for providing floating user object.
*/
private transient StandardUsernameCredentials credentials;
/**
* Field jvmOptions.
*/
private String jvmOptions;
/**
* Field javaPath.
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility.")
public String javaPath;
/**
* SSH connection to the agent.
*/
private transient volatile Connection connection;
/**
* Indicates that the {@link #tearDownConnection(SlaveComputer, TaskListener)} is in progress.
* It is used in {@link #afterDisconnect(SlaveComputer, TaskListener)} to avoid multiple parallel calls.
*/
private transient volatile boolean tearingDownConnection;
/**
* The session inside {@link #connection} that controls the agent process.
*/
private transient Session session;
/**
* Field prefixStartSlaveCmd.
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility.")
public String prefixStartSlaveCmd;
/**
* Field suffixStartSlaveCmd.
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility.")
public String suffixStartSlaveCmd;
/**
* Field launchTimeoutSeconds.
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility.")
public Integer launchTimeoutSeconds;
/**
* Field maxNumRetries.
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility.")
public Integer maxNumRetries;
/**
* Field retryWaitTime (seconds).
*/
@SuppressFBWarnings(value = "PA_PUBLIC_PRIMITIVE_ATTRIBUTE", justification = "Preserve API compatibility.")
public Integer retryWaitTime;
// TODO: It is a bad idea to create a new Executor service for each launcher.
// Maybe a Remoting thread pool should be used, but it requires the logic rework to Futures
/**
* Keeps executor service for the async launch operation.
*/
@CheckForNull
private transient volatile ExecutorService launcherExecutorService;
/**
* The verifier to use for checking the SSH key presented by the host
* responding to the connection
*/
@CheckForNull
private SshHostKeyVerificationStrategy sshHostKeyVerificationStrategy;
/**
* Allow to enable/disable the TCP_NODELAY flag on the SSH connection.
*/
private Boolean tcpNoDelay;
/**
* Set the value to add to the remoting parameter -workDir
* @see <a href="https://github.com/jenkinsci/remoting/blob/master/docs/workDir.md#remoting-work-directory">Remoting Work directory</a>
*/
private String workDir;
private class ServerHostKeyVerifierImpl implements ServerHostKeyVerifier {
private final SlaveComputer computer;
private final TaskListener listener;
public ServerHostKeyVerifierImpl(final SlaveComputer computer, final TaskListener listener) {
this.computer = computer;
this.listener = listener;
}
@Override
public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
final HostKey key = new HostKey(serverHostKeyAlgorithm, serverHostKey);
return getSshHostKeyVerificationStrategyDefaulted().verify(computer, key, listener);
}
}
/**
* Constructor SSHLauncher creates a new SSHLauncher instance.
*
* @param host The host to connect to.
* @param port The port to connect on.
* @param credentialsId The credentials id to connect as.
* @param jvmOptions Options passed to the java vm.
* @param javaPath Path to the host jdk installation. If <code>null</code> the jdk will be auto detected.
* @param prefixStartSlaveCmd This will prefix the start agent command. For instance if you want to execute the command with a different shell.
* @param suffixStartSlaveCmd This will suffix the start agent command.
* @param launchTimeoutSeconds Launch timeout in seconds
* @param maxNumRetries The number of times to retry connection if the SSH connection is refused during initial connect
* @param retryWaitTime The number of seconds to wait between retries
* @param sshHostKeyVerificationStrategy Host key verification method selected.
*/
public SSHLauncher(@NonNull String host, int port, String credentialsId,
String jvmOptions, String javaPath, String prefixStartSlaveCmd, String suffixStartSlaveCmd,
Integer launchTimeoutSeconds, Integer maxNumRetries, Integer retryWaitTime,
@CheckForNull SshHostKeyVerificationStrategy sshHostKeyVerificationStrategy) {
setHost(host);
setJvmOptions(jvmOptions);
setPort(port);
this.credentialsId = credentialsId;
setJavaPath(javaPath);
setPrefixStartSlaveCmd(prefixStartSlaveCmd);
setSuffixStartSlaveCmd(suffixStartSlaveCmd);
setLaunchTimeoutSeconds(launchTimeoutSeconds);
setMaxNumRetries(maxNumRetries);
setRetryWaitTime(retryWaitTime);
this.sshHostKeyVerificationStrategy = sshHostKeyVerificationStrategy;
}
/**
* Constructor SSHLauncher creates a new SSHLauncher instance.
*
* @param host The host to connect to.
* @param port The port to connect on.
* @param credentialsId The credentials id to connect as.
*/
@DataBoundConstructor
public SSHLauncher(@NonNull String host, int port, String credentialsId) {
setHost(host);
setPort(port);
this.credentialsId = credentialsId;
this.launchTimeoutSeconds = DEFAULT_LAUNCH_TIMEOUT_SECONDS;
this.maxNumRetries = DEFAULT_MAX_NUM_RETRIES;
this.retryWaitTime = DEFAULT_RETRY_WAIT_TIME;
}
public static StandardUsernameCredentials lookupSystemCredentials(String credentialsId) {
return CredentialsMatchers.firstOrNull(
CredentialsProvider
.lookupCredentialsInItemGroup(StandardUsernameCredentials.class, Jenkins.get(), ACL.SYSTEM2,
List.of(SSH_SCHEME)),
CredentialsMatchers.withId(credentialsId)
);
}
public Object readResolve(){
if(tcpNoDelay == null){
tcpNoDelay = true;
}
//JENKINS-58589 we include 210 seconds because it was the default value before 1.30.3
if(this.launchTimeoutSeconds == null || launchTimeoutSeconds <= 0 || launchTimeoutSeconds == 210){
this.launchTimeoutSeconds = DEFAULT_LAUNCH_TIMEOUT_SECONDS;
}
if(this.maxNumRetries == null){
this.maxNumRetries = DEFAULT_MAX_NUM_RETRIES;
}
if(this.retryWaitTime == null){
this.retryWaitTime = DEFAULT_RETRY_WAIT_TIME;
}
return this;
}
public StandardUsernameCredentials getCredentials() {
String credentialsId = this.credentialsId == null
? (this.credentials == null ? null : this.credentials.getId())
: this.credentialsId;
try {
// only ever want from the system
// lookup every time so that we always have the latest
StandardUsernameCredentials credentials = credentialsId != null ?
SSHLauncher.lookupSystemCredentials(credentialsId) : null;
if (credentials != null) {
this.credentials = credentials;
return credentials;
}
} catch (Throwable t) {
// ignore
}
return this.credentials;
}
/**
* {@inheritDoc}
*/
@Override
public boolean isLaunchSupported() {
return true;
}
/**
* Gets the optional JVM Options used to launch the agent JVM.
* @return The optional JVM Options used to launch the agent JVM.
*/
public String getJvmOptions() {
return jvmOptions == null ? "" : jvmOptions;
}
/**
* Gets the optional java command to use to launch the agent JVM.
* @return The optional java command to use to launch the agent JVM.
*/
@SuppressWarnings("unused") // Used by vsphere-cloud-plugin
@Deprecated
public String getJavaPath() {
return javaPath == null ? "" : javaPath;
}
/**
* Gets the formatted current time stamp.
*
* @return the formatted current time stamp.
*/
@Restricted(NoExternalUse.class)
public static String getTimestamp() {
return String.format("[%1$tD %1$tT]", new Date());
}
/**
* Returns the remote root workspace (without trailing slash).
*
* @param computer The computer to get the root workspace of.
*
* @return the remote root workspace (without trailing slash).
*
*/
@CheckForNull
public static String getWorkingDirectory(SlaveComputer computer) {
return getWorkingDirectory(computer.getNode());
}
@CheckForNull
private static String getWorkingDirectory(@CheckForNull Slave agent) {
if (agent == null) {
return null;
}
String workingDirectory = agent.getRemoteFS();
while (workingDirectory.endsWith("/")) {
workingDirectory = workingDirectory.substring(0, workingDirectory.length() - 1);
}
return workingDirectory;
}
/**
* {@inheritDoc}
*/
@Override
public void launch(final SlaveComputer computer, final TaskListener listener) throws InterruptedException {
final Node node = computer.getNode();
final String host = this.host;
final int port = this.port;
checkConfig();
synchronized (this) {
if(connection != null){
listener.getLogger().println(Messages.SSHLauncher_alreadyConnected());
return;
}
connection = new Connection(host, port);
launcherExecutorService = Executors.newSingleThreadExecutor(
new NamingThreadFactory(Executors.defaultThreadFactory(), "SSHLauncher.launch for '" + computer.getName() + "' node"));
Set<Callable<Boolean>> callables = new HashSet<>();
callables.add(() -> {
Boolean rval = Boolean.FALSE;
try {
String[] preferredKeyAlgorithms = getSshHostKeyVerificationStrategyDefaulted().getPreferredKeyAlgorithms(computer);
if (preferredKeyAlgorithms != null && preferredKeyAlgorithms.length > 0) { // JENKINS-44832
connection.setServerHostKeyAlgorithms(preferredKeyAlgorithms);
} else {
listener.getLogger().println("Warning: no key algorithms provided; JENKINS-42959 disabled");
}
listener.getLogger().println(logConfiguration());
openConnection(listener, computer);
verifyNoHeaderJunk(listener);
reportEnvironment(listener);
final String workingDirectory = getWorkingDirectory(computer);
if (workingDirectory == null) {
listener.error("Cannot get the working directory for " + computer);
return Boolean.FALSE;
}
String java = null;
if (StringUtils.isNotBlank(javaPath)) {
java = expandExpression(computer, javaPath);
} else {
checkJavaIsInPath(listener);
//FIXME deprecated on 2020-12-10, it will removed after 2021-09-01
JavaVersionChecker javaVersionChecker = new JavaVersionChecker(computer, listener, getJvmOptions(),
connection);
java = javaVersionChecker.resolveJava();
}
copyAgentJar(listener, workingDirectory);
startAgent(computer, listener, java, workingDirectory);
PluginImpl.register(connection);
rval = Boolean.TRUE;
} catch (RuntimeException|Error e) {
String msg = Messages.SSHLauncher_UnexpectedError();
if(StringUtils.isNotBlank(e.getMessage())){
msg = e.getMessage();
}
e.printStackTrace(listener.error(msg));
} catch (AbortException e) {
listener.getLogger().println(e.getMessage());
} catch (IOException e) {
e.printStackTrace(listener.getLogger());
} finally {
return rval;
}
});
final String nodeName = node != null ? node.getNodeName(): "unknown";
try {
long time = System.currentTimeMillis();
List<Future<Boolean>> results;
final ExecutorService srv = launcherExecutorService;
if (srv == null) {
throw new IllegalStateException("Launcher Executor Service should be always non-null here, because the task allocates and closes service on its own");
}
results = srv.invokeAll(callables);
long duration = System.currentTimeMillis() - time;
Boolean res;
try {
res = results.get(0).get();
} catch (CancellationException | ExecutionException e) {
res = Boolean.FALSE;
listener.getLogger().println(Messages.SSHLauncher_launchCanceled());
}
if (!res) {
LOGGER.warning(() -> Messages.SSHLauncher_LaunchFailedDuration(nodeName, host, duration));
listener.getLogger().println(getTimestamp() + " Launch failed - cleaning up connection");
cleanupConnection(listener);
} else {
LOGGER.fine(() -> Messages.SSHLauncher_LaunchCompletedDuration(nodeName, host, duration));
}
} catch (InterruptedException e) {
LOGGER.warning(() -> Messages.SSHLauncher_LaunchFailed(nodeName, host));
} finally {
shutdownAndAwaitTerminationOfLauncher();
}
}
if (node != null && getTrackCredentials()) {
CredentialsProvider.track(node, getCredentials());
}
}
/**
* try to run the Java command in the PATH ad report its version.
* @param listener lister to print the output of the java command.
*/
private void checkJavaIsInPath(TaskListener listener) {
String msg = "Java is not in the PATH nor configured with the javaPath setting,"
+ " Jenkins will try to guess where is Java, "
+ "this guess will be removed in the future. :"
+ getDescriptor().getDisplayName();
int ret = 0;
try {
listener.getLogger().println("Checking Java version in the PATH");
ret = connection.exec("java -version", listener.getLogger());
} catch (Exception e){
ret = -1;
}
if(ret != 0){
LOGGER.log(WARNING, msg);
listener.getLogger().println(msg);
}
}
/**
* Called to terminate the SSH connection. Used liberally when we back out from an error.
*/
private void cleanupConnection(TaskListener listener) {
// we might be called multiple times from multiple finally/catch block,
Connection _connection = connection;
if (_connection != null) {
Computer.threadPoolForRemoting.submit(_connection::close);
connection = null;
listener.getLogger().println(Messages.SSHLauncher_ConnectionClosed(getTimestamp()));
}
}
private String expandExpression(SlaveComputer computer, String expression) {
return getEnvVars(computer).expand(expression);
}
private EnvVars getEnvVars(SlaveComputer computer) {
final EnvVars global = getEnvVars(Jenkins.get());
final Node node = computer.getNode();
final EnvVars local = node != null ? getEnvVars(node) : null;
if (global != null) {
if (local != null) {
final EnvVars merged = new EnvVars(global);
merged.overrideAll(local);
return merged;
} else {
return global;
}
} else if (local != null) {
return local;
} else {
return new EnvVars();
}
}
private EnvVars getEnvVars(Jenkins h) {
return getEnvVars(h.getGlobalNodeProperties());
}
private EnvVars getEnvVars(Node n) {
return getEnvVars(n.getNodeProperties());
}
private EnvVars getEnvVars(DescribableList<NodeProperty<?>, NodePropertyDescriptor> dl) {
final EnvironmentVariablesNodeProperty evnp = dl.get(EnvironmentVariablesNodeProperty.class);
if (evnp == null) {
return null;
}
return evnp.getEnvVars();
}
/**
* Makes sure that SSH connection won't produce any unwanted text, which will interfere with sftp execution.
*/
private void verifyNoHeaderJunk(TaskListener listener) throws IOException, InterruptedException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
connection.exec("exit 0",baos);
final String s;
//TODO: Seems we need to retrieve the encoding from the connection destination
try {
s = baos.toString(Charset.defaultCharset().name());
} catch (UnsupportedEncodingException ex) { // Should not happen
throw new IOException("Default encoding is unsupported", ex);
}
if (s.length()!=0) {
listener.getLogger().println(Messages.SSHLauncher_SSHHeaderJunkDetected());
listener.getLogger().println(s);
throw new AbortException();
}
}
/**
* Starts the agent process.
*
* @param computer The computer.
* @param listener The listener.
* @param java The full path name of the java executable to use.
* @param workingDirectory The working directory from which to start the java process.
*
* @throws IOException If something goes wrong.
*/
private void startAgent(SlaveComputer computer, final TaskListener listener, String java,
String workingDirectory) throws IOException {
session = connection.openSession();
expandChannelBufferSize(session,listener);
String cmd = "cd \"" + workingDirectory + "\" && " + java + " " + getJvmOptions() + " -jar " + AGENT_JAR +
getWorkDirParam(workingDirectory);
//This will wrap the cmd with prefix commands and suffix commands if they are set.
cmd = getPrefixStartSlaveCmd() + cmd + getSuffixStartSlaveCmd();
listener.getLogger().println(Messages.SSHLauncher_StartingAgentProcess(getTimestamp(), cmd));
session.execCommand(cmd);
session.pipeStderr(new DelegateNoCloseOutputStream(listener.getLogger()));
try {
computer.setChannel(session.getStdout(), session.getStdin(), listener.getLogger(), null);
} catch (InterruptedException e) {
session.close();
throw new IOException(Messages.SSHLauncher_AbortedDuringConnectionOpen(), e);
} catch (IOException e) {
try {
// often times error this early means the JVM has died, so let's see if we can capture all stderr
// and exit code
throw new AbortException(getSessionOutcomeMessage(session,false));
} catch (InterruptedException x) {
throw new IOException(e);
}
}
}
private void expandChannelBufferSize(Session session, TaskListener listener) {
// see hudson.remoting.Channel.PIPE_WINDOW_SIZE for the discussion of why 1MB is in the right ball park
// but this particular session is where all the controller/agent communication will happen, so
// it's worth using a bigger buffer to really better utilize bandwidth even when the latency is even larger
// (and since we are draining this pipe very rapidly, it's unlikely that we'll actually accumulate this much data)
int sz = 4;
session.setWindowSize(sz*1024*1024);
listener.getLogger().println("Expanded the channel window size to "+sz+"MB");
}
/**
* Method copies the agent jar to the remote system.
*
* @param listener The listener.
* @param workingDirectory The directory into which the agent jar will be copied.
*
* @throws IOException If something goes wrong.
*/
private void copyAgentJar(TaskListener listener, String workingDirectory) throws IOException, InterruptedException {
String fileName = workingDirectory + SLASH_AGENT_JAR;
listener.getLogger().println(Messages.SSHLauncher_StartingSFTPClient(getTimestamp()));
SFTPClient sftpClient = null;
try {
sftpClient = new SFTPClient(connection);
try {
SFTPv3FileAttributes fileAttributes = sftpClient._stat(workingDirectory);
if (fileAttributes==null) {
listener.getLogger().println(Messages.SSHLauncher_RemoteFSDoesNotExist(getTimestamp(),
workingDirectory));
sftpClient.mkdirs(workingDirectory, 0700);
} else if (fileAttributes.isRegularFile()) {
throw new IOException(Messages.SSHLauncher_RemoteFSIsAFile(workingDirectory));
}
listener.getLogger().println(Messages.SSHLauncher_CopyingAgentJar(getTimestamp()));
byte[] agentJar = new Slave.JnlpJar(AGENT_JAR).readFully();
// If the agent jar already exists see if it needs to be updated
boolean overwrite = true;
if (sftpClient.exists(fileName)) {
String sourceAgentHash = getMd5Hash(agentJar);
String existingAgentHash = getMd5Hash(readInputStreamIntoByteArrayAndClose(sftpClient.read(fileName)));
listener.getLogger().println(MessageFormat.format( "Source agent hash is {0}. "
+ "Installed agent hash is {1}", sourceAgentHash, existingAgentHash));
overwrite = !sourceAgentHash.equals(existingAgentHash);
}
if (overwrite) {
try {
// try to delete the file in case the agent we are copying is shorter than the agent
// that is already there
sftpClient.rm(fileName);
} catch (IOException e) {
// the file did not exist... so no need to delete it!
}
try (OutputStream os = sftpClient.writeToFile(fileName)) {
os.write(agentJar);
listener.getLogger()
.println(Messages.SSHLauncher_CopiedXXXBytes(getTimestamp(), agentJar.length));
} catch (Error error) {
throw error;
} catch (Throwable e) {
throw new IOException(Messages.SSHLauncher_ErrorCopyingAgentJarTo(fileName), e);
}
}else{
listener.getLogger().println("Verified agent jar. No update is necessary.");
}
} catch (Error error) {
throw error;
} catch (Throwable e) {
throw new IOException(Messages.SSHLauncher_ErrorCopyingAgentJarInto(workingDirectory), e);
}
} catch (IOException e) {
if (sftpClient == null) {
e.printStackTrace(listener.error(Messages.SSHLauncher_StartingSCPClient(getTimestamp())));
// lets try to recover if the agent doesn't have an SFTP service
copySlaveJarUsingSCP(listener, workingDirectory);
} else {
throw e;
}
} finally {
if (sftpClient != null) {
sftpClient.close();
}
}
}
/**
* Method reads a byte array and returns an upper case md5 hash for it.
*
* @param bytes
* @return
* @throws NoSuchAlgorithmException
*/
static String getMd5Hash(byte[] bytes) throws NoSuchAlgorithmException {
String hash;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
byte[] digest = md.digest();
char[] hexCode = "0123456789ABCDEF".toCharArray();
StringBuilder r = new StringBuilder(digest.length * 2);
for (byte b : digest) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
hash = r.toString().toUpperCase();
}catch (NoSuchAlgorithmException e){
throw e;
}
return hash;
}
/**
* Method reads an input stream into a byte array and closes the input stream when finished.
* Added for reading the remoting jar and generating a hash value for it.
*
* @param inputStream
* @return
* @throws IOException
*/
static byte[] readInputStreamIntoByteArrayAndClose(InputStream inputStream) throws IOException {
byte[] bytes = null;
try{
bytes = IOUtils.toByteArray(inputStream);
}catch(IOException e){
throw e;
} finally {
IOUtils.closeQuietly(inputStream);
if(bytes==null) {
bytes = new byte[ 1 ];
}
}
return bytes;
}
/**
* Method copies the agent jar to the remote system using scp.
*
* @param listener The listener.
* @param workingDirectory The directory into which the agent jar will be copied.
*
* @throws IOException If something goes wrong.
* @throws InterruptedException If something goes wrong.
*/
private void copySlaveJarUsingSCP(TaskListener listener, String workingDirectory) throws IOException, InterruptedException {
SCPClient scp = new SCPClient(connection);
try {
// check if the working directory exists
if (connection.exec("test -d " + workingDirectory ,listener.getLogger())!=0) {
listener.getLogger().println(
Messages.SSHLauncher_RemoteFSDoesNotExist(getTimestamp(), workingDirectory));
// working directory doesn't exist, lets make it.
if (connection.exec("mkdir -p " + workingDirectory, listener.getLogger())!=0) {
listener.getLogger().println("Failed to create "+workingDirectory);
}
}
// delete the agent jar as we do with SFTP
connection.exec("rm " + workingDirectory + SLASH_AGENT_JAR, new NullStream());
// SCP it to the agent. hudson.Util.ByteArrayOutputStream2 doesn't work for this. It pads the byte array.
listener.getLogger().println(Messages.SSHLauncher_CopyingAgentJar(getTimestamp()));
scp.put(new Slave.JnlpJar(AGENT_JAR).readFully(), AGENT_JAR, workingDirectory, "0644");
} catch (IOException e) {
throw new IOException(Messages.SSHLauncher_ErrorCopyingAgentJarInto(workingDirectory), e);
}
}
protected void reportEnvironment(TaskListener listener) throws IOException, InterruptedException {
listener.getLogger().println(Messages._SSHLauncher_RemoteUserEnvironment(getTimestamp()));
connection.exec("set",listener.getLogger());
}
protected void openConnection(final TaskListener listener, final SlaveComputer computer) throws IOException, InterruptedException {
PrintStream logger = listener.getLogger();
logger.println(Messages.SSHLauncher_OpeningSSHConnection(getTimestamp(), host + ":" + port));
connection.setTCPNoDelay(getTcpNoDelay());
int maxNumRetries = getMaxNumRetries();
for (int i = 0; i <= maxNumRetries; i++) {
try {
int launchTimeoutMillis = (int)getLaunchTimeoutMillis();
connection.connect(new ServerHostKeyVerifierImpl(computer, listener),
launchTimeoutMillis, 0 /*read timeout - JENKINS-48618*/,
(int) (launchTimeoutMillis + TimeUnit.SECONDS.toMillis(5)));
break;
} catch (Exception ex) {
String message = "unknown error";
Throwable cause = ex.getCause();
if (cause != null) {
message = cause.getMessage();
logger.println(message);
} else if(ex.getMessage() != null){
message = ex.getMessage();
logger.println(message);
}
connection.close();
if (maxNumRetries - i > 0) {
logger.println("SSH Connection failed with IOException: \"" + message
+ "\", retrying in " + getRetryWaitTime() + " seconds." +
" There are " + (maxNumRetries - i) + " more retries left.");
}
}
Thread.sleep(TimeUnit.SECONDS.toMillis(getRetryWaitTime()));
}
StandardUsernameCredentials credentials = getCredentials();
if (credentials == null) {
throw new AbortException("Cannot find SSH User credentials with id: " + credentialsId);
}
if (SSHAuthenticator.newInstance(connection, credentials).authenticate(listener)
&& connection.isAuthenticationComplete()) {
logger.println(Messages.SSHLauncher_AuthenticationSuccessful(getTimestamp()));
} else {
logger.println(Messages.SSHLauncher_AuthenticationFailed(getTimestamp()));
throw new AbortException(Messages.SSHLauncher_AuthenticationFailedException());
}
}
private void checkConfig() throws InterruptedException {
//JENKINS-58340 some plugins does not implement Descriptor
Descriptor descriptorOrg = Jenkins.get().getDescriptor(this.getClass());
if (!(descriptorOrg instanceof DescriptorImpl)) {
return;
}
DescriptorImpl descriptor = (DescriptorImpl) descriptorOrg;
String message = "Validate configuration:\n";
boolean isValid = true;
String port = String.valueOf(this.port);
FormValidation validatePort = descriptor.doCheckPort(port);
FormValidation validateHost = descriptor.doCheckHost(this.host);
FormValidation validateCredentials = descriptor.doCheckCredentialsId(Jenkins.get(), Jenkins.get(), this.host, port, this.credentialsId);
if(validatePort.kind == FormValidation.Kind.ERROR){
isValid = false;
message += validatePort.getMessage() + "\n";
}
if(validateHost.kind == FormValidation.Kind.ERROR){
isValid = false;
message += validateHost.getMessage() + "\n";
}
if(validateCredentials.kind == FormValidation.Kind.ERROR){
isValid = false;
message += validateCredentials.getMessage() + "\n";
}
if(!isValid){
throw new InterruptedException(message);
}
}
/**
* {@inheritDoc}
*/
@Override
public void afterDisconnect(SlaveComputer slaveComputer, final TaskListener listener) {
if (connection == null) {
// Nothing to do here, the connection is not established
return;
}
shutdownAndAwaitTerminationOfLauncher();
if (tearingDownConnection) {
// tear down operation is in progress, do not even try to synchronize the call.
//TODO: what if reconnect attempts collide? It should not be possible due to locks, but maybe it worth investigation
LOGGER.log(Level.FINE, "There is already a tear down operation in progress for connection {0}. Skipping the call", connection);
return;
}
tearDownConnection(slaveComputer, listener);
}
private synchronized void tearDownConnection(@NonNull SlaveComputer slaveComputer, final @NonNull TaskListener listener) {
if (connection != null) {
tearDownConnectionImpl(slaveComputer, listener);
}
}
private void tearDownConnectionImpl(@NonNull SlaveComputer slaveComputer, final @NonNull TaskListener listener) {
try {
tearingDownConnection = true;
boolean connectionLost = reportTransportLoss(connection, listener);
if (session!=null) {
// give the process 3 seconds to write out its dying message before we cut the loss
// and give up on this process. if the agent process had JVM crash, OOME, or any other
// critical problem, this will allow us to capture that.
// exit code is also an useful info to figure out why the process has died.
try {
listener.getLogger().println(getSessionOutcomeMessage(session,connectionLost));
session.getStdout().close();
session.close();
} catch (Throwable t) {
t.printStackTrace(listener.error(Messages.SSHLauncher_ErrorWhileClosingConnection()));
}
session = null;
}
PluginImpl.unregister(connection);
cleanupConnection(listener);
} finally {
tearingDownConnection = false;
}
}
private void shutdownAndAwaitTerminationOfLauncher() {
ExecutorService srv = launcherExecutorService;
if (srv == null) {
return;
}
srv.shutdown(); // Disable new tasks from being submitted
launcherExecutorService = null;
try {
// Wait a while for existing tasks to terminate
if (!srv.awaitTermination(10, TimeUnit.SECONDS)) {
srv.shutdownNow(); // Cancel currently executing tasks
// Wait a while for tasks to respond to being cancelled
if (!srv.awaitTermination(10, TimeUnit.SECONDS)) {
LOGGER.log(WARNING, "launcherExecutorService thread pool did not terminate cleanly");
}
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
srv.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}