-
Notifications
You must be signed in to change notification settings - Fork 318
/
DockerTemplate.java
272 lines (209 loc) · 8.26 KB
/
DockerTemplate.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
package com.nirima.jenkins.plugins.docker;
import com.cloudbees.jenkins.plugins.sshcredentials.SSHAuthenticator;
import com.cloudbees.jenkins.plugins.sshcredentials.SSHUserListBoxModel;
import com.cloudbees.plugins.credentials.CredentialsProvider;
import com.cloudbees.plugins.credentials.common.StandardUsernameCredentials;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Strings;
import com.nirima.docker.client.DockerException;
import com.nirima.docker.client.DockerClient;
import com.nirima.docker.client.model.*;
import com.trilead.ssh2.Connection;
import hudson.Extension;
import hudson.Util;
import hudson.model.*;
import hudson.model.labels.LabelAtom;
import hudson.plugins.sshslaves.SSHLauncher;
import hudson.security.ACL;
import hudson.slaves.ComputerLauncher;
import hudson.slaves.NodeProperty;
import hudson.slaves.RetentionStrategy;
import hudson.util.ListBoxModel;
import hudson.util.StreamTaskListener;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.IOException;
import java.io.PrintStream;
import java.util.*;
import java.util.logging.Logger;
public class DockerTemplate implements Describable<DockerTemplate> {
private static final Logger LOGGER = Logger.getLogger(DockerTemplate.class.getName());
public final String image;
public final String labelString;
// SSH settings
/**
* The id of the credentials to use.
*/
public final String credentialsId;
/**
* Field dockerCommand
*/
public final String dockerCommand;
/**
* Field jvmOptions.
*/
public final String jvmOptions;
/**
* Field javaPath.
*/
public final String javaPath;
/**
* Field prefixStartSlaveCmd.
*/
public final String prefixStartSlaveCmd;
/**
* Field suffixStartSlaveCmd.
*/
public final String suffixStartSlaveCmd;
public final String remoteFs; // = "/home/jenkins";
public final int instanceCap;
public final String[] dnsHosts;
public final boolean tagOnCompletion;
private transient /*almost final*/ Set<LabelAtom> labelSet;
public transient DockerCloud parent;
public final String additionalTag;
public final boolean pushOnSuccess;
public final boolean privileged;
@DataBoundConstructor
public DockerTemplate(String image, String labelString,
String remoteFs,
String credentialsId, String jvmOptions, String javaPath,
String prefixStartSlaveCmd, String suffixStartSlaveCmd,
boolean tagOnCompletion, String instanceCapStr, String dnsString,
String additionalTag, boolean pushOnSuccess, String dockerCommand,
boolean privileged
) {
this.image = image;
this.labelString = Util.fixNull(labelString);
this.credentialsId = credentialsId;
this.jvmOptions = jvmOptions;
this.javaPath = javaPath;
this.prefixStartSlaveCmd = prefixStartSlaveCmd;
this.suffixStartSlaveCmd = suffixStartSlaveCmd;
this.remoteFs = Strings.isNullOrEmpty(remoteFs)?"/home/jenkins":remoteFs;
this.tagOnCompletion = tagOnCompletion;
this.dockerCommand = dockerCommand;
this.privileged = privileged;
if(instanceCapStr.equals("")) {
this.instanceCap = Integer.MAX_VALUE;
} else {
this.instanceCap = Integer.parseInt(instanceCapStr);
}
this.dnsHosts = dnsString.split(" ");
this.additionalTag = additionalTag;
this.pushOnSuccess = pushOnSuccess;
readResolve();
}
public String getInstanceCapStr() {
if (instanceCap==Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(instanceCap);
}
}
public String getDnsString() {
return Joiner.on(" ").join(dnsHosts);
}
public Descriptor<DockerTemplate> getDescriptor() {
return Jenkins.getInstance().getDescriptor(getClass());
}
public Set<LabelAtom> getLabelSet(){
return labelSet;
}
/**
* Initializes data structure that we don't persist.
*/
protected Object readResolve() {
labelSet = Label.parse(labelString);
return this;
}
public String getDisplayName() {
return "Image of " + image;
}
public DockerCloud getParent() {
return parent;
}
public DockerSlave provision(StreamTaskListener listener) throws IOException, Descriptor.FormException, DockerException {
PrintStream logger = listener.getLogger();
logger.println("Launching " + image );
int numExecutors = 1;
Node.Mode mode = Node.Mode.EXCLUSIVE;
RetentionStrategy retentionStrategy = new DockerRetentionStrategy();//RetentionStrategy.INSTANCE;
List<? extends NodeProperty<?>> nodeProperties = new ArrayList();
ContainerInspectResponse containerInspectResponse = provisionNew();
String containerId = containerInspectResponse.getId();
ComputerLauncher launcher = new DockerComputerLauncher(this, containerInspectResponse);
// Build a description up:
String nodeDescription = "Docker Node [" + image + " on ";
try {
nodeDescription += getParent().getDisplayName();
} catch(Exception ex)
{
nodeDescription += "???";
}
nodeDescription += "]";
return new DockerSlave(this, containerId,
containerId.substring(0,12),
nodeDescription,
remoteFs, numExecutors, mode, labelString,
launcher, retentionStrategy, nodeProperties);
}
public ContainerInspectResponse provisionNew() throws DockerException {
DockerClient dockerClient = getParent().connect();
ContainerConfig containerConfig = new ContainerConfig();
containerConfig.setImage(image);
String[] dockerCommandArray;
if(dockerCommand != null && !dockerCommand.isEmpty()){
dockerCommandArray = dockerCommand.split(" ");
} else {
//default value to preserve comptability
dockerCommandArray = new String[]{"/usr/sbin/sshd", "-D"};
}
containerConfig.setCmd(dockerCommandArray);
containerConfig.setPortSpecs(new String[]{"22/tcp"});
//containerConfig.setPortSpecs(new String[]{"22/tcp"});
//containerConfig.getExposedPorts().put("22/tcp",new ExposedPort());
if( dnsHosts.length > 0 )
containerConfig.setDns(dnsHosts);
ContainerCreateResponse container = dockerClient.containers().create(containerConfig);
// Launch it.. :
// MAybe should be in computerLauncher
Map<String, PortBinding[]> bports = new HashMap<String, PortBinding[]>();
PortBinding binding = new PortBinding();
binding.hostIp = "0.0.0.0";
//binding.hostPort = ":";
bports.put("22/tcp", new PortBinding[] { binding });
HostConfig hostConfig = new HostConfig();
hostConfig.setPortBindings(bports);
hostConfig.setPrivileged(this.privileged);
if( dnsHosts.length > 0 )
hostConfig.setDns(dnsHosts);
dockerClient.container(container.getId()).start(hostConfig);
String containerId = container.getId();
return dockerClient.container(containerId).inspect();
}
public int getNumExecutors() {
return 1;
}
@Extension
public static final class DescriptorImpl extends Descriptor<DockerTemplate> {
@Override
public String getDisplayName() {
return "Docker Template";
}
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
return new SSHUserListBoxModel().withMatching(SSHAuthenticator.matcher(Connection.class),
CredentialsProvider.lookupCredentials(StandardUsernameCredentials.class, context,
ACL.SYSTEM, SSHLauncher.SSH_SCHEME));
}
}
@Override
public String toString() {
return Objects.toStringHelper(this)
.add("image", image)
.add("parent", parent)
.toString();
}
}