List of usage examples for com.amazonaws.services.ec2.model InstanceState getCode
public Integer getCode()
The state of the instance as a 16-bit unsigned integer.
From source file:com.rmn.qa.aws.AwsVmManager.java
License:Open Source License
/** * Terminates the specified instance.//from w w w . ja va 2s.co m * * @param instanceId Id of the instance to terminate */ public boolean terminateInstance(final String instanceId) { TerminateInstancesRequest terminateRequest = new TerminateInstancesRequest(); terminateRequest.withInstanceIds(instanceId); AmazonEC2Client localClient = getClient(); if (localClient == null) { throw new RuntimeException("The client is not initialized"); } TerminateInstancesResult result; try { result = localClient.terminateInstances(terminateRequest); } catch (AmazonServiceException ase) { // If the node was terminated outside of this plugin, handle the error appropriately if (ase.getErrorCode().equals("InvalidInstanceID.NotFound")) { log.error("Node not found when attempting to remove: " + instanceId); return false; } else { throw ase; } } List<InstanceStateChange> stateChanges = result.getTerminatingInstances(); boolean terminatedInstance = false; for (InstanceStateChange stateChange : stateChanges) { if (instanceId.equals(stateChange.getInstanceId())) { terminatedInstance = true; InstanceState currentState = stateChange.getCurrentState(); if (currentState.getCode() != 32 && currentState.getCode() != 48) { log.error(String.format( "Machine state for id %s should be terminated (48) or shutting down (32) but was %s instead", instanceId, currentState.getCode())); return false; } } } if (!terminatedInstance) { log.error("Matching terminated instance was not found for instance " + instanceId); return false; } log.info(String.format("Node [%s] successfully terminated", instanceId)); return true; }
From source file:com.stfciz.aws.ec2.data.EC2InstancesManager.java
/** * * @param region/*from w w w. j a v a2 s . co m*/ * @return */ public List<EC2Instance> getEC2Instances(String region) { if (this.credentials == null) { return null; } List<EC2Instance> ec2Instances; ec2Instances = new ArrayList<>(); if (region != null) { this.amazonEC2Client.setRegion(Region.getRegion(Regions.fromName(region))); } final DescribeInstancesResult describeInstances = this.amazonEC2Client.describeInstances(); final List<Reservation> reservations = describeInstances.getReservations(); for (Reservation reservation : reservations) { final List<Instance> instances = reservation.getInstances(); for (Instance instance : instances) { EC2Instance ec2Instance = new EC2Instance(); ec2Instance.setId(instance.getInstanceId()); ec2Instance.setPublicDnsName(instance.getPublicDnsName()); List<Tag> tags = instance.getTags(); if (tags != null && !tags.isEmpty()) { StringBuilder name = new StringBuilder(); for (Tag tag : tags) { if (name.length() > 0) { name.append(", "); } name.append(tag.getValue()); } ec2Instance.setName(name.toString()); } final InstanceState state = instance.getState(); ec2Instance.setStatus(state.getName()); ec2Instance.setStatusCode(state.getCode()); if (this.tagIncludes != null && ec2Instance.getName() != null) { for (String tagInclude : this.tagIncludes) { if (ec2Instance.getName().contains(tagInclude)) { ec2Instance.setPublicDnsName(instance.getPublicDnsName()); ec2Instances.add(ec2Instance); break; } } } else { ec2Instances.add(ec2Instance); } } } return ec2Instances; }
From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSUtils.java
License:Open Source License
/** * Maps the Aws machine state to {@link PowerState} * @param state//from w w w. ja v a 2 s. c o m * @return the {@link PowerState} of the machine */ public static PowerState mapToPowerState(InstanceState state) { PowerState powerState = PowerState.UNKNOWN; switch (state.getCode()) { case 16: powerState = PowerState.ON; break; case 80: powerState = PowerState.OFF; break; default: break; } return powerState; }
From source file:edu.brandeis.wisedb.aws.VMCreator.java
License:Open Source License
public VM createInstance(VMType type, VMDiskConfiguration disk, boolean waitForRunning) throws VirtualMachineException { AmazonEC2Client ec2 = getEC2();//from w ww . ja v a2 s . co m RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); // TODO: figure out how to change storage type String instanceType = ""; switch (type) { case C4_LARGE: instanceType = "c4.large"; break; case C4_XLARGE: instanceType = "c4.xlarge"; break; case M3_LARGE: instanceType = "m3.large"; break; case M3_MEDIUM: instanceType = "m3.medium"; break; case T2_MEDIUM: instanceType = "t2.medium"; break; case T2_SMALL: instanceType = "t2.small"; break; default: break; } BlockDeviceMapping bdm = null; switch (disk) { case HD100: bdm = new BlockDeviceMapping().withDeviceName("/dev/sda1") .withEbs(new EbsBlockDevice().withVolumeSize(100).withVolumeType(VolumeType.Standard) .withDeleteOnTermination(true).withSnapshotId(config.getSnapshotID())); case SSD10: bdm = new BlockDeviceMapping().withDeviceName("/dev/sda1") .withEbs(new EbsBlockDevice().withVolumeSize(10).withVolumeType(VolumeType.Gp2) .withDeleteOnTermination(true).withSnapshotId(config.getSnapshotID())); case SSD30: bdm = new BlockDeviceMapping().withDeviceName("/dev/sda1") .withEbs(new EbsBlockDevice().withVolumeSize(30).withVolumeType(VolumeType.Gp2) .withDeleteOnTermination(true).withSnapshotId(config.getSnapshotID())); default: break; } System.out.println(instanceType); runInstancesRequest = runInstancesRequest.withImageId(config.getAMIID()).withInstanceType(instanceType) .withMinCount(1).withMaxCount(1).withKeyName(config.getKeyPairName()) .withSubnetId(config.getSubnet()).withBlockDeviceMappings(bdm); RunInstancesResult rir = ec2.runInstances(runInstancesRequest); String instanceID = rir.getReservation().getInstances().get(0).getInstanceId(); String ip; if (waitForRunning) { int maxTry = 60; while (true) { try { DescribeInstancesResult dir = ec2 .describeInstances(new DescribeInstancesRequest().withInstanceIds(instanceID)); InstanceState is = dir.getReservations().get(0).getInstances().get(0).getState(); //System.out.println("Got state: " + is); // apparently this constant isn't stored anywhere... *sigh* if (is.getCode() == 16) { ip = dir.getReservations().get(0).getInstances().get(0).getPublicIpAddress(); break; } } catch (AmazonServiceException e) { //System.err.println("Trouble with AWS: " + e.getMessage()); } maxTry--; if (maxTry == 0) { throw new VirtualMachineException("machine never entered running state"); } try { Thread.sleep(2000); } catch (InterruptedException e) { } } VM toR = new VM(instanceID, ip, this); return toR; } VM toR = new VM(instanceID, null, this); return toR; }
From source file:integratedtoolkit.connectors.amazon.EC2.java
License:Apache License
public ResourceDescription waitCreation(Object vm, ResourceDescription requested) throws ConnectorException { ResourceDescription granted = new ResourceDescription(); try {//from w w w . j a v a2 s .com InstanceState status = ((RunInstancesResult) vm).getReservation().getInstances().get(0).getState(); DescribeInstancesResult dir = null; Thread.sleep(30000); while (status.getCode() == 0) { Thread.sleep(10000); DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); ArrayList<String> l = new ArrayList<String>(); l.add(((RunInstancesResult) vm).getReservation().getInstances().get(0).getInstanceId()); describeInstancesRequest.setInstanceIds(l); dir = client.describeInstances(describeInstancesRequest); status = dir.getReservations().get(0).getInstances().get(0).getState(); } Instance instance = dir.getReservations().get(0).getInstances().get(0); String instanceType = instance.getInstanceType(); String instanceId = instance.getInstanceId(); String IP = instance.getPublicIpAddress(); granted.setName(IP); synchronized (stats) { synchronized (IPToName) { IPToName.put(IP, instanceId); } IPToType.put(IP, instanceType); IPToStart.put(IP, System.currentTimeMillis()); if (instanceType.compareTo(smallCode) == 0) { smallCount++; granted.setProcessorCoreCount(smallCPUCount); granted.setMemoryPhysicalSize(smallMemory / 1024f); granted.setStorageElemSize(smallDisk / 1024f); granted.setType("small"); } else if (instanceType.compareTo(largeCode) == 0) { largeCount++; granted.setProcessorCoreCount(largeCPUCount); granted.setMemoryPhysicalSize(largeMemory / 1024f); granted.setStorageElemSize(largeDisk / 1024f); granted.setType("large"); } else { xlargeCount++; if (requested.getProcessorCoreCount() > xlargeCPUCount) { granted.setProcessorCoreCount(requested.getProcessorCoreCount()); } else { granted.setProcessorCoreCount(xlargeCPUCount); } if (requested.getMemoryPhysicalSize() > xlargeMemory) { granted.setMemoryPhysicalSize(requested.getMemoryPhysicalSize()); } else { granted.setMemoryPhysicalSize(xlargeMemory); } if (requested.getStorageElemSize() > xlargeDisk) { granted.setStorageElemSize(requested.getStorageElemSize()); } else { granted.setStorageElemSize(xlargeDisk); } granted.setType("xlarge"); } } granted.setProcessorArchitecture(requested.getProcessorArchitecture()); granted.setProcessorSpeed(requested.getProcessorSpeed()); granted.setMemoryVirtualSize(requested.getMemoryVirtualSize()); granted.setMemorySTR(requested.getMemorySTR()); granted.setMemoryAccessTime(requested.getMemoryAccessTime()); granted.setStorageElemAccessTime(requested.getStorageElemAccessTime()); granted.setStorageElemSTR(requested.getStorageElemSTR()); granted.setOperatingSystemType("Linux"); granted.setSlots(requested.getSlots()); List<String> apps = requested.getAppSoftware(); for (int i = 0; i < apps.size(); i++) { granted.addAppSoftware(apps.get(i)); } granted.setImage(requested.getImage()); granted.setValue(getMachineCostPerHour(granted)); String[] cmd = { "/bin/sh", "-c", "ssh-keyscan " + IP }; String[] cmdSSH = { "ssh", "-o ConnectTimeout 30", "ec2-user@" + IP, "ps -ef " }; boolean machineReady = false; boolean hasKey = false; long initTime = System.currentTimeMillis(); while (!machineReady) { if (System.currentTimeMillis() < (initTime + 60000)) { if (!hasKey) { String key = execCommand(cmd); if (key != null) { //S'afegeix a la llista de known_Hosts int exitValue2 = -1; synchronized (known_hosts) { String[] cmdKnown = new String[] { "/bin/sh", "-c", "echo " + key + " >> " + System.getProperty("user.home") + "/.ssh/known_hosts" }; Process p = Runtime.getRuntime().exec(cmdKnown); p.waitFor(); String checkCommand[] = { "/bin/sh", "-c", "grep " + IP + " " + System.getProperty("user.home") + "/.ssh/known_hosts" }; key = execCommand(checkCommand); if (key != null) { hasKey = true; } } } } if (hasKey) { String key = execCommand(cmdSSH); if (key != null) { machineReady = true; } } } else { org.apache.log4j.Logger logger = org.apache.log4j.Logger .getLogger(integratedtoolkit.log.Loggers.TS_COMP); logger.info("There are some connection issues with " + IP + ". Rebooting VM..."); reboot(instanceId); initTime = System.currentTimeMillis(); } } return granted; } catch (Exception e) { throw new ConnectorException(e); } }
From source file:integratedtoolkit.connectors.amazon.EC2.java
License:Apache License
private void reboot(String instanceId) throws Exception { RebootInstancesRequest rirq = new RebootInstancesRequest(); LinkedList<String> ids = new LinkedList<String>(); ids.add(instanceId);/*from w ww .ja v a 2 s . c o m*/ rirq.setInstanceIds(ids); client.rebootInstances(rirq); Thread.sleep(5000); DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); ArrayList<String> l = new ArrayList<String>(); l.add(instanceId); describeInstancesRequest.setInstanceIds(l); DescribeInstancesResult dir = client.describeInstances(describeInstancesRequest); InstanceState status = dir.getReservations().get(0).getInstances().get(0).getState(); while (status.getCode() == 0) { Thread.sleep(5000); dir = client.describeInstances(describeInstancesRequest); status = dir.getReservations().get(0).getInstances().get(0).getState(); } }
From source file:integratedtoolkit.connectors.amazon.EC2_2.java
License:Apache License
public ResourceDescription waitCreation(Object vm, ResourceDescription requested) throws ConnectorException { ResourceDescription granted = new ResourceDescription(); Integer poll_time = 5; //Seconds Integer polls = 0;//w ww . j ava 2s . c o m int errors = 0; DescribeInstancesResult dir = null; InstanceState status = ((RunInstancesResult) vm).getReservation().getInstances().get(0).getState(); //Thread.sleep(30000); //Thread.sleep(poll_time * 1000); //Valid values: 0 (pending) | 16 (running) | 32 (shutting-down) | 48 (terminated) | 64 (stopping) | 80 (stopped) while (status.getCode() == 0) { try { //Thread.sleep(10000); Thread.sleep(poll_time * 1000); if (poll_time * polls >= Integer.parseInt(MAX_VM_CREATION_TIME) * 60) { throw new ConnectorException("Maximum VM creation time reached."); } polls++; DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest(); ArrayList<String> l = new ArrayList<String>(); l.add(((RunInstancesResult) vm).getReservation().getInstances().get(0).getInstanceId()); describeInstancesRequest.setInstanceIds(l); dir = client.describeInstances(describeInstancesRequest); status = dir.getReservations().get(0).getInstances().get(0).getState(); errors = 0; } catch (Exception e) { errors++; if (errors == 3) { throw new ConnectorException(e); } } } Instance instance = dir.getReservations().get(0).getInstances().get(0); String instanceType = instance.getInstanceType(); String instanceId = instance.getInstanceId(); String ip = instance.getPublicIpAddress(); granted.setName(ip); VM vmInfo = new VM(instanceId, granted, instanceType, placement); //logger.debug("Virtual machine created: " + vmInfo); float oneHourCost = VM.getPrice(instanceType, vmInfo.getPlacement()); currentCostPerHour += oneHourCost; //totalCost += oneHourCost; int cpuCount = vmInfo.getType().getCpucount(); granted.setProcessorCoreCount(cpuCount); granted.setProcessorArchitecture(requested.getProcessorArchitecture()); granted.setProcessorSpeed(requested.getProcessorSpeed()); float memorySize = vmInfo.getType().getMemory() / 1024f; granted.setMemoryAccessTime(requested.getMemoryAccessTime()); granted.setMemoryPhysicalSize(memorySize); granted.setMemorySTR(requested.getMemorySTR()); granted.setMemoryVirtualSize(requested.getMemoryVirtualSize()); float homeSize = vmInfo.getType().getDisk() / 1024f; granted.setStorageElemAccessTime(requested.getStorageElemAccessTime()); granted.setStorageElemSTR(requested.getStorageElemSTR()); granted.setStorageElemSize(homeSize); granted.setOperatingSystemType("Linux"); granted.setSlots(requested.getSlots()); List<String> apps = requested.getAppSoftware(); for (int i = 0; i < apps.size(); i++) { granted.addAppSoftware(apps.get(i)); } granted.setType(requested.getType()); granted.setImage(requested.getImage()); granted.setValue(getMachineCostPerHour(granted)); addMachine(vmInfo); return granted; }
From source file:org.deeplearning4j.aws.ec2.Ec2BoxCreator.java
License:Apache License
public boolean allRunning() { if (boxesCreated == null) return false; else {/*from w w w. ja v a 2 s . com*/ DescribeInstancesResult result = getEc2().describeInstances(); List<Reservation> reservations = result.getReservations(); for (Reservation r : reservations) { List<Instance> instances = r.getInstances(); for (Instance instance : instances) { InstanceState state = instance.getState(); if (state.getCode() == 48) continue; if (state.getCode() != 16) return false; } } return true; } }
From source file:org.deeplearning4j.aws.ec2.Ec2BoxCreator.java
License:Apache License
public List<String> getHosts() { DescribeInstancesResult result = getEc2().describeInstances(); List<String> hosts = new ArrayList<>(); List<Reservation> reservations = result.getReservations(); for (Reservation r : reservations) { List<Instance> instances = r.getInstances(); for (Instance instance : instances) { InstanceState state = instance.getState(); if (state.getCode() == 48) continue; hosts.add(instance.getPublicDnsName()); }/*w w w . jav a2s .c o m*/ } return hosts; }
From source file:org.occiware.clouddriver.util.InstanceDataFactory.java
License:Apache License
public static InstanceDO buildInstanceDataFromModel(Instance instance) { InstanceDO instanceDO = new InstanceDO(); buildBasicInstanceData(instance, instanceDO); Placement placement = instance.getPlacement(); if (placement != null) { PlacementDO placementDO = buildPlacementDO(instanceDO, placement); instanceDO.setPlacement(placementDO); }//from w w w .jav a 2 s. c o m // Ebs volumes attached on instance. if (instance.getBlockDeviceMappings() != null && !instance.getBlockDeviceMappings().isEmpty()) { List<InstanceVolumeDO> instanceVolumeDOs = BuildInstanceVolumeDOs(instance); instanceDO.setVolumes(instanceVolumeDOs); } if (instance.getIamInstanceProfile() != null) { IamInstanceProfileDO profileDO = buildIamInstanceProfileDO(instance); instanceDO.setIamInstanceProfile(profileDO); } if (instance.getMonitoring() != null) { Monitoring monitoring = instance.getMonitoring(); instanceDO.setMonitoringState(monitoring.getState()); } // Network part. if (instance.getNetworkInterfaces() != null && !instance.getNetworkInterfaces().isEmpty()) { List<NetworkInterfaceDO> networkInterfaceDOs = buildNetworkInterfacesDatas(instance); instanceDO.setNetworkAdapters(networkInterfaceDOs); } List<ProductCode> productCodes = instance.getProductCodes(); if (productCodes != null && !productCodes.isEmpty()) { List<ProductCodeDO> productCodeDOs = buildProductCodesDatas(productCodes); instanceDO.setProductCodes(productCodeDOs); } List<GroupIdentifier> groups = instance.getSecurityGroups(); if (groups != null && !groups.isEmpty()) { List<GroupIdentifierDO> groupIdentifierDOs = buildSecurityGroupsDatas(groups); instanceDO.setSecurityGroups(groupIdentifierDOs); } InstanceState state = instance.getState(); if (state != null) { instanceDO.setInstanceState(state.getName()); instanceDO.setInstanceStateCode(state.getCode()); StateReason stateReason = instance.getStateReason(); if (stateReason != null) { instanceDO.setInstanceStateReasonMessage(stateReason.getMessage()); instanceDO.setInstanceStateReasonCode(stateReason.getCode()); } } List<Tag> tags = instance.getTags(); if (tags != null && !tags.isEmpty()) { List<TagDO> tagDOs = buildTagsDatas(tags); instanceDO.setTags(tagDOs); } return instanceDO; }