use of software.amazon.awssdk.services.ec2.model.Instance in project GNS by MobilityFirst.
the class AWSEC2 method createAndInitInstance.
/**
* Creates an EC2 instance in the region given. Timeout in milleseconds can be specified.
*
* @param ec2
* @param region
* @param amiRecord
* @param instanceName
* @param keyName
* @param securityGroupName
* @param script
* @param tags
* @param elasticIP
* @param timeout
* @return a new instance instance
*/
public static Instance createAndInitInstance(AmazonEC2 ec2, RegionRecord region, AMIRecord amiRecord, String instanceName, String keyName, String securityGroupName, String script, Map<String, String> tags, String elasticIP, int timeout) {
try {
// set the region (AKA endpoint)
setRegion(ec2, region);
// create the instance
SecurityGroup securityGroup = findOrCreateSecurityGroup(ec2, securityGroupName);
String keyPair = findOrCreateKeyPair(ec2, keyName);
String instanceID = createInstanceAndWait(ec2, amiRecord, keyPair, securityGroup);
if (instanceID == null) {
return null;
}
System.out.println("Instance " + instanceName + " is running in " + region.name());
// add a name to the instance
addInstanceTag(ec2, instanceID, "Name", instanceName);
if (tags != null) {
addInstanceTags(ec2, instanceID, tags);
}
Instance instance = findInstance(ec2, instanceID);
if (instance == null) {
return null;
}
String hostname = instance.getPublicDnsName();
System.out.println("Waiting " + timeout / 1000 + " seconds for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable.");
long startTime = System.currentTimeMillis();
while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
ThreadUtils.sleep(1000);
System.out.print(".");
if (System.currentTimeMillis() - startTime > timeout) {
System.out.println(instanceName + " (" + hostname + ")" + " timed out during reachability check.");
return null;
}
}
System.out.println();
System.out.println(instanceName + " (" + hostname + ")" + " is reachable.");
// associate the elasticIP if one is provided
if (elasticIP != null) {
System.out.println("Using ElasticIP " + elasticIP + " for instance " + instanceName + " (" + instanceID + ")");
AWSEC2.associateAddress(ec2, elasticIP, instance);
// get a new copy cuz things have changed
instance = findInstance(ec2, instanceID);
if (instance == null) {
return null;
}
// recheck reachability
hostname = instance.getPublicDnsName();
System.out.println("Waiting " + timeout / 1000 + " s for " + instanceName + " (" + hostname + ", " + instanceID + ") to be reachable after Elastic IP change.");
startTime = System.currentTimeMillis();
while (!Pinger.isReachable(hostname, SSHPORT, 2000)) {
ThreadUtils.sleep(1000);
System.out.print(".");
if (System.currentTimeMillis() - startTime > timeout) {
// give it a minute and ahalf
System.out.println(instanceName + " (" + hostname + ")" + " timed out during second (elastic IP) reachability check.");
return null;
}
}
System.out.println();
System.out.println(instanceName + " (" + hostname + ")" + " is still reachable.");
}
if (script != null) {
File keyFile = new File(KEYHOME + FILESEPARATOR + keyName + PRIVATEKEYFILEEXTENSION);
ExecuteBash.executeBashScript("ec2-user", hostname, keyFile, true, "installScript.sh", script);
}
return instance;
} catch (AmazonServiceException ase) {
System.out.println("Caught Exception: " + ase.getMessage());
System.out.println("Reponse Status Code: " + ase.getStatusCode());
System.out.println("Error Code: " + ase.getErrorCode());
System.out.println("Request ID: " + ase.getRequestId());
}
return null;
}
use of software.amazon.awssdk.services.ec2.model.Instance in project camel by apache.
the class AmazonEC2ClientMock method describeInstances.
@Override
public DescribeInstancesResult describeInstances(DescribeInstancesRequest describeInstancesRequest) {
DescribeInstancesResult result = new DescribeInstancesResult();
if (describeInstancesRequest.getInstanceIds().isEmpty()) {
Collection<Reservation> list = new ArrayList<Reservation>();
Reservation res = new Reservation();
res.setOwnerId("1");
res.setRequesterId("user-test");
res.setReservationId("res-1");
Collection<Instance> instances = new ArrayList();
Instance ins = new Instance();
ins.setImageId("id-1");
ins.setInstanceType(InstanceType.T2Micro);
ins.setInstanceId("instance-1");
instances.add(ins);
Instance ins1 = new Instance();
ins1.setImageId("id-2");
ins1.setInstanceType(InstanceType.T2Micro);
ins1.setInstanceId("instance-2");
instances.add(ins1);
res.setInstances(instances);
list.add(res);
result.setReservations(list);
} else {
if (describeInstancesRequest.getInstanceIds().contains("instance-1")) {
Collection<Reservation> list = new ArrayList<Reservation>();
Reservation res = new Reservation();
res.setOwnerId("1");
res.setRequesterId("user-test");
res.setReservationId("res-1");
Collection<Instance> instances = new ArrayList();
Instance ins = new Instance();
ins.setImageId("id-1");
ins.setInstanceType(InstanceType.T2Micro);
ins.setInstanceId("instance-1");
instances.add(ins);
res.setInstances(instances);
list.add(res);
result.setReservations(list);
}
}
return result;
}
use of software.amazon.awssdk.services.ec2.model.Instance in project camel by apache.
the class AmazonEC2ClientMock method runInstances.
@Override
public RunInstancesResult runInstances(RunInstancesRequest runInstancesRequest) {
RunInstancesResult result = new RunInstancesResult();
if (runInstancesRequest.getImageId().equals("test-1")) {
Reservation res = new Reservation();
res.setOwnerId("1");
res.setRequesterId("user-test");
res.setReservationId("res-1");
Collection<Instance> instances = new ArrayList();
Instance ins = new Instance();
ins.setImageId(runInstancesRequest.getImageId());
ins.setInstanceType(runInstancesRequest.getInstanceType());
ins.setInstanceId("instance-1");
if (runInstancesRequest.getSecurityGroups() != null) {
if (runInstancesRequest.getSecurityGroups().contains("secgroup-1") && runInstancesRequest.getSecurityGroups().contains("secgroup-2")) {
GroupIdentifier id1 = new GroupIdentifier();
id1.setGroupId("id-1");
id1.setGroupName("secgroup-1");
GroupIdentifier id2 = new GroupIdentifier();
id2.setGroupId("id-2");
id2.setGroupName("secgroup-2");
Collection secGroups = new ArrayList<GroupIdentifier>();
secGroups.add(id1);
secGroups.add(id2);
ins.setSecurityGroups(secGroups);
} else if (ObjectHelper.isNotEmpty(runInstancesRequest.getKeyName())) {
if (ObjectHelper.isNotEmpty(runInstancesRequest.getKeyName().contains("keypair-1"))) {
GroupIdentifier id1 = new GroupIdentifier();
id1.setGroupId("id-3");
id1.setGroupName("secgroup-3");
GroupIdentifier id2 = new GroupIdentifier();
id2.setGroupId("id-4");
id2.setGroupName("secgroup-4");
Collection secGroups = new ArrayList<GroupIdentifier>();
secGroups.add(id1);
secGroups.add(id2);
ins.setSecurityGroups(secGroups);
}
}
}
instances.add(ins);
res.setInstances(instances);
result.setReservation(res);
} else {
throw new AmazonServiceException("The image-id doesn't exists");
}
return result;
}
use of software.amazon.awssdk.services.ec2.model.Instance in project photon-model by vmware.
the class AWSComputeDiskDay2ServiceTest method testDiskOperations.
/**
* This test performs the following steps in sequence.
* 1. provision a VM with one bootdisk, two new inline disks and one existing disk.
* 2. Create three independent disks and then explicitly attach all of them to the VM
* 3. Detach the first two disks that are explicitly attached.
* 4. Delete VM(all the attached disks which are marked are not marked to persist will also be deleted).
*/
@Test
public void testDiskOperations() throws Throwable {
Gson gson = new Gson();
DiskState diskspec1 = createAWSDiskState(this.host, this.endpointState, this.currentTestName.getMethodName() + "_disk1", Boolean.FALSE, this.zoneId, regionId);
// create a disk
provisionSingleDisk(diskspec1);
assertEquals(1, diskspec1.endpointLinks.size());
// attach a disk while provisioning the vm
provisionVMAndAttachDisk(this.zoneId, diskspec1.documentSelfLink, true);
// check that the VM has been created
ServiceDocumentQueryResult computeQueryResult = ProvisioningUtils.queryComputeInstances(this.host, 2);
ComputeState vmStateAfterAttach1 = gson.fromJson(computeQueryResult.documents.get(this.vmState.documentSelfLink).toString(), ComputeState.class);
Instance instance = null;
if (!this.isMock) {
List<Instance> instances = getAwsInstancesByIds(this.client, this.host, Collections.singletonList(vmStateAfterAttach1.id));
instance = instances.get(0);
ComputeState vm = this.host.getServiceState(null, ComputeState.class, UriUtils.buildUri(this.host, this.vmState.documentSelfLink));
assertAndSetVMSecurityGroupsToBeDeleted(instance, vm);
// verify that the disk is attached while provisioning the vm.
DiskState attachedDisk1 = this.host.getServiceState(null, DiskState.class, UriUtils.buildUri(this.host, diskspec1.documentSelfLink));
assertEquals("disk status not matching", DiskService.DiskStatus.ATTACHED, attachedDisk1.status);
assertEquals(1, attachedDisk1.endpointLinks.size());
this.volumeId = attachedDisk1.id;
}
ServiceDocumentQueryResult initialDiskQueryResult = ProvisioningUtils.queryDiskInstances(this.host, vmStateAfterAttach1.diskLinks.size());
List<String> existingNames = new ArrayList<>();
for (String diskLink : initialDiskQueryResult.documentLinks) {
DiskState diskState = Utils.fromJson(initialDiskQueryResult.documents.get(diskLink), DiskState.class);
existingNames.add(diskState.customProperties.get(AWSConstants.DEVICE_NAME));
}
ComputeState vmStateBeforeAttach = vmStateAfterAttach1;
int numExternalDisks = 3;
List<String> externallyProvisionedDisks = new ArrayList<>();
ComputeState vmAfterExternalDiskAttach = createAndAttachExternalDisks(instance, existingNames, vmStateBeforeAttach, externallyProvisionedDisks, numExternalDisks);
List<String> diskLinksToDetach = externallyProvisionedDisks.stream().filter(diskLink -> !diskLink.equals(externallyProvisionedDisks.get(numExternalDisks - 1))).collect(Collectors.toList());
// detach disks from the vm and verify the details of the detached disks
ComputeState vmStateAfterExplicitDetach = detachDiskAndVerify(vmAfterExternalDiskAttach, diskLinksToDetach, this.disksToCleanUp);
assertEquals(5, vmStateAfterExplicitDetach.diskLinks.size());
// On VM delete, two inline(Test_Volume_1 and Test_Volume_2), one non-inline external(*_disk1),
// one external-disk should be deleted. Only one of the attached disks should be persisted.
deleteVMAndVerifyDisks(vmStateAfterExplicitDetach.documentSelfLink, vmStateAfterExplicitDetach.diskLinks);
}
use of software.amazon.awssdk.services.ec2.model.Instance in project photon-model by vmware.
the class AWSRebootServiceTest method testReboot.
// Test the reboot operation.
@Test
public void testReboot() throws Throwable {
provisionSingleAWS();
// check that the VM has been created
ProvisioningUtils.queryComputeInstances(this.host, 2);
ComputeState compute = getCompute(this.host, this.vmState.documentSelfLink);
if (!this.isMock) {
List<Instance> instances = getAwsInstancesByIds(this.client, this.host, Collections.singletonList(compute.id));
Instance instance = instances.get(0);
ComputeState vm = this.host.getServiceState(null, ComputeState.class, UriUtils.buildUri(this.host, this.vmState.documentSelfLink));
assertAndSetVMSecurityGroupsToBeDeleted(instance, vm);
}
String taskLink = UUID.randomUUID().toString();
ResourceOperationRequest request = new ResourceOperationRequest();
request.isMockRequest = this.isMock;
request.operation = ResourceOperation.REBOOT.operation;
request.payload = new HashMap<>();
request.resourceReference = UriUtils.buildUri(this.host, compute.documentSelfLink);
request.taskReference = UriUtils.buildUri(this.host, taskLink);
TestContext ctx = this.host.testCreate(2);
createTaskResultListener(this.host, taskLink, (u) -> {
if (u.getAction() != Service.Action.PATCH) {
return false;
}
ResourceOperationResponse response = u.getBody(ResourceOperationResponse.class);
if (TaskState.isFailed(response.taskInfo)) {
ctx.failIteration(new IllegalStateException(response.taskInfo.failure.message));
} else if (TaskState.isFinished(response.taskInfo)) {
ctx.completeIteration();
}
return true;
});
Operation rebootOp = Operation.createPatch(UriUtils.buildUri(this.host, AWSRebootService.SELF_LINK)).setBody(request).setReferer(this.host.getReferer()).setCompletion((o, e) -> {
if (e != null) {
ctx.failIteration(e);
return;
}
ctx.completeIteration();
});
this.host.send(rebootOp);
ctx.await();
ComputeState vm = this.host.getServiceState(null, ComputeState.class, UriUtils.buildUri(this.host, this.vmState.documentSelfLink));
assertEquals(ComputeService.PowerState.ON, vm.powerState);
}
Aggregations