@Test public void createAndRunInstancesWithSecurityGroupsTest() { template.send("direct:createAndRun", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(EC2Constants.IMAGE_ID, "ami-fd65ba94"); exchange.getIn().setHeader(EC2Constants.INSTANCE_TYPE, InstanceType.T2Micro); exchange.getIn().setHeader(EC2Constants.INSTANCE_MIN_COUNT, 1); exchange.getIn().setHeader(EC2Constants.INSTANCE_MAX_COUNT, 1); Collection<String> secGroups = new ArrayList<String>(); secGroups.add("secgroup-1"); secGroups.add("secgroup-2"); exchange.getIn().setHeader(EC2Constants.INSTANCE_SECURITY_GROUPS, secGroups); } }); }
public void testConfigRoundtrip() throws Exception { String ami = "ami1"; String description = "foo ami"; EC2Tag tag1 = new EC2Tag( "name1", "value1" ); EC2Tag tag2 = new EC2Tag( "name2", "value2" ); List<EC2Tag> tags = new ArrayList<EC2Tag>(); tags.add( tag1 ); tags.add( tag2 ); SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", tags, null, false, null, "", true, false, "", false, ""); List<SlaveTemplate> templates = new ArrayList<SlaveTemplate>(); templates.add(orig); AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "def", "us-east-1", "ghi", "3", templates); hudson.clouds.add(ac); submit(createWebClient().goTo("configure").getFormByName("config")); SlaveTemplate received = ((EC2Cloud)hudson.clouds.iterator().next()).getTemplate(description); assertEqualBeans(orig, received, "ami,zone,description,remoteFS,type,jvmopts,stopOnTerminate,securityGroups,subnetId,usePrivateDnsName,useEphemeralDevices,useDedicatedTenancy"); }
public void testConfigRoundtripWithPrivateDns() throws Exception { String ami = "ami1"; String description = "foo ami"; EC2Tag tag1 = new EC2Tag( "name1", "value1" ); EC2Tag tag2 = new EC2Tag( "name2", "value2" ); List<EC2Tag> tags = new ArrayList<EC2Tag>(); tags.add( tag1 ); tags.add( tag2 ); SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", tags, null, true, null, "", false, false, "", false, ""); List<SlaveTemplate> templates = new ArrayList<SlaveTemplate>(); templates.add(orig); AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "def", "us-east-1", "ghi", "3", templates); hudson.clouds.add(ac); submit(createWebClient().goTo("configure").getFormByName("config")); SlaveTemplate received = ((EC2Cloud)hudson.clouds.iterator().next()).getTemplate(description); assertEqualBeans(orig, received, "ami,zone,description,remoteFS,type,jvmopts,stopOnTerminate,securityGroups,subnetId,tags,usePrivateDnsName"); }
/** * Tests to make sure the slave created has been configured properly. * Also tests to make sure the spot max bid price has been set properly. * @throws Exception - Exception that can be thrown by the Jenkins test harness */ public void testConfigWithSpotBidPrice() throws Exception { String ami = "ami1"; String description = "foo ami"; EC2Tag tag1 = new EC2Tag( "name1", "value1" ); EC2Tag tag2 = new EC2Tag( "name2", "value2" ); List<EC2Tag> tags = new ArrayList<EC2Tag>(); tags.add( tag1 ); tags.add( tag2 ); SpotConfiguration spotConfig = new SpotConfiguration(".05", SpotInstanceType.OneTime.toString()); SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, spotConfig, "default", "foo", InstanceType.M1Large, "ttt", Node.Mode.NORMAL, "foo ami", "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", tags, null, true, null, "", false, false, "", false, ""); List<SlaveTemplate> templates = new ArrayList<SlaveTemplate>(); templates.add(orig); AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "def", "us-east-1", "ghi", "3", templates); hudson.clouds.add(ac); submit(createWebClient().goTo("configure").getFormByName("config")); SlaveTemplate received = ((EC2Cloud)hudson.clouds.iterator().next()).getTemplate(description); assertEqualBeans(orig, received, "ami,zone,spotConfig,description,remoteFS,type,jvmopts,stopOnTerminate,securityGroups,subnetId,tags,usePrivateDnsName"); }
/** * Test to make sure the IAM Role is set properly. * * @throws Exception */ public void testConfigRoundtripIamRole() throws Exception { String ami = "ami1"; String description = "foo ami"; EC2Tag tag1 = new EC2Tag( "name1", "value1" ); EC2Tag tag2 = new EC2Tag( "name2", "value2" ); List<EC2Tag> tags = new ArrayList<EC2Tag>(); tags.add( tag1 ); tags.add( tag2 ); SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", tags, null, false, null, "iamInstanceProfile", false, false, "", false, ""); List<SlaveTemplate> templates = new ArrayList<SlaveTemplate>(); templates.add(orig); AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "def", "us-east-1", "ghi", "3", templates); hudson.clouds.add(ac); submit(createWebClient().goTo("configure").getFormByName("config")); SlaveTemplate received = ((EC2Cloud)hudson.clouds.iterator().next()).getTemplate(description); assertEqualBeans(orig, received, "ami,zone,description,remoteFS,type,jvmopts,stopOnTerminate,securityGroups,subnetId,usePrivateDnsName,iamInstanceProfile"); }
public void testWindowsConfigRoundTrip() throws Exception { String ami = "ami1"; String description = "foo ami"; EC2Tag tag1 = new EC2Tag( "name1", "value1" ); EC2Tag tag2 = new EC2Tag( "name2", "value2" ); List<EC2Tag> tags = new ArrayList<EC2Tag>(); tags.add( tag1 ); tags.add( tag2 ); SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "rrr", new WindowsData("password", false, ""), "-Xmx1g", false, "subnet 456", tags, null, false, null, "", true, false, "", false, ""); List<SlaveTemplate> templates = new ArrayList<SlaveTemplate>(); templates.add(orig); AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "def", "us-east-1", "ghi", "3", templates); hudson.clouds.add(ac); submit(createWebClient().goTo("configure").getFormByName("config")); SlaveTemplate received = ((EC2Cloud)hudson.clouds.iterator().next()).getTemplate(description); assertEqualBeans(orig, received, "amiType"); }
public void testUnixConfigRoundTrip() throws Exception { String ami = "ami1"; String description = "foo ami"; EC2Tag tag1 = new EC2Tag( "name1", "value1" ); EC2Tag tag2 = new EC2Tag( "name2", "value2" ); List<EC2Tag> tags = new ArrayList<EC2Tag>(); tags.add( tag1 ); tags.add( tag2 ); SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "rrr", new UnixData("sudo", "22"), "-Xmx1g", false, "subnet 456", tags, null, false, null, "", true, false, "", false, ""); List<SlaveTemplate> templates = new ArrayList<SlaveTemplate>(); templates.add(orig); AmazonEC2Cloud ac = new AmazonEC2Cloud("us-east-1", false, "abc", "def", "us-east-1", "ghi", "3", templates); hudson.clouds.add(ac); submit(createWebClient().goTo("configure").getFormByName("config")); SlaveTemplate received = ((EC2Cloud)hudson.clouds.iterator().next()).getTemplate(description); assertEqualBeans(orig, received, "amiType"); }
private com.amazonaws.services.ec2.model.Instance createInstance(KeyPair keyPair, String sgId) throws Exception { RunInstancesRequest request = new RunInstancesRequest() .withKeyName(keyPair.remoteKeyPair.getKeyName()) .withInstanceType(InstanceType.M4Large) .withImageId(resource.baseAMI.imageId()) .withMinCount(1) .withMaxCount(1) .withSecurityGroupIds(sgId); if (bakeSubnet != null) request.withSubnetId(bakeSubnet.getSubnetId()); return AWS.ec2.runInstances(request, tagHelper.name(resourceId), tagHelper.env(), tagHelper.resourceId(resourceId), tagHelper.type("ami"), tagHelper.amiImageId(resource.id())).get(0); }
@Test public void basicSanity() { Ec2ProvisioningTemplate config = new Ec2ProvisioningTemplate(INSTANCE_TYPE, AMI, SUBNET_IDS, ASSIGN_PUBLIC_IP, KEYPAIR, INSTANCE_PROFILE_ARN, SECURITY_GROUP_IDS, USER_DATA, EBS_OPTIMIZED, TAGS); config.validate(); assertThat(config.getInstanceType(), is(InstanceType.fromValue(INSTANCE_TYPE))); assertThat(config.getAmiId(), is(AMI)); assertThat(config.getSubnetIds(), is(SUBNET_IDS)); assertThat(config.isAssignPublicIp(), is(ASSIGN_PUBLIC_IP)); assertThat(config.getKeyPair(), is(KEYPAIR)); assertThat(config.getIamInstanceProfileARN(), is(INSTANCE_PROFILE_ARN)); assertThat(config.getSecurityGroupIds(), is(SECURITY_GROUP_IDS)); assertThat(config.getEncodedUserData(), is(USER_DATA)); assertThat(config.isEbsOptimized(), is(EBS_OPTIMIZED)); assertThat(config.getTags(), is(TAGS)); }
/** * Only instanceType, amiId, and subnetIds are mandatory. */ @Test public void onlyMandatoryArguments() { Ec2ProvisioningTemplate config = new Ec2ProvisioningTemplate(INSTANCE_TYPE, AMI, SUBNET_IDS, null, null, null, null, null, null, null); config.validate(); assertThat(config.getInstanceType(), is(InstanceType.fromValue(INSTANCE_TYPE))); assertThat(config.getAmiId(), is(AMI)); assertThat(config.getSubnetIds(), is(SUBNET_IDS)); assertThat(config.isAssignPublicIp(), is(false)); assertThat(config.getKeyPair(), is(nullValue())); assertThat(config.getIamInstanceProfileARN(), is(nullValue())); assertThat(config.getSecurityGroupIds(), is(Collections.emptyList())); assertThat(config.getEncodedUserData(), is(nullValue())); assertThat(config.isEbsOptimized(), is(false)); assertThat(config.getTags(), is(Collections.emptyMap())); }
@Test public void convertCompleteInstance() { DateTime launchTime = UtcTime.now(); Instance instance = new Instance().withInstanceId("i-1") .withState(new InstanceState().withName(InstanceStateName.Running)).withPublicIpAddress("1.2.3.4") .withPrivateIpAddress("1.2.3.5").withInstanceType(InstanceType.M1Small) .withLaunchTime(launchTime.toDate()) .withMonitoring(new Monitoring().withState(MonitoringState.Disabled)).withHypervisor(HypervisorType.Xen) .withPlacement(new Placement("us-east-1c")); Machine machine = convert(instance); assertThat(machine.getId(), is(instance.getInstanceId())); assertThat(machine.getLaunchTime(), is(launchTime)); assertThat(machine.getMachineState(), is(MachineState.RUNNING)); assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_EC2)); assertThat(machine.getRegion(), is("us-east-1")); assertThat(machine.getMachineSize(), is("m1.small")); assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus())); assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN)); assertThat(machine.getPublicIps().size(), is(1)); assertThat(machine.getPublicIps().get(0), is(instance.getPublicIpAddress())); assertThat(machine.getPrivateIps().size(), is(1)); assertThat(machine.getPrivateIps().get(0), is(instance.getPrivateIpAddress())); assertThat(machine.getMetadata(), is(JsonUtils.toJson(instance))); }
@Test public void convertInstanceMissingPublicIp() { DateTime launchTime = UtcTime.now(); Instance instance = new Instance().withInstanceId("i-1") .withState(new InstanceState().withName(InstanceStateName.Running)).withPrivateIpAddress("1.2.3.5") .withInstanceType(InstanceType.M1Small).withLaunchTime(launchTime.toDate()) .withMonitoring(new Monitoring().withState(MonitoringState.Disabled)).withHypervisor(HypervisorType.Xen) .withPlacement(new Placement("us-east-1a")); Machine machine = convert(instance); assertThat(machine.getId(), is(instance.getInstanceId())); assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_EC2)); assertThat(machine.getRegion(), is("us-east-1")); assertThat(machine.getMachineSize(), is("m1.small")); assertThat(machine.getLaunchTime(), is(launchTime)); assertThat(machine.getMachineState(), is(MachineState.RUNNING)); assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus())); assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN)); assertThat(machine.getPublicIps().size(), is(0)); assertThat(machine.getPrivateIps().size(), is(1)); assertThat(machine.getPrivateIps().get(0), is(instance.getPrivateIpAddress())); assertThat(machine.getMetadata(), is(JsonUtils.toJson(instance))); }
@Test public void convertInstanceMissingPrivateIp() { DateTime launchTime = UtcTime.now(); Instance instance = new Instance().withInstanceId("i-1") .withState(new InstanceState().withName(InstanceStateName.Running)).withPublicIpAddress("1.2.3.4") .withInstanceType(InstanceType.M1Medium).withLaunchTime(launchTime.toDate()) .withMonitoring(new Monitoring().withState(MonitoringState.Disabled)).withHypervisor(HypervisorType.Xen) .withPlacement(new Placement("us-east-1b")); Machine machine = convert(instance); assertThat(machine.getId(), is(instance.getInstanceId())); assertThat(machine.getCloudProvider(), is(CloudProviders.AWS_EC2)); assertThat(machine.getRegion(), is("us-east-1")); assertThat(machine.getMachineSize(), is("m1.medium")); assertThat(machine.getLaunchTime(), is(launchTime)); assertThat(machine.getMachineState(), is(MachineState.RUNNING)); assertThat(machine.getMembershipStatus(), is(MembershipStatus.defaultStatus())); assertThat(machine.getServiceState(), is(ServiceState.UNKNOWN)); assertThat(machine.getPublicIps().size(), is(1)); assertThat(machine.getPublicIps().get(0), is(instance.getPublicIpAddress())); assertThat(machine.getPrivateIps().size(), is(0)); assertThat(machine.getMetadata(), is(JsonUtils.toJson(instance))); }
/** * A converted spot instance {@link Machine} should have a cloud provider * value of {@link CloudProviders#AWS_SPOT} to distinguish it from a regular * EC2 on-demand instance. */ @Test public void convertSpotInstance() { // convert on-demand instance: cloud provider should be AWS_EC2 Instance onDemandInstance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium) .withState(new InstanceState().withName(InstanceStateName.Running)) .withPlacement(new Placement("us-east-1b")); Machine onDemandMachine = convert(onDemandInstance); assertThat(onDemandMachine.getCloudProvider(), is(CloudProviders.AWS_EC2)); // convert spot instance: cloud provider should be AWS_EC2 Instance spotInstance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium) .withState(new InstanceState().withName(InstanceStateName.Running)).withSpotInstanceRequestId("sir-123") .withPlacement(new Placement("us-east-1b")); Machine spotMachine = convert(spotInstance); assertThat(spotMachine.getCloudProvider(), is(CloudProviders.AWS_SPOT)); }
/** * If the actual size of the Auto Scaling Group is less than desired * capacity (for example, when there is a shortage in supply of instances) * the {@link AwsAsPoolDriver} should report the missing instances as being * pseudo instances in state {@link MachineState#REQUESTED}, to not fool the * {@link BaseCloudPool} from believing that the {@link CloudPoolDriver} is * too small and order new machines to be started (and increase the desired * capacity even more). */ @Test public void listMachinesOnGroupThatHasNotReachedDesiredCapacity() throws CloudPoolDriverException { // two missing instances: desired capacity: 3, actual capacity: 1 int desiredCapacity = 3; setUpMockedAutoScalingGroup(GROUP_NAME, ONDEMAND_LAUNCH_CONFIG, desiredCapacity, ec2Instances(ec2Instance("i-1", "running"))); List<Machine> groupMembers = this.driver.listMachines(); assertThat(groupMembers, is(MachinesMatcher.machines("i-1", "i-requested1", "i-requested2"))); assertThat(groupMembers.get(0).getMachineState(), is(MachineState.RUNNING)); assertThat(groupMembers.get(0).getCloudProvider(), is(CloudProviders.AWS_EC2)); assertThat(groupMembers.get(0).getMachineSize(), is(InstanceType.M1Medium.toString())); assertThat(groupMembers.get(1).getMachineState(), is(MachineState.REQUESTED)); assertThat(groupMembers.get(1).getCloudProvider(), is(CloudProviders.AWS_EC2)); assertThat(groupMembers.get(1).getMachineSize(), is(InstanceType.M1Medium.toString())); assertThat(groupMembers.get(2).getMachineState(), is(MachineState.REQUESTED)); assertThat(groupMembers.get(2).getCloudProvider(), is(CloudProviders.AWS_EC2)); assertThat(groupMembers.get(2).getMachineSize(), is(InstanceType.M1Medium.toString())); }
/** * Make sure that requested but not yet acquired pseudo instances get * correctly reported for an Auto Scaling Group of spot instances as well. */ @Test public void listPsuedoMachinesOnGroupWithSpotInstances() { // two missing instances: desired capacity: 3, actual capacity: 1 int desiredCapacity = 3; setUpMockedAutoScalingGroup(GROUP_NAME, SPOT_LAUNCH_CONFIG, desiredCapacity, ec2Instances(spotInstance("sir-1", "i-1", "running"))); List<Machine> groupMembers = this.driver.listMachines(); assertThat(groupMembers, is(MachinesMatcher.machines("i-1", "i-requested1", "i-requested2"))); assertThat(groupMembers.get(0).getMachineState(), is(MachineState.RUNNING)); assertThat(groupMembers.get(0).getCloudProvider(), is(CloudProviders.AWS_SPOT)); assertThat(groupMembers.get(0).getMachineSize(), is(InstanceType.M1Medium.toString())); assertThat(groupMembers.get(1).getMachineState(), is(MachineState.REQUESTED)); assertThat(groupMembers.get(1).getCloudProvider(), is(CloudProviders.AWS_SPOT)); assertThat(groupMembers.get(1).getMachineSize(), is(InstanceType.M1Medium.toString())); assertThat(groupMembers.get(2).getMachineState(), is(MachineState.REQUESTED)); assertThat(groupMembers.get(2).getCloudProvider(), is(CloudProviders.AWS_SPOT)); assertThat(groupMembers.get(2).getMachineSize(), is(InstanceType.M1Medium.toString())); }
/** * @inheritDoc */ @Override public String launchInstance( CreateInstanceOptions options, Identity identity ) { RunInstancesRequest request = new RunInstancesRequest(); if ( options.getInstanceProfileName() != null ) { request.setIamInstanceProfile( new IamInstanceProfileSpecification().withName( options.getInstanceProfileName() ) ); } request.setSubnetId( options.getWorkerOptions().getSubnetId() ); request.setSecurityGroupIds( options.getWorkerOptions().getSecurityGroupIds() ); if ( options.getUserData() != null ) { request.setUserData( Base64.encodeBase64String( options.getUserData().getBytes() ) ); } request.withMinCount( 1 ).withMaxCount( 1 ).withImageId( config.getAgentAmiId() ).withInstanceType( InstanceType.T1Micro ); request.setKeyName( options.getWorkerOptions().getKeyPairName() ); request.setClientToken( "launch-ec2-worker-" + contextProvider.getActivityExecutionContext().getWorkflowExecution().getWorkflowId() ); AmazonEC2 ec2 = ActivityUtils.createClient( AmazonEC2Client.class, identity ); RunInstancesResult result = ec2.runInstances( request ); return result.getReservation().getInstances().get( 0 ).getInstanceId(); }
@Override public void handleGet(Operation op) { Map<String, String> queryParams = UriUtils.parseUriQueryParams(op.getUri()); String endpointLink = queryParams.get(URI_PARAM_ENDPOINT); DeferredResult.completed(new Context(endpointLink)) .thenCompose(this::getEndpointState) .thenCompose(this::getInstanceTypes) .whenComplete((context, err) -> { if (err != null) { op.fail(err); return; } String instanceTypeId = queryParams.get(URI_PARAM_INSTANCE_TYPE); if (instanceTypeId != null) { InstanceTypeList.InstanceType instanceType = context.instanceTypes.instanceTypes .stream().filter(type -> type.id.equals(instanceTypeId)) .findFirst().orElse(null); if (instanceType == null) { op.fail(new IllegalArgumentException( String.format("%s not found", instanceTypeId))); return; } op.setBody(instanceType).complete(); return; } op.setBodyNoCloning(context.instanceTypes).complete(); }); }
/** * Return the instance types by loading them from AWS SDK {@link InstanceType}. */ private DeferredResult<Context> getInstanceTypes(Context context) { AssertUtil.assertNotNull(context.endpointState, "Endpoint state was not retrieved."); context.instanceTypes = new InstanceTypeList(); // Set tenant links as specified in the endpoint. context.instanceTypes.tenantLinks = context.endpointState.tenantLinks; context.instanceTypes.instanceTypes = // Use AWS SDK InstanceType enum as primary source of instance type data. Arrays.stream(InstanceType.values()) .map(instanceType -> { InstanceTypeList.InstanceType result = new InstanceTypeList.InstanceType( instanceType.toString(), instanceType.toString()); InstanceTypeList.InstanceType instanceTypeInfo = this.instanceTypeInfo .get(instanceType.toString()); if (instanceTypeInfo != null) { // We have additional information -> populate additional fields. result.cpuCount = instanceTypeInfo.cpuCount; result.memoryInMB = instanceTypeInfo.memoryInMB; result.networkType = instanceTypeInfo.networkType; result.storageType = instanceTypeInfo.storageType; result.dataDiskMaxCount = instanceTypeInfo.dataDiskMaxCount; result.dataDiskSizeInMB = instanceTypeInfo.dataDiskSizeInMB; } return result; }) // Filter out deprecated types. .filter(instanceType -> !Integer.valueOf(-1).equals(instanceType.cpuCount)) .collect(Collectors.toList()); return DeferredResult.completed(context); }
public static void main(String[] args) { final String USAGE = "To run this example, supply an instance name and AMI image id\n" + "Ex: CreateInstance <instance-name> <ami-image-id>\n"; if (args.length != 2) { System.out.println(USAGE); System.exit(1); } String name = args[0]; String ami_id = args[1]; final AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient(); RunInstancesRequest run_request = new RunInstancesRequest() .withImageId(ami_id) .withInstanceType(InstanceType.T1Micro) .withMaxCount(1) .withMinCount(1); RunInstancesResult run_response = ec2.runInstances(run_request); String instance_id = run_response.getReservation().getReservationId(); Tag tag = new Tag() .withKey("Name") .withValue(name); CreateTagsRequest tag_request = new CreateTagsRequest() .withTags(tag); CreateTagsResult tag_response = ec2.createTags(tag_request); System.out.printf( "Successfully started EC2 instance %s based on AMI %s", instance_id, ami_id); }
@Test public void createAndRunInstancesTest() { template.send("direct:createAndRun", new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(EC2Constants.IMAGE_ID, "ami-fd65ba94"); exchange.getIn().setHeader(EC2Constants.INSTANCE_TYPE, InstanceType.T2Micro); exchange.getIn().setHeader(EC2Constants.INSTANCE_MIN_COUNT, 1); exchange.getIn().setHeader(EC2Constants.INSTANCE_MAX_COUNT, 1); } }); }
/** * Get the size of the instance * * @param size * The size requested * @return The size assigned */ private static InstanceType getInstanceType(String size) { InstanceType output = InstanceType.C42xlarge; try { output = InstanceType.fromValue(size); } catch (Exception e) { LOG.warn("Error parsing vminstanceType " + size, e); } return output; }
/** * Given an AMI start an EC2 Instance. * * @param amiId * to start * @return the id of the running instance. * @throws ServiceBrokerException */ public String startEC2Instance(String amiId) throws ServiceBrokerException { RunInstancesResult instance = ec2Client .runInstances(new RunInstancesRequest().withImageId(amiId) .withInstanceType("m1.small").withMinCount(1) .withMaxCount(1).withSubnetId(subnetId) .withInstanceType(InstanceType.T2Micro)); String instanceId = getInstanceId(instance); addElasticIp(instanceId); log.info("Instance " + instanceId + " started successfully"); return instanceId; }
public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) { InstanceType instanceType = null; String stringValue = reader.getValue(); try { instanceType = InstanceType.valueOf(stringValue); } catch (IllegalArgumentException e) { instanceType = TYPICAL_INSTANCE_TYPES.get(stringValue.toUpperCase()); } return instanceType; }
@Test public void testUpdateRemoteTags() throws Exception { AmazonEC2 ec2 = new AmazonEC2Client() { @Override public void createTags(com.amazonaws.services.ec2.model.CreateTagsRequest createTagsRequest) { } }; String ami = "ami1"; String description = "foo ami"; EC2Tag tag1 = new EC2Tag("name1", "value1"); EC2Tag tag2 = new EC2Tag("name2", "value2"); List<EC2Tag> tags = new ArrayList<EC2Tag>(); tags.add(tag1); tags.add(tag2); String instanceId = "123"; SlaveTemplate orig = new SlaveTemplate(ami, EC2AbstractSlave.TEST_ZONE, null, "default", "foo", InstanceType.M1Large, "ttt", Node.Mode.NORMAL, description, "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", false, "subnet 456", tags, null, false, null, "", true, false, "", false, "") { @Override protected Object readResolve() { return null; } }; ArrayList<Tag> awsTags = new ArrayList<Tag>(); awsTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "value1")); awsTags.add(new Tag(EC2Tag.TAG_NAME_JENKINS_SLAVE_TYPE, "value2")); final Object params[] = {ec2, awsTags, "InvalidInstanceRequestID.NotFound", instanceId}; Whitebox.invokeMethod(orig, "updateRemoteTags", params); assertEquals(0, handler.getRecords().size()); }
private void setUpCloud(String label, Node.Mode mode) throws Exception{ EC2Tag tag1 = new EC2Tag( "name1", "value1" ); EC2Tag tag2 = new EC2Tag( "name2", "value2" ); List<EC2Tag> tags = new ArrayList<EC2Tag>(); tags.add( tag1 ); tags.add( tag2 ); SlaveTemplate template = new SlaveTemplate("ami", "foo", null, "default", "zone", InstanceType.M1Large, label, mode,"foo ami", "bar", "bbb", "aaa", "10", "fff", null, "-Xmx1g", true, "subnet 456", tags, null, false, null, "", false, false, null, false, ""); List<SlaveTemplate> templates = new ArrayList<SlaveTemplate>(); templates.add(template); ac = new AmazonEC2Cloud("us-east-1", false, "abc", "def", "us-east-1", "ghi", "3", templates); }
@Test public void testGetEnvironmentFromInstance() throws Exception { final Date launchTime = new Date(); final Instance instance = new Instance().withInstanceId("instance").withInstanceType(InstanceType.C1Xlarge).withTags(new Tag(EC2Connector.DEFAULT_INSTANCE_NAME_TAG, "unknown")) .withState(new InstanceState().withName(InstanceStateName.Running)).withLaunchTime(launchTime).withPublicIpAddress("127.0.0.1"); ServerEnvironment serverEnv = Whitebox.<ServerEnvironment> invokeMethod(env, "getEnvironmentFromInstance", instance); assertThat(serverEnv, notNullValue()); assertThat(serverEnv.getInstanceId(), is("instance")); assertThat(serverEnv.getInstanceType(), is(InstanceType.C1Xlarge.toString())); assertThat(serverEnv.getType(), is(ENVIRONMENT_TYPES.TEST)); assertThat(serverEnv.getEnvironmentTag(), is("unknown")); assertThat(serverEnv.getState().getName(), is(InstanceStateName.Running.toString())); assertThat(serverEnv.getLaunchTime(), is(launchTime)); assertThat(serverEnv.getPublicIpAddress(), is("127.0.0.1")); }
@Test public void testGetEnvironmentFromInstanceProd() throws Exception { final Instance instance = new Instance().withInstanceId("instance").withInstanceType(InstanceType.C1Xlarge).withTags(new Tag(EC2Connector.DEFAULT_INSTANCE_NAME_TAG, EC2Connector.PROD_VALUE)); ServerEnvironment serverEnv = Whitebox.<ServerEnvironment> invokeMethod(env, "getEnvironmentFromInstance", instance); assertThat(serverEnv, notNullValue()); assertThat(serverEnv.getType(), is(ENVIRONMENT_TYPES.PRODUCTION)); }
@Test public void testGetEnvironmentFromInstanceStage() throws Exception { final Instance instance = new Instance().withInstanceId("instance").withInstanceType(InstanceType.C1Xlarge) .withTags(new Tag(EC2Connector.DEFAULT_INSTANCE_NAME_TAG, EC2Connector.STAGING_VALUE)); ServerEnvironment serverEnv = Whitebox.<ServerEnvironment> invokeMethod(env, "getEnvironmentFromInstance", instance); assertThat(serverEnv, notNullValue()); assertThat(serverEnv.getType(), is(ENVIRONMENT_TYPES.STAGING)); }
@Test public void testGetEnvironmentFromInstanceJenkins() throws Exception { final Instance instance = new Instance().withInstanceId("instance").withInstanceType(InstanceType.C1Xlarge) .withTags(new Tag(EC2Connector.DEFAULT_INSTANCE_NAME_TAG, EC2Connector.JENKINS_VALUE)); ServerEnvironment serverEnv = Whitebox.<ServerEnvironment> invokeMethod(env, "getEnvironmentFromInstance", instance); assertThat(serverEnv, notNullValue()); assertThat(serverEnv.getType(), is(ENVIRONMENT_TYPES.JENKINS)); }
@Test public void testGetEnvironmentFromInstanceTest() throws Exception { final Instance instance = new Instance().withInstanceId("instance").withInstanceType(InstanceType.C1Xlarge).withTags(new Tag(EC2Connector.DEFAULT_INSTANCE_NAME_TAG, EC2Connector.TEST_VALUE)); ServerEnvironment serverEnv = Whitebox.<ServerEnvironment> invokeMethod(env, "getEnvironmentFromInstance", instance); assertThat(serverEnv, notNullValue()); assertThat(serverEnv.getType(), is(ENVIRONMENT_TYPES.TEST)); }
@Test public void testGetEnvironmentFromInstanceVersion() throws Exception { final Instance instance = new Instance().withInstanceId("instance").withInstanceType(InstanceType.C1Xlarge).withTags(new Tag(EC2Connector.VERSION_TAG, "1.2.3")); ServerEnvironment serverEnv = Whitebox.<ServerEnvironment> invokeMethod(env, "getEnvironmentFromInstance", instance); assertThat(serverEnv, notNullValue()); assertThat(serverEnv.getVersion(), is("1.2.3")); }
private void validateMachineHasInstanceType(List<String> results, Machine machine) { if (StringUtils.isEmpty(machine.getInstanceType())) results.add(ERROR + "You must provide an instance type for the machine"); else { String instanceType = machine.getInstanceType(); try { InstanceType.fromValue(instanceType); results.add(SUCCESS + "Valid instance type"); } catch (IllegalArgumentException e) { results.add(ERROR + "Unknown instance type"); } } }
/** * Performs basic validation of this configuration. * * @throws IllegalArgumentException */ public void validate() throws IllegalArgumentException { checkArgument(this.instanceType != null, "provisioningTemplate: missing instanceType"); try { InstanceType.fromValue(this.instanceType); } catch (IllegalArgumentException e) { throw new IllegalArgumentException( String.format("provisioingTemplate: unrecognized instanceType: %s", this.instanceType)); } checkArgument(this.amiId != null, "provisioningTemplate: missing amiId"); checkArgument(this.subnetIds != null, "provisioningTemplate: missing subnetIds"); checkArgument(!this.subnetIds.isEmpty(), "provisioningTemplate: at least one subnet id must be specified"); }
@Test public void convertWithServiceStateTag() { Tag serviceStateTag = new Tag().withKey(ScalingTags.SERVICE_STATE_TAG) .withValue(ServiceState.OUT_OF_SERVICE.name()); Instance instance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium) .withState(new InstanceState().withName(InstanceStateName.Running)) .withPlacement(new Placement("us-east-1b")).withTags(serviceStateTag); Machine machine = convert(instance); assertThat(machine.getServiceState(), is(ServiceState.OUT_OF_SERVICE)); }
@Test public void convertWithMembershipStatusTag() { MembershipStatus status = MembershipStatus.awaitingService(); String statusJsonString = JsonUtils.toString(JsonUtils.toJson(status)); Tag membershipStatusTag = new Tag().withKey(ScalingTags.MEMBERSHIP_STATUS_TAG).withValue(statusJsonString); Instance instance = new Instance().withInstanceId("i-1").withInstanceType(InstanceType.M1Medium) .withState(new InstanceState().withName(InstanceStateName.Running)) .withPlacement(new Placement("us-east-1b")).withTags(membershipStatusTag); Machine machine = convert(instance); assertThat(machine.getMembershipStatus(), is(status)); }
private CreateInstanceTask readyInstanceTask() { CreateInstanceTask instanceTask = new CreateInstanceTask(); instanceTask.setProject(project); instanceTask.setInstanceType(InstanceType.M1Small.toString()); instanceTask.setAvailabilityZone(AVAILABILITY_ZONE); return instanceTask; }
private InstanceType getInstanceType(IProperty[] macProps) { String instanceTypeString = Utils.getInstanceType(macProps, controllerServices); InstanceType instanceType = InstanceType.M1Small; try { instanceType = InstanceType.fromValue(instanceTypeString); } catch (IllegalArgumentException e) { //Should never occur logger.log(Level.INFO, "Invalid instance type. Using m1.small", e); } return instanceType; }
public static void run(AmazonEC2 machines, String pathToScript, int count, String profileArn) throws IOException { machines.runInstances( new RunInstancesRequest() .withImageId("ami-c7c0d6b3") // This used to be the official, Ireland running, 32 bit Amazon Machine Image. Or pick, for instance, [Ubuntu](http://cloud-images.ubuntu.com/locator/ec2/) .withInstanceType(InstanceType.T1Micro) // Smallest possible, cheapest. Be warned: Cc28xlarge can set you back 3.75$ per call per machine per hour... [Pricing](http://aws.amazon.com/fr/ec2/#pricing) .withMaxCount(count) .withMinCount(count) .withInstanceInitiatedShutdownBehavior(ShutdownBehavior.Terminate) .withIamInstanceProfile(new IamInstanceProfileSpecification().withArn(profileArn)) .withUserData(printBase64Binary(FileUtils.readFileToString(new File(pathToScript), "UTF-8").getBytes("UTF-8"))) ); }
@Test public void testGetInstanceTypesPositive() throws Throwable { EndpointState ep = createEndpointState(); TestContext ctx = this.host.testCreate(1); Operation getOperation = Operation .createGet(UriUtils.buildUri(this.host, AWSInstanceTypeService.SELF_LINK + "?endpoint=" + ep.documentSelfLink)) .setCompletion((operation, throwable) -> { try { if (throwable != null) { ctx.failIteration(throwable); return; } assertEquals(Operation.STATUS_CODE_OK, operation.getStatusCode()); InstanceTypeList instanceTypes = operation.getBody(InstanceTypeList.class); assertNotNull("Tenant links should ne set.", instanceTypes.tenantLinks); assertEquals("Tenant links size equal to endpoint tenant links size is " + "expecteed.", ep.tenantLinks.size(), instanceTypes.tenantLinks.size()); assertNotNull("Instance types should not be null.", instanceTypes.instanceTypes); instanceTypes.instanceTypes.stream() .filter(instanceType -> instanceType.id == null || instanceType.name == null) .findFirst() .ifPresent(instanceType -> fail("Found instance type without id " + "or name.")); // Validate that all types have cpu and memory extended data set. instanceTypes.instanceTypes.stream() .filter(instanceType -> instanceType.cpuCount == null || instanceType.memoryInMB == null) .findFirst() .ifPresent(instanceType -> fail("Found instance type without extended data present: " + instanceType.id)); // Check that one of the well known type is present. InstanceTypeList.InstanceType t2MicroType = instanceTypes.instanceTypes .stream() .filter(instanceType -> InstanceType.T2Micro.toString().equals (instanceType.id)) .findFirst() .orElseThrow(() -> new AssertionError("Unable to " + "find t2.micro instance type.")); assertEquals(1, t2MicroType.cpuCount.intValue()); assertEquals(1024, t2MicroType.memoryInMB.intValue()); assertNotNull(t2MicroType.storageType); assertNotNull(t2MicroType.networkType); ctx.completeIteration(); } catch (AssertionError err) { ctx.failIteration(err); } }); this.send(getOperation); this.testWait(ctx); }