Java 类com.amazonaws.services.ec2.model.RunInstancesRequest 实例源码

项目:aws-cluster-toolkit    文件:AwsClusterManager.java   
private RunInstancesResult runInstance(String GROUP_NAME, String clustertype) {
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();

    runInstancesRequest.withImageId(ami)
    .withInstanceType(type)
    .withMinCount(1)
    .withMaxCount(1)
    .withKeyName(MY_KEY)
    .withSecurityGroups(GROUP_NAME);

    RunInstancesResult result = ec2.runInstances(runInstancesRequest);
    System.out.println(clustertype+" node reservation:"+result.getReservation().getInstances().get(0).getInstanceId());

    tagInstance(result.getReservation().getInstances().get(0).getInstanceId(),"Name",name+"-"+clustertype,ec2);

    return result;
}
项目:oscm    文件:EC2CommunicationTest.java   
@Test
public void testCreateInstanceUserData() throws Exception {
    String userData = "line1\nline2\n";
    String userDataBase64 = Base64.encodeBase64String(userData.getBytes());
    File myFile = createUserDataFile(userData);
    try {
        URL fileUrl = myFile.toURI().toURL();
        parameters.put(PropertyHandler.USERDATA_URL, new Setting(
                PropertyHandler.USERDATA_URL, fileUrl.toString()));
        ec2mock.createRunInstancesResult("instance2");
        ec2mock.createDescribeImagesResult("image1");
        ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
        ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
                "security_group1,security_group2");
        ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
        Image image = ec2comm.resolveAMI("image1");

        ec2comm.createInstance(image);
        String result = ph.getAWSInstanceId();
        assertEquals("instance2", result);
        ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
                .forClass(RunInstancesRequest.class);
        verify(ec2).runInstances(arg1.capture());
        RunInstancesRequest rir = arg1.getValue();
        assertEquals(userDataBase64, rir.getUserData());
    } finally {
        myFile.delete();
    }
}
项目:oscm    文件:EC2CommunicationTest.java   
@Test
public void testCreateInstanceSecurityGroupsMultiple() throws Exception {
    parameters.put(PropertyHandler.SECURITY_GROUP_NAMES, new Setting(
            PropertyHandler.SECURITY_GROUP_NAMES,
            "security_group1, security_group2"));
    ec2mock.createRunInstancesResult("instance3");
    ec2mock.createDescribeImagesResult("image1");
    ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
    ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
            "security_group1,security_group2");
    ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
    Image image = ec2comm.resolveAMI("image1");
    ec2comm.createInstance(image);
    String result = ph.getAWSInstanceId();
    assertEquals("instance3", result);

    ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
            .forClass(RunInstancesRequest.class);
    verify(ec2).runInstances(arg1.capture());
    RunInstancesRequest rir = arg1.getValue();
    // Network interfaces and an instance-level security groups may not be
    // specified on the same request..
    assertEquals(2, rir.getNetworkInterfaces().get(0).getGroups().size());
    // assertEquals("security_group1", rir.getSecurityGroups().get(0));
    // assertEquals("security_group2", rir.getSecurityGroups().get(1));
}
项目:photon-model    文件:TestAWSSetupUtils.java   
/**
 * Method to directly provision instances on the AWS endpoint without the knowledge of the local
 * system. This is used to spawn instances and to test that the discovery of items not
 * provisioned by Xenon happens correctly.
 *
 * @throws Throwable
 */
public static List<String> provisionAWSVMWithEC2Client(AmazonEC2AsyncClient client,
        VerificationHost host, int numberOfInstance, String instanceType, String subnetId,
        String securityGroupId) throws Throwable {
    host.log("Provisioning %d instances on the AWS endpoint using the EC2 client.",
            numberOfInstance);

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
            .withSubnetId(subnetId)
            .withImageId(EC2_LINUX_AMI).withInstanceType(instanceType)
            .withMinCount(numberOfInstance).withMaxCount(numberOfInstance)
            .withSecurityGroupIds(securityGroupId);

    // handler invoked once the EC2 runInstancesAsync commands completes
    AWSRunInstancesAsyncHandler creationHandler = new AWSRunInstancesAsyncHandler(
            host);
    client.runInstancesAsync(runInstancesRequest, creationHandler);
    host.waitFor("Waiting for instanceIds to be retured from AWS", () -> {
        return checkInstanceIdsReturnedFromAWS(numberOfInstance, creationHandler.instanceIds);

    });

    return creationHandler.instanceIds;
}
项目:photon-model    文件:TestAWSSetupUtils.java   
public static String provisionAWSVMWithEC2Client(VerificationHost host, AmazonEC2Client client,
        String ami, String subnetId, String securityGroupId) {

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
            .withSubnetId(subnetId)
            .withImageId(ami)
            .withInstanceType(instanceType)
            .withMinCount(1).withMaxCount(1)
            .withSecurityGroupIds(securityGroupId);

    // handler invoked once the EC2 runInstancesAsync commands completes
    RunInstancesResult result = null;
    try {
        result = client.runInstances(runInstancesRequest);
    } catch (Exception e) {
        host.log(Level.SEVERE, "Error encountered in provisioning machine on AWS",
                Utils.toString(e));
    }
    assertNotNull(result);
    assertNotNull(result.getReservation());
    assertNotNull(result.getReservation().getInstances());
    assertEquals(1, result.getReservation().getInstances().size());

    return result.getReservation().getInstances().get(0).getInstanceId();
}
项目:photon-model    文件:TestAWSSetupUtils.java   
public static String provisionAWSEBSVMWithEC2Client(VerificationHost host, AmazonEC2Client client,
        String ami, String subnetId, String securityGroupId, BlockDeviceMapping blockDeviceMapping) {

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
            .withSubnetId(subnetId)
            .withImageId(ami)
            .withInstanceType(instanceType)
            .withMinCount(1).withMaxCount(1)
            .withSecurityGroupIds(securityGroupId)
            .withBlockDeviceMappings(blockDeviceMapping);

    // handler invoked once the EC2 runInstancesAsync commands completes
    RunInstancesResult result = null;
    try {
        result = client.runInstances(runInstancesRequest);
    } catch (Exception e) {
        host.log(Level.SEVERE, "Error encountered in provisioning machine on AWS",
                Utils.toString(e));
    }
    assertNotNull(result);
    assertNotNull(result.getReservation());
    assertNotNull(result.getReservation().getInstances());
    assertEquals(1, result.getReservation().getInstances().size());

    return result.getReservation().getInstances().get(0).getInstanceId();
}
项目:development    文件:EC2CommunicationTest.java   
@Test
public void testCreateInstanceSecurityGroupsMultiple() throws Exception {
    parameters.put(PropertyHandler.SECURITY_GROUP_NAMES, new Setting(
            PropertyHandler.SECURITY_GROUP_NAMES,
            "security_group1, security_group2"));
    ec2mock.createRunInstancesResult("instance3");
    ec2mock.createDescribeImagesResult("image1");
    ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
    ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
            "security_group1,security_group2");
    ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
    Image image = ec2comm.resolveAMI("image1");
    ec2comm.createInstance(image);
    String result = ph.getAWSInstanceId();
    assertEquals("instance3", result);

    ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
            .forClass(RunInstancesRequest.class);
    verify(ec2).runInstances(arg1.capture());
    RunInstancesRequest rir = arg1.getValue();
    // Network interfaces and an instance-level security groups may not be
    // specified on the same request..
    assertEquals(2, rir.getNetworkInterfaces().get(0).getGroups().size());
    // assertEquals("security_group1", rir.getSecurityGroups().get(0));
    // assertEquals("security_group2", rir.getSecurityGroups().get(1));
}
项目:cmn-project    文件:EC2.java   
public List<Instance> runInstances(RunInstancesRequest request, Tag... tags) throws Exception {
    logger.info("create ec2 instance, request={}", request);

    RunInstancesResult result = new Runner<RunInstancesResult>()
        .maxAttempts(3)
        .retryInterval(Duration.ofSeconds(20))
        .retryOn(this::retryOnRunInstance)
        .run(() -> ec2.runInstances(request));

    Threads.sleepRoughly(Duration.ofSeconds(5)); // wait little bit to make sure instance is visible to tag service
    List<String> instanceIds = result.getReservation().getInstances().stream().map(Instance::getInstanceId).collect(Collectors.toList());

    CreateTagsRequest tagsRequest = new CreateTagsRequest()
        .withResources(instanceIds)
        .withTags(tags);

    createTags(tagsRequest);

    waitUntilRunning(instanceIds);

    return describeInstances(instanceIds);
}
项目:cmn-project    文件:BakeAMITask.java   
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);
}
项目:primecloud-controller    文件:ExceptionHandleAwsClientWrapper.java   
protected AutoException handleException(AmazonServiceException exception, Method method, Object[] args) {
    Object request = null;
    if (method.getParameterTypes().length > 0) {
        request = args[0];
    }

    // UserDataにはパスワードが含まれているためマスクする
    if (request instanceof RunInstancesRequest) {
        ((RunInstancesRequest) request).setUserData(null);
    }

    String str = StringUtils.reflectToString(request);

    return new AutoException("EAWS-000003", exception, method.getName(), exception.getErrorCode(),
            exception.getMessage(), str);
}
项目:SeleniumGridScaler    文件:VmManagerTest.java   
@Test
// Happy path test flow for launching nodes
public void testLaunchNodes() throws NodesCouldNotBeStartedException{
    MockAmazonEc2Client client = new MockAmazonEc2Client(null);
    RunInstancesResult runInstancesResult = new RunInstancesResult();
    Reservation reservation = new Reservation();
    reservation.setInstances(Arrays.asList(new Instance()));
    runInstancesResult.setReservation(reservation);
    client.setRunInstances(runInstancesResult);
    Properties properties = new Properties();
    String region = "east", uuid="uuid",browser="chrome",os="windows";
    Integer threadCount = 5,maxSessions=5;
    MockManageVm manageEC2 = new MockManageVm(client,properties,region);
    String userData = "userData";
    manageEC2.setUserData(userData);
    List<Instance> instances = manageEC2.launchNodes(uuid,os,browser,null,threadCount,maxSessions);
    RunInstancesRequest request = client.getRunInstancesRequest();
    Assert.assertEquals("Min count should match thread count requested", threadCount, request.getMinCount());
    Assert.assertEquals("Max count should match thread count requested", threadCount, request.getMaxCount());
    Assert.assertEquals("User data should match", userData, request.getUserData());
    Assert.assertTrue("No security group should be set", request.getSecurityGroupIds().isEmpty());
    Assert.assertNull("No subnet should be set", request.getSubnetId());
    Assert.assertNull("No key name should be set", request.getKeyName());
}
项目:incubator-provisionr    文件:RunOnDemandInstances.java   
@Override
public void execute(AmazonEC2 client, Pool pool, DelegateExecution execution) throws IOException {

    final RunInstancesRequest request = createOnDemandInstancesRequest(pool, execution);
    // TODO allow for more options (e.g. monitoring & termination protection etc.)

    LOG.info(">> Sending RunInstances request: {}", request);
    RunInstancesResult result = client.runInstances(request);
    LOG.info("<< Got RunInstances result: {}", result);

    // TODO tag instances: managed-by: Apache Provisionr, business-key: ID etc.

    execution.setVariable(ProcessVariables.RESERVATION_ID,
        result.getReservation().getReservationId());
    execution.setVariable(ProcessVariables.INSTANCE_IDS,
        collectInstanceIdsAsList(result.getReservation().getInstances()));
}
项目:aws-mock    文件:RunInstancesExample.java   
/**
 * Run some new ec2 instances.
 *
 * @param imageId
 *            AMI for running new instances from
 * @param runCount
 *            count of instances to run
 * @return a list of started instances
 */
public static List<Instance> runInstances(final String imageId, final int runCount) {
    // pass any credentials as aws-mock does not authenticate them at all
    AWSCredentials credentials = new BasicAWSCredentials("foo", "bar");
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);

    // the mock endpoint for ec2 which runs on your computer
    String ec2Endpoint = "http://localhost:8000/aws-mock/ec2-endpoint/";
    amazonEC2Client.setEndpoint(ec2Endpoint);

    // instance type
    String instanceType = "m1.large";

    // run 10 instances
    RunInstancesRequest request = new RunInstancesRequest();
    final int minRunCount = runCount;
    final int maxRunCount = runCount;
    request.withImageId(imageId).withInstanceType(instanceType)
            .withMinCount(minRunCount).withMaxCount(maxRunCount);
    RunInstancesResult result = amazonEC2Client.runInstances(request);

    return result.getReservation().getInstances();
}
项目:aws-mock    文件:BaseTest.java   
/**
 * Run instances with a random AMI ID.
 *
 * @param type
 *            instance type
 * @param minCount
 *            minimum start up instance number
 * @param maxCount
 *            maximum start up instance number
 * @return a list of instances started.
 */
protected final List<Instance> runInstances(final InstanceType type,
        final int minCount, final int maxCount) {
    log.info("Run instances: type=" + type + ", minCount=" + minCount
            + ", maxCount=" + maxCount);
    RunInstancesRequest request = new RunInstancesRequest();

    String imageId = randomAMI();

    request.withImageId(imageId).withInstanceType(type.getName())
            .withMinCount(minCount).withMaxCount(maxCount);

    RunInstancesResult result = amazonEC2Client.runInstances(request);

    return result.getReservation().getInstances();
}
项目:datamung    文件:Ec2ActivitiesImpl.java   
/**
 * @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();
}
项目:oscm    文件:EC2ProcessorTest.java   
@Test
public void process_CREATION_REQUESTED() throws Exception {
    ph.setOperation(Operation.EC2_CREATION);
    ph.setState(FlowState.CREATION_REQUESTED);
    InstanceStatus result = ec2proc.process();
    assertFalse(result.isReady());
    assertEquals(FlowState.CREATING, ph.getState());

    verify(ec2).runInstances(any(RunInstancesRequest.class));
}
项目:oscm    文件:EC2CommunicationTest.java   
@Test
public void testCreateInstance() throws Exception {
    ec2mock.createRunInstancesResult("instance1");
    ec2mock.createDescribeImagesResult("image1");
    ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
    ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
            "security_group1,security_group2");
    ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
    Image image = ec2comm.resolveAMI("image1");
    ec2comm.createInstance(image);
    String result = ph.getAWSInstanceId();
    assertEquals("instance1", result);
    ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
            .forClass(RunInstancesRequest.class);
    verify(ec2).runInstances(arg1.capture());
    RunInstancesRequest rir = arg1.getValue();
    assertEquals("image1", rir.getImageId());
    assertEquals("type1", rir.getInstanceType());
    assertEquals("key_pair", rir.getKeyName());
    assertEquals(1, rir.getMinCount().intValue());
    assertEquals(1, rir.getMaxCount().intValue());

    ArgumentCaptor<CreateTagsRequest> arg2 = ArgumentCaptor
            .forClass(CreateTagsRequest.class);
    verify(ec2).createTags(arg2.capture());
    CreateTagsRequest ctr = arg2.getValue();
    for (Tag t : ctr.getTags()) {
        if (t.getKey().equalsIgnoreCase("Name")) {
            assertEquals("name1", t.getValue());
        } else if (t.getKey().equalsIgnoreCase("SubscriptionId")) {
            assertEquals("subId", t.getValue());
        } else if (t.getKey().equalsIgnoreCase("OrganizationId")) {
            assertEquals("orgId", t.getValue());
        }
    }

    parameters.put("USERDATA_URL", new Setting("USERDATA_URL", "userdata"));

}
项目:oscm    文件:EC2CommunicationTest.java   
@Test
public void testCreateInstanceSecurityGroups() throws Exception {
    parameters.put(PropertyHandler.SECURITY_GROUP_NAMES, new Setting(
            PropertyHandler.SECURITY_GROUP_NAMES, "security_group"));
    ec2mock.createRunInstancesResult("instance3");

    ec2mock.createDescribeImagesResult("image1");
    ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
    ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
            "security_group");
    ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
    Image image = ec2comm.resolveAMI("image1");
    ec2comm.createInstance(image);
    String result = ph.getAWSInstanceId();
    assertEquals("instance3", result);

    ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
            .forClass(RunInstancesRequest.class);
    verify(ec2).runInstances(arg1.capture());
    RunInstancesRequest rir = arg1.getValue();
    // Network interfaces and an instance-level security groups may not be
    // specified on the same request..
    assertEquals(1, rir.getNetworkInterfaces().get(0).getGroups().size());
    /*
     * assertEquals("security_group",
     * rir.getNetworkInterfaces().get(0).getGroups().get(0));
     */
}
项目:oscm    文件:EC2Mockup.java   
public void createRunInstancesResult(String... instanceIds) {
    Collection<Instance> instances = new ArrayList<Instance>();
    for (int i = 0; i < instanceIds.length; i++) {
        instances.add(new Instance().withInstanceId(instanceIds[i]));
    }
    Reservation reservation = new Reservation().withInstances(instances);
    RunInstancesResult result = new RunInstancesResult()
            .withReservation(reservation);
    doReturn(result).when(ec2).runInstances(any(RunInstancesRequest.class));
}
项目:CloudPrime    文件:AutoScaling.java   
public static InstanceObject startInstance(AmazonEC2 ec2)
{
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    runInstancesRequest.withImageId("ami-f6ed6785")
    .withMonitoring(true)
       .withInstanceType("t2.micro")
       .withMinCount(1)
       .withMaxCount(1)
       .withKeyName("CNV-lab-AWS")
       .withSecurityGroups("CNV-ssh+http");
    RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);

    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {}

    DescribeInstancesResult describeInstancesResult  = ec2.describeInstances();
    List<Reservation> reservations = describeInstancesResult.getReservations();
    ArrayList<Instance> auxListOfInstances = new ArrayList<Instance>();
       for (Reservation reservation : reservations) {
        auxListOfInstances.addAll(reservation.getInstances());
       }

       InstanceObject instanceObject = null;
       for (Instance instance : auxListOfInstances) {
            if(instance.getInstanceId().equals(runInstancesResult.getReservation().getInstances().get(0).getInstanceId())) //id do load balancer, nao adicionamos este as instancias 
                instanceObject = new InstanceObject(instance);              
       }

       //retornamos a instance criada
       return instanceObject;
}
项目:photon-model    文件:TestAWSSetupUtils.java   
@Override
public void onSuccess(RunInstancesRequest request, RunInstancesResult result) {
    for (Instance i : result.getReservation().getInstances()) {
        this.instanceIds.add(i.getInstanceId());
        this.host.log("Successfully created instances on AWS endpoint %s",
                i.getInstanceId());
    }
}
项目:aws-doc-sdk-examples    文件:CreateInstance.java   
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);
}
项目:development    文件:EC2ProcessorTest.java   
@Test
public void process_CREATION_REQUESTED() throws Exception {
    ph.setOperation(Operation.EC2_CREATION);
    ph.setState(FlowState.CREATION_REQUESTED);
    InstanceStatus result = ec2proc.process();
    assertFalse(result.isReady());
    assertEquals(FlowState.CREATING, ph.getState());

    verify(ec2).runInstances(any(RunInstancesRequest.class));
}
项目:development    文件:EC2CommunicationTest.java   
@Test
public void testCreateInstance() throws Exception {
    ec2mock.createRunInstancesResult("instance1");
    ec2mock.createDescribeImagesResult("image1");
    ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
    ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
            "security_group1,security_group2");
    ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
    Image image = ec2comm.resolveAMI("image1");
    ec2comm.createInstance(image);
    String result = ph.getAWSInstanceId();
    assertEquals("instance1", result);
    ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
            .forClass(RunInstancesRequest.class);
    verify(ec2).runInstances(arg1.capture());
    RunInstancesRequest rir = arg1.getValue();
    assertEquals("image1", rir.getImageId());
    assertEquals("type1", rir.getInstanceType());
    assertEquals("key_pair", rir.getKeyName());
    assertEquals(1, rir.getMinCount().intValue());
    assertEquals(1, rir.getMaxCount().intValue());

    ArgumentCaptor<CreateTagsRequest> arg2 = ArgumentCaptor
            .forClass(CreateTagsRequest.class);
    verify(ec2).createTags(arg2.capture());
    CreateTagsRequest ctr = arg2.getValue();
    for (Tag t : ctr.getTags()) {
        if (t.getKey().equalsIgnoreCase("Name")) {
            assertEquals("name1", t.getValue());
        } else if (t.getKey().equalsIgnoreCase("SubscriptionId")) {
            assertEquals("subId", t.getValue());
        } else if (t.getKey().equalsIgnoreCase("OrganizationId")) {
            assertEquals("orgId", t.getValue());
        }
    }

    parameters.put("USERDATA_URL", new Setting("USERDATA_URL", "userdata"));

}
项目:development    文件:EC2CommunicationTest.java   
@Test
public void testCreateInstanceUserData() throws Exception {
    String userData = "line1\nline2\n";
    String userDataBase64 = Base64.encodeBase64String(userData.getBytes());
    File myFile = createUserDataFile(userData);
    try {
        URL fileUrl = myFile.toURI().toURL();
        parameters.put(PropertyHandler.USERDATA_URL, new Setting(
                PropertyHandler.USERDATA_URL, fileUrl.toString()));
        ec2mock.createRunInstancesResult("instance2");
        ec2mock.createDescribeImagesResult("image1");
        ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
        ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
                "security_group1,security_group2");
        ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
        Image image = ec2comm.resolveAMI("image1");

        ec2comm.createInstance(image);
        String result = ph.getAWSInstanceId();
        assertEquals("instance2", result);
        ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
                .forClass(RunInstancesRequest.class);
        verify(ec2).runInstances(arg1.capture());
        RunInstancesRequest rir = arg1.getValue();
        assertEquals(userDataBase64, rir.getUserData());
    } finally {
        myFile.delete();
    }
}
项目:development    文件:EC2CommunicationTest.java   
@Test
public void testCreateInstanceSecurityGroups() throws Exception {
    parameters.put(PropertyHandler.SECURITY_GROUP_NAMES, new Setting(
            PropertyHandler.SECURITY_GROUP_NAMES, "security_group"));
    ec2mock.createRunInstancesResult("instance3");

    ec2mock.createDescribeImagesResult("image1");
    ec2mock.createDescribeSubnetsResult("subnet-a77430d0");
    ec2mock.createDescribeSecurityGroupResult("subnet-a77430d0",
            "security_group");
    ec2mock.createDescribeInstancesResult("instance1", "ok", "1.2.3.4");
    Image image = ec2comm.resolveAMI("image1");
    ec2comm.createInstance(image);
    String result = ph.getAWSInstanceId();
    assertEquals("instance3", result);

    ArgumentCaptor<RunInstancesRequest> arg1 = ArgumentCaptor
            .forClass(RunInstancesRequest.class);
    verify(ec2).runInstances(arg1.capture());
    RunInstancesRequest rir = arg1.getValue();
    // Network interfaces and an instance-level security groups may not be
    // specified on the same request..
    assertEquals(1, rir.getNetworkInterfaces().get(0).getGroups().size());
    /*
     * assertEquals("security_group",
     * rir.getNetworkInterfaces().get(0).getGroups().get(0));
     */
}
项目:development    文件:EC2Mockup.java   
public void createRunInstancesResult(String... instanceIds) {
    Collection<Instance> instances = new ArrayList<Instance>();
    for (int i = 0; i < instanceIds.length; i++) {
        instances.add(new Instance().withInstanceId(instanceIds[i]));
    }
    Reservation reservation = new Reservation().withInstances(instances);
    RunInstancesResult result = new RunInstancesResult()
            .withReservation(reservation);
    doReturn(result).when(ec2).runInstances(any(RunInstancesRequest.class));
}
项目:distributed-image-classification    文件:NodesMgmt.java   
public List<String> runInstances(int numberOfInstances) {
    if (numberOfInstances <= 0)
        return null;

    if (numberOfInstances > 20) {
        numberOfInstances = 20;
        logger.info("Can't run more than 20 instances.");
    }


       RunInstancesRequest request = new RunInstancesRequest(Configuration.EC2_IMAGE_ID, numberOfInstances, numberOfInstances);
       request.setInstanceType(Configuration.EC2_INSTANCE_TYPE);
       IamInstanceProfileSpecification prof = new IamInstanceProfileSpecification();
       prof.setName(Configuration.EC2_IAM_PROFILE); // security concerns
       request.setIamInstanceProfile(prof);
       request.setUserData(getStartupScript()); // base64
       request.setKeyName(Configuration.EC2_KEYPAIR_NAME);
       List<Instance> instances = _ec2.runInstances(request).getReservation().getInstances();

       List<Tag> tags = new ArrayList<Tag>();
       tags.add(new Tag(_tagKey, _defaultTag));
       tags.add(new Tag("Name", _ofType.toString().toLowerCase()));

       logger.info("Launch instances: " + instances);

       List<String> instancesID = new ArrayList<String>();
       for (Instance instance : instances) {
        instancesID.add(instance.getInstanceId());
       }

       // tag the resources
    CreateTagsRequest tagreq = new CreateTagsRequest(instancesID, tags);
       _ec2.createTags(tagreq);

       return instancesID;
}
项目:data-lifecycle-service-broker    文件:AWSHelper.java   
/**
 * 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;
}
项目:primecloud-controller    文件:ExceptionHandleAwsClientWrapper.java   
protected AutoException handleException(AmazonClientException exception, Method method, Object[] args) {
    Object request = null;
    if (method.getParameterTypes().length > 0) {
        request = args[0];
    }

    // UserDataにはパスワードが含まれているためマスクする
    if (request instanceof RunInstancesRequest) {
        ((RunInstancesRequest) request).setUserData(null);
    }

    String str = StringUtils.reflectToString(request);
    return new AutoException("EAWS-000001", exception, method.getName(), str);
}
项目:DeployMan    文件:Launcher.java   
private Instance runVirtualMachineLaunch(Formation formation) {
  Properties generalProperties = getMetaInformationProperties(formation);
  Machine machine = formation.getMachine();
  CloudInitScript initScript = getParallelCloudInitScript(machine, generalProperties);

  initScript.save();
  this.console.newLine();

  // if ( true )
  // return null;

  BlockDeviceMapping volumn = this.ec2Client.getBlockDeviceMapping("/dev/sda1", 20);
  IamInstanceProfileSpecification profil =
      this.ec2Client.getIamInstanceProfileSpecification(getUserProperty(REPO_PROFILE));

  RunInstancesRequest request =
      new RunInstancesRequest().withInstanceType(machine.getInstanceType())
          .withImageId(machine.getImageId()).withIamInstanceProfile(profil).withMinCount(1)
          .withMaxCount(1).withBlockDeviceMappings(volumn)
          .withUserData(initScript.renderAsBase64())
          .withSecurityGroupIds(machine.getSecurityGroup())
          .withKeyName(getUserProperty(EC2_INSTANCE_KEY));

  String instanceId = runInstance(request);

  this.console.writeNl("Starting...");

  waitForInstanceState(instanceId, "running");
  assigneIpIfAvailable(instanceId, machine);
  assigneName(instanceId, machine);

  return this.ec2Client.getEC2InstanceById(instanceId);
}
项目:scale.cloudpool    文件:CreateInstances.java   
@Override
public List<Instance> call() {
    RunInstancesRequest request = new RunInstancesRequest();
    request.withInstanceType(this.instanceTemplate.getInstanceType());
    request.withImageId(this.instanceTemplate.getAmiId());

    InstanceNetworkInterfaceSpecification nic = new InstanceNetworkInterfaceSpecification();
    nic.withDeviceIndex(0);
    // select a subnet at random
    nic.withSubnetId(randomSubnet());
    nic.withAssociatePublicIpAddress(this.instanceTemplate.isAssignPublicIp());
    nic.withGroups(this.instanceTemplate.getSecurityGroupIds());
    request.withNetworkInterfaces(nic);

    request.withKeyName(this.instanceTemplate.getKeyPair());
    request.withIamInstanceProfile(
            new IamInstanceProfileSpecification().withArn(this.instanceTemplate.getIamInstanceProfileARN()));
    request.withUserData(this.instanceTemplate.getEncodedUserData());
    request.withEbsOptimized(this.instanceTemplate.isEbsOptimized());
    request.withMinCount(this.count).withMaxCount(this.count);
    if (!this.instanceTemplate.getTags().isEmpty()) {
        TagSpecification tagSpecifications = new TagSpecification().withResourceType(ResourceType.Instance);
        tagSpecifications.withTags(tags());
        request.withTagSpecifications(tagSpecifications);
    }

    RunInstancesResult result = getClient().getApi().runInstances(request);
    List<Instance> launchedInstances = result.getReservation().getInstances();
    List<String> instanceIds = launchedInstances.stream().map(Instance::getInstanceId).collect(Collectors.toList());

    return awaitInstances(instanceIds);
}
项目:roboconf-platform    文件:Ec2IaasHandler.java   
@Override
public String createMachine( TargetHandlerParameters parameters ) throws TargetException {

    this.logger.fine( "Creating a new machine on AWS." );

    // For IaaS, we only expect root instance names to be passed
    if( InstanceHelpers.countInstances( parameters.getScopedInstancePath()) > 1 )
        throw new TargetException( "Only root instances can be passed in arguments." );

    String rootInstanceName = InstanceHelpers.findRootInstancePath( parameters.getScopedInstancePath());

    // Deal with the creation
    String instanceId;
    try {
        AmazonEC2 ec2 = createEc2Client( parameters.getTargetProperties());
        String userData = UserDataHelpers.writeUserDataAsString(
                parameters.getMessagingProperties(),
                parameters.getDomain(),
                parameters.getApplicationName(),
                rootInstanceName );

        RunInstancesRequest runInstancesRequest = prepareEC2RequestNode( parameters.getTargetProperties(), userData );
        RunInstancesResult runInstanceResult = ec2.runInstances( runInstancesRequest );
        instanceId = runInstanceResult.getReservation().getInstances().get( 0 ).getInstanceId();

    } catch( Exception e ) {
        this.logger.severe( "An error occurred while creating a new machine on EC2. " + e.getMessage());
        throw new TargetException( e );
    }

    return instanceId;
}
项目:roboconf-platform    文件:Ec2IaasHandler.java   
/**
 * Prepares the request.
 * @param targetProperties the target properties
 * @param userData the user data to pass
 * @return a request
 * @throws UnsupportedEncodingException
 */
private RunInstancesRequest prepareEC2RequestNode( Map<String,String> targetProperties, String userData )
throws UnsupportedEncodingException {

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest();
    String flavor = targetProperties.get(Ec2Constants.VM_INSTANCE_TYPE);
    if( Utils.isEmptyOrWhitespaces( flavor ))
        flavor = "t1.micro";

    runInstancesRequest.setInstanceType( flavor );
    runInstancesRequest.setImageId( targetProperties.get( Ec2Constants.AMI_VM_NODE ));

    runInstancesRequest.setMinCount( 1 );
    runInstancesRequest.setMaxCount( 1 );
    runInstancesRequest.setKeyName( targetProperties.get(Ec2Constants.SSH_KEY_NAME));

    String secGroup = targetProperties.get(Ec2Constants.SECURITY_GROUP_NAME);
    if( Utils.isEmptyOrWhitespaces(secGroup))
        secGroup = "default";

    runInstancesRequest.setSecurityGroups(Collections.singletonList(secGroup));

    String availabilityZone = targetProperties.get(Ec2Constants.AVAILABILITY_ZONE);
    if(! Utils.isEmptyOrWhitespaces(availabilityZone))
        runInstancesRequest.setPlacement(new Placement(availabilityZone));

    // The following part enables to transmit data to the VM.
    // When the VM is up, it will be able to read this data.
    String encodedUserData = new String( Base64.encodeBase64( userData.getBytes( StandardCharsets.UTF_8 )), "UTF-8" );
    runInstancesRequest.setUserData( encodedUserData );

    return runInstancesRequest;
}
项目:jcloudscale    文件:EC2Wrapper.java   
public void startNewHost(String size) {

    // TODO: this is more efficient the way we do it in the OS wrapper
    String imageId = lookupImageId(config.getImageName());

    if(imageId == null) 
    {
        String message = "Cannot scale up as requested since no valid " +
                        "EC2 image could be found for name " + config.getImageName(); 
           log.severe(message);
           throw new JCloudScaleException(message);
    }

    String flavId = null;
    if(size == null)
        flavId = config.getInstanceType();
    else
        flavId = size;

    String userData = config.generateHostUserData();

       BASE64Encoder enc = new BASE64Encoder();
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
        // instances in EC2 don't have a name
        .withInstanceType(flavId)
        .withImageId(imageId)
        .withMinCount(1)
        .withMaxCount(1)
        .withKeyName(config.getSshKey())
        .withUserData(enc.encode(userData.getBytes()));
        // .withUserData(userData);

    try {
        ec2Client.runInstances(runInstancesRequest);
    } catch(Exception e) {
        throw new JCloudScaleException("Unable to scale up using Amazon EC2: "+e.getMessage());
    }
}
项目:jcloudscale    文件:EC2Wrapper.java   
/**
 * Starts MQ server with specified name.
 * @param serverName The name of the server to start. Consider it to be unique.
 * @return OpenStack internal id if server was start up successfully. Otherwise, <b>null</b>.
 */
public String startNewMessageQeueHost()
{

    String mqImageId = lookupImageId(config.getMqImageName());

    if(mqImageId == null) 
    {
        String message = "Cannot scale up as requested since no valid " +
                "EC2 image could be found for name " + config.getMqImageName(); 
        log.severe(message);
        throw new JCloudScaleException(message);
    }

    String flavId = config.getMqInstanceTypeName();

    RunInstancesRequest runInstancesRequest = new RunInstancesRequest()
        // instances in EC2 don't have a name
        .withInstanceType(flavId)
        .withImageId(mqImageId)
        .withMinCount(1)
        .withMaxCount(1)
        .withKeyName(config.getSshKey());

    RunInstancesResult result = null;
    try {
        result = ec2Client.runInstances(runInstancesRequest);
    } catch(Exception e) {
        throw new JCloudScaleException("Unable to instantiate MQ image using Amazon EC2: "+e.getMessage());
    }

    String instanceId = result.getReservation().getInstances().get(0).getInstanceId();

    // TODO how do we associate the correct IP here?

    return instanceId;
}
项目:aws-sdk-java-resources    文件:SubnetImpl.java   
@Override
public List<Instance> createInstances(RunInstancesRequest request,
        ResultCapture<RunInstancesResult> extractor) {

    ActionResult result = resource.performAction("CreateInstances", request,
            extractor);

    if (result == null) return null;
    return CodecUtils.transform(result.getResources(), InstanceImpl.CODEC);
}
项目:aws-sdk-java-resources    文件:EC2Impl.java   
@Override
public List<Instance> createInstances(RunInstancesRequest request,
        ResultCapture<RunInstancesResult> extractor) {

    ActionResult result = service.performAction("CreateInstances", request,
            extractor);

    if (result == null) return null;
    return CodecUtils.transform(result.getResources(), InstanceImpl.CODEC);
}
项目:aws-sdk-java-resources    文件:EC2Impl.java   
@Override
public List<Instance> createInstances(String imageId, Integer minCount,
        Integer maxCount, ResultCapture<RunInstancesResult> extractor) {

    RunInstancesRequest request = new RunInstancesRequest()
        .withImageId(imageId)
        .withMinCount(minCount)
        .withMaxCount(maxCount);
    return createInstances(request, extractor);
}
项目:SeleniumGridScaler    文件:MockAmazonEc2Client.java   
@Override
public RunInstancesResult runInstances(RunInstancesRequest runInstancesRequest) throws AmazonServiceException, AmazonClientException {
    if(throwRunInstancesError != null) {
        AmazonClientException exceptionToThrow = throwRunInstancesError;
        if(!throwExceptionsInRunInstancesIndefinitely) {
            throwRunInstancesError = null;
        }
        throw exceptionToThrow;
    }
    this.runInstancesRequest = runInstancesRequest;
    return runInstancesResult;
}