List of usage examples for com.amazonaws.services.ec2.model InstanceStateName Stopped
InstanceStateName Stopped
To view the source code for com.amazonaws.services.ec2.model InstanceStateName Stopped.
Click Source Link
From source file:com.carrotgarden.maven.aws.ecc.CarrotElasticCompute.java
License:BSD License
/** * http://shlomoswidler.com/2009/07/ec2-instance-life-cycle.html *///from www . ja va 2s . com public void instanceStart(final String instanceId) throws Exception { final Instance instance = findInstance(instanceId); final InstanceStateName state = stateFrom(instance); logger.info("start: current state=" + state); switch (state) { case Running: return; case Pending: waitForIstanceState(instanceId, InstanceStateName.Running); return; case Stopped: break; case Stopping: waitForIstanceState(instanceId, InstanceStateName.Stopped); break; case ShuttingDown: case Terminated: throw new IllegalStateException("start: dead instance"); default: throw new IllegalStateException("start: unknown state"); } final StartInstancesRequest request = new StartInstancesRequest(); request.setInstanceIds(wrapList(instanceId)); final StartInstancesResult result = amazonClient.startInstances(request); waitForIstanceState(instanceId, InstanceStateName.Running); }
From source file:com.carrotgarden.maven.aws.ecc.CarrotElasticCompute.java
License:BSD License
/** * http://shlomoswidler.com/2009/07/ec2-instance-life-cycle.html *///from w w w . jav a 2 s.c o m public void instanceStop(final String instanceId) throws Exception { final Instance instance = findInstance(instanceId); final InstanceStateName state = stateFrom(instance); logger.info("stop: current state=" + state); switch (state) { case Pending: waitForIstanceState(instanceId, InstanceStateName.Running); case Running: break; case Stopping: waitForIstanceState(instanceId, InstanceStateName.Stopped); case Stopped: case Terminated: case ShuttingDown: return; default: throw new IllegalStateException("start: unknown state"); } final StopInstancesRequest request = new StopInstancesRequest(); request.setInstanceIds(wrapList(instanceId)); final StopInstancesResult result = amazonClient.stopInstances(request); waitForIstanceState(instanceId, InstanceStateName.Stopped); }
From source file:com.carrotgarden.maven.aws.ecc.CarrotElasticCompute.java
License:BSD License
/** * stop instance and take image snapshot *///from ww w. j a v a 2s . c o m public Image imageCreate(final String instanceId, final String name, final String description) throws Exception { logger.info("ensure instance state : instanceId=" + instanceId); final InstanceStateName state = stateFrom(instanceId); final boolean wasRunning; switch (state) { case Pending: waitForIstanceState(instanceId, InstanceStateName.Running); case Running: wasRunning = true; break; case Stopping: waitForIstanceState(instanceId, InstanceStateName.Stopped); case Stopped: wasRunning = false; break; default: throw new Exception("image create : invalid instance state=" + state); } if (wasRunning) { instanceStop(instanceId); } final CreateImageRequest request = new CreateImageRequest(); request.setInstanceId(instanceId); request.setName(name); request.setDescription(description); final CreateImageResult result = amazonClient.createImage(request); final String imageId = result.getImageId(); logger.info("ensure image state: imageId=" + imageId); final Image image = waitForImageCreate(imageId); if (wasRunning) { instanceStart(instanceId); } return image; }
From source file:hudson.plugins.ec2.SlaveTemplate.java
License:Open Source License
/** * Provisions an On-demand EC2 slave by launching a new instance or * starting a previously-stopped instance. *//* w w w . j a v a 2 s.c o m*/ private EC2AbstractSlave provisionOndemand(TaskListener listener) throws AmazonClientException, IOException { PrintStream logger = listener.getLogger(); AmazonEC2 ec2 = getParent().connect(); try { String msg = "Launching " + ami + " for template " + description; logger.println(msg); LOGGER.info(msg); KeyPair keyPair = getKeyPair(ec2); RunInstancesRequest riRequest = new RunInstancesRequest(ami, 1, 1); InstanceNetworkInterfaceSpecification net = new InstanceNetworkInterfaceSpecification(); if (useEphemeralDevices) { setupEphemeralDeviceMapping(riRequest); } else { setupCustomDeviceMapping(riRequest); } List<Filter> diFilters = new ArrayList<Filter>(); diFilters.add(new Filter("image-id").withValues(ami)); if (StringUtils.isNotBlank(getZone())) { Placement placement = new Placement(getZone()); if (getUseDedicatedTenancy()) { placement.setTenancy("dedicated"); } riRequest.setPlacement(placement); diFilters.add(new Filter("availability-zone").withValues(getZone())); } if (StringUtils.isNotBlank(getSubnetId())) { if (getAssociatePublicIp()) { net.setSubnetId(getSubnetId()); } 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 (!securityGroupSet.isEmpty()) { List<String> group_ids = getEc2SecurityGroups(ec2); if (!group_ids.isEmpty()) { if (getAssociatePublicIp()) { net.setGroups(group_ids); } else { riRequest.setSecurityGroupIds(group_ids); } diFilters.add(new Filter("instance.group-id").withValues(group_ids)); } } } else { /* No subnet: we can use standard security groups by name */ riRequest.setSecurityGroups(securityGroupSet); if (securityGroupSet.size() > 0) diFilters.add(new Filter("instance.group-name").withValues(securityGroupSet)); } String userDataString = Base64.encodeBase64String(userData.getBytes()); riRequest.setUserData(userDataString); riRequest.setKeyName(keyPair.getKeyName()); diFilters.add(new Filter("key-name").withValues(keyPair.getKeyName())); riRequest.setInstanceType(type.toString()); diFilters.add(new Filter("instance-type").withValues(type.toString())); if (getAssociatePublicIp()) { net.setAssociatePublicIpAddress(true); net.setDeviceIndex(0); riRequest.withNetworkInterfaces(net); } boolean hasCustomTypeTag = false; HashSet<Tag> inst_tags = null; if (tags != null && !tags.isEmpty()) { inst_tags = new HashSet<Tag>(); for (EC2Tag t : tags) { inst_tags.add(new Tag(t.getName(), 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) { inst_tags = new HashSet<Tag>(); } 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())); diRequest.setFilters(diFilters); msg = "Looking for existing instances with describe-instance: " + diRequest; logger.println(msg); LOGGER.fine(msg); DescribeInstancesResult diResult = ec2.describeInstances(diRequest); Instance existingInstance = null; 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; } } } } else if (diResult.getReservations().size() > 0) { existingInstance = diResult.getReservations().get(0).getInstances().get(0); } if (existingInstance == null) { // 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) { for (int i = 0; i < 5; i++) { try { updateRemoteTags(ec2, inst_tags, inst.getInstanceId()); break; } catch (AmazonServiceException e) { if (e.getErrorCode().equals("InvalidInstanceRequestID.NotFound")) { Thread.sleep(5000); continue; } throw e; } } // That was a remote request - we should also update our local instance data. inst.setTags(inst_tags); } msg = "No existing instance found - created: " + inst; logger.println(msg); LOGGER.info(msg); return newOndemandSlave(inst); } msg = "Found existing stopped instance: " + existingInstance; logger.println(msg); LOGGER.info(msg); List<String> instances = new ArrayList<String>(); instances.add(existingInstance.getInstanceId()); StartInstancesRequest siRequest = new StartInstancesRequest(instances); StartInstancesResult siResult = ec2.startInstances(siRequest); msg = "Starting existing instance: " + existingInstance + " result:" + siResult; logger.println(msg); LOGGER.fine(msg); for (EC2AbstractSlave ec2Node : NodeIterator.nodes(EC2AbstractSlave.class)) { if (ec2Node.getInstanceId().equals(existingInstance.getInstanceId())) { msg = "Found existing corresponding Jenkins slave: " + ec2Node; logger.println(msg); LOGGER.finer(msg); return ec2Node; } } // Existing slave not found msg = "Creating new Jenkins slave for existing instance: " + existingInstance; logger.println(msg); LOGGER.info(msg); return newOndemandSlave(existingInstance); } catch (FormException e) { throw new AssertionError(); // we should have discovered all configuration issues upfront } catch (InterruptedException e) { throw new RuntimeException(e); } }
From source file:jenkins.plugins.ec2slave.EC2ImageLaunchWrapper.java
License:Open Source License
public void stopInstance(PrintStream logger) { logger.println("EC2InstanceComputerLauncher: Stopping EC2 instance [" + instanceId + "] ..."); if (testMode) return;//from w w w. j ava2s.c o m StopInstancesResult result = ec2.stopInstances(new StopInstancesRequest().withInstanceIds(instanceId)); if (result.getStoppingInstances().size() > 0 && result.getStoppingInstances().get(0).getCurrentState().equals(InstanceStateName.Stopped) && result.getStoppingInstances().get(0).getInstanceId().equals(instanceId)) { logger.println("EC2InstanceComputerLauncher: Stopped EC2 instance [" + instanceId + "] ..."); } }
From source file:jp.primecloud.auto.process.aws.AwsCommonProcess.java
License:Open Source License
public Instance waitInstance(AwsProcessClient awsProcessClient, String instanceId) { // ???//from w w w. jav a 2s . c o m Instance instance; while (true) { try { Thread.sleep(1000L * awsProcessClient.getDescribeInterval()); } catch (InterruptedException ignore) { } instance = describeInstance(awsProcessClient, instanceId); InstanceStateName state; try { state = InstanceStateName.fromValue(instance.getState().getName()); } catch (IllegalArgumentException e) { // ??? AutoException exception = new AutoException("EPROCESS-000104", instanceId, instance.getState().getName()); exception.addDetailInfo("result=" + ReflectionToStringBuilder.toString(instance)); throw exception; } // ????? if (state == InstanceStateName.Running || state == InstanceStateName.Terminated || state == InstanceStateName.Stopped) { break; } } return instance; }
From source file:jp.primecloud.auto.process.aws.AwsInstanceProcess.java
License:Open Source License
/** * TODO: /*w w w .j a va2s . co m*/ * * @param awsProcessClient * @param instanceNo */ public void startInstance(AwsProcessClient awsProcessClient, Long instanceNo) { AwsInstance awsInstance = awsInstanceDao.read(instanceNo); Instance instance = instanceDao.read(instanceNo); Image image = imageDao.read(instance.getImageNo()); ImageAws imageAws = imageAwsDao.read(instance.getImageNo()); // ???EBS???? if (BooleanUtils.isNotTrue(imageAws.getEbsImage()) || StringUtils.isEmpty(awsInstance.getInstanceId())) { // ID???? if (!StringUtils.isEmpty(awsInstance.getInstanceId())) { return; } // ?? run(awsProcessClient, instanceNo); // ??? waitRun(awsProcessClient, instanceNo); // ??? createTag(awsProcessClient, instanceNo); // Windows????????????? if (StringUtils.startsWithIgnoreCase(image.getOs(), "windows")) { waitGetPasswordData(awsProcessClient, instanceNo); } } // EBS?2???? else { // ??????? if (!StringUtils.equals(awsInstance.getStatus(), InstanceStateName.Stopped.toString())) { return; } // ? modify(awsProcessClient, instanceNo); // ? start(awsProcessClient, instanceNo); // ?? waitStart(awsProcessClient, instanceNo); } }
From source file:jp.primecloud.auto.process.aws.AwsInstanceProcess.java
License:Open Source License
public void waitStop(AwsProcessClient awsProcessClient, Long instanceNo) { AwsInstance awsInstance = awsInstanceDao.read(instanceNo); String instanceId = awsInstance.getInstanceId(); // ???/*w ww . j av a2 s . c o m*/ com.amazonaws.services.ec2.model.Instance instance = awsCommonProcess.waitInstance(awsProcessClient, instanceId); if (!instance.getState().getName().equals(InstanceStateName.Stopped.toString())) { // ? AutoException exception = new AutoException("EPROCESS-000129", instanceId, instance.getState().getName()); exception.addDetailInfo("result=" + ReflectionToStringBuilder.toString(instance)); throw exception; } // if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100114", instanceId)); } // Instance instance2 = instanceDao.read(instanceNo); processLogger.debug(null, instance2, "AwsInstanceStopFinish", new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId }); // awsInstance.setAvailabilityZone(instance.getPlacement().getAvailabilityZone()); awsInstance.setStatus(instance.getState().getName()); awsInstance.setDnsName(instance.getPublicDnsName()); awsInstance.setPrivateDnsName(instance.getPrivateDnsName()); awsInstance.setIpAddress(instance.getPublicIpAddress()); awsInstance.setPrivateIpAddress(instance.getPrivateIpAddress()); awsInstanceDao.update(awsInstance); }