getTemplates() {
public SlaveTemplate getTemplate(String template) {
for (SlaveTemplate t : templates) {
- if(t.description.equals(template)) {
+ if (t.description.equals(template)) {
return t;
}
}
@@ -194,12 +195,12 @@ public SlaveTemplate getTemplate(String template) {
*/
public SlaveTemplate getTemplate(Label label) {
for (SlaveTemplate t : templates) {
- if(t.getMode() == Node.Mode.NORMAL) {
- if(label == null || label.matches(t.getLabelSet())) {
+ if (t.getMode() == Node.Mode.NORMAL) {
+ if (label == null || label.matches(t.getLabelSet())) {
return t;
}
- } else if (t.getMode() == Node.Mode.EXCLUSIVE){
- if(label != null && label.matches(t.getLabelSet())) {
+ } else if (t.getMode() == Node.Mode.EXCLUSIVE) {
+ if (label != null && label.matches(t.getLabelSet())) {
return t;
}
}
@@ -211,7 +212,7 @@ public SlaveTemplate getTemplate(Label label) {
* Gets the {@link KeyPairInfo} used for the launch.
*/
public synchronized KeyPair getKeyPair() throws AmazonClientException, IOException {
- if(usableKeyPair==null)
+ if (usableKeyPair == null)
usableKeyPair = privateKey.find(connect());
return usableKeyPair;
}
@@ -219,12 +220,13 @@ public synchronized KeyPair getKeyPair() throws AmazonClientException, IOExcepti
/**
* Counts the number of instances in EC2 currently running that are using the specifed image.
*
- * @param ami If AMI is left null, then all instances are counted.
- *
- * This includes those instances that may be started outside Hudson.
+ * @param ami
+ * If AMI is left null, then all instances are counted.
+ *
+ * This includes those instances that may be started outside Hudson.
*/
public int countCurrentEC2Slaves(String ami) throws AmazonClientException {
- int n=0;
+ int n = 0;
for (Reservation r : connect().describeInstances().getReservations()) {
for (Instance i : r.getInstances()) {
if (isEc2ProvisionedSlave(i, ami)) {
@@ -255,26 +257,27 @@ protected boolean isEc2ProvisionedSlave(Instance i, String ami) {
/**
* Debug command to attach to a running instance.
*/
- public void doAttach(StaplerRequest req, StaplerResponse rsp, @QueryParameter String id) throws ServletException, IOException, AmazonClientException {
+ public void doAttach(StaplerRequest req, StaplerResponse rsp, @QueryParameter String id) throws ServletException,
+ IOException, AmazonClientException {
checkPermission(PROVISION);
SlaveTemplate t = getTemplates().get(0);
StringWriter sw = new StringWriter();
StreamTaskListener listener = new StreamTaskListener(sw);
- EC2AbstractSlave node = t.attach(id,listener);
+ EC2AbstractSlave node = t.attach(id, listener);
Hudson.getInstance().addNode(node);
- rsp.sendRedirect2(req.getContextPath()+"/computer/"+node.getNodeName());
+ rsp.sendRedirect2(req.getContextPath() + "/computer/" + node.getNodeName());
}
public HttpResponse doProvision(@QueryParameter String template) throws ServletException, IOException {
checkPermission(PROVISION);
- if(template==null) {
- throw HttpResponses.error(SC_BAD_REQUEST,"The 'template' query parameter is missing");
+ if (template == null) {
+ throw HttpResponses.error(SC_BAD_REQUEST, "The 'template' query parameter is missing");
}
SlaveTemplate t = getTemplate(template);
- if(t==null) {
- throw HttpResponses.error(SC_BAD_REQUEST,"No such template: "+template);
+ if (t == null) {
+ throw HttpResponses.error(SC_BAD_REQUEST, "No such template: " + template);
}
StringWriter sw = new StringWriter();
@@ -283,17 +286,15 @@ public HttpResponse doProvision(@QueryParameter String template) throws ServletE
EC2AbstractSlave node = t.provision(listener);
Hudson.getInstance().addNode(node);
- return HttpResponses.redirectViaContextPath("/computer/"+node.getNodeName());
+ return HttpResponses.redirectViaContextPath("/computer/" + node.getNodeName());
} catch (AmazonClientException e) {
- throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR,e);
+ throw HttpResponses.error(SC_INTERNAL_SERVER_ERROR, e);
}
}
-
/**
- * Check for the count of EC2 slaves and determine if a new slave can be added.
- * Takes into account both what Amazon reports as well as an internal count
- * of slaves currently being "provisioned".
+ * Check for the count of EC2 slaves and determine if a new slave can be added. Takes into account both what Amazon
+ * reports as well as an internal count of slaves currently being "provisioned".
*/
private boolean addProvisionedSlave(String ami, int amiCap) throws AmazonClientException {
int estimatedTotalSlaves = countCurrentEC2Slaves(null);
@@ -307,34 +308,26 @@ private boolean addProvisionedSlave(String ami, int amiCap) throws AmazonClientE
}
try {
currentProvisioning = provisioningAmis.get(ami);
- }
- catch (NullPointerException npe) {
+ } catch (NullPointerException npe) {
currentProvisioning = 0;
}
estimatedAmiSlaves += currentProvisioning;
- if(estimatedTotalSlaves >= instanceCap) {
- LOGGER.log(Level.INFO, "Total instance cap of " + instanceCap +
- " reached, not provisioning.");
- return false; // maxed out
+ if (estimatedTotalSlaves >= instanceCap) {
+ LOGGER.log(Level.INFO, "Total instance cap of " + instanceCap + " reached, not provisioning.");
+ return false; // maxed out
}
if (estimatedAmiSlaves >= amiCap) {
- LOGGER.log(Level.INFO, "AMI Instance cap of " + amiCap +
- " reached for ami " + ami +
- ", not provisioning.");
- return false; // maxed out
+ LOGGER.log(Level.INFO, "AMI Instance cap of " + amiCap + " reached for ami " + ami
+ + ", not provisioning.");
+ return false; // maxed out
}
- LOGGER.log(Level.INFO,
- "Provisioning for AMI " + ami + "; " +
- "Estimated number of total slaves: "
- + String.valueOf(estimatedTotalSlaves) + "; " +
- "Estimated number of slaves for ami "
- + ami + ": "
- + String.valueOf(estimatedAmiSlaves)
- );
+ LOGGER.log(Level.INFO, "Provisioning for AMI " + ami + "; " + "Estimated number of total slaves: "
+ + String.valueOf(estimatedTotalSlaves) + "; " + "Estimated number of slaves for ami " + ami + ": "
+ + String.valueOf(estimatedAmiSlaves));
provisioningAmis.put(ami, currentProvisioning + 1);
return true;
@@ -349,7 +342,7 @@ private void decrementAmiSlaveProvision(String ami) {
int currentProvisioning;
try {
currentProvisioning = provisioningAmis.get(ami);
- } catch(NullPointerException npe) {
+ } catch (NullPointerException npe) {
return;
}
provisioningAmis.put(ami, Math.max(currentProvisioning - 1, 0));
@@ -357,93 +350,94 @@ private void decrementAmiSlaveProvision(String ami) {
}
@Override
- public Collection provision(Label label, int excessWorkload) {
+ public Collection provision(Label label, int excessWorkload) {
try {
// Count number of pending executors from spot requests
- for(EC2SpotSlave n : NodeIterator.nodes(EC2SpotSlave.class)){
- // If the slave is online then it is already counted by Jenkins
- // We only want to count potential additional Spot instance slaves
- if (n.getComputer().isOffline() && label.matches(n.getAssignedLabels())){
- DescribeSpotInstanceRequestsRequest dsir =
- new DescribeSpotInstanceRequestsRequest().withSpotInstanceRequestIds(n.getSpotInstanceRequestId());
-
- for(SpotInstanceRequest sir : connect().describeSpotInstanceRequests(dsir).getSpotInstanceRequests()) {
- // Count Spot requests that are open and still have a chance to be active
- // A request can be active and not yet registered as a slave. We check above
- // to ensure only unregistered slaves get counted
- if(sir.getState().equals("open") || sir.getState().equals("active")){
- excessWorkload -= n.getNumExecutors();
- }
- }
- }
- }
- LOGGER.log(Level.INFO, "Excess workload after pending Spot instances: " + excessWorkload);
+ for (EC2SpotSlave n : NodeIterator.nodes(EC2SpotSlave.class)) {
+ // If the slave is online then it is already counted by Jenkins
+ // We only want to count potential additional Spot instance
+ // slaves
+ if (n.getComputer().isOffline() && label.matches(n.getAssignedLabels())) {
+ DescribeSpotInstanceRequestsRequest dsir = new DescribeSpotInstanceRequestsRequest().withSpotInstanceRequestIds(n.getSpotInstanceRequestId());
+
+ for (SpotInstanceRequest sir : connect().describeSpotInstanceRequests(dsir).getSpotInstanceRequests()) {
+ // Count Spot requests that are open and still have a
+ // chance to be active
+ // A request can be active and not yet registered as a
+ // slave. We check above
+ // to ensure only unregistered slaves get counted
+ if (sir.getState().equals("open") || sir.getState().equals("active")) {
+ excessWorkload -= n.getNumExecutors();
+ }
+ }
+ }
+ }
+ LOGGER.log(Level.INFO, "Excess workload after pending Spot instances: " + excessWorkload);
List r = new ArrayList();
final SlaveTemplate t = getTemplate(label);
int amiCap = t.getInstanceCap();
- while (excessWorkload>0) {
+ while (excessWorkload > 0) {
if (!addProvisionedSlave(t.ami, amiCap)) {
break;
}
- r.add(new PlannedNode(t.getDisplayName(),
- Computer.threadPoolForRemoting.submit(new Callable() {
- public Node call() throws Exception {
- // TODO: record the output somewhere
- try {
- EC2AbstractSlave s = t.provision(StreamTaskListener.fromStdout());
- Hudson.getInstance().addNode(s);
- // EC2 instances may have a long init script. If we declare
- // the provisioning complete by returning without the connect
- // operation, NodeProvisioner may decide that it still wants
- // one more instance, because it sees that (1) all the slaves
- // are offline (because it's still being launched) and
- // (2) there's no capacity provisioned yet.
- //
- // deferring the completion of provisioning until the launch
- // goes successful prevents this problem.
- s.toComputer().connect(false).get();
- return s;
- }
- finally {
- decrementAmiSlaveProvision(t.ami);
- }
- }
- })
- ,t.getNumExecutors()));
+ r.add(new PlannedNode(t.getDisplayName(), Computer.threadPoolForRemoting.submit(new Callable() {
+ public Node call() throws Exception {
+ // TODO: record the output somewhere
+ try {
+ EC2AbstractSlave s = t.provision(StreamTaskListener.fromStdout());
+ Hudson.getInstance().addNode(s);
+ // EC2 instances may have a long init script. If we
+ // declare
+ // the provisioning complete by returning without
+ // the connect
+ // operation, NodeProvisioner may decide that it
+ // still wants
+ // one more instance, because it sees that (1) all
+ // the slaves
+ // are offline (because it's still being launched)
+ // and
+ // (2) there's no capacity provisioned yet.
+ //
+ // deferring the completion of provisioning until
+ // the launch
+ // goes successful prevents this problem.
+ s.toComputer().connect(false).get();
+ return s;
+ } finally {
+ decrementAmiSlaveProvision(t.ami);
+ }
+ }
+ }), t.getNumExecutors()));
excessWorkload -= t.getNumExecutors();
}
return r;
} catch (AmazonClientException e) {
- LOGGER.log(Level.WARNING,"Failed to count the # of live instances on EC2",e);
+ LOGGER.log(Level.WARNING, "Failed to count the # of live instances on EC2", e);
return Collections.emptyList();
}
}
@Override
- public boolean canProvision(Label label) {
- return getTemplate(label)!=null;
+ public boolean canProvision(Label label) {
+ return getTemplate(label) != null;
}
private AWSCredentialsProvider createCredentialsProvider() {
return createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
}
- public static AWSCredentialsProvider createCredentialsProvider(
- final boolean useInstanceProfileForCredentials,
- final String accessId, final String secretKey) {
+ public static AWSCredentialsProvider createCredentialsProvider(final boolean useInstanceProfileForCredentials, final String accessId, final String secretKey) {
return createCredentialsProvider(useInstanceProfileForCredentials, accessId.trim(), Secret.fromString(secretKey.trim()));
}
- public static AWSCredentialsProvider createCredentialsProvider(
- final boolean useInstanceProfileForCredentials,
- final String accessId, final Secret secretKey) {
+ public static AWSCredentialsProvider createCredentialsProvider(final boolean useInstanceProfileForCredentials, final String accessId, final Secret secretKey) {
if (useInstanceProfileForCredentials) {
return new InstanceProfileCredentialsProvider();
@@ -463,27 +457,29 @@ public synchronized AmazonEC2 connect() throws AmazonClientException {
}
return connection;
} catch (IOException e) {
- throw new AmazonClientException("Failed to retrieve the endpoint",e);
+ throw new AmazonClientException("Failed to retrieve the endpoint", e);
}
}
/***
* Connect to an EC2 instance.
+ *
* @return {@link AmazonEC2} client
*/
public synchronized static AmazonEC2 connect(AWSCredentialsProvider credentialsProvider, URL endpoint) {
awsCredentialsProvider = credentialsProvider;
ClientConfiguration config = new ClientConfiguration();
- config.setMaxErrorRetry(16); // Default retry limit (3) is low and often cause problems. Raise it a bit.
+ config.setMaxErrorRetry(16); // Default retry limit (3) is low and often
+ // cause problems. Raise it a bit.
// See: https://issues.jenkins-ci.org/browse/JENKINS-26800
config.setSignerOverride("QueryStringSignerType");
ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(endpoint.getHost());
- if (! proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
+ if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) proxy.address();
config.setProxyHost(address.getHostName());
config.setProxyPort(address.getPort());
- if(null != proxyConfig.getUserName()) {
+ if (null != proxyConfig.getUserName()) {
config.setProxyUsername(proxyConfig.getUserName());
config.setProxyPassword(proxyConfig.getPassword());
}
@@ -497,7 +493,7 @@ public synchronized static AmazonEC2 connect(AWSCredentialsProvider credentialsP
* Convert a configured hostname like 'us-east-1' to a FQDN or ip address
*/
public static String convertHostName(String ec2HostName) {
- if (ec2HostName == null || ec2HostName.length()==0)
+ if (ec2HostName == null || ec2HostName.length() == 0)
ec2HostName = DEFAULT_EC2_HOST;
if (!ec2HostName.contains("."))
ec2HostName = ec2HostName + "." + EC2_URL_HOST;
@@ -505,8 +501,7 @@ public static String convertHostName(String ec2HostName) {
}
/***
- * Convert a user entered string into a port number
- * "" -> -1 to indicate default based on SSL setting
+ * Convert a user entered string into a port number "" -> -1 to indicate default based on SSL setting
*/
public static Integer convertPort(String ec2Port) {
if (ec2Port == null || ec2Port.length() == 0)
@@ -518,11 +513,11 @@ public static Integer convertPort(String ec2Port) {
* Computes the presigned URL for the given S3 resource.
*
* @param path
- * String like "/bucketName/folder/folder/abc.txt" that represents the resource to request.
+ * String like "/bucketName/folder/folder/abc.txt" that represents the resource to request.
*/
public URL buildPresignedURL(String path) throws AmazonClientException {
AWSCredentials credentials = awsCredentialsProvider.getCredentials();
- long expires = System.currentTimeMillis()+60*60*1000;
+ long expires = System.currentTimeMillis() + 60 * 60 * 1000;
GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(path, credentials.getAWSSecretKey());
request.setExpiration(new Date(expires));
AmazonS3 s3 = new AmazonS3Client(credentials);
@@ -538,7 +533,6 @@ public static URL checkEndPoint(String url) throws FormValidation {
}
}
-
public static abstract class DescriptorImpl extends Descriptor {
public InstanceType[] getInstanceTypes() {
return InstanceType.values();
@@ -548,11 +542,11 @@ public FormValidation doCheckAccessId(@QueryParameter String value) throws IOExc
if (value.trim().length() != 20) {
return FormValidation.error(Messages.EC2Cloud_InvalidAccessId());
}
- return FormValidation.validateBase64(value,false,false,Messages.EC2Cloud_InvalidAccessId());
+ return FormValidation.validateBase64(value, false, false, Messages.EC2Cloud_InvalidAccessId());
}
public FormValidation doCheckSecretKey(@QueryParameter String value) throws IOException, ServletException {
- return FormValidation.validateBase64(value,false,false,Messages.EC2Cloud_InvalidSecretKey());
+ return FormValidation.validateBase64(value, false, false, Messages.EC2Cloud_InvalidSecretKey());
}
public FormValidation doCheckUseInstanceProfileForCredentials(@QueryParameter boolean value) {
@@ -568,61 +562,62 @@ public FormValidation doCheckUseInstanceProfileForCredentials(@QueryParameter bo
}
public FormValidation doCheckPrivateKey(@QueryParameter String value) throws IOException, ServletException {
- boolean hasStart=false,hasEnd=false;
+ boolean hasStart = false, hasEnd = false;
BufferedReader br = new BufferedReader(new StringReader(value));
String line;
while ((line = br.readLine()) != null) {
if (line.equals("-----BEGIN RSA PRIVATE KEY-----"))
- hasStart=true;
+ hasStart = true;
if (line.equals("-----END RSA PRIVATE KEY-----"))
- hasEnd=true;
+ hasEnd = true;
}
- if(!hasStart)
+ if (!hasStart)
return FormValidation.error("This doesn't look like a private key at all");
- if(!hasEnd)
+ if (!hasEnd)
return FormValidation.error("The private key is missing the trailing 'END RSA PRIVATE KEY' marker. Copy&paste error?");
return FormValidation.ok();
}
- protected FormValidation doTestConnection( URL ec2endpoint,
- boolean useInstanceProfileForCredentials, String accessId, String secretKey, String privateKey) throws IOException, ServletException {
- try {
+ protected FormValidation doTestConnection(URL ec2endpoint, boolean useInstanceProfileForCredentials, String accessId, String secretKey, String privateKey)
+ throws IOException, ServletException {
+ try {
AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
AmazonEC2 ec2 = connect(credentialsProvider, ec2endpoint);
ec2.describeInstances();
- if(privateKey==null)
+ if (privateKey == null)
return FormValidation.error("Private key is not specified. Click 'Generate Key' to generate one.");
- if(privateKey.trim().length()>0) {
+ if (privateKey.trim().length() > 0) {
// check if this key exists
EC2PrivateKey pk = new EC2PrivateKey(privateKey);
- if(pk.find(ec2)==null)
- return FormValidation.error("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is "+pk.getFingerprint()+")");
+ if (pk.find(ec2) == null)
+ return FormValidation.error("The EC2 key pair private key isn't registered to this EC2 region (fingerprint is "
+ + pk.getFingerprint() + ")");
}
return FormValidation.ok(Messages.EC2Cloud_Success());
} catch (AmazonClientException e) {
- LOGGER.log(Level.WARNING, "Failed to check EC2 credential",e);
+ LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
return FormValidation.error(e.getMessage());
}
}
public FormValidation doGenerateKey(StaplerResponse rsp, URL ec2EndpointUrl, boolean useInstanceProfileForCredentials, String accessId, String secretKey)
- throws IOException, ServletException {
+ throws IOException, ServletException {
try {
AWSCredentialsProvider credentialsProvider = createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
AmazonEC2 ec2 = connect(credentialsProvider, ec2EndpointUrl);
List existingKeys = ec2.describeKeyPairs().getKeyPairs();
int n = 0;
- while(true) {
+ while (true) {
boolean found = false;
for (KeyPairInfo k : existingKeys) {
- if(k.getKeyName().equals("hudson-"+n))
- found=true;
+ if (k.getKeyName().equals("hudson-" + n))
+ found = true;
}
- if(!found)
+ if (!found)
break;
n++;
}
@@ -630,12 +625,12 @@ public FormValidation doGenerateKey(StaplerResponse rsp, URL ec2EndpointUrl, boo
CreateKeyPairRequest request = new CreateKeyPairRequest("hudson-" + n);
KeyPair key = ec2.createKeyPair(request).getKeyPair();
-
- rsp.addHeader("script","findPreviousFormItem(button,'privateKey').value='"+key.getKeyMaterial().replace("\n","\\n")+"'");
+ rsp.addHeader("script", "findPreviousFormItem(button,'privateKey').value='"
+ + key.getKeyMaterial().replace("\n", "\\n") + "'");
return FormValidation.ok(Messages.EC2Cloud_Success());
} catch (AmazonClientException e) {
- LOGGER.log(Level.WARNING, "Failed to check EC2 credential",e);
+ LOGGER.log(Level.WARNING, "Failed to check EC2 credential", e);
return FormValidation.error(e.getMessage());
}
}
diff --git a/src/main/java/hudson/plugins/ec2/EC2Computer.java b/src/main/java/hudson/plugins/ec2/EC2Computer.java
index a41cec289..0b541047f 100644
--- a/src/main/java/hudson/plugins/ec2/EC2Computer.java
+++ b/src/main/java/hudson/plugins/ec2/EC2Computer.java
@@ -52,28 +52,28 @@ public EC2Computer(EC2AbstractSlave slave) {
@Override
public EC2AbstractSlave getNode() {
- return (EC2AbstractSlave)super.getNode();
+ return (EC2AbstractSlave) super.getNode();
}
public String getInstanceId() {
EC2AbstractSlave node = (EC2AbstractSlave) super.getNode();
- return node.getInstanceId();
+ return node.getInstanceId();
}
public String getEc2Type() {
- return getNode().getEc2Type();
+ return getNode().getEc2Type();
}
- public String getSpotInstanceRequestId(){
- if(getNode() instanceof EC2SpotSlave) {
- return ((EC2SpotSlave) getNode()).getSpotInstanceRequestId();
- }
- return "";
+ public String getSpotInstanceRequestId() {
+ if (getNode() instanceof EC2SpotSlave) {
+ return ((EC2SpotSlave) getNode()).getSpotInstanceRequestId();
+ }
+ return "";
}
- public EC2Cloud getCloud() {
- EC2AbstractSlave node = (EC2AbstractSlave) super.getNode();
- return node.getCloud();
+ public EC2Cloud getCloud() {
+ EC2AbstractSlave node = (EC2AbstractSlave) super.getNode();
+ return node.getCloud();
}
/**
@@ -89,13 +89,13 @@ public String getConsoleOutput() throws AmazonClientException {
* Obtains the instance state description in EC2.
*
*
- * This method returns a cached state, so it's not suitable to check {@link Instance#getState()}
- * from the returned instance (but all the other fields are valid as it won't change.)
+ * This method returns a cached state, so it's not suitable to check {@link Instance#getState()} from the returned
+ * instance (but all the other fields are valid as it won't change.)
*
* The cache can be flushed using {@link #updateInstanceDescription()}
*/
public Instance describeInstance() throws AmazonClientException, InterruptedException {
- if(ec2InstanceDescription==null)
+ if (ec2InstanceDescription == null)
ec2InstanceDescription = _describeInstance();
return ec2InstanceDescription;
}
@@ -114,7 +114,7 @@ public Instance updateInstanceDescription() throws AmazonClientException, Interr
* Unlike {@link #describeInstance()}, this method always return the current status by calling EC2.
*/
public InstanceState getState() throws AmazonClientException, InterruptedException {
- ec2InstanceDescription=_describeInstance();
+ ec2InstanceDescription = _describeInstance();
return InstanceState.find(ec2InstanceDescription.getState().getName());
}
@@ -122,7 +122,7 @@ public InstanceState getState() throws AmazonClientException, InterruptedExcepti
* Number of milli-secs since the instance was started.
*/
public long getUptime() throws AmazonClientException, InterruptedException {
- return System.currentTimeMillis()-describeInstance().getLaunchTime().getTime();
+ return System.currentTimeMillis() - describeInstance().getLaunchTime().getTime();
}
/**
@@ -154,7 +154,7 @@ private Instance _describeInstance() throws AmazonClientException, InterruptedEx
private Instance _describeInstanceOnce() throws AmazonClientException {
DescribeInstancesRequest request = new DescribeInstancesRequest();
- request.setInstanceIds(Collections.singletonList(getNode().getInstanceId()));
+ request.setInstanceIds(Collections. singletonList(getNode().getInstanceId()));
return getCloud().connect().describeInstances(request).getReservations().get(0).getInstances().get(0);
}
@@ -165,11 +165,12 @@ private Instance _describeInstanceOnce() throws AmazonClientException {
public HttpResponse doDoDelete() throws IOException {
checkPermission(DELETE);
if (getNode() != null)
- getNode().terminate();
+ getNode().terminate();
return new HttpRedirect("..");
}
- /** What username to use to run root-like commands
+ /**
+ * What username to use to run root-like commands
*
*/
public String getRemoteAdmin() {
@@ -177,18 +178,18 @@ public String getRemoteAdmin() {
}
public int getSshPort() {
- return getNode().getSshPort();
- }
+ return getNode().getSshPort();
+ }
public String getRootCommandPrefix() {
return getNode().getRootCommandPrefix();
}
- public void onConnected(){
- EC2AbstractSlave node = getNode();
- if (node != null) {
- node.onConnected();
- }
- }
+ public void onConnected() {
+ EC2AbstractSlave node = getNode();
+ if (node != null) {
+ node.onConnected();
+ }
+ }
}
diff --git a/src/main/java/hudson/plugins/ec2/EC2ComputerLauncher.java b/src/main/java/hudson/plugins/ec2/EC2ComputerLauncher.java
index 34afdae37..50cf231b2 100644
--- a/src/main/java/hudson/plugins/ec2/EC2ComputerLauncher.java
+++ b/src/main/java/hudson/plugins/ec2/EC2ComputerLauncher.java
@@ -40,8 +40,8 @@
import com.amazonaws.services.ec2.model.StartInstancesResult;
/**
- * {@link ComputerLauncher} for EC2 that waits for the instance to really come up before proceeding to
- * the real user-specified {@link ComputerLauncher}.
+ * {@link ComputerLauncher} for EC2 that waits for the instance to really come up before proceeding to the real
+ * user-specified {@link ComputerLauncher}.
*
* @author Kohsuke Kawaguchi
*/
@@ -49,52 +49,51 @@ public abstract class EC2ComputerLauncher extends ComputerLauncher {
@Override
public void launch(SlaveComputer _computer, TaskListener listener) {
try {
- EC2Computer computer = (EC2Computer)_computer;
+ EC2Computer computer = (EC2Computer) _computer;
PrintStream logger = listener.getLogger();
- final String baseMsg = "Node " + computer.getName() + "("+computer.getInstanceId()+")";
+ final String baseMsg = "Node " + computer.getName() + "(" + computer.getInstanceId() + ")";
String msg;
- OUTER:
- while(true) {
+ OUTER: while (true) {
switch (computer.getState()) {
- case PENDING:
- msg = baseMsg + " is still pending/launching, waiting 5s";
- break;
- case STOPPING:
- msg = baseMsg + " is still stopping, waiting 5s";
- break;
- case RUNNING:
- msg = baseMsg + " is ready";
- LOGGER.finer(msg);
- logger.println(msg);
- break OUTER;
- case STOPPED:
- msg = baseMsg + " is stopped, sending start request";
- LOGGER.finer(msg);
- logger.println(msg);
+ case PENDING:
+ msg = baseMsg + " is still pending/launching, waiting 5s";
+ break;
+ case STOPPING:
+ msg = baseMsg + " is still stopping, waiting 5s";
+ break;
+ case RUNNING:
+ msg = baseMsg + " is ready";
+ LOGGER.finer(msg);
+ logger.println(msg);
+ break OUTER;
+ case STOPPED:
+ msg = baseMsg + " is stopped, sending start request";
+ LOGGER.finer(msg);
+ logger.println(msg);
- AmazonEC2 ec2 = computer.getCloud().connect();
- List instances = new ArrayList();
- instances.add(computer.getInstanceId());
+ AmazonEC2 ec2 = computer.getCloud().connect();
+ List instances = new ArrayList();
+ instances.add(computer.getInstanceId());
- StartInstancesRequest siRequest = new StartInstancesRequest(instances);
- StartInstancesResult siResult = ec2.startInstances(siRequest);
+ StartInstancesRequest siRequest = new StartInstancesRequest(instances);
+ StartInstancesResult siResult = ec2.startInstances(siRequest);
- msg = baseMsg + ": sent start request, result: " + siResult;
- LOGGER.finer(baseMsg);
- logger.println(baseMsg);
- continue OUTER;
- case SHUTTING_DOWN:
- case TERMINATED:
- // abort
- msg = baseMsg + " is terminated or terminating, aborting launch";
- LOGGER.info(msg);
- logger.println(msg);
- return;
- default:
- msg = baseMsg + " is in an unknown state, retrying in 5s";
- break;
+ msg = baseMsg + ": sent start request, result: " + siResult;
+ LOGGER.finer(baseMsg);
+ logger.println(baseMsg);
+ continue OUTER;
+ case SHUTTING_DOWN:
+ case TERMINATED:
+ // abort
+ msg = baseMsg + " is terminated or terminating, aborting launch";
+ LOGGER.info(msg);
+ logger.println(msg);
+ return;
+ default:
+ msg = baseMsg + " is in an unknown state, retrying in 5s";
+ break;
}
// check every 5 secs
diff --git a/src/main/java/hudson/plugins/ec2/EC2ComputerListener.java b/src/main/java/hudson/plugins/ec2/EC2ComputerListener.java
index 564f4efcb..db79e2380 100644
--- a/src/main/java/hudson/plugins/ec2/EC2ComputerListener.java
+++ b/src/main/java/hudson/plugins/ec2/EC2ComputerListener.java
@@ -8,10 +8,10 @@
@Extension
public class EC2ComputerListener extends ComputerListener {
- @Override
- public void onOnline(Computer c, TaskListener listener) {
- if(c instanceof EC2Computer){
- ((EC2Computer) c).onConnected();
- }
- }
+ @Override
+ public void onOnline(Computer c, TaskListener listener) {
+ if (c instanceof EC2Computer) {
+ ((EC2Computer) c).onConnected();
+ }
+ }
}
diff --git a/src/main/java/hudson/plugins/ec2/EC2OndemandSlave.java b/src/main/java/hudson/plugins/ec2/EC2OndemandSlave.java
index 3b66c6997..713d42aa3 100644
--- a/src/main/java/hudson/plugins/ec2/EC2OndemandSlave.java
+++ b/src/main/java/hudson/plugins/ec2/EC2OndemandSlave.java
@@ -29,19 +29,23 @@
* @author Kohsuke Kawaguchi
*/
public final class EC2OndemandSlave extends EC2AbstractSlave {
-
- public EC2OndemandSlave(String instanceId, String description, String remoteFS, int numExecutors, String labelString, Mode mode, String initScript, String tmpDir, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, String publicDNS, String privateDNS, List tags, String cloudName,int launchTimeout, AMITypeData amiType) throws FormException, IOException {
- this(description + " (" + instanceId + ")", instanceId, description, remoteFS, numExecutors, labelString, mode, initScript, tmpDir, Collections.>emptyList(), remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, publicDNS, privateDNS, tags, cloudName, false, false, launchTimeout, amiType);
+
+ public EC2OndemandSlave(String instanceId, String description, String remoteFS, int numExecutors, String labelString, Mode mode, String initScript, String tmpDir, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, String publicDNS, String privateDNS, List tags, String cloudName, int launchTimeout, AMITypeData amiType)
+ throws FormException, IOException {
+ this(description + " (" + instanceId + ")", instanceId, description, remoteFS, numExecutors, labelString, mode, initScript, tmpDir, Collections.> emptyList(), remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, publicDNS, privateDNS, tags, cloudName, false, false, launchTimeout, amiType);
+ }
+
+ public EC2OndemandSlave(String instanceId, String description, String remoteFS, int numExecutors, String labelString, Mode mode, String initScript, String tmpDir, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, String publicDNS, String privateDNS, List tags, String cloudName, boolean usePrivateDnsName, boolean useDedicatedTenancy, int launchTimeout, AMITypeData amiType)
+ throws FormException, IOException {
+ this(description + " (" + instanceId + ")", instanceId, description, remoteFS, numExecutors, labelString, mode, initScript, tmpDir, Collections.> emptyList(), remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, publicDNS, privateDNS, tags, cloudName, usePrivateDnsName, useDedicatedTenancy, launchTimeout, amiType);
}
-
- public EC2OndemandSlave(String instanceId, String description, String remoteFS, int numExecutors, String labelString, Mode mode, String initScript, String tmpDir, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, String publicDNS, String privateDNS, List tags, String cloudName, boolean usePrivateDnsName, boolean useDedicatedTenancy, int launchTimeout, AMITypeData amiType) throws FormException, IOException {
- this(description + " (" + instanceId + ")", instanceId, description, remoteFS, numExecutors, labelString, mode, initScript, tmpDir, Collections.>emptyList(), remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, publicDNS, privateDNS, tags, cloudName, usePrivateDnsName, useDedicatedTenancy, launchTimeout, amiType);
- }
@DataBoundConstructor
- public EC2OndemandSlave(String name, String instanceId, String description, String remoteFS, int numExecutors, String labelString, Mode mode, String initScript, String tmpDir, List extends NodeProperty>> nodeProperties, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, String publicDNS, String privateDNS, List tags, String cloudName, boolean usePrivateDnsName, boolean useDedicatedTenancy, int launchTimeout, AMITypeData amiType) throws FormException, IOException {
-
- super(name, instanceId, description, remoteFS, numExecutors, mode, labelString, amiType.isWindows() ? new EC2WindowsLauncher() : new EC2UnixLauncher(), new EC2RetentionStrategy(idleTerminationMinutes), initScript, tmpDir, nodeProperties, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, tags, cloudName, usePrivateDnsName, useDedicatedTenancy, launchTimeout, amiType);
+ public EC2OndemandSlave(String name, String instanceId, String description, String remoteFS, int numExecutors, String labelString, Mode mode, String initScript, String tmpDir, List extends NodeProperty>> nodeProperties, String remoteAdmin, String jvmopts, boolean stopOnTerminate, String idleTerminationMinutes, String publicDNS, String privateDNS, List tags, String cloudName, boolean usePrivateDnsName, boolean useDedicatedTenancy, int launchTimeout, AMITypeData amiType)
+ throws FormException, IOException {
+
+ super(name, instanceId, description, remoteFS, numExecutors, mode, labelString, amiType.isWindows() ? new EC2WindowsLauncher()
+ : new EC2UnixLauncher(), new EC2RetentionStrategy(idleTerminationMinutes), initScript, tmpDir, nodeProperties, remoteAdmin, jvmopts, stopOnTerminate, idleTerminationMinutes, tags, cloudName, usePrivateDnsName, useDedicatedTenancy, launchTimeout, amiType);
this.publicDNS = publicDNS;
this.privateDNS = privateDNS;
@@ -51,35 +55,36 @@ public EC2OndemandSlave(String name, String instanceId, String description, Stri
* Constructor for debugging.
*/
public EC2OndemandSlave(String instanceId) throws FormException, IOException {
- this(instanceId, instanceId, "debug", "/tmp/hudson", 1, "debug", Mode.NORMAL, "", "/tmp", Collections.>emptyList(), null, null, false, null, "Fake public", "Fake private", null, null, false, false, 0, new UnixData(null, null));
+ this(instanceId, instanceId, "debug", "/tmp/hudson", 1, "debug", Mode.NORMAL, "", "/tmp", Collections.> emptyList(), null, null, false, null, "Fake public", "Fake private", null, null, false, false, 0, new UnixData(null, null));
}
-
/**
* Terminates the instance in EC2.
*/
public void terminate() {
try {
if (!isAlive(true)) {
- /* The node has been killed externally, so we've nothing to do here */
- LOGGER.info("EC2 instance already terminated: "+getInstanceId());
+ /*
+ * The node has been killed externally, so we've nothing to do here
+ */
+ LOGGER.info("EC2 instance already terminated: " + getInstanceId());
} else {
AmazonEC2 ec2 = getCloud().connect();
TerminateInstancesRequest request = new TerminateInstancesRequest(Collections.singletonList(getInstanceId()));
ec2.terminateInstances(request);
- LOGGER.info("Terminated EC2 instance (terminated): "+getInstanceId());
+ LOGGER.info("Terminated EC2 instance (terminated): " + getInstanceId());
}
Hudson.getInstance().removeNode(this);
- LOGGER.info("Removed EC2 instance from jenkins master: "+getInstanceId());
+ LOGGER.info("Removed EC2 instance from jenkins master: " + getInstanceId());
} catch (AmazonClientException e) {
- LOGGER.log(Level.WARNING,"Failed to terminate EC2 instance: "+getInstanceId(),e);
+ LOGGER.log(Level.WARNING, "Failed to terminate EC2 instance: " + getInstanceId(), e);
} catch (IOException e) {
- LOGGER.log(Level.WARNING,"Failed to terminate EC2 instance: "+getInstanceId(),e);
+ LOGGER.log(Level.WARNING, "Failed to terminate EC2 instance: " + getInstanceId(), e);
}
}
@Override
- public Node reconfigure(final StaplerRequest req, JSONObject form) throws FormException {
+ public Node reconfigure(final StaplerRequest req, JSONObject form) throws FormException {
if (form == null) {
return null;
}
@@ -89,9 +94,10 @@ public Node reconfigure(final StaplerRequest req, JSONObject form) throws FormEx
try {
Hudson.getInstance().removeNode(this);
} catch (IOException ioe) {
- LOGGER.log(Level.WARNING, "Attempt to reconfigure EC2 instance which has been externally terminated: " + getInstanceId(), ioe);
+ LOGGER.log(Level.WARNING, "Attempt to reconfigure EC2 instance which has been externally terminated: "
+ + getInstanceId(), ioe);
}
-
+
return null;
}
@@ -101,15 +107,15 @@ public Node reconfigure(final StaplerRequest req, JSONObject form) throws FormEx
@Extension
public static final class DescriptorImpl extends EC2AbstractSlave.DescriptorImpl {
@Override
- public String getDisplayName() {
- return Messages.EC2OndemandSlave_AmazonEC2();
+ public String getDisplayName() {
+ return Messages.EC2OndemandSlave_AmazonEC2();
}
}
private static final Logger LOGGER = Logger.getLogger(EC2OndemandSlave.class.getName());
- @Override
- public String getEc2Type() {
- return Messages.EC2OndemandSlave_OnDemand();
- }
+ @Override
+ public String getEc2Type() {
+ return Messages.EC2OndemandSlave_OnDemand();
+ }
}
diff --git a/src/main/java/hudson/plugins/ec2/EC2PrivateKey.java b/src/main/java/hudson/plugins/ec2/EC2PrivateKey.java
index 7292b4144..4d8262dae 100644
--- a/src/main/java/hudson/plugins/ec2/EC2PrivateKey.java
+++ b/src/main/java/hudson/plugins/ec2/EC2PrivateKey.java
@@ -62,7 +62,7 @@ public class EC2PrivateKey {
}
public String getPrivateKey() {
- return privateKey.getPlainText();
+ return privateKey.getPlainText();
}
/**
@@ -74,7 +74,7 @@ public String getPrivateKey() {
public String getFingerprint() throws IOException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Reader r = new BufferedReader(new StringReader(privateKey.getPlainText()));
- PEMReader pem = new PEMReader(r,new PasswordFinder() {
+ PEMReader pem = new PEMReader(r, new PasswordFinder() {
public char[] getPassword() {
throw PRIVATE_KEY_WITH_PASSWORD;
}
@@ -82,11 +82,12 @@ public char[] getPassword() {
try {
KeyPair pair = (KeyPair) pem.readObject();
- if(pair==null) return null;
+ if (pair == null)
+ return null;
PrivateKey key = pair.getPrivate();
return digest(key);
} catch (RuntimeException e) {
- if (e==PRIVATE_KEY_WITH_PASSWORD)
+ if (e == PRIVATE_KEY_WITH_PASSWORD)
throw new IOException("This private key is password protected, which isn't supported yet");
throw e;
} finally {
@@ -97,7 +98,7 @@ public char[] getPassword() {
public String getPublicFingerprint() throws IOException {
Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
Reader r = new BufferedReader(new StringReader(privateKey.getPlainText()));
- PEMReader pem = new PEMReader(r,new PasswordFinder() {
+ PEMReader pem = new PEMReader(r, new PasswordFinder() {
public char[] getPassword() {
throw PRIVATE_KEY_WITH_PASSWORD;
}
@@ -105,11 +106,12 @@ public char[] getPassword() {
try {
KeyPair pair = (KeyPair) pem.readObject();
- if(pair==null) return null;
+ if (pair == null)
+ return null;
PublicKey key = pair.getPublic();
- return digestOpt(key,"MD5");
+ return digestOpt(key, "MD5");
} catch (RuntimeException e) {
- if (e==PRIVATE_KEY_WITH_PASSWORD)
+ if (e == PRIVATE_KEY_WITH_PASSWORD)
throw new IOException("This private key is password protected, which isn't supported yet");
throw e;
} finally {
@@ -136,15 +138,15 @@ public boolean isPrivateKey() throws IOException {
public com.amazonaws.services.ec2.model.KeyPair find(AmazonEC2 ec2) throws IOException, AmazonClientException {
String fp = getFingerprint();
String pfp = getPublicFingerprint();
- for(KeyPairInfo kp : ec2.describeKeyPairs().getKeyPairs()) {
- if(kp.getKeyFingerprint().equalsIgnoreCase(fp)) {
- com.amazonaws.services.ec2.model.KeyPair keyPair = new com.amazonaws.services.ec2.model.KeyPair();
- keyPair.setKeyName(kp.getKeyName());
- keyPair.setKeyFingerprint(fp);
- keyPair.setKeyMaterial(Secret.toString(privateKey));
- return keyPair;
+ for (KeyPairInfo kp : ec2.describeKeyPairs().getKeyPairs()) {
+ if (kp.getKeyFingerprint().equalsIgnoreCase(fp)) {
+ com.amazonaws.services.ec2.model.KeyPair keyPair = new com.amazonaws.services.ec2.model.KeyPair();
+ keyPair.setKeyName(kp.getKeyName());
+ keyPair.setKeyFingerprint(fp);
+ keyPair.setKeyMaterial(Secret.toString(privateKey));
+ return keyPair;
}
- if(kp.getKeyFingerprint().equalsIgnoreCase(pfp)) {
+ if (kp.getKeyFingerprint().equalsIgnoreCase(pfp)) {
com.amazonaws.services.ec2.model.KeyPair keyPair = new com.amazonaws.services.ec2.model.KeyPair();
keyPair.setKeyName(kp.getKeyName());
keyPair.setKeyFingerprint(pfp);
@@ -162,7 +164,7 @@ public int hashCode() {
@Override
public boolean equals(Object that) {
- return that instanceof EC2PrivateKey && this.privateKey.equals(((EC2PrivateKey)that).privateKey);
+ return that instanceof EC2PrivateKey && this.privateKey.equals(((EC2PrivateKey) that).privateKey);
}
@Override
@@ -170,11 +172,11 @@ public String toString() {
return privateKey.getPlainText();
}
- /*package*/ static String digest(PrivateKey k) throws IOException {
- return digestOpt(k,"SHA1");
+ /* package */static String digest(PrivateKey k) throws IOException {
+ return digestOpt(k, "SHA1");
}
- /*package*/ static String digestOpt(Key k, String dg) throws IOException {
+ /* package */static String digestOpt(Key k, String dg) throws IOException {
try {
MessageDigest md5 = MessageDigest.getInstance(dg);
@@ -187,9 +189,10 @@ public String toString() {
}
StringBuilder buf = new StringBuilder();
char[] hex = Hex.encodeHex(md5.digest());
- for( int i=0; i0) buf.append(':');
- buf.append(hex,i,2);
+ for (int i = 0; i < hex.length; i += 2) {
+ if (buf.length() > 0)
+ buf.append(':');
+ buf.append(hex, i, 2);
}
return buf.toString();
} catch (NoSuchAlgorithmException e) {
diff --git a/src/main/java/hudson/plugins/ec2/EC2RetentionStrategy.java b/src/main/java/hudson/plugins/ec2/EC2RetentionStrategy.java
index 22e185a73..80884007f 100644
--- a/src/main/java/hudson/plugins/ec2/EC2RetentionStrategy.java
+++ b/src/main/java/hudson/plugins/ec2/EC2RetentionStrategy.java
@@ -38,16 +38,18 @@
* @author Kohsuke Kawaguchi
*/
public class EC2RetentionStrategy extends RetentionStrategy {
- /** Number of minutes of idleness before an instance should be terminated.
- A value of zero indicates that the instance should never be automatically terminated.
- Negative values are times in remaining minutes before end of billing period. */
+ /**
+ * Number of minutes of idleness before an instance should be terminated. A value of zero indicates that the
+ * instance should never be automatically terminated. Negative values are times in remaining minutes before end of
+ * billing period.
+ */
public final int idleTerminationMinutes;
private transient ReentrantLock checkLock;
@DataBoundConstructor
public EC2RetentionStrategy(String idleTerminationMinutes) {
- readResolve();
+ readResolve();
if (idleTerminationMinutes == null || idleTerminationMinutes.trim() == "") {
this.idleTerminationMinutes = 0;
} else {
@@ -55,7 +57,7 @@ public EC2RetentionStrategy(String idleTerminationMinutes) {
try {
value = Integer.parseInt(idleTerminationMinutes);
} catch (NumberFormatException nfe) {
- LOGGER.info("Malformed default idleTermination value: " + idleTerminationMinutes);
+ LOGGER.info("Malformed default idleTermination value: " + idleTerminationMinutes);
}
this.idleTerminationMinutes = value;
@@ -63,8 +65,8 @@ public EC2RetentionStrategy(String idleTerminationMinutes) {
}
@Override
- public long check(EC2Computer c) {
- if (! checkLock.tryLock()) {
+ public long check(EC2Computer c) {
+ if (!checkLock.tryLock()) {
return 1;
} else {
try {
@@ -78,24 +80,26 @@ public long check(EC2Computer c) {
private long _check(EC2Computer c) {
/* If we've been told never to terminate, then we're done. */
- if (idleTerminationMinutes == 0) {
- return 1;
+ if (idleTerminationMinutes == 0) {
+ return 1;
}
/*
- * Don't idle-out instances that're offline, per JENKINS-23792. This
- * prevents a node from being idled down while it's still starting up.
+ * Don't idle-out instances that're offline, per JENKINS-23792. This prevents a node from being idled down while
+ * it's still starting up.
*/
if (c.isOffline()) {
return 1;
}
if (c.isIdle() && !disabled) {
- final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();
+ final long idleMilliseconds = System.currentTimeMillis() - c.getIdleStartMilliseconds();
if (idleTerminationMinutes > 0) {
- // TODO: really think about the right strategy here, see JENKINS-23792
+ // TODO: really think about the right strategy here, see
+ // JENKINS-23792
if (idleMilliseconds > TimeUnit2.MINUTES.toMillis(idleTerminationMinutes)) {
- LOGGER.info("Idle timeout of "+c.getName() + " after " + TimeUnit2.MILLISECONDS.toMinutes(idleMilliseconds) + " idle minutes");
+ LOGGER.info("Idle timeout of " + c.getName() + " after "
+ + TimeUnit2.MILLISECONDS.toMinutes(idleMilliseconds) + " idle minutes");
c.getNode().idleTimeout();
}
} else {
@@ -104,14 +108,20 @@ private long _check(EC2Computer c) {
uptime = c.getUptime();
} catch (InterruptedException e) {
// We'll just retry next time we test for idleness.
- LOGGER.fine("Interrupted while checking host uptime for " + c.getName() + ", will retry next check. Interrupted by: " + e);
- return 1;
+ LOGGER.fine("Interrupted while checking host uptime for " + c.getName()
+ + ", will retry next check. Interrupted by: " + e);
+ return 1;
}
- final int freeSecondsLeft = (60*60) - (int)(TimeUnit2.SECONDS.convert(uptime, TimeUnit2.MILLISECONDS) % (60*60));
- // if we have less "free" (aka already paid for) time left than our idle time, stop/terminate the instance
+ final int freeSecondsLeft = (60 * 60)
+ - (int) (TimeUnit2.SECONDS.convert(uptime, TimeUnit2.MILLISECONDS) % (60 * 60));
+ // if we have less "free" (aka already paid for) time left than
+ // our idle time, stop/terminate the instance
// See JENKINS-23821
- if (freeSecondsLeft <= (Math.abs(idleTerminationMinutes*60))) {
- LOGGER.info("Idle timeout of "+c.getName()+" after " + TimeUnit2.MILLISECONDS.toMinutes(idleMilliseconds) + " idle minutes, with " + TimeUnit2.MILLISECONDS.toMinutes(freeSecondsLeft) + " minutes remaining in billing period");
+ if (freeSecondsLeft <= (Math.abs(idleTerminationMinutes * 60))) {
+ LOGGER.info("Idle timeout of " + c.getName() + " after "
+ + TimeUnit2.MILLISECONDS.toMinutes(idleMilliseconds) + " idle minutes, with "
+ + TimeUnit2.MILLISECONDS.toMinutes(freeSecondsLeft)
+ + " minutes remaining in billing period");
c.getNode().idleTimeout();
}
}
@@ -124,25 +134,26 @@ private long _check(EC2Computer c) {
*/
@Override
public void start(EC2Computer c) {
- LOGGER.info("Start requested for " + c.getName());
+ LOGGER.info("Start requested for " + c.getName());
c.connect(false);
}
- // no registration since this retention strategy is used only for EC2 nodes that we provision automatically.
+ // no registration since this retention strategy is used only for EC2 nodes
+ // that we provision automatically.
// @Extension
public static class DescriptorImpl extends Descriptor> {
@Override
- public String getDisplayName() {
+ public String getDisplayName() {
return "EC2";
}
}
-
+
protected Object readResolve() {
- checkLock = new ReentrantLock(false);
- return this;
+ checkLock = new ReentrantLock(false);
+ return this;
}
private static final Logger LOGGER = Logger.getLogger(EC2RetentionStrategy.class.getName());
- public static boolean disabled = Boolean.getBoolean(EC2RetentionStrategy.class.getName()+".disabled");
+ public static boolean disabled = Boolean.getBoolean(EC2RetentionStrategy.class.getName() + ".disabled");
}
diff --git a/src/main/java/hudson/plugins/ec2/EC2SpotComputerLauncher.java b/src/main/java/hudson/plugins/ec2/EC2SpotComputerLauncher.java
index 789de7ce7..b7564ca4f 100644
--- a/src/main/java/hudson/plugins/ec2/EC2SpotComputerLauncher.java
+++ b/src/main/java/hudson/plugins/ec2/EC2SpotComputerLauncher.java
@@ -8,9 +8,9 @@
public class EC2SpotComputerLauncher extends ComputerLauncher {
- @Override
- public void launch(SlaveComputer _computer, TaskListener listener) {
- EC2Computer computer = (EC2Computer)_computer;
+ @Override
+ public void launch(SlaveComputer _computer, TaskListener listener) {
+ EC2Computer computer = (EC2Computer) _computer;
PrintStream logger = listener.getLogger();
logger.println("The instance " + computer.getNode().getNodeName() + " is a Spot slave.");
diff --git a/src/main/java/hudson/plugins/ec2/EC2SpotRetentionStrategy.java b/src/main/java/hudson/plugins/ec2/EC2SpotRetentionStrategy.java
index 4737003ea..01f8b4281 100644
--- a/src/main/java/hudson/plugins/ec2/EC2SpotRetentionStrategy.java
+++ b/src/main/java/hudson/plugins/ec2/EC2SpotRetentionStrategy.java
@@ -2,16 +2,16 @@
public class EC2SpotRetentionStrategy extends EC2RetentionStrategy {
- public EC2SpotRetentionStrategy(String idleTerminationMinutes) {
- super(idleTerminationMinutes);
- }
+ public EC2SpotRetentionStrategy(String idleTerminationMinutes) {
+ super(idleTerminationMinutes);
+ }
- @Override
- public void start(EC2Computer c) {
- // Do nothing, wait for the slave to connect via JNLP
- // If we try to connect to it right away there is no server
- // to connect to due to the delay in Spot requests being fulfilled
- // By doing nothing we prevent the failed connection error from
- // displaying to the user
- }
+ @Override
+ public void start(EC2Computer c) {
+ // Do nothing, wait for the slave to connect via JNLP
+ // If we try to connect to it right away there is no server
+ // to connect to due to the delay in Spot requests being fulfilled
+ // By doing nothing we prevent the failed connection error from
+ // displaying to the user
+ }
}
diff --git a/src/main/java/hudson/plugins/ec2/EC2SpotSlave.java b/src/main/java/hudson/plugins/ec2/EC2SpotSlave.java
index 9d138d8e1..a37cff776 100644
--- a/src/main/java/hudson/plugins/ec2/EC2SpotSlave.java
+++ b/src/main/java/hudson/plugins/ec2/EC2SpotSlave.java
@@ -24,134 +24,137 @@
public final class EC2SpotSlave extends EC2AbstractSlave {
- private final String spotInstanceRequestId;
-
- public EC2SpotSlave(String name, String spotInstanceRequestId, String description, String remoteFS, int numExecutors, Mode mode, String initScript, String tmpDir, String labelString, String remoteAdmin, String jvmopts, String idleTerminationMinutes, List tags, String cloudName, boolean usePrivateDnsName, int launchTimeout, AMITypeData amiType) throws FormException, IOException {
- this(name, spotInstanceRequestId, description, remoteFS, numExecutors, mode, initScript, tmpDir, labelString, Collections.>emptyList(), remoteAdmin, jvmopts, idleTerminationMinutes, tags, cloudName, usePrivateDnsName, launchTimeout, amiType);
- }
-
- @DataBoundConstructor
- public EC2SpotSlave(String name, String spotInstanceRequestId, String description, String remoteFS, int numExecutors, Mode mode, String initScript, String tmpDir, String labelString, List extends NodeProperty>> nodeProperties, String remoteAdmin, String jvmopts, String idleTerminationMinutes, List tags, String cloudName, boolean usePrivateDnsName, int launchTimeout, AMITypeData amiType) throws FormException, IOException {
-
- super(name, "", description, remoteFS, numExecutors, mode, labelString, new EC2SpotComputerLauncher(), new EC2SpotRetentionStrategy(idleTerminationMinutes), initScript, tmpDir, nodeProperties, remoteAdmin, jvmopts, false, idleTerminationMinutes, tags, cloudName, usePrivateDnsName, false, launchTimeout, amiType);
- this.name = name;
- this.spotInstanceRequestId = spotInstanceRequestId;
- }
-
-
- /**
- * Cancel the spot request for the instance.
- * Terminate the instance if it is up.
- * Remove the slave from Jenkins.
- */
- @Override
- public void terminate() {
- // Cancel the spot request
- AmazonEC2 ec2 = getCloud().connect();
-
- String instanceId = getInstanceId();
- List requestIds = Collections.singletonList(spotInstanceRequestId);
- CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(requestIds);
- try{
- ec2.cancelSpotInstanceRequests(cancelRequest);
- LOGGER.info("Canceled Spot request: "+ spotInstanceRequestId);
-
- // Terminate the slave if it is running
- if (instanceId != null && !instanceId.equals("")){
- if (!isAlive(true)) {
- /* The node has been killed externally, so we've nothing to do here */
- LOGGER.info("EC2 instance already terminated: "+instanceId);
- } else{
- TerminateInstancesRequest request = new TerminateInstancesRequest(Collections.singletonList(instanceId));
- ec2.terminateInstances(request);
- LOGGER.info("Terminated EC2 instance (terminated): "+instanceId);
- }
-
- }
-
- } catch (AmazonServiceException e){
- // Spot request is no longer valid
- LOGGER.log(Level.WARNING, "Failed to terminated instance and cancel Spot request: " + spotInstanceRequestId, e);
- } catch (AmazonClientException e){
- // Spot request is no longer valid
- LOGGER.log(Level.WARNING, "Failed to terminated instance and cancel Spot request: " + spotInstanceRequestId, e);
- }
-
- try{
- Hudson.getInstance().removeNode(this);
- } catch (IOException e){
- LOGGER.log(Level.WARNING,"Failed to remove slave: "+name, e);
- }
- }
-
- /**
- * Retrieve the SpotRequest for a requestId
- * @param requestId
- * @return SpotInstanceRequest object for the requestId, or null
- */
- private SpotInstanceRequest getSpotRequest(String spotRequestId){
- AmazonEC2 ec2 = getCloud().connect();
-
- DescribeSpotInstanceRequestsRequest dsirRequest = new DescribeSpotInstanceRequestsRequest().withSpotInstanceRequestIds(spotRequestId);
- DescribeSpotInstanceRequestsResult dsirResult = null;
- List siRequests = null;
-
- try{
- dsirResult = ec2.describeSpotInstanceRequests(dsirRequest);
- siRequests = dsirResult.getSpotInstanceRequests();
-
- } catch (AmazonServiceException e){
- // Spot request is no longer valid
- LOGGER.log(Level.WARNING, "Failed to fetch spot instance request for requestId: " + spotRequestId);
- } catch (AmazonClientException e){
- // Spot request is no longer valid
- LOGGER.log(Level.WARNING, "Failed to fetch spot instance request for requestId: " + spotRequestId);
- }
-
- if (dsirResult == null || siRequests.size() <= 0) return null;
- return siRequests.get(0);
- }
-
- /**
- * Accessor for the spotInstanceRequestId
- */
- public String getSpotInstanceRequestId(){
- return spotInstanceRequestId;
- }
-
- @Override
- public String getInstanceId() {
- if (instanceId == null || instanceId.equals("")) {
- SpotInstanceRequest sr = getSpotRequest(spotInstanceRequestId);
- if (sr != null)
- instanceId = sr.getInstanceId();
- }
- return instanceId;
- }
-
- @Override
- public void onConnected() {
- // The spot request has been fulfilled and is connected. If the Spot
- // request had tags, we want those on the instance.
- pushLiveInstancedata();
- }
-
- @Extension
- public static final class DescriptorImpl extends EC2AbstractSlave.DescriptorImpl {
-
- @Override
- public String getDisplayName() {
- return Messages.EC2SpotSlave_AmazonEC2SpotInstance();
- }
- }
-
- private static final Logger LOGGER = Logger.getLogger(EC2SpotSlave.class.getName());
-
- @Override
- public String getEc2Type() {
- String spotMaxBidPrice = this.getSpotRequest(spotInstanceRequestId).getSpotPrice();
- return Messages.EC2SpotSlave_Spot1() + spotMaxBidPrice.substring(0, spotMaxBidPrice.length() - 3) + Messages.EC2SpotSlave_Spot2();
- }
-
+ private final String spotInstanceRequestId;
+
+ public EC2SpotSlave(String name, String spotInstanceRequestId, String description, String remoteFS, int numExecutors, Mode mode, String initScript, String tmpDir, String labelString, String remoteAdmin, String jvmopts, String idleTerminationMinutes, List tags, String cloudName, boolean usePrivateDnsName, int launchTimeout, AMITypeData amiType)
+ throws FormException, IOException {
+ this(name, spotInstanceRequestId, description, remoteFS, numExecutors, mode, initScript, tmpDir, labelString, Collections.> emptyList(), remoteAdmin, jvmopts, idleTerminationMinutes, tags, cloudName, usePrivateDnsName, launchTimeout, amiType);
+ }
+
+ @DataBoundConstructor
+ public EC2SpotSlave(String name, String spotInstanceRequestId, String description, String remoteFS, int numExecutors, Mode mode, String initScript, String tmpDir, String labelString, List extends NodeProperty>> nodeProperties, String remoteAdmin, String jvmopts, String idleTerminationMinutes, List tags, String cloudName, boolean usePrivateDnsName, int launchTimeout, AMITypeData amiType)
+ throws FormException, IOException {
+
+ super(name, "", description, remoteFS, numExecutors, mode, labelString, new EC2SpotComputerLauncher(), new EC2SpotRetentionStrategy(idleTerminationMinutes), initScript, tmpDir, nodeProperties, remoteAdmin, jvmopts, false, idleTerminationMinutes, tags, cloudName, usePrivateDnsName, false, launchTimeout, amiType);
+ this.name = name;
+ this.spotInstanceRequestId = spotInstanceRequestId;
+ }
+
+ /**
+ * Cancel the spot request for the instance. Terminate the instance if it is up. Remove the slave from Jenkins.
+ */
+ @Override
+ public void terminate() {
+ // Cancel the spot request
+ AmazonEC2 ec2 = getCloud().connect();
+
+ String instanceId = getInstanceId();
+ List requestIds = Collections.singletonList(spotInstanceRequestId);
+ CancelSpotInstanceRequestsRequest cancelRequest = new CancelSpotInstanceRequestsRequest(requestIds);
+ try {
+ ec2.cancelSpotInstanceRequests(cancelRequest);
+ LOGGER.info("Canceled Spot request: " + spotInstanceRequestId);
+
+ // Terminate the slave if it is running
+ if (instanceId != null && !instanceId.equals("")) {
+ if (!isAlive(true)) {
+ /*
+ * The node has been killed externally, so we've nothing to do here
+ */
+ LOGGER.info("EC2 instance already terminated: " + instanceId);
+ } else {
+ TerminateInstancesRequest request = new TerminateInstancesRequest(Collections.singletonList(instanceId));
+ ec2.terminateInstances(request);
+ LOGGER.info("Terminated EC2 instance (terminated): " + instanceId);
+ }
+
+ }
+
+ } catch (AmazonServiceException e) {
+ // Spot request is no longer valid
+ LOGGER.log(Level.WARNING, "Failed to terminated instance and cancel Spot request: " + spotInstanceRequestId, e);
+ } catch (AmazonClientException e) {
+ // Spot request is no longer valid
+ LOGGER.log(Level.WARNING, "Failed to terminated instance and cancel Spot request: " + spotInstanceRequestId, e);
+ }
+
+ try {
+ Hudson.getInstance().removeNode(this);
+ } catch (IOException e) {
+ LOGGER.log(Level.WARNING, "Failed to remove slave: " + name, e);
+ }
+ }
+
+ /**
+ * Retrieve the SpotRequest for a requestId
+ *
+ * @param requestId
+ * @return SpotInstanceRequest object for the requestId, or null
+ */
+ private SpotInstanceRequest getSpotRequest(String spotRequestId) {
+ AmazonEC2 ec2 = getCloud().connect();
+
+ DescribeSpotInstanceRequestsRequest dsirRequest = new DescribeSpotInstanceRequestsRequest().withSpotInstanceRequestIds(spotRequestId);
+ DescribeSpotInstanceRequestsResult dsirResult = null;
+ List siRequests = null;
+
+ try {
+ dsirResult = ec2.describeSpotInstanceRequests(dsirRequest);
+ siRequests = dsirResult.getSpotInstanceRequests();
+
+ } catch (AmazonServiceException e) {
+ // Spot request is no longer valid
+ LOGGER.log(Level.WARNING, "Failed to fetch spot instance request for requestId: " + spotRequestId);
+ } catch (AmazonClientException e) {
+ // Spot request is no longer valid
+ LOGGER.log(Level.WARNING, "Failed to fetch spot instance request for requestId: " + spotRequestId);
+ }
+
+ if (dsirResult == null || siRequests.size() <= 0)
+ return null;
+ return siRequests.get(0);
+ }
+
+ /**
+ * Accessor for the spotInstanceRequestId
+ */
+ public String getSpotInstanceRequestId() {
+ return spotInstanceRequestId;
+ }
+
+ @Override
+ public String getInstanceId() {
+ if (instanceId == null || instanceId.equals("")) {
+ SpotInstanceRequest sr = getSpotRequest(spotInstanceRequestId);
+ if (sr != null)
+ instanceId = sr.getInstanceId();
+ }
+ return instanceId;
+ }
+
+ @Override
+ public void onConnected() {
+ // The spot request has been fulfilled and is connected. If the Spot
+ // request had tags, we want those on the instance.
+ pushLiveInstancedata();
+ }
+
+ @Extension
+ public static final class DescriptorImpl extends EC2AbstractSlave.DescriptorImpl {
+
+ @Override
+ public String getDisplayName() {
+ return Messages.EC2SpotSlave_AmazonEC2SpotInstance();
+ }
+ }
+
+ private static final Logger LOGGER = Logger.getLogger(EC2SpotSlave.class.getName());
+
+ @Override
+ public String getEc2Type() {
+ String spotMaxBidPrice = this.getSpotRequest(spotInstanceRequestId).getSpotPrice();
+ return Messages.EC2SpotSlave_Spot1() + spotMaxBidPrice.substring(0, spotMaxBidPrice.length() - 3)
+ + Messages.EC2SpotSlave_Spot2();
+ }
}
diff --git a/src/main/java/hudson/plugins/ec2/EC2Tag.java b/src/main/java/hudson/plugins/ec2/EC2Tag.java
index 5c4910545..7108d48b6 100644
--- a/src/main/java/hudson/plugins/ec2/EC2Tag.java
+++ b/src/main/java/hudson/plugins/ec2/EC2Tag.java
@@ -33,79 +33,75 @@
import com.amazonaws.services.ec2.model.Tag;
-
-public class EC2Tag extends AbstractDescribableImpl
-{
- private String name;
- private String value;
-
- /**
- * Tag name for the specific jenkings slave type tag, used to identify the
- * EC2 instances provisioned by this plugin.
- */
- public static final String TAG_NAME_JENKINS_SLAVE_TYPE = "jenkins_slave_type";
-
- @DataBoundConstructor
- public EC2Tag(String name, String value) {
- this.name = name;
- this.value = value;
- }
-
-
- /* Constructor from Amazon Tag */
- public EC2Tag(Tag t) {
- name = t.getKey();
- value = t.getValue();
- }
-
-
- public String getName() {
- return name;
- }
-
-
- public String getValue() {
- return value;
- }
-
-
- @Override
- public String toString() {
- return "EC2Tag: " + name + "->" + value;
- }
-
-
- @Override
- public boolean equals(Object o) {
- if (o == null) return false;
- if (!(o instanceof EC2Tag)) return false;
-
- EC2Tag other = (EC2Tag) o;
- if ((name == null && other.name != null) || !name.equals( other.name)) return false;
- if ((value == null && other.value != null) || !value.equals( other.value)) return false;
-
- return true;
- }
-
-
- @Extension
- public static class DescriptorImpl extends Descriptor {
- @Override
- public String getDisplayName() { return ""; }
- }
-
-
- /* Helper method to convert lists of Amazon tags into internal format */
- public static List fromAmazonTags(List amazon_tags) {
- if (null == amazon_tags) {
- return null;
- }
-
- LinkedList result = new LinkedList();
- for (Tag t : amazon_tags) {
- result.add(new EC2Tag(t));
- }
-
- return result;
- }
+public class EC2Tag extends AbstractDescribableImpl {
+ private String name;
+ private String value;
+
+ /**
+ * Tag name for the specific jenkings slave type tag, used to identify the EC2 instances provisioned by this plugin.
+ */
+ public static final String TAG_NAME_JENKINS_SLAVE_TYPE = "jenkins_slave_type";
+
+ @DataBoundConstructor
+ public EC2Tag(String name, String value) {
+ this.name = name;
+ this.value = value;
+ }
+
+ /* Constructor from Amazon Tag */
+ public EC2Tag(Tag t) {
+ name = t.getKey();
+ value = t.getValue();
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public String getValue() {
+ return value;
+ }
+
+ @Override
+ public String toString() {
+ return "EC2Tag: " + name + "->" + value;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o == null)
+ return false;
+ if (!(o instanceof EC2Tag))
+ return false;
+
+ EC2Tag other = (EC2Tag) o;
+ if ((name == null && other.name != null) || !name.equals(other.name))
+ return false;
+ if ((value == null && other.value != null) || !value.equals(other.value))
+ return false;
+
+ return true;
+ }
+
+ @Extension
+ public static class DescriptorImpl extends Descriptor {
+ @Override
+ public String getDisplayName() {
+ return "";
+ }
+ }
+
+ /* Helper method to convert lists of Amazon tags into internal format */
+ public static List fromAmazonTags(List amazon_tags) {
+ if (null == amazon_tags) {
+ return null;
+ }
+
+ LinkedList result = new LinkedList();
+ for (Tag t : amazon_tags) {
+ result.add(new EC2Tag(t));
+ }
+
+ return result;
+ }
}
diff --git a/src/main/java/hudson/plugins/ec2/Eucalyptus.java b/src/main/java/hudson/plugins/ec2/Eucalyptus.java
index da59ab8a1..e29d714ce 100644
--- a/src/main/java/hudson/plugins/ec2/Eucalyptus.java
+++ b/src/main/java/hudson/plugins/ec2/Eucalyptus.java
@@ -46,7 +46,8 @@ public class Eucalyptus extends EC2Cloud {
public final URL s3endpoint;
@DataBoundConstructor
- public Eucalyptus(URL ec2endpoint, URL s3endpoint, boolean useInstanceProfileForCredentials, String accessId, String secretKey, String privateKey, String instanceCapStr, List templates) throws IOException {
+ public Eucalyptus(URL ec2endpoint, URL s3endpoint, boolean useInstanceProfileForCredentials, String accessId, String secretKey, String privateKey, String instanceCapStr, List templates)
+ throws IOException {
super("eucalyptus", useInstanceProfileForCredentials, accessId, secretKey, privateKey, instanceCapStr, templates);
this.ec2endpoint = ec2endpoint;
this.s3endpoint = s3endpoint;
@@ -70,18 +71,14 @@ public String getDisplayName() {
}
@Override
- public FormValidation doTestConnection(
- @QueryParameter URL ec2endpoint,
- @QueryParameter boolean useInstanceProfileForCredentials,
- @QueryParameter String accessId,
- @QueryParameter String secretKey,
- @QueryParameter String privateKey) throws IOException, ServletException {
+ public FormValidation doTestConnection(@QueryParameter URL ec2endpoint, @QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String accessId, @QueryParameter String secretKey, @QueryParameter String privateKey)
+ throws IOException, ServletException {
return super.doTestConnection(ec2endpoint, useInstanceProfileForCredentials, accessId, secretKey, privateKey);
}
@Override
- public FormValidation doGenerateKey(
- StaplerResponse rsp, @QueryParameter URL url, @QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String accessId, @QueryParameter String secretKey) throws IOException, ServletException {
+ public FormValidation doGenerateKey(StaplerResponse rsp, @QueryParameter URL url, @QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String accessId, @QueryParameter String secretKey)
+ throws IOException, ServletException {
return super.doGenerateKey(rsp, url, useInstanceProfileForCredentials, accessId, secretKey);
}
}
diff --git a/src/main/java/hudson/plugins/ec2/InstanceState.java b/src/main/java/hudson/plugins/ec2/InstanceState.java
index 917b93bdb..4384bdca2 100644
--- a/src/main/java/hudson/plugins/ec2/InstanceState.java
+++ b/src/main/java/hudson/plugins/ec2/InstanceState.java
@@ -24,23 +24,18 @@
package hudson.plugins.ec2;
/**
- * Constants that represent the running state of EC2.
+ * Constants that represent the running state of EC2.
*
* @author Kohsuke Kawaguchi
*/
public enum InstanceState {
- PENDING,
- RUNNING,
- SHUTTING_DOWN,
- TERMINATED,
- STOPPING,
- STOPPED;
+ PENDING, RUNNING, SHUTTING_DOWN, TERMINATED, STOPPING, STOPPED;
public String getCode() {
- return name().toLowerCase().replace('_','-');
+ return name().toLowerCase().replace('_', '-');
}
public static InstanceState find(String name) {
- return Enum.valueOf(InstanceState.class,name.toUpperCase().replace('-','_'));
+ return Enum.valueOf(InstanceState.class, name.toUpperCase().replace('-', '_'));
}
}
diff --git a/src/main/java/hudson/plugins/ec2/InstanceTypeConverter.java b/src/main/java/hudson/plugins/ec2/InstanceTypeConverter.java
index 15c08b810..c659aa263 100644
--- a/src/main/java/hudson/plugins/ec2/InstanceTypeConverter.java
+++ b/src/main/java/hudson/plugins/ec2/InstanceTypeConverter.java
@@ -39,43 +39,43 @@
*/
public class InstanceTypeConverter implements Converter {
- private static final Map TYPICAL_INSTANCE_TYPES = new HashMap();
+ private static final Map TYPICAL_INSTANCE_TYPES = new HashMap();
- static {
- TYPICAL_INSTANCE_TYPES.put("DEFAULT", InstanceType.M1Small);
- TYPICAL_INSTANCE_TYPES.put("LARGE", InstanceType.M1Large);
- TYPICAL_INSTANCE_TYPES.put("XLARGE", InstanceType.M1Xlarge);
- TYPICAL_INSTANCE_TYPES.put("MEDIUM_HCPU", InstanceType.C1Medium);
- TYPICAL_INSTANCE_TYPES.put("XLARGE_HCPU", InstanceType.C1Xlarge);
- TYPICAL_INSTANCE_TYPES.put("XLARGE_HMEM", InstanceType.M2Xlarge);
- TYPICAL_INSTANCE_TYPES.put("XLARGE_HMEM_M3", InstanceType.M3Xlarge);
- TYPICAL_INSTANCE_TYPES.put("XLARGE_DOUBLE_HMEM", InstanceType.M22xlarge);
- TYPICAL_INSTANCE_TYPES.put("XLARGE_QUAD_HMEM", InstanceType.M24xlarge);
- TYPICAL_INSTANCE_TYPES.put("XLARGE_QUAD_HMEM_M3", InstanceType.M32xlarge);
- TYPICAL_INSTANCE_TYPES.put("XLARGE_CLUSTER_COMPUTE", InstanceType.Cc14xlarge);
- }
+ static {
+ TYPICAL_INSTANCE_TYPES.put("DEFAULT", InstanceType.M1Small);
+ TYPICAL_INSTANCE_TYPES.put("LARGE", InstanceType.M1Large);
+ TYPICAL_INSTANCE_TYPES.put("XLARGE", InstanceType.M1Xlarge);
+ TYPICAL_INSTANCE_TYPES.put("MEDIUM_HCPU", InstanceType.C1Medium);
+ TYPICAL_INSTANCE_TYPES.put("XLARGE_HCPU", InstanceType.C1Xlarge);
+ TYPICAL_INSTANCE_TYPES.put("XLARGE_HMEM", InstanceType.M2Xlarge);
+ TYPICAL_INSTANCE_TYPES.put("XLARGE_HMEM_M3", InstanceType.M3Xlarge);
+ TYPICAL_INSTANCE_TYPES.put("XLARGE_DOUBLE_HMEM", InstanceType.M22xlarge);
+ TYPICAL_INSTANCE_TYPES.put("XLARGE_QUAD_HMEM", InstanceType.M24xlarge);
+ TYPICAL_INSTANCE_TYPES.put("XLARGE_QUAD_HMEM_M3", InstanceType.M32xlarge);
+ TYPICAL_INSTANCE_TYPES.put("XLARGE_CLUSTER_COMPUTE", InstanceType.Cc14xlarge);
+ }
- public boolean canConvert(Class type) {
- return InstanceType.class == type;
- }
+ public boolean canConvert(Class type) {
+ return InstanceType.class == type;
+ }
- public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
- InstanceType instanceType = (InstanceType) source;
- writer.setValue(instanceType.name());
- }
+ public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
+ InstanceType instanceType = (InstanceType) source;
+ writer.setValue(instanceType.name());
+ }
- public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
- InstanceType instanceType = null;
+ public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
+ InstanceType instanceType = null;
- String stringValue = reader.getValue();
+ String stringValue = reader.getValue();
- try {
- instanceType = InstanceType.valueOf(stringValue);
- } catch (IllegalArgumentException e) {
- instanceType = TYPICAL_INSTANCE_TYPES.get(stringValue.toUpperCase());
- }
+ try {
+ instanceType = InstanceType.valueOf(stringValue);
+ } catch (IllegalArgumentException e) {
+ instanceType = TYPICAL_INSTANCE_TYPES.get(stringValue.toUpperCase());
+ }
- return instanceType;
- }
+ return instanceType;
+ }
}
diff --git a/src/main/java/hudson/plugins/ec2/PluginImpl.java b/src/main/java/hudson/plugins/ec2/PluginImpl.java
index 7b3fcc94b..a72620f73 100644
--- a/src/main/java/hudson/plugins/ec2/PluginImpl.java
+++ b/src/main/java/hudson/plugins/ec2/PluginImpl.java
@@ -38,16 +38,16 @@ public class PluginImpl extends Plugin implements Describable {
@Override
public void start() throws Exception {
// backward compatibility with the legacy class name
- Jenkins.XSTREAM.alias("hudson.plugins.ec2.EC2Cloud",AmazonEC2Cloud.class);
- Jenkins.XSTREAM.alias("hudson.plugins.ec2.EC2Slave",EC2OndemandSlave.class);
+ Jenkins.XSTREAM.alias("hudson.plugins.ec2.EC2Cloud", AmazonEC2Cloud.class);
+ Jenkins.XSTREAM.alias("hudson.plugins.ec2.EC2Slave", EC2OndemandSlave.class);
// backward compatibility with the legacy instance type
Jenkins.XSTREAM.registerConverter(new InstanceTypeConverter());
-
+
load();
}
public DescriptorImpl getDescriptor() {
- return (DescriptorImpl)Hudson.getInstance().getDescriptorOrDie(getClass());
+ return (DescriptorImpl) Hudson.getInstance().getDescriptorOrDie(getClass());
}
public static PluginImpl get() {
diff --git a/src/main/java/hudson/plugins/ec2/SlaveTemplate.java b/src/main/java/hudson/plugins/ec2/SlaveTemplate.java
index 8c9ea3b29..0d54f71da 100644
--- a/src/main/java/hudson/plugins/ec2/SlaveTemplate.java
+++ b/src/main/java/hudson/plugins/ec2/SlaveTemplate.java
@@ -142,12 +142,11 @@ public class SlaveTemplate implements Describable {
public boolean connectBySSHProcess;
public final boolean connectUsingPublicIp;
- private transient /*almost final*/ Set labelSet;
- private transient /*almost final*/ Set securityGroupSet;
+ private transient/* almost final */Set labelSet;
+ private transient/* almost final */Set securityGroupSet;
/*
- * Necessary to handle reading from old configurations. The UnixData object is
- * created in readResolve()
+ * Necessary to handle reading from old configurations. The UnixData object is created in readResolve()
*/
@Deprecated
public transient String sshPort;
@@ -191,7 +190,7 @@ public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, Stri
try {
this.launchTimeout = Integer.parseInt(launchTimeoutStr);
- } catch (NumberFormatException nfe ) {
+ } catch (NumberFormatException nfe) {
this.launchTimeout = Integer.MAX_VALUE;
}
@@ -201,25 +200,25 @@ public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, Stri
readResolve(); // initialize
}
-
+
public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping, boolean connectBySSHProcess) {
this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, connectBySSHProcess, false);
}
public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, AMITypeData amiType, String jvmopts, boolean stopOnTerminate, String subnetId, List tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, boolean useDedicatedTenancy, String launchTimeoutStr, boolean associatePublicIp, String customDeviceMapping) {
- this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, false);
+ this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, amiType, jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, useDedicatedTenancy, launchTimeoutStr, associatePublicIp, customDeviceMapping, false);
}
/**
* Backward compatible constructor for reloading previous version data
*/
- public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, String sshPort, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix, String jvmopts, boolean stopOnTerminate, String subnetId, List tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, String launchTimeoutStr)
- {
+ public SlaveTemplate(String ami, String zone, SpotConfiguration spotConfig, String securityGroups, String remoteFS, String sshPort, InstanceType type, boolean ebsOptimized, String labelString, Node.Mode mode, String description, String initScript, String tmpDir, String userData, String numExecutors, String remoteAdmin, String rootCommandPrefix, String jvmopts, boolean stopOnTerminate, String subnetId, List tags, String idleTerminationMinutes, boolean usePrivateDnsName, String instanceCapStr, String iamInstanceProfile, boolean useEphemeralDevices, String launchTimeoutStr) {
this(ami, zone, spotConfig, securityGroups, remoteFS, type, ebsOptimized, labelString, mode, description, initScript, tmpDir, userData, numExecutors, remoteAdmin, new UnixData(rootCommandPrefix, sshPort), jvmopts, stopOnTerminate, subnetId, tags, idleTerminationMinutes, usePrivateDnsName, instanceCapStr, iamInstanceProfile, useEphemeralDevices, false, launchTimeoutStr, false, null);
}
public boolean isConnectBySSHProcess() {
- // See src/main/resources/hudson/plugins/ec2/SlaveTemplate/help-connectBySSHProcess.html
+ // See
+ // src/main/resources/hudson/plugins/ec2/SlaveTemplate/help-connectBySSHProcess.html
return connectBySSHProcess;
}
@@ -227,8 +226,8 @@ public EC2Cloud getParent() {
return parent;
}
- public String getBidType(){
- if(spotConfig == null)
+ public String getBidType() {
+ if (spotConfig == null)
return null;
return spotConfig.spotInstanceBidType;
}
@@ -242,7 +241,7 @@ public Node.Mode getMode() {
}
public String getDisplayName() {
- return description+" ("+ami+")";
+ return description + " (" + ami + ")";
}
String getZone() {
@@ -277,7 +276,7 @@ public int getSshPort() {
try {
String sshPort = "";
if (amiType.isUnix()) {
- sshPort = ((UnixData)amiType).getSshPort();
+ sshPort = ((UnixData) amiType).getSshPort();
}
return Integer.parseInt(sshPort);
} catch (NumberFormatException e) {
@@ -290,7 +289,7 @@ public String getRemoteAdmin() {
}
public String getRootCommandPrefix() {
- return amiType.isUnix() ? ((UnixData)amiType).getRootCommandPrefix() : "";
+ return amiType.isUnix() ? ((UnixData) amiType).getRootCommandPrefix() : "";
}
public String getSubnetId() {
@@ -301,13 +300,13 @@ public boolean getAssociatePublicIp() {
return associatePublicIp;
}
- public boolean isConnectUsingPublicIp()
- {
+ public boolean isConnectUsingPublicIp() {
return connectUsingPublicIp;
}
public List getTags() {
- if (null == tags) return null;
+ if (null == tags)
+ return null;
return Collections.unmodifiableList(tags);
}
@@ -319,7 +318,7 @@ public boolean getUseDedicatedTenancy() {
return useDedicatedTenancy;
}
- public Set getLabelSet(){
+ public Set getLabelSet() {
return labelSet;
}
@@ -336,14 +335,14 @@ public int getInstanceCap() {
}
public String getInstanceCapStr() {
- if (instanceCap==Integer.MAX_VALUE) {
+ if (instanceCap == Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(instanceCap);
}
}
- public String getSpotMaxBidPrice(){
+ public String getSpotMaxBidPrice() {
if (spotConfig == null)
return null;
return SpotConfiguration.normalizeBid(spotConfig.spotMaxBidPrice);
@@ -359,15 +358,14 @@ public String getIamInstanceProfile() {
* @return always non-null. This needs to be then added to {@link Hudson#addNode(Node)}.
*/
public EC2AbstractSlave provision(TaskListener listener) throws AmazonClientException, IOException {
- if (this.spotConfig != null){
+ if (this.spotConfig != null) {
return provisionSpot(listener);
}
return provisionOndemand(listener);
}
/**
- * Provisions an On-demand EC2 slave by launching a new instance or
- * starting a previously-stopped instance.
+ * Provisions an On-demand EC2 slave by launching a new instance or starting a previously-stopped instance.
*/
private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonClientException, IOException {
PrintStream logger = listener.getLogger();
@@ -387,8 +385,7 @@ private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonC
if (useEphemeralDevices) {
setupEphemeralDeviceMapping(riRequest);
- }
- else {
+ } else {
setupCustomDeviceMapping(riRequest);
}
@@ -407,20 +404,22 @@ private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonC
if (StringUtils.isNotBlank(getSubnetId())) {
if (getAssociatePublicIp()) {
net.setSubnetId(getSubnetId());
- }else{
+ } else {
riRequest.setSubnetId(getSubnetId());
}
diFilters.add(new Filter("subnet-id").withValues(getSubnetId()));
- /* If we have a subnet ID then we can only use VPC security groups */
+ /*
+ * If we have a subnet ID then we can only use VPC security groups
+ */
if (!securityGroupSet.isEmpty()) {
List group_ids = getEc2SecurityGroups(ec2);
if (!group_ids.isEmpty()) {
if (getAssociatePublicIp()) {
net.setGroups(group_ids);
- }else{
+ } else {
riRequest.setSecurityGroupIds(group_ids);
}
@@ -451,28 +450,27 @@ private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonC
HashSet inst_tags = null;
if (tags != null && !tags.isEmpty()) {
inst_tags = new HashSet();
- for(EC2Tag t : tags) {
+ for (EC2Tag t : tags) {
inst_tags.add(new Tag(t.getName(), t.getValue()));
- diFilters.add(new Filter("tag:"+t.getName()).withValues(t.getValue()));
+ diFilters.add(new Filter("tag:" + t.getName()).withValues(t.getValue()));
if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
hasCustomTypeTag = true;
}
}
}
if (!hasCustomTypeTag) {
- if (inst_tags == null){
+ if (inst_tags == null) {
inst_tags = new HashSet();
}
inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "demand"));
}
DescribeInstancesRequest diRequest = new DescribeInstancesRequest();
- diFilters.add(new Filter("instance-state-name").withValues(InstanceStateName.Stopped.toString(),
- InstanceStateName.Stopping.toString()));
+ diFilters.add(new Filter("instance-state-name").withValues(InstanceStateName.Stopped.toString(), InstanceStateName.Stopping.toString()));
diRequest.setFilters(diFilters);
- logger.println("Looking for existing instances with describe-instance: "+diRequest);
- LOGGER.fine("Looking for existing instances with describe-instance: "+diRequest);
+ logger.println("Looking for existing instances with describe-instance: " + diRequest);
+ LOGGER.fine("Looking for existing instances with describe-instance: " + diRequest);
DescribeInstancesResult diResult = ec2.describeInstances(diRequest);
@@ -480,15 +478,15 @@ private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonC
if (StringUtils.isNotBlank(getIamInstanceProfile())) {
riRequest.setIamInstanceProfile(new IamInstanceProfileSpecification().withArn(getIamInstanceProfile()));
// cannot filter on IAM Instance Profile, so search in result
- reservationLoop:
- for (Reservation reservation : diResult.getReservations()) {
- for (Instance instance : reservation.getInstances()) {
- if (instance.getIamInstanceProfile() != null && instance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())) {
- existingInstance = instance;
- break reservationLoop;
- }
+ reservationLoop: for (Reservation reservation : diResult.getReservations()) {
+ for (Instance instance : reservation.getInstances()) {
+ if (instance.getIamInstanceProfile() != null
+ && instance.getIamInstanceProfile().getArn().equals(getIamInstanceProfile())) {
+ existingInstance = instance;
+ break reservationLoop;
}
}
+ }
} else if (diResult.getReservations().size() > 0) {
existingInstance = diResult.getReservations().get(0).getInstances().get(0);
}
@@ -497,46 +495,47 @@ private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonC
// Have to create a new instance
Instance inst = ec2.runInstances(riRequest).getReservation().getInstances().get(0);
-
/* Now that we have our instance, we can set tags on it */
if (inst_tags != null) {
updateRemoteTags(ec2, inst_tags, "InvalidInstanceID.NotFound", inst.getInstanceId());
- // That was a remote request - we should also update our local instance data.
+ // That was a remote request - we should also update our
+ // local instance data.
inst.setTags(inst_tags);
}
- logger.println("No existing instance found - created: "+inst);
- LOGGER.info("No existing instance found - created: "+inst);
+ logger.println("No existing instance found - created: " + inst);
+ LOGGER.info("No existing instance found - created: " + inst);
return newOndemandSlave(inst);
}
- logger.println("Found existing stopped instance: "+existingInstance);
- LOGGER.info("Found existing stopped instance: "+existingInstance);
+ logger.println("Found existing stopped instance: " + existingInstance);
+ LOGGER.info("Found existing stopped instance: " + existingInstance);
List instances = new ArrayList();
instances.add(existingInstance.getInstanceId());
StartInstancesRequest siRequest = new StartInstancesRequest(instances);
StartInstancesResult siResult = ec2.startInstances(siRequest);
- logger.println("Starting existing instance: "+existingInstance+ " result:"+siResult);
- LOGGER.fine("Starting existing instance: "+existingInstance+ " result:"+siResult);
+ logger.println("Starting existing instance: " + existingInstance + " result:" + siResult);
+ LOGGER.fine("Starting existing instance: " + existingInstance + " result:" + siResult);
- for (EC2AbstractSlave ec2Node: NodeIterator.nodes(EC2AbstractSlave.class)){
+ for (EC2AbstractSlave ec2Node : NodeIterator.nodes(EC2AbstractSlave.class)) {
if (ec2Node.getInstanceId().equals(existingInstance.getInstanceId())) {
- logger.println("Found existing corresponding Jenkins slave: "+ec2Node);
- LOGGER.finer("Found existing corresponding Jenkins slave: "+ec2Node);
+ logger.println("Found existing corresponding Jenkins slave: " + ec2Node);
+ LOGGER.finer("Found existing corresponding Jenkins slave: " + ec2Node);
return ec2Node;
}
}
// Existing slave not found
- logger.println("Creating new Jenkins slave for existing instance: "+existingInstance);
- LOGGER.info("Creating new Jenkins slave for existing instance: "+existingInstance);
+ logger.println("Creating new Jenkins slave for existing instance: " + existingInstance);
+ LOGGER.info("Creating new Jenkins slave for existing instance: " + existingInstance);
return newOndemandSlave(existingInstance);
} catch (FormException e) {
- throw new AssertionError(); // we should have discovered all configuration issues upfront
- } catch (InterruptedException e) {
+ throw new AssertionError(); // we should have discovered all
+ // configuration issues upfront
+ } catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@@ -546,26 +545,22 @@ private void setupEphemeralDeviceMapping(RunInstancesRequest riRequest) {
final List oldDeviceMapping = getAmiBlockDeviceMappings();
final Set occupiedDevices = new HashSet();
- for (final BlockDeviceMapping mapping: oldDeviceMapping ) {
+ for (final BlockDeviceMapping mapping : oldDeviceMapping) {
occupiedDevices.add(mapping.getDeviceName());
}
- final List available = new ArrayList(Arrays.asList(
- "ephemeral0", "ephemeral1", "ephemeral2", "ephemeral3"
- ));
+ final List available = new ArrayList(Arrays.asList("ephemeral0", "ephemeral1", "ephemeral2", "ephemeral3"));
final List newDeviceMapping = new ArrayList(4);
for (char suffix = 'b'; suffix <= 'z' && !available.isEmpty(); suffix++) {
final String deviceName = String.format("/dev/xvd%s", suffix);
- if (occupiedDevices.contains(deviceName)) continue;
+ if (occupiedDevices.contains(deviceName))
+ continue;
- final BlockDeviceMapping newMapping = new BlockDeviceMapping()
- .withDeviceName(deviceName)
- .withVirtualName(available.get(0))
- ;
+ final BlockDeviceMapping newMapping = new BlockDeviceMapping().withDeviceName(deviceName).withVirtualName(available.get(0));
newDeviceMapping.add(newMapping);
available.remove(0);
@@ -580,7 +575,7 @@ private List getAmiBlockDeviceMappings() {
* AmazonEC2#describeImageAttribute does not work due to a bug
* https://forums.aws.amazon.com/message.jspa?messageID=231972
*/
- for (final Image image: getParent().connect().describeImages().getImages()) {
+ for (final Image image : getParent().connect().describeImages().getImages()) {
if (ami.equals(image.getImageId())) {
@@ -604,8 +599,8 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
PrintStream logger = listener.getLogger();
AmazonEC2 ec2 = getParent().connect();
- try{
- logger.println("Launching " + ami + " for template " + description);
+ try {
+ logger.println("Launching " + ami + " for template " + description);
LOGGER.info("Launching " + ami + " for template " + description);
KeyPair keyPair = getKeyPair(ec2);
@@ -613,8 +608,9 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
RequestSpotInstancesRequest spotRequest = new RequestSpotInstancesRequest();
// Validate spot bid before making the request
- if (getSpotMaxBidPrice() == null){
- // throw new FormException("Invalid Spot price specified: " + getSpotMaxBidPrice(), "spotMaxBidPrice");
+ if (getSpotMaxBidPrice() == null) {
+ // throw new FormException("Invalid Spot price specified: " +
+ // getSpotMaxBidPrice(), "spotMaxBidPrice");
throw new AmazonClientException("Invalid Spot price specified: " + getSpotMaxBidPrice());
}
@@ -636,17 +632,19 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
if (StringUtils.isNotBlank(getSubnetId())) {
if (getAssociatePublicIp()) {
net.setSubnetId(getSubnetId());
- }else{
+ } else {
launchSpecification.setSubnetId(getSubnetId());
}
- /* If we have a subnet ID then we can only use VPC security groups */
+ /*
+ * If we have a subnet ID then we can only use VPC security groups
+ */
if (!securityGroupSet.isEmpty()) {
List group_ids = getEc2SecurityGroups(ec2);
- if (!group_ids.isEmpty()){
+ if (!group_ids.isEmpty()) {
if (getAssociatePublicIp()) {
net.setGroups(group_ids);
- }else{
+ } else {
ArrayList groups = new ArrayList();
for (String group_id : group_ids) {
@@ -666,20 +664,29 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
}
// The slave must know the Jenkins server to register with as well
- // as the name of the node in Jenkins it should register as. The only
- // way to give information to the Spot slaves is through the ec2 user data
+ // as the name of the node in Jenkins it should register as. The
+ // only
+ // way to give information to the Spot slaves is through the ec2
+ // user data
String jenkinsUrl = Hudson.getInstance().getRootUrl();
- // We must provide a unique node name for the slave to connect to Jenkins.
- // We don't have the EC2 generated instance ID, or the Spot request ID
- // until after the instance is requested, which is then too late to set the
- // user-data for the request. Instead we generate a unique name from UUID
- // so that the slave has a unique name within Jenkins to register to.
+ // We must provide a unique node name for the slave to connect to
+ // Jenkins.
+ // We don't have the EC2 generated instance ID, or the Spot request
+ // ID
+ // until after the instance is requested, which is then too late to
+ // set the
+ // user-data for the request. Instead we generate a unique name from
+ // UUID
+ // so that the slave has a unique name within Jenkins to register
+ // to.
String slaveName = UUID.randomUUID().toString();
String newUserData = "";
- // We want to allow node configuration with cloud-init and user-data,
+ // We want to allow node configuration with cloud-init and
+ // user-data,
// while maintaining backward compatibility with old ami's
- // The 'new' way is triggered by the presence of '${SLAVE_NAME}'' in the user data
+ // The 'new' way is triggered by the presence of '${SLAVE_NAME}'' in
+ // the user data
// (which is not too much to ask)
if (userData.contains("${SLAVE_NAME}")) {
// The cloud-init compatible way
@@ -688,9 +695,8 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
newUserData = newUserData.replace("${JENKINS_URL}", jenkinsUrl);
} else {
// The 'old' way - maitain full backward compatibility
- newUserData = "JENKINS_URL=" + jenkinsUrl +
- "&SLAVE_NAME=" + slaveName +
- "&USER_DATA=" + Base64.encodeBase64String(userData.getBytes());
+ newUserData = "JENKINS_URL=" + jenkinsUrl + "&SLAVE_NAME=" + slaveName + "&USER_DATA="
+ + Base64.encodeBase64String(userData.getBytes());
}
String userDataString = Base64.encodeBase64String(newUserData.getBytes());
@@ -709,7 +715,7 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
HashSet inst_tags = null;
if (tags != null && !tags.isEmpty()) {
inst_tags = new HashSet();
- for(EC2Tag t : tags) {
+ for (EC2Tag t : tags) {
inst_tags.add(new Tag(t.getName(), t.getValue()));
if (StringUtils.equals(t.getName(), EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE)) {
hasCustomTypeTag = true;
@@ -718,7 +724,7 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
}
if (!hasCustomTypeTag) {
if (inst_tags != null)
- inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "spot"));
+ inst_tags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "spot"));
}
if (StringUtils.isNotBlank(getIamInstanceProfile())) {
@@ -731,12 +737,12 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
RequestSpotInstancesResult reqResult = ec2.requestSpotInstances(spotRequest);
List reqInstances = reqResult.getSpotInstanceRequests();
- if (reqInstances.size() <= 0){
+ if (reqInstances.size() <= 0) {
throw new AmazonClientException("No spot instances found");
}
SpotInstanceRequest spotInstReq = reqInstances.get(0);
- if (spotInstReq == null){
+ if (spotInstReq == null) {
throw new AmazonClientException("Spot instance request is null");
}
@@ -744,7 +750,8 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
if (inst_tags != null) {
updateRemoteTags(ec2, inst_tags, "InvalidSpotInstanceRequestID.NotFound", spotInstReq.getSpotInstanceRequestId());
- // That was a remote request - we should also update our local instance data.
+ // That was a remote request - we should also update our local
+ // instance data.
spotInstReq.setTags(inst_tags);
}
@@ -753,9 +760,10 @@ private EC2AbstractSlave provisionSpot(TaskListener listener) throws AmazonClien
return newSpotSlave(spotInstReq, slaveName);
- } catch (FormException e) {
- throw new AssertionError(); // we should have discovered all configuration issues upfront
- } catch (InterruptedException e) {
+ } catch (FormException e) {
+ throw new AssertionError(); // we should have discovered all
+ // configuration issues upfront
+ } catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
@@ -771,24 +779,26 @@ protected EC2SpotSlave newSpotSlave(SpotInstanceRequest sir, String name) throws
/**
* Get a KeyPair from the configured information for the slave template
*/
- private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException, AmazonClientException{
+ private KeyPair getKeyPair(AmazonEC2 ec2) throws IOException, AmazonClientException {
KeyPair keyPair = parent.getPrivateKey().find(ec2);
- if(keyPair==null) {
+ if (keyPair == null) {
throw new AmazonClientException("No matching keypair found on EC2. Is the EC2 private key a valid one?");
}
return keyPair;
}
/**
- * Update the tags stored in EC2 with the specified information.
- * Re-try 5 times if instances isn't up by catchErrorCode - e.g. InvalidSpotInstanceRequestID.NotFound or InvalidInstanceRequestID.NotFound
+ * Update the tags stored in EC2 with the specified information. Re-try 5 times if instances isn't up by
+ * catchErrorCode - e.g. InvalidSpotInstanceRequestID.NotFound or InvalidInstanceRequestID.NotFound
+ *
* @param ec2
* @param inst_tags
* @param catchErrorCode
* @param params
* @throws InterruptedException
*/
- private void updateRemoteTags(AmazonEC2 ec2, Collection inst_tags, String catchErrorCode, String... params) throws InterruptedException {
+ private void updateRemoteTags(AmazonEC2 ec2, Collection inst_tags, String catchErrorCode, String... params)
+ throws InterruptedException {
for (int i = 0; i < 5; i++) {
try {
CreateTagsRequest tag_request = new CreateTagsRequest();
@@ -808,7 +818,7 @@ private void updateRemoteTags(AmazonEC2 ec2, Collection inst_tags, String c
/**
* Get a list of security group ids for the slave
*/
- private List getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException{
+ private List getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientException {
List group_ids = new ArrayList();
DescribeSecurityGroupsResult group_result = getSecurityGroupsBy("group-name", securityGroupSet, ec2);
@@ -828,14 +838,14 @@ private List getEc2SecurityGroups(AmazonEC2 ec2) throws AmazonClientExce
DescribeSubnetsResult subnet_result = ec2.describeSubnets(subnet_req);
List subnets = subnet_result.getSubnets();
- if(subnets != null && !subnets.isEmpty()) {
+ if (subnets != null && !subnets.isEmpty()) {
group_ids.add(group.getGroupId());
}
}
}
if (securityGroupSet.size() != group_ids.size()) {
- throw new AmazonClientException( "Security groups must all be VPC security groups to work in a VPC context" );
+ throw new AmazonClientException("Security groups must all be VPC security groups to work in a VPC context");
}
return group_ids;
@@ -848,22 +858,22 @@ private DescribeSecurityGroupsResult getSecurityGroupsBy(String filterName, Set<
}
/**
- * Provisions a new EC2 slave based on the currently running instance on EC2,
- * instead of starting a new one.
+ * Provisions a new EC2 slave based on the currently running instance on EC2, instead of starting a new one.
*/
public EC2AbstractSlave attach(String instanceId, TaskListener listener) throws AmazonClientException, IOException {
PrintStream logger = listener.getLogger();
AmazonEC2 ec2 = getParent().connect();
try {
- logger.println("Attaching to "+instanceId);
- LOGGER.info("Attaching to "+instanceId);
+ logger.println("Attaching to " + instanceId);
+ LOGGER.info("Attaching to " + instanceId);
DescribeInstancesRequest request = new DescribeInstancesRequest();
request.setInstanceIds(Collections.singletonList(instanceId));
Instance inst = ec2.describeInstances(request).getReservations().get(0).getInstances().get(0);
return newOndemandSlave(inst);
} catch (FormException e) {
- throw new AssertionError(); // we should have discovered all configuration issues upfront
+ throw new AssertionError(); // we should have discovered all
+ // configuration issues upfront
}
}
@@ -875,12 +885,12 @@ protected Object readResolve() {
securityGroupSet = parseSecurityGroups();
/**
- * In releases of this plugin prior to 1.18, template-specific instance caps could be configured
- * but were not enforced. As a result, it was possible to have the instance cap for a template
- * be configured to 0 (zero) with no ill effects. Starting with version 1.18, template-specific
- * instance caps are enforced, so if a configuration has a cap of zero for a template, no instances
- * will be launched from that template. Since there is no practical value of intentionally setting
- * the cap to zero, this block will override such a setting to a value that means 'no cap'.
+ * In releases of this plugin prior to 1.18, template-specific instance caps could be configured but were not
+ * enforced. As a result, it was possible to have the instance cap for a template be configured to 0 (zero) with
+ * no ill effects. Starting with version 1.18, template-specific instance caps are enforced, so if a
+ * configuration has a cap of zero for a template, no instances will be launched from that template. Since there
+ * is no practical value of intentionally setting the cap to zero, this block will override such a setting to a
+ * value that means 'no cap'.
*/
if (instanceCap == 0) {
instanceCap = Integer.MAX_VALUE;
@@ -901,30 +911,27 @@ public int getLaunchTimeout() {
}
public String getLaunchTimeoutStr() {
- if (launchTimeout==Integer.MAX_VALUE) {
+ if (launchTimeout == Integer.MAX_VALUE) {
return "";
} else {
return String.valueOf(launchTimeout);
}
}
- public boolean isWindowsSlave()
- {
+ public boolean isWindowsSlave() {
return amiType.isWindows();
}
- public boolean isUnixSlave()
- {
+ public boolean isUnixSlave() {
return amiType.isUnix();
}
- public String getAdminPassword()
- {
- return amiType.isWindows() ? ((WindowsData)amiType).getPassword() : "";
+ public String getAdminPassword() {
+ return amiType.isWindows() ? ((WindowsData) amiType).getPassword() : "";
}
public boolean isUseHTTPS() {
- return amiType.isWindows() ? ((WindowsData)amiType).isUseHTTPS() : false;
+ return amiType.isWindows() ? ((WindowsData) amiType).isUseHTTPS() : false;
}
@Extension
@@ -934,9 +941,8 @@ public String getDisplayName() {
return null;
}
- public List> getAMITypeDescriptors()
- {
- return Hudson.getInstance().>getDescriptorList(AMITypeData.class);
+ public List> getAMITypeDescriptors() {
+ return Hudson.getInstance().> getDescriptorList(AMITypeData.class);
}
/**
@@ -945,9 +951,9 @@ public List> getAMITypeDescriptors()
@Override
public String getHelpFile(String fieldName) {
String p = super.getHelpFile(fieldName);
- if (p==null)
+ if (p == null)
p = Hudson.getInstance().getDescriptor(EC2OndemandSlave.class).getHelpFile(fieldName);
- if (p==null)
+ if (p == null)
p = Hudson.getInstance().getDescriptor(EC2SpotSlave.class).getHelpFile(fieldName);
return p;
}
@@ -955,11 +961,8 @@ public String getHelpFile(String fieldName) {
/***
* Check that the AMI requested is available in the cloud and can be used.
*/
- public FormValidation doValidateAmi(
- @QueryParameter boolean useInstanceProfileForCredentials,
- @QueryParameter String accessId, @QueryParameter String secretKey,
- @QueryParameter String ec2endpoint, @QueryParameter String region,
- final @QueryParameter String ami) throws IOException {
+ public FormValidation doValidateAmi(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String accessId, @QueryParameter String secretKey, @QueryParameter String ec2endpoint, @QueryParameter String region, final @QueryParameter String ami)
+ throws IOException {
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
AmazonEC2 ec2;
if (region != null) {
@@ -967,7 +970,7 @@ public FormValidation doValidateAmi(
} else {
ec2 = EC2Cloud.connect(credentialsProvider, new URL(ec2endpoint));
}
- if(ec2!=null) {
+ if (ec2 != null) {
try {
List images = new LinkedList();
images.add(ami);
@@ -978,78 +981,85 @@ public FormValidation doValidateAmi(
request.setOwners(owners);
request.setExecutableUsers(users);
List img = ec2.describeImages(request).getImages();
- if(img==null || img.isEmpty()) {
- // de-registered AMI causes an empty list to be returned. so be defensive
+ if (img == null || img.isEmpty()) {
+ // de-registered AMI causes an empty list to be
+ // returned. so be defensive
// against other possibilities
- return FormValidation.error("No such AMI, or not usable with this accessId: "+ami);
+ return FormValidation.error("No such AMI, or not usable with this accessId: " + ami);
}
String ownerAlias = img.get(0).getImageOwnerAlias();
- return FormValidation.ok(img.get(0).getImageLocation() +
- (ownerAlias != null ? " by " + ownerAlias : ""));
+ return FormValidation.ok(img.get(0).getImageLocation()
+ + (ownerAlias != null ? " by " + ownerAlias : ""));
} catch (AmazonClientException e) {
return FormValidation.error(e.getMessage());
}
} else
- return FormValidation.ok(); // can't test
+ return FormValidation.ok(); // can't test
}
public FormValidation doCheckLabelString(@QueryParameter String value, @QueryParameter Node.Mode mode) {
if (mode == Node.Mode.EXCLUSIVE && (value == null || value.trim() == "")) {
- return FormValidation.warning("You may want to assign labels to this node;" +
- " it's marked to only run jobs that are exclusively tied to itself or a label.");
+ return FormValidation.warning("You may want to assign labels to this node;"
+ + " it's marked to only run jobs that are exclusively tied to itself or a label.");
}
return FormValidation.ok();
}
public FormValidation doCheckIdleTerminationMinutes(@QueryParameter String value) {
- if (value == null || value.trim() == "") return FormValidation.ok();
+ if (value == null || value.trim() == "")
+ return FormValidation.ok();
try {
int val = Integer.parseInt(value);
- if (val >= -59) return FormValidation.ok();
+ if (val >= -59)
+ return FormValidation.ok();
+ } catch (NumberFormatException nfe) {
}
- catch ( NumberFormatException nfe ) {}
return FormValidation.error("Idle Termination time must be a greater than -59 (or null)");
}
public FormValidation doCheckInstanceCapStr(@QueryParameter String value) {
- if (value == null || value.trim() == "") return FormValidation.ok();
+ if (value == null || value.trim() == "")
+ return FormValidation.ok();
try {
int val = Integer.parseInt(value);
- if (val > 0) return FormValidation.ok();
- } catch ( NumberFormatException nfe ) {}
+ if (val > 0)
+ return FormValidation.ok();
+ } catch (NumberFormatException nfe) {
+ }
return FormValidation.error("InstanceCap must be a non-negative integer (or null)");
}
public FormValidation doCheckLaunchTimeoutStr(@QueryParameter String value) {
- if (value == null || value.trim() == "") return FormValidation.ok();
+ if (value == null || value.trim() == "")
+ return FormValidation.ok();
try {
int val = Integer.parseInt(value);
- if (val >= 0) return FormValidation.ok();
- } catch ( NumberFormatException nfe ) {}
+ if (val >= 0)
+ return FormValidation.ok();
+ } catch (NumberFormatException nfe) {
+ }
return FormValidation.error("Launch Timeout must be a non-negative integer (or null)");
}
- public ListBoxModel doFillZoneItems( @QueryParameter boolean useInstanceProfileForCredentials,
- @QueryParameter String accessId,
- @QueryParameter String secretKey,
- @QueryParameter String region)
- throws IOException, ServletException
- {
+ public ListBoxModel doFillZoneItems(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String accessId, @QueryParameter String secretKey, @QueryParameter String region)
+ throws IOException, ServletException {
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
return EC2AbstractSlave.fillZoneItems(credentialsProvider, region);
- }
+ }
- /* Validate the Spot Max Bid Price to ensure that it is a floating point number >= .001 */
- public FormValidation doCheckSpotMaxBidPrice( @QueryParameter String spotMaxBidPrice ) {
- if(SpotConfiguration.normalizeBid(spotMaxBidPrice) != null){
+ /*
+ * Validate the Spot Max Bid Price to ensure that it is a floating point number >= .001
+ */
+ public FormValidation doCheckSpotMaxBidPrice(@QueryParameter String spotMaxBidPrice) {
+ if (SpotConfiguration.normalizeBid(spotMaxBidPrice) != null) {
return FormValidation.ok();
}
return FormValidation.error("Not a correct bid price");
}
// Retrieve the availability zones for the region
- private ArrayList getAvailabilityZones(AmazonEC2 ec2) {
+ private ArrayList getAvailabilityZones(AmazonEC2 ec2) {
ArrayList availabilityZones = new ArrayList();
DescribeAvailabilityZonesResult zones = ec2.describeAvailabilityZones();
@@ -1064,6 +1074,7 @@ private ArrayList getAvailabilityZones(AmazonEC2 ec2) {
/**
* Populates the Bid Type Drop down on the slave template config.
+ *
* @return
*/
public ListBoxModel doFillBidTypeItems() {
@@ -1073,27 +1084,31 @@ public ListBoxModel doFillBidTypeItems() {
return items;
}
- /* Check the current Spot price of the selected instance type for the selected region */
- public FormValidation doCurrentSpotPrice( @QueryParameter boolean useInstanceProfileForCredentials,
- @QueryParameter String accessId, @QueryParameter String secretKey,
- @QueryParameter String region, @QueryParameter String type,
- @QueryParameter String zone ) throws IOException, ServletException {
+ /*
+ * Check the current Spot price of the selected instance type for the selected region
+ */
+ public FormValidation doCurrentSpotPrice(@QueryParameter boolean useInstanceProfileForCredentials, @QueryParameter String accessId, @QueryParameter String secretKey, @QueryParameter String region, @QueryParameter String type, @QueryParameter String zone)
+ throws IOException, ServletException {
String cp = "";
String zoneStr = "";
- // Connect to the EC2 cloud with the access id, secret key, and region queried from the created cloud
+ // Connect to the EC2 cloud with the access id, secret key, and
+ // region queried from the created cloud
AWSCredentialsProvider credentialsProvider = EC2Cloud.createCredentialsProvider(useInstanceProfileForCredentials, accessId, secretKey);
AmazonEC2 ec2 = EC2Cloud.connect(credentialsProvider, AmazonEC2Cloud.getEc2EndpointUrl(region));
- if(ec2!=null) {
+ if (ec2 != null) {
try {
- // Build a new price history request with the currently selected type
+ // Build a new price history request with the currently
+ // selected type
DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest();
- // If a zone is specified, set the availability zone in the request
- // Else, proceed with no availability zone which will result with the cheapest Spot price
- if(getAvailabilityZones(ec2).contains(zone)){
+ // If a zone is specified, set the availability zone in the
+ // request
+ // Else, proceed with no availability zone which will result
+ // with the cheapest Spot price
+ if (getAvailabilityZones(ec2).contains(zone)) {
request.setAvailabilityZone(zone);
zoneStr = zone + " availability zone";
} else {
@@ -1101,25 +1116,24 @@ public FormValidation doCurrentSpotPrice( @QueryParameter boolean useInstancePro
}
/*
- * Iterate through the AWS instance types to see if can find a match for the databound
- * String type. This is necessary because the AWS API needs the instance type
- * string formatted a particular way to retrieve prices and the form gives us the strings
- * in a different format. For example "T1Micro" vs "t1.micro".
+ * Iterate through the AWS instance types to see if can find a match for the databound String type.
+ * This is necessary because the AWS API needs the instance type string formatted a particular way
+ * to retrieve prices and the form gives us the strings in a different format. For example "T1Micro"
+ * vs "t1.micro".
*/
InstanceType ec2Type = null;
- for(InstanceType it : InstanceType.values()){
- if (it.name().toString().equals(type)){
+ for (InstanceType it : InstanceType.values()) {
+ if (it.name().toString().equals(type)) {
ec2Type = it;
break;
}
}
/*
- * If the type string cannot be matched with an instance type,
- * throw a Form error
+ * If the type string cannot be matched with an instance type, throw a Form error
*/
- if(ec2Type == null){
+ if (ec2Type == null) {
return FormValidation.error("Could not resolve instance type: " + type);
}
@@ -1128,10 +1142,11 @@ public FormValidation doCurrentSpotPrice( @QueryParameter boolean useInstancePro
request.setInstanceTypes(instanceType);
request.setStartTime(new Date());
- // Retrieve the price history request result and store the current price
+ // Retrieve the price history request result and store the
+ // current price
DescribeSpotPriceHistoryResult result = ec2.describeSpotPriceHistory(request);
- if(!result.getSpotPriceHistory().isEmpty()){
+ if (!result.getSpotPriceHistory().isEmpty()) {
SpotPrice currentPrice = result.getSpotPriceHistory().get(0);
cp = currentPrice.getSpotPrice();
@@ -1142,21 +1157,18 @@ public FormValidation doCurrentSpotPrice( @QueryParameter boolean useInstancePro
}
}
/*
- * If we could not return the current price of the instance display an error
- * Else, remove the additional zeros from the current price and return it to the interface
- * in the form of a message
+ * If we could not return the current price of the instance display an error Else, remove the additional
+ * zeros from the current price and return it to the interface in the form of a message
*/
- if(cp.isEmpty()){
+ if (cp.isEmpty()) {
return FormValidation.error("Could not retrieve current Spot price");
} else {
cp = cp.substring(0, cp.length() - 3);
- return FormValidation.ok("The current Spot price for a " + type +
- " in the " + zoneStr + " is $" + cp );
+ return FormValidation.ok("The current Spot price for a " + type + " in the " + zoneStr + " is $" + cp);
}
}
}
private static final Logger LOGGER = Logger.getLogger(SlaveTemplate.class.getName());
}
-
diff --git a/src/main/java/hudson/plugins/ec2/SpotConfiguration.java b/src/main/java/hudson/plugins/ec2/SpotConfiguration.java
index c82d2be1d..c89fab97b 100644
--- a/src/main/java/hudson/plugins/ec2/SpotConfiguration.java
+++ b/src/main/java/hudson/plugins/ec2/SpotConfiguration.java
@@ -3,45 +3,46 @@
import org.kohsuke.stapler.DataBoundConstructor;
public final class SpotConfiguration {
- public final String spotMaxBidPrice;
- public final String spotInstanceBidType;
-
- @DataBoundConstructor
- public SpotConfiguration(String spotMaxBidPrice, String bidType) {
- this.spotMaxBidPrice = spotMaxBidPrice;
- this.spotInstanceBidType = bidType;
- }
-
- @Override
- public boolean equals(Object obj) {
- if(obj == null || (this.getClass() != obj.getClass())) {
- return false;
- }
- final SpotConfiguration config = (SpotConfiguration) obj;
-
- return normalizeBid(this.spotMaxBidPrice).equals(normalizeBid(config.spotMaxBidPrice)) &&
- this.spotInstanceBidType.equals(config.spotInstanceBidType);
- }
-
- /**
- * Check if the specified value is a valid bid price to make a Spot request
- * and return the normalized string for the float of the specified bid
- * Bids must be >= .001
- * @param bid - price to check
- * @return The normalized string for a Float if possible, otherwise null
- */
- public static String normalizeBid(String bid){
- try {
- Float spotPrice = Float.parseFloat(bid);
-
- /* The specified bid price cannot be less than 0.001 */
- if(spotPrice < 0.001) {
- return null;
- }
- return spotPrice.toString();
- } catch (NumberFormatException ex) {
- return null;
- }
-
- }
+ public final String spotMaxBidPrice;
+ public final String spotInstanceBidType;
+
+ @DataBoundConstructor
+ public SpotConfiguration(String spotMaxBidPrice, String bidType) {
+ this.spotMaxBidPrice = spotMaxBidPrice;
+ this.spotInstanceBidType = bidType;
+ }
+
+ @Override
+ public boolean equals(Object obj) {
+ if (obj == null || (this.getClass() != obj.getClass())) {
+ return false;
+ }
+ final SpotConfiguration config = (SpotConfiguration) obj;
+
+ return normalizeBid(this.spotMaxBidPrice).equals(normalizeBid(config.spotMaxBidPrice))
+ && this.spotInstanceBidType.equals(config.spotInstanceBidType);
+ }
+
+ /**
+ * Check if the specified value is a valid bid price to make a Spot request and return the normalized string for the
+ * float of the specified bid Bids must be >= .001
+ *
+ * @param bid
+ * - price to check
+ * @return The normalized string for a Float if possible, otherwise null
+ */
+ public static String normalizeBid(String bid) {
+ try {
+ Float spotPrice = Float.parseFloat(bid);
+
+ /* The specified bid price cannot be less than 0.001 */
+ if (spotPrice < 0.001) {
+ return null;
+ }
+ return spotPrice.toString();
+ } catch (NumberFormatException ex) {
+ return null;
+ }
+
+ }
}
diff --git a/src/main/java/hudson/plugins/ec2/UnixData.java b/src/main/java/hudson/plugins/ec2/UnixData.java
index 9ef583d5e..c32a18074 100644
--- a/src/main/java/hudson/plugins/ec2/UnixData.java
+++ b/src/main/java/hudson/plugins/ec2/UnixData.java
@@ -11,8 +11,7 @@ public class UnixData extends AMITypeData {
private final String sshPort;
@DataBoundConstructor
- public UnixData(String rootCommandPrefix, String sshPort)
- {
+ public UnixData(String rootCommandPrefix, String sshPort) {
this.rootCommandPrefix = rootCommandPrefix;
this.sshPort = sshPort;
}
@@ -26,8 +25,7 @@ public boolean isUnix() {
}
@Extension
- public static class DescriptorImpl extends Descriptor
- {
+ public static class DescriptorImpl extends Descriptor {
public String getDisplayName() {
return "unix";
}
@@ -45,10 +43,7 @@ public String getSshPort() {
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime
- * result
- + ((rootCommandPrefix == null) ? 0 : rootCommandPrefix
- .hashCode());
+ result = prime * result + ((rootCommandPrefix == null) ? 0 : rootCommandPrefix.hashCode());
result = prime * result + ((sshPort == null) ? 0 : sshPort.hashCode());
return result;
}
diff --git a/src/main/java/hudson/plugins/ec2/WindowsData.java b/src/main/java/hudson/plugins/ec2/WindowsData.java
index 0620c1ae9..a2bb5b052 100644
--- a/src/main/java/hudson/plugins/ec2/WindowsData.java
+++ b/src/main/java/hudson/plugins/ec2/WindowsData.java
@@ -14,11 +14,10 @@ public class WindowsData extends AMITypeData {
private final String bootDelay;
@DataBoundConstructor
- public WindowsData(String password, boolean useHTTPS, String bootDelay)
- {
+ public WindowsData(String password, boolean useHTTPS, String bootDelay) {
this.password = password;
this.useHTTPS = useHTTPS;
- this.bootDelay= bootDelay;
+ this.bootDelay = bootDelay;
}
public boolean isWindows() {
@@ -44,14 +43,13 @@ public String getBootDelay() {
public int getBootDelayInMillis() {
try {
return (int) TimeUnit.SECONDS.toMillis(Integer.parseInt(bootDelay));
- } catch (NumberFormatException nfe ) {
+ } catch (NumberFormatException nfe) {
return 0;
}
}
@Extension
- public static class DescriptorImpl extends Descriptor
- {
+ public static class DescriptorImpl extends Descriptor {
public String getDisplayName() {
return "windows";
}
diff --git a/src/main/java/hudson/plugins/ec2/ebs/ZPoolExpandNotice.java b/src/main/java/hudson/plugins/ec2/ebs/ZPoolExpandNotice.java
index 034de0b55..e4a81b241 100644
--- a/src/main/java/hudson/plugins/ec2/ebs/ZPoolExpandNotice.java
+++ b/src/main/java/hudson/plugins/ec2/ebs/ZPoolExpandNotice.java
@@ -27,8 +27,7 @@
import hudson.Extension;
/**
- * {@link AdministrativeMonitor} that tells the user that ZFS pool is filling up
- * and they need to add more storage.
+ * {@link AdministrativeMonitor} that tells the user that ZFS pool is filling up and they need to add more storage.
*
* @author Kohsuke Kawaguchi
*/
@@ -37,14 +36,14 @@ public class ZPoolExpandNotice extends AdministrativeMonitor {
/**
* Set by {@link ZPoolMonitor}.
*/
- /*package*/ boolean activated = false;
+ /* package */boolean activated = false;
public ZPoolExpandNotice() {
super("zpool.ebs");
}
@Override
- public boolean isActivated() {
+ public boolean isActivated() {
return activated;
}
}
diff --git a/src/main/java/hudson/plugins/ec2/ebs/ZPoolMonitor.java b/src/main/java/hudson/plugins/ec2/ebs/ZPoolMonitor.java
index df30bfd0a..a8d442909 100644
--- a/src/main/java/hudson/plugins/ec2/ebs/ZPoolMonitor.java
+++ b/src/main/java/hudson/plugins/ec2/ebs/ZPoolMonitor.java
@@ -43,20 +43,20 @@
@Extension
public class ZPoolMonitor extends PeriodicWork {
@Override
- public long getRecurrencePeriod() {
+ public long getRecurrencePeriod() {
return TimeUnit2.HOURS.toMillis(1);
}
@Override
- protected void doRun() {
- ZFSFileSystem fs=null;
+ protected void doRun() {
+ ZFSFileSystem fs = null;
try {
- if(isInsideEC2())
+ if (isInsideEC2())
fs = new LibZFS().getFileSystemByMountPoint(Hudson.getInstance().getRootDir());
} catch (LinkageError e) {
// probably not running on OpenSolaris
}
- if(fs==null) {
+ if (fs == null) {
cancel();
return;
}
@@ -64,10 +64,11 @@ protected void doRun() {
long a = pool.getAvailableSize();
long t = pool.getSize();
- // if the disk is 90% filled up and the available space is less than 1GB,
+ // if the disk is 90% filled up and the available space is less than
+ // 1GB,
// notify the user
ZPoolExpandNotice zen = AdministrativeMonitor.all().get(ZPoolExpandNotice.class);
- zen.activated = t/a>10 && a<1000L*1000*1000;
+ zen.activated = t / a > 10 && a < 1000L * 1000 * 1000;
}
private static Boolean isInsideEC2;
@@ -76,7 +77,7 @@ protected void doRun() {
* Returns true if this JVM runs inside EC2.
*/
public static synchronized boolean isInsideEC2() {
- if(isInsideEC2==null) {
+ if (isInsideEC2 == null) {
try {
new URL("http://169.254.169.254/latest").openStream().close();
isInsideEC2 = true;
diff --git a/src/main/java/hudson/plugins/ec2/ssh/EC2UnixLauncher.java b/src/main/java/hudson/plugins/ec2/ssh/EC2UnixLauncher.java
index 2b4b48ef0..aede00994 100644
--- a/src/main/java/hudson/plugins/ec2/ssh/EC2UnixLauncher.java
+++ b/src/main/java/hudson/plugins/ec2/ssh/EC2UnixLauncher.java
@@ -67,22 +67,23 @@
*/
public class EC2UnixLauncher extends EC2ComputerLauncher {
- private final int FAILED=-1;
- private final int SAMEUSER=0;
+ private final int FAILED = -1;
+ private final int SAMEUSER = 0;
protected String buildUpCommand(EC2Computer computer, String command) {
- if (!computer.getRemoteAdmin().equals("root")) {
- command = computer.getRootCommandPrefix() + " " + command;
- }
- return command;
+ if (!computer.getRemoteAdmin().equals("root")) {
+ command = computer.getRootCommandPrefix() + " " + command;
+ }
+ return command;
}
-
@Override
- protected void launch(EC2Computer computer, TaskListener listener, Instance inst) throws IOException, AmazonClientException, InterruptedException {
+ protected void launch(EC2Computer computer, TaskListener listener, Instance inst) throws IOException,
+ AmazonClientException, InterruptedException {
final Connection bootstrapConn;
final Connection conn;
- Connection cleanupConn = null; // java's code path analysis for final doesn't work that well.
+ Connection cleanupConn = null; // java's code path analysis for final
+ // doesn't work that well.
boolean successful = false;
PrintStream logger = listener.getLogger();
@@ -90,16 +91,14 @@ protected void launch(EC2Computer computer, TaskListener listener, Instance inst
bootstrapConn = connectToSsh(computer, logger);
int bootstrapResult = bootstrap(bootstrapConn, computer, logger);
if (bootstrapResult == FAILED) {
- logger.println("bootstrapresult failed");
+ logger.println("bootstrapresult failed");
return; // bootstrap closed for us.
- }
- else if (bootstrapResult == SAMEUSER) {
+ } else if (bootstrapResult == SAMEUSER) {
cleanupConn = bootstrapConn; // take over the connection
logger.println("take over connection");
- }
- else {
+ } else {
// connect fresh as ROOT
- logger.println("connect fresh as root");
+ logger.println("connect fresh as root");
cleanupConn = connectToSsh(computer, logger);
KeyPair key = computer.getCloud().getKeyPair();
if (!cleanupConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "")) {
@@ -111,67 +110,72 @@ else if (bootstrapResult == SAMEUSER) {
SCPClient scp = conn.createSCPClient();
String initScript = computer.getNode().initScript;
- String tmpDir = (Util.fixEmptyAndTrim(computer.getNode().tmpDir) != null ? computer.getNode().tmpDir : "/tmp");
+ String tmpDir = (Util.fixEmptyAndTrim(computer.getNode().tmpDir) != null ? computer.getNode().tmpDir
+ : "/tmp");
logger.println("Creating tmp directory (" + tmpDir + ") if it does not exist");
conn.exec("mkdir -p " + tmpDir, logger);
- if(initScript!=null && initScript.trim().length()>0 && conn.exec("test -e ~/.hudson-run-init", logger) !=0) {
+ if (initScript != null && initScript.trim().length() > 0
+ && conn.exec("test -e ~/.hudson-run-init", logger) != 0) {
logger.println("Executing init script");
- scp.put(initScript.getBytes("UTF-8"),"init.sh",tmpDir,"0700");
+ scp.put(initScript.getBytes("UTF-8"), "init.sh", tmpDir, "0700");
Session sess = conn.openSession();
- sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr
+ sess.requestDumbPTY(); // so that the remote side bundles stdout
+ // and stderr
sess.execCommand(buildUpCommand(computer, tmpDir + "/init.sh"));
- sess.getStdin().close(); // nothing to write here
- sess.getStderr().close(); // we are not supposed to get anything from stderr
- IOUtils.copy(sess.getStdout(),logger);
+ sess.getStdin().close(); // nothing to write here
+ sess.getStderr().close(); // we are not supposed to get anything
+ // from stderr
+ IOUtils.copy(sess.getStdout(), logger);
int exitStatus = waitCompletion(sess);
- if (exitStatus!=0) {
- logger.println("init script failed: exit code="+exitStatus);
+ if (exitStatus != 0) {
+ logger.println("init script failed: exit code=" + exitStatus);
return;
}
sess.close();
// Needs a tty to run sudo.
sess = conn.openSession();
- sess.requestDumbPTY(); // so that the remote side bundles stdout and stderr
+ sess.requestDumbPTY(); // so that the remote side bundles stdout
+ // and stderr
sess.execCommand(buildUpCommand(computer, "touch ~/.hudson-run-init"));
sess.close();
}
// TODO: parse the version number. maven-enforcer-plugin might help
logger.println("Verifying that java exists");
- if(conn.exec("java -fullversion", logger) !=0) {
+ if (conn.exec("java -fullversion", logger) != 0) {
logger.println("Installing Java");
String jdk = "java1.6.0_12";
String path = "/hudson-ci/jdk/linux-i586/" + jdk + ".tgz";
URL url = computer.getCloud().buildPresignedURL(path);
- if(conn.exec("wget -nv -O " + tmpDir + "/" + jdk + ".tgz '" + url + "'", logger) !=0) {
+ if (conn.exec("wget -nv -O " + tmpDir + "/" + jdk + ".tgz '" + url + "'", logger) != 0) {
logger.println("Failed to download Java");
return;
}
- if(conn.exec(buildUpCommand(computer, "tar xz -C /usr -f " + tmpDir + "/" + jdk + ".tgz"), logger) !=0) {
+ if (conn.exec(buildUpCommand(computer, "tar xz -C /usr -f " + tmpDir + "/" + jdk + ".tgz"), logger) != 0) {
logger.println("Failed to install Java");
return;
}
- if(conn.exec(buildUpCommand(computer, "ln -s /usr/" + jdk + "/bin/java /bin/java"), logger) !=0) {
+ if (conn.exec(buildUpCommand(computer, "ln -s /usr/" + jdk + "/bin/java /bin/java"), logger) != 0) {
logger.println("Failed to symlink Java");
return;
}
}
- // TODO: on Windows with ec2-sshd, this scp command ends up just putting slave.jar as c:\tmp
+ // TODO: on Windows with ec2-sshd, this scp command ends up just
+ // putting slave.jar as c:\tmp
// bug in ec2-sshd?
logger.println("Copying slave.jar");
- scp.put(Hudson.getInstance().getJnlpJars("slave.jar").readFully(),
- "slave.jar",tmpDir);
+ scp.put(Hudson.getInstance().getJnlpJars("slave.jar").readFully(), "slave.jar", tmpDir);
String jvmopts = computer.getNode().jvmopts;
String launchString = "java " + (jvmopts != null ? jvmopts : "") + " -jar " + tmpDir + "/slave.jar";
@@ -184,13 +188,7 @@ else if (bootstrapResult == SAMEUSER) {
try {
// Obviously the master must have an installed ssh client.
- String sshClientLaunchString =
- String.format("ssh -o StrictHostKeyChecking=no -i %s %s@%s -p %d %s",
- identityKeyFile.getAbsolutePath(),
- node.remoteAdmin,
- getEC2HostAddress(computer, inst),
- node.getSshPort(),
- launchString);
+ String sshClientLaunchString = String.format("ssh -o StrictHostKeyChecking=no -i %s %s@%s -p %d %s", identityKeyFile.getAbsolutePath(), node.remoteAdmin, getEC2HostAddress(computer, inst), node.getSshPort(), launchString);
logger.println("Launching slave agent (via SSH client process): " + sshClientLaunchString);
CommandLauncher commandLauncher = new CommandLauncher(sshClientLaunchString);
@@ -202,7 +200,7 @@ else if (bootstrapResult == SAMEUSER) {
logger.println("Launching slave agent (via Trilead SSH2 Connection): " + launchString);
final Session sess = conn.openSession();
sess.execCommand(launchString);
- computer.setChannel(sess.getStdout(),sess.getStdin(),logger,new Listener() {
+ computer.setChannel(sess.getStdout(), sess.getStdin(), logger, new Listener() {
@Override
public void onClosed(Channel channel, IOException cause) {
sess.close();
@@ -213,20 +211,22 @@ public void onClosed(Channel channel, IOException cause) {
successful = true;
} finally {
- if(cleanupConn != null && !successful)
+ if (cleanupConn != null && !successful)
cleanupConn.close();
}
}
-
+
/**
* Return the first {@link SlaveTemplate} from the given {@link EC2Computer} instance.
+ *
* @param computer
* @return
*/
- private SlaveTemplate getSlaveTemplate(EC2Computer computer)
- {
- // TODO: I don't get these templates. How are they named/labeled and when will there be multiples?
- // Need to find out how to map this stuff onto the EC2AbstractSlave instance as it seems to have
+ private SlaveTemplate getSlaveTemplate(EC2Computer computer) {
+ // TODO: I don't get these templates. How are they named/labeled and
+ // when will there be multiples?
+ // Need to find out how to map this stuff onto the EC2AbstractSlave
+ // instance as it seems to have
// some of the same props.
List templates = computer.getCloud().getTemplates();
SlaveTemplate slaveTemplate = null;
@@ -257,15 +257,17 @@ private File createIdentityKeyFile(EC2Computer computer) throws IOException {
}
}
- private int bootstrap(Connection bootstrapConn, EC2Computer computer, PrintStream logger) throws IOException, InterruptedException, AmazonClientException {
- logger.println("bootstrap()" );
+ private int bootstrap(Connection bootstrapConn, EC2Computer computer, PrintStream logger) throws IOException,
+ InterruptedException, AmazonClientException {
+ logger.println("bootstrap()");
boolean closeBootstrap = true;
try {
int tries = 20;
boolean isAuthenticated = false;
- logger.println("Getting keypair..." );
+ logger.println("Getting keypair...");
KeyPair key = computer.getCloud().getKeyPair();
- logger.println("Using key: " + key.getKeyName() + "\n" + key.getKeyFingerprint() + "\n" + key.getKeyMaterial().substring(0, 160) );
+ logger.println("Using key: " + key.getKeyName() + "\n" + key.getKeyFingerprint() + "\n"
+ + key.getKeyMaterial().substring(0, 160));
while (tries-- > 0) {
logger.println("Authenticating as " + computer.getRemoteAdmin());
isAuthenticated = bootstrapConn.authenticateWithPublicKey(computer.getRemoteAdmin(), key.getKeyMaterial().toCharArray(), "");
@@ -287,15 +289,17 @@ private int bootstrap(Connection bootstrapConn, EC2Computer computer, PrintStrea
}
}
- private Connection connectToSsh(EC2Computer computer, PrintStream logger) throws AmazonClientException, InterruptedException {
+ private Connection connectToSsh(EC2Computer computer, PrintStream logger) throws AmazonClientException,
+ InterruptedException {
final long timeout = computer.getNode().getLaunchTimeoutInMillis();
final long startTime = System.currentTimeMillis();
- while(true) {
+ while (true) {
try {
long waitTime = System.currentTimeMillis() - startTime;
- if ( timeout > 0 && waitTime > timeout )
- {
- throw new AmazonClientException("Timed out after "+ (waitTime / 1000) + " seconds of waiting for ssh to become available. (maximum timeout configured is "+ (timeout / 1000) + ")" );
+ if (timeout > 0 && waitTime > timeout) {
+ throw new AmazonClientException("Timed out after " + (waitTime / 1000)
+ + " seconds of waiting for ssh to become available. (maximum timeout configured is "
+ + (timeout / 1000) + ")");
}
Instance instance = computer.updateInstanceDescription();
String host = getEC2HostAddress(computer, instance);
@@ -307,11 +311,12 @@ private Connection connectToSsh(EC2Computer computer, PrintStream logger) throws
int port = computer.getSshPort();
Integer slaveConnectTimeout = Integer.getInteger("jenkins.ec2.slaveConnectTimeout", 10000);
- logger.println("Connecting to " + host + " on port " + port + ", with timeout " + slaveConnectTimeout + ".");
+ logger.println("Connecting to " + host + " on port " + port + ", with timeout " + slaveConnectTimeout
+ + ".");
Connection conn = new Connection(host, port);
ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy;
Proxy proxy = proxyConfig == null ? Proxy.NO_PROXY : proxyConfig.createProxy(host);
- if (! proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
+ if (!proxy.equals(Proxy.NO_PROXY) && proxy.address() instanceof InetSocketAddress) {
InetSocketAddress address = (InetSocketAddress) proxy.address();
HTTPProxyData proxyData = null;
if (null != proxyConfig.getUserName()) {
@@ -322,10 +327,12 @@ private Connection connectToSsh(EC2Computer computer, PrintStream logger) throws
conn.setProxyData(proxyData);
logger.println("Using HTTP Proxy Configuration");
}
- // currently OpenSolaris offers no way of verifying the host certificate, so just accept it blindly,
+ // currently OpenSolaris offers no way of verifying the host
+ // certificate, so just accept it blindly,
// hoping that no man-in-the-middle attack is going on.
conn.connect(new ServerHostKeyVerifier() {
- public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
+ public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey)
+ throws Exception {
return true;
}
}, slaveConnectTimeout, slaveConnectTimeout);
@@ -346,35 +353,38 @@ private String getEC2HostAddress(EC2Computer computer, Instance inst) {
} else {
String host = inst.getPublicDnsName();
// If we fail to get a public DNS name, try to get the public IP
- // (but only if the plugin config let us use the public IP to connect to the slave).
+ // (but only if the plugin config let us use the public IP to
+ // connect to the slave).
if (host == null || host.equals("")) {
SlaveTemplate slaveTemplate = getSlaveTemplate(computer);
- if (inst.getPublicIpAddress() != null && slaveTemplate.isConnectUsingPublicIp())
- {
+ if (inst.getPublicIpAddress() != null && slaveTemplate.isConnectUsingPublicIp()) {
host = inst.getPublicIpAddress();
}
}
- // If we fail to get a public DNS name or public IP, use the private IP.
+ // If we fail to get a public DNS name or public IP, use the private
+ // IP.
if (host == null || host.equals("")) {
host = inst.getPrivateIpAddress();
}
-
+
return host;
}
}
private int waitCompletion(Session session) throws InterruptedException {
- // I noticed that the exit status delivery often gets delayed. Wait up to 1 sec.
- for( int i=0; i<10; i++ ) {
+ // I noticed that the exit status delivery often gets delayed. Wait up
+ // to 1 sec.
+ for (int i = 0; i < 10; i++) {
Integer r = session.getExitStatus();
- if(r!=null) return r;
+ if (r != null)
+ return r;
Thread.sleep(100);
}
return -1;
}
@Override
- public Descriptor getDescriptor() {
+ public Descriptor getDescriptor() {
throw new UnsupportedOperationException();
}
}
diff --git a/src/main/java/hudson/plugins/ec2/ssh/HostKeyVerifierImpl.java b/src/main/java/hudson/plugins/ec2/ssh/HostKeyVerifierImpl.java
index 34e95048f..273df9887 100644
--- a/src/main/java/hudson/plugins/ec2/ssh/HostKeyVerifierImpl.java
+++ b/src/main/java/hudson/plugins/ec2/ssh/HostKeyVerifierImpl.java
@@ -43,22 +43,24 @@ private String getFingerprint(byte[] serverHostKey) {
md5.digest(fingerprint);
StringBuilder buf = new StringBuilder();
- for( byte b : fingerprint ) {
- if(buf.length()>0) buf.append(':');
- buf.append(String.format("%02x",b));
+ for (byte b : fingerprint) {
+ if (buf.length() > 0)
+ buf.append(':');
+ buf.append(String.format("%02x", b));
}
return buf.toString();
}
- public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey) throws Exception {
+ public boolean verifyServerHostKey(String hostname, int port, String serverHostKeyAlgorithm, byte[] serverHostKey)
+ throws Exception {
String fingerprint = getFingerprint(serverHostKey);
- LOGGER.fine("Host key fingerprint of "+hostname+" is "+fingerprint);
+ LOGGER.fine("Host key fingerprint of " + hostname + " is " + fingerprint);
boolean matches = console.contains(fingerprint);
- if(!matches)
- LOGGER.severe("No matching fingerprint found in the console output: "+console);
+ if (!matches)
+ LOGGER.severe("No matching fingerprint found in the console output: " + console);
return matches;
}
diff --git a/src/main/java/hudson/plugins/ec2/util/DeviceMappingParser.java b/src/main/java/hudson/plugins/ec2/util/DeviceMappingParser.java
index 32a64edb9..1856ff1ba 100644
--- a/src/main/java/hudson/plugins/ec2/util/DeviceMappingParser.java
+++ b/src/main/java/hudson/plugins/ec2/util/DeviceMappingParser.java
@@ -35,7 +35,7 @@ public static List parse(String customDeviceMapping) {
List deviceMappings = new ArrayList();
- for (String mapping: customDeviceMapping.split(",")) {
+ for (String mapping : customDeviceMapping.split(",")) {
String[] mappingPair = mapping.split("=");
String device = mappingPair[0];
String blockDevice = mappingPair[1];
@@ -44,11 +44,9 @@ public static List parse(String customDeviceMapping) {
if (blockDevice.equals("none")) {
deviceMapping.setNoDevice("none");
- }
- else if (blockDevice.startsWith("ephemeral")) {
+ } else if (blockDevice.startsWith("ephemeral")) {
deviceMapping.setVirtualName(blockDevice);
- }
- else {
+ } else {
deviceMapping.setEbs(parseEbs(blockDevice));
}
@@ -89,8 +87,7 @@ private static EbsBlockDevice parseEbs(String blockDevice) {
private static String getOrEmpty(String[] arr, int idx) {
if (idx < arr.length) {
return arr[idx];
- }
- else {
+ } else {
return "";
}
}
diff --git a/src/main/java/hudson/plugins/ec2/win/EC2WindowsLauncher.java b/src/main/java/hudson/plugins/ec2/win/EC2WindowsLauncher.java
index 29f5d02cf..da63f8c13 100644
--- a/src/main/java/hudson/plugins/ec2/win/EC2WindowsLauncher.java
+++ b/src/main/java/hudson/plugins/ec2/win/EC2WindowsLauncher.java
@@ -25,29 +25,30 @@ public class EC2WindowsLauncher extends EC2ComputerLauncher {
final long sleepBetweenAttemps = TimeUnit.SECONDS.toMillis(10);
@Override
- protected void launch(EC2Computer computer, TaskListener listener, Instance inst) throws IOException, AmazonClientException,
- InterruptedException {
+ protected void launch(EC2Computer computer, TaskListener listener, Instance inst) throws IOException,
+ AmazonClientException, InterruptedException {
final PrintStream logger = listener.getLogger();
final WinConnection connection = connectToWinRM(computer, logger);
try {
String initScript = computer.getNode().initScript;
- String tmpDir = (computer.getNode().tmpDir != null && !computer.getNode().tmpDir.equals("") ? computer.getNode().tmpDir : "C:\\Windows\\Temp\\");
+ String tmpDir = (computer.getNode().tmpDir != null && !computer.getNode().tmpDir.equals("") ? computer.getNode().tmpDir
+ : "C:\\Windows\\Temp\\");
logger.println("Creating tmp directory if it does not exist");
connection.execute("if not exist " + tmpDir + " mkdir " + tmpDir);
- if(initScript!=null && initScript.trim().length()>0 && !connection.exists(tmpDir + ".jenkins-init")) {
+ if (initScript != null && initScript.trim().length() > 0 && !connection.exists(tmpDir + ".jenkins-init")) {
logger.println("Executing init script");
OutputStream init = connection.putFile(tmpDir + "init.bat");
init.write(initScript.getBytes("utf-8"));
WindowsProcess initProcess = connection.execute("cmd /c " + tmpDir + "init.bat");
- IOUtils.copy(initProcess.getStdout(),logger);
+ IOUtils.copy(initProcess.getStdout(), logger);
int exitStatus = initProcess.waitFor();
- if (exitStatus!=0) {
- logger.println("init script failed: exit code="+exitStatus);
+ if (exitStatus != 0) {
+ logger.println("init script failed: exit code=" + exitStatus);
return;
}
@@ -56,14 +57,14 @@ protected void launch(EC2Computer computer, TaskListener listener, Instance inst
logger.println("init script ran successfully");
}
-
OutputStream slaveJar = connection.putFile(tmpDir + "slave.jar");
slaveJar.write(Hudson.getInstance().getJnlpJars("slave.jar").readFully());
logger.println("slave.jar sent remotely. Bootstrapping it");
final String jvmopts = computer.getNode().jvmopts;
- final WindowsProcess process = connection.execute("java " + (jvmopts != null ? jvmopts : "") + " -jar " + tmpDir + "slave.jar", 86400);
+ final WindowsProcess process = connection.execute("java " + (jvmopts != null ? jvmopts : "") + " -jar "
+ + tmpDir + "slave.jar", 86400);
computer.setChannel(process.getStdout(), process.getStdin(), logger, new Listener() {
@Override
public void onClosed(Channel channel, IOException cause) {
@@ -80,7 +81,7 @@ public void onClosed(Channel channel, IOException cause) {
}
private WinConnection connectToWinRM(EC2Computer computer, PrintStream logger) throws AmazonClientException,
- InterruptedException {
+ InterruptedException {
final long timeout = computer.getNode().getLaunchTimeoutInMillis();
final long startTime = System.currentTimeMillis();
@@ -98,16 +99,21 @@ private WinConnection connectToWinRM(EC2Computer computer, PrintStream logger) t
if (computer.getNode().usePrivateDnsName) {
host = instance.getPrivateDnsName();
- ip = instance.getPrivateIpAddress(); // SmbFile doesn't quite work with hostnames
+ ip = instance.getPrivateIpAddress(); // SmbFile doesn't
+ // quite work with
+ // hostnames
} else {
host = instance.getPublicDnsName();
if (host == null || host.equals("")) {
host = instance.getPrivateDnsName();
- ip = instance.getPrivateIpAddress(); // SmbFile doesn't quite work with hostnames
- }
- else {
+ ip = instance.getPrivateIpAddress(); // SmbFile doesn't
+ // quite work with
+ // hostnames
+ } else {
host = instance.getPublicDnsName();
- ip = instance.getPublicIpAddress(); // SmbFile doesn't quite work with hostnames
+ ip = instance.getPublicIpAddress(); // SmbFile doesn't
+ // quite work with
+ // hostnames
}
}
@@ -127,7 +133,8 @@ private WinConnection connectToWinRM(EC2Computer computer, PrintStream logger) t
}
if (!alreadyBooted || computer.getNode().stopOnTerminate) {
- logger.println("WinRM service responded. Waiting for WinRM service to stabilize on " + computer.getNode().getDisplayName());
+ logger.println("WinRM service responded. Waiting for WinRM service to stabilize on "
+ + computer.getNode().getDisplayName());
Thread.sleep(computer.getNode().getBootDelay());
alreadyBooted = true;
logger.println("WinRM should now be ok on " + computer.getNode().getDisplayName());
diff --git a/src/main/java/hudson/plugins/ec2/win/WinConnection.java b/src/main/java/hudson/plugins/ec2/win/WinConnection.java
index 98b62d8fc..c53ccd3da 100644
--- a/src/main/java/hudson/plugins/ec2/win/WinConnection.java
+++ b/src/main/java/hudson/plugins/ec2/win/WinConnection.java
@@ -72,7 +72,7 @@ public boolean exists(String path) throws IOException {
SmbFile smbFile = new SmbFile(encodeForSmb(path), authentication);
return smbFile.exists();
}
-
+
private String encodeForSmb(String path) {
if (!VALIDATE_WINDOWS_PATH.matcher(path).matches()) {
throw new IllegalArgumentException("Path '" + path + "' is not a valid windows path like C:\\Windows\\Temp");
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/WinRM.java b/src/main/java/hudson/plugins/ec2/win/winrm/WinRM.java
index 2eced1033..71723ffec 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/WinRM.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/WinRM.java
@@ -92,8 +92,8 @@ public void setTimeout(int timeout) {
/**
* # Convert the number of seconds to an ISO8601 duration format # @see
- * http://tools.ietf.org/html/rfc2445#section-4.3.6 # @param [Fixnum]
- * seconds The amount of seconds for this duration
+ * http://tools.ietf.org/html/rfc2445#section-4.3.6 # @param [Fixnum] seconds The amount of seconds for this
+ * duration
*
* @param timeout
* @return
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/WinRMClient.java b/src/main/java/hudson/plugins/ec2/win/winrm/WinRMClient.java
index 676cc93d4..5ff9e032b 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/WinRMClient.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/WinRMClient.java
@@ -70,7 +70,6 @@ public class WinRMClient {
private Scheme httpsScheme;
private BasicCredentialsProvider credsProvider;
-
public WinRMClient(URL url, String username, String password) {
this.url = url;
this.username = username;
@@ -139,13 +138,13 @@ public boolean slurpOutput(PipedOutputStream stdout, PipedOutputStream stderr) t
for (Element e : (List) xpath.selectNodes(response)) {
PipedOutputStream stream = streams.get(e.attribute("Name").getText().toLowerCase());
final byte[] decode = base64.decode(e.getText());
- log.log(Level.FINE, "piping " + decode.length + " bytes from " + e.attribute("Name").getText().toLowerCase());
+ log.log(Level.FINE, "piping " + decode.length + " bytes from "
+ + e.attribute("Name").getText().toLowerCase());
stream.write(decode);
}
- XPath done = DocumentHelper
- .createXPath("//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']");
+ XPath done = DocumentHelper.createXPath("//*[@State='http://schemas.microsoft.com/wbem/wsman/1/windows/shell/CommandState/Done']");
done.setNamespaceContext(namespaceContext);
if (Iterables.isEmpty(done.selectNodes(response))) {
log.log(Level.FINE, "keep going baby!");
@@ -172,8 +171,7 @@ private static String first(Document doc, String selector) {
private void setupHTTPClient() {
credsProvider = new BasicCredentialsProvider();
- credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(
- username, password));
+ credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username, password));
if (useHTTPS) {
SSLSocketFactory socketFactory;
@@ -188,13 +186,12 @@ private void setupHTTPClient() {
}
}
- private DefaultHttpClient buildHTTPClient()
- {
+ private DefaultHttpClient buildHTTPClient() {
DefaultHttpClient httpclient = new DefaultHttpClient();
- //httpclient.getAuthSchemes().unregister(AuthPolicy.SPNEGO);
+ // httpclient.getAuthSchemes().unregister(AuthPolicy.SPNEGO);
httpclient.setCredentialsProvider(credsProvider);
httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
- //httpclient.setHttpRequestRetryHandler(new WinRMRetryHandler());
+ // httpclient.setHttpRequestRetryHandler(new WinRMRetryHandler());
return httpclient;
}
@@ -235,14 +232,14 @@ private Document sendRequest(Document request, int retry) {
// check for possible timeout
if (response.getStatusLine().getStatusCode() == 500
- && (responseEntity.getContentType() != null && entity.getContentType().getValue()
- .startsWith("application/soap+xml"))) {
+ && (responseEntity.getContentType() != null && entity.getContentType().getValue().startsWith("application/soap+xml"))) {
String respStr = EntityUtils.toString(responseEntity);
if (respStr.contains("TimedOut")) {
return DocumentHelper.parseText(respStr);
}
} else {
- // this shouldn't happen, as httpclient knows how to auth the request
+ // this shouldn't happen, as httpclient knows how to auth
+ // the request
// but I've seen it. I blame keep-alive, so we're just going
// to scrap the connections, and try again
if (response.getStatusLine().getStatusCode() == 401) {
@@ -258,14 +255,16 @@ private Document sendRequest(Document request, int retry) {
return sendRequest(request, ++retry);
}
log.log(Level.WARNING, "winrm service " + shellId + " unexpected HTTP Response ("
- + response.getStatusLine().getReasonPhrase() + "): " + EntityUtils.toString(response.getEntity()));
+ + response.getStatusLine().getReasonPhrase() + "): "
+ + EntityUtils.toString(response.getEntity()));
- throw new RuntimeException("Unexpected HTTP response " + response.getStatusLine().getStatusCode() + " on "
- + url + ": " + response.getStatusLine().getReasonPhrase());
+ throw new RuntimeException("Unexpected HTTP response " + response.getStatusLine().getStatusCode()
+ + " on " + url + ": " + response.getStatusLine().getReasonPhrase());
}
}
- if (responseEntity.getContentType() == null || !entity.getContentType().getValue().startsWith("application/soap+xml")) {
+ if (responseEntity.getContentType() == null
+ || !entity.getContentType().getValue().startsWith("application/soap+xml")) {
throw new RuntimeException("Unexepected WinRM content type: " + entity.getContentType());
}
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/WindowsProcess.java b/src/main/java/hudson/plugins/ec2/win/winrm/WindowsProcess.java
index 2f35edd7a..a3a3854ee 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/WindowsProcess.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/WindowsProcess.java
@@ -122,10 +122,13 @@ public void run() {
int n = 0;
try {
n = toCallersStdin.read(buf);
- } catch(IOException ioe) {
- // it's safe to ignore IO Exception coming from Jenkins
- // This can happen with PipedInputStream if the writing Thread
- // is killed but the input stream is handed to another thread
+ } catch (IOException ioe) {
+ // it's safe to ignore IO Exception coming from
+ // Jenkins
+ // This can happen with PipedInputStream if the
+ // writing Thread
+ // is killed but the input stream is handed to
+ // another thread
// in this case, we can still read from the pipe.
continue;
}
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/request/AbstractWinRMRequest.java b/src/main/java/hudson/plugins/ec2/win/winrm/request/AbstractWinRMRequest.java
index f48d5cc97..14bd5d1e4 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/request/AbstractWinRMRequest.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/request/AbstractWinRMRequest.java
@@ -28,24 +28,15 @@ public AbstractWinRMRequest(URL url) {
protected abstract void construct();
-
-
public Document build() {
construct();
return message.build();
}
- protected HeaderBuilder defaultHeader() throws URISyntaxException
- {
- return header.to(url.toURI())
- .replyTo(new URI("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous"))
- .maxEnvelopeSize(envelopSize)
- .id(generateUUID())
- .locale(locale)
- .timeout(timeout);
+ protected HeaderBuilder defaultHeader() throws URISyntaxException {
+ return header.to(url.toURI()).replyTo(new URI("http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous")).maxEnvelopeSize(envelopSize).id(generateUUID()).locale(locale).timeout(timeout);
}
-
protected void setBody(Element body) {
message.addHeader(header.build());
message.addBody(body);
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/request/DeleteShellRequest.java b/src/main/java/hudson/plugins/ec2/win/winrm/request/DeleteShellRequest.java
index 0cb7fd420..3ee650a9c 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/request/DeleteShellRequest.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/request/DeleteShellRequest.java
@@ -16,8 +16,7 @@ public DeleteShellRequest(URL url, String shellId) {
@Override
protected void construct() {
try {
- defaultHeader().action(new URI("http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete")).shellId(shellId)
- .resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd"));
+ defaultHeader().action(new URI("http://schemas.xmlsoap.org/ws/2004/09/transfer/Delete")).shellId(shellId).resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd"));
setBody(null);
} catch (URISyntaxException e) {
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/request/ExecuteCommandRequest.java b/src/main/java/hudson/plugins/ec2/win/winrm/request/ExecuteCommandRequest.java
index 084c0f5c7..0256a6142 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/request/ExecuteCommandRequest.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/request/ExecuteCommandRequest.java
@@ -27,9 +27,7 @@ public ExecuteCommandRequest(URL url, String shellId, String command) {
@Override
protected void construct() {
try {
- defaultHeader().action(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command"))
- .resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).shellId(shellId)
- .options(ImmutableList.of(new Option("WINRS_CONSOLEMODE_STDIN", "FALSE")));
+ defaultHeader().action(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command")).resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).shellId(shellId).options(ImmutableList.of(new Option("WINRS_CONSOLEMODE_STDIN", "FALSE")));
Element body = DocumentHelper.createElement(QName.get("CommandLine", Namespaces.NS_WIN_SHELL));
body.addElement(QName.get("Command", Namespaces.NS_WIN_SHELL)).addText("\"" + command + "\"");
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/request/GetOutputRequest.java b/src/main/java/hudson/plugins/ec2/win/winrm/request/GetOutputRequest.java
index fd42c3916..ca1d3c6a0 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/request/GetOutputRequest.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/request/GetOutputRequest.java
@@ -23,12 +23,10 @@ public GetOutputRequest(URL url, String shellId, String commandId) {
@Override
protected void construct() {
try {
- defaultHeader().action(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive"))
- .resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).shellId(shellId);
+ defaultHeader().action(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Receive")).resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).shellId(shellId);
Element body = DocumentHelper.createElement(QName.get("Receive", Namespaces.NS_WIN_SHELL));
- body.addElement(QName.get("DesiredStream", Namespaces.NS_WIN_SHELL)).addAttribute("CommandId", commandId)
- .addText("stdout stderr");
+ body.addElement(QName.get("DesiredStream", Namespaces.NS_WIN_SHELL)).addAttribute("CommandId", commandId).addText("stdout stderr");
setBody(body);
} catch (URISyntaxException e) {
throw new RuntimeException("Error while building request content", e);
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/request/OpenShellRequest.java b/src/main/java/hudson/plugins/ec2/win/winrm/request/OpenShellRequest.java
index e270a7cd1..9df5c7c12 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/request/OpenShellRequest.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/request/OpenShellRequest.java
@@ -21,9 +21,7 @@ public OpenShellRequest(URL url) {
protected void construct() {
try {
- defaultHeader().action(new URI("http://schemas.xmlsoap.org/ws/2004/09/transfer/Create"))
- .resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd"))
- .options(ImmutableList.of(new Option("WINRS_NOPROFILE", "FALSE"), new Option("WINRS_CODEPAGE", "437")));
+ defaultHeader().action(new URI("http://schemas.xmlsoap.org/ws/2004/09/transfer/Create")).resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).options(ImmutableList.of(new Option("WINRS_NOPROFILE", "FALSE"), new Option("WINRS_CODEPAGE", "437")));
Element body = DocumentHelper.createElement(QName.get("Shell", Namespaces.NS_WIN_SHELL));
body.addElement(QName.get("InputStreams", Namespaces.NS_WIN_SHELL)).addText("stdin");
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/request/SendInputRequest.java b/src/main/java/hudson/plugins/ec2/win/winrm/request/SendInputRequest.java
index 461197b03..9d12bd8f2 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/request/SendInputRequest.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/request/SendInputRequest.java
@@ -26,13 +26,11 @@ public SendInputRequest(URL url, byte[] input, String shellId, String commandId)
@Override
protected void construct() {
try {
- defaultHeader().action(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Send"))
- .resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).shellId(shellId);
+ defaultHeader().action(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Send")).resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).shellId(shellId);
Element body = DocumentHelper.createElement(QName.get("Send", Namespaces.NS_WIN_SHELL));
Base64 base64 = new Base64(0);
- body.addElement(QName.get("Stream", Namespaces.NS_WIN_SHELL)).addAttribute("Name", "stdin")
- .addAttribute("CommandId", commandId).addText(base64.encodeToString(input));
+ body.addElement(QName.get("Stream", Namespaces.NS_WIN_SHELL)).addAttribute("Name", "stdin").addAttribute("CommandId", commandId).addText(base64.encodeToString(input));
setBody(body);
} catch (URISyntaxException e) {
throw new RuntimeException("Error while building request content", e);
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/request/SignalRequest.java b/src/main/java/hudson/plugins/ec2/win/winrm/request/SignalRequest.java
index 31abb46a7..0b6ca9109 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/request/SignalRequest.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/request/SignalRequest.java
@@ -23,15 +23,11 @@ public SignalRequest(URL url, String shellId, String commandId) {
@Override
protected void construct() {
try {
- defaultHeader().action(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command"))
- .resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).shellId(shellId);
+ defaultHeader().action(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/Command")).resourceURI(new URI("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/cmd")).shellId(shellId);
- Element body = DocumentHelper.createElement(QName.get("Signal", Namespaces.NS_WIN_SHELL)).addAttribute(
- "CommandId",
- commandId);
+ Element body = DocumentHelper.createElement(QName.get("Signal", Namespaces.NS_WIN_SHELL)).addAttribute("CommandId", commandId);
- body.addElement(QName.get("Code", Namespaces.NS_WIN_SHELL))
- .addText("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate");
+ body.addElement(QName.get("Code", Namespaces.NS_WIN_SHELL)).addText("http://schemas.microsoft.com/wbem/wsman/1/windows/shell/signal/terminate");
setBody(body);
} catch (URISyntaxException e) {
throw new RuntimeException("Error while building request content", e);
diff --git a/src/main/java/hudson/plugins/ec2/win/winrm/soap/Header.java b/src/main/java/hudson/plugins/ec2/win/winrm/soap/Header.java
index 10bfc2115..c6891004a 100644
--- a/src/main/java/hudson/plugins/ec2/win/winrm/soap/Header.java
+++ b/src/main/java/hudson/plugins/ec2/win/winrm/soap/Header.java
@@ -17,8 +17,7 @@ public class Header {
private String resourceURI;
private ImmutableList