com.amazonaws.services.ec2.model.StartInstancesRequest Java Examples

The following examples show how to use com.amazonaws.services.ec2.model.StartInstancesRequest. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AWSControllerIT.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void activateInstance() throws Exception {

    parameters.put(PropertyHandler.FLOW_STATE,
            new Setting(PropertyHandler.FLOW_STATE,
                    FlowState.ACTIVATION_REQUESTED.name()));
    parameters.put(PropertyHandler.OPERATION, new Setting(
            PropertyHandler.OPERATION, Operation.EC2_ACTIVATION.name()));

    ec2mock.createDescribeInstancesResult("instance1", "running", "1.2.3.4");
    ec2mock.createDescribeInstanceStatusResult("instance1", "ok", "ok",
            "ok");
    ec2mock.createDescribeImagesResult(IMAGE_ID);
    ec2mock.createRunInstancesResult(INSTANCE_ID);

    runUntilReady();

    verify(ec2).startInstances(any(StartInstancesRequest.class));

}
 
Example #2
Source File: AWSControllerIT.java    From development with Apache License 2.0 6 votes vote down vote up
@Test
public void executeServiceOperation_Start() throws Exception {

    parameters.put(PropertyHandler.FLOW_STATE, new Setting(
            PropertyHandler.FLOW_STATE, FlowState.START_REQUESTED.name()));
    parameters.put(PropertyHandler.OPERATION, new Setting(
            PropertyHandler.OPERATION, Operation.EC2_OPERATION.name()));

    ec2mock.createDescribeInstancesResult("instance1", "running", "1.2.3.4");
    ec2mock.createDescribeInstanceStatusResult("instance1", "ok", "ok",
            "ok");
    ec2mock.createDescribeImagesResult(IMAGE_ID);
    ec2mock.createRunInstancesResult(INSTANCE_ID);

    runUntilReady();

    verify(ec2).startInstances(any(StartInstancesRequest.class));

}
 
Example #3
Source File: StartInstancesExample.java    From aws-mock with MIT License 6 votes vote down vote up
/**
 * Start specified instances (power-on the instances).
 *
 * @param instanceIDs
 *            IDs of the instances start
 * @return a list of state changes for the instances
 */
public static List<InstanceStateChange> startInstances(final List<String> instanceIDs) {
    // 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);

    // send the start request with args as instance IDs to start existing instances
    StartInstancesRequest request = new StartInstancesRequest();
    request.withInstanceIds(instanceIDs);
    StartInstancesResult result = amazonEC2Client.startInstances(request);

    return result.getStartingInstances();
}
 
Example #4
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@Test
public void testStartPollingWithSuccess() {
    String status = "Running";
    InstanceStatus stopped1 = AwsInstanceStatusMapper.getInstanceStatusByAwsStatus(status);
    int lastStatusCode = 16;
    //given
    mockDescribeInstances(POLLING_LIMIT - 2, status, lastStatusCode);
    ArgumentCaptor<StartInstancesRequest> captorStart = ArgumentCaptor.forClass(StartInstancesRequest.class);

    //then
    List<CloudVmInstanceStatus> result = underTest.start(authenticatedContext, List.of(), inputList);

    //then
    verify(amazonEC2Client, times(1)).startInstances(captorStart.capture());
    Assertions.assertTrue(captorStart.getValue().getInstanceIds().size() == inputList.size());
    Assert.assertThat(result, hasItem(allOf(hasProperty("status", is(stopped1)))));
}
 
Example #5
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void awsClientSetup() {
    when(awsClient.getAmazonEC2Client(any(AwsSessionCredentialProvider.class))).thenReturn(amazonEC2Client);
    when(awsClient.getAmazonEC2Client(any(BasicAWSCredentials.class))).thenReturn(amazonEC2Client);
    when(awsClient.getInstanceProfileProvider()).thenReturn(instanceProfileCredentialsProvider);

    CloudContext context = new CloudContext(1L, "context", "AWS", "AWS",
            Location.location(Region.region("region")), "user", "account");
    CloudCredential credential = new CloudCredential("id", "alma",
            Map.of("accessKey", "ac", "secretKey", "secret"), false);
    authenticatedContext = awsAuthenticator.authenticate(context, credential);

    StopInstancesResult stopInstancesResult = new StopInstancesResult();
    StartInstancesResult startInstanceResult = new StartInstancesResult();
    when(amazonEC2Client.stopInstances(any(StopInstancesRequest.class))).thenReturn(stopInstancesResult);
    when(amazonEC2Client.startInstances(any(StartInstancesRequest.class))).thenReturn(startInstanceResult);

    inputList = getCloudInstances();
}
 
Example #6
Source File: BaseTest.java    From aws-mock with MIT License 5 votes vote down vote up
/**
 * Start instances.
 *
 * @param instanceIds
 *            instances' IDs
 * @return list of instances change
 */
protected final List<InstanceStateChange> startInstances(
        final Collection<String> instanceIds) {
    log.info("Start instances:" + toString(instanceIds));

    StartInstancesRequest request = new StartInstancesRequest();
    request.setInstanceIds(instanceIds);
    StartInstancesResult result = amazonEC2Client.startInstances(request);
    return result.getStartingInstances();
}
 
Example #7
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartPollingWithFail() {
    mockDescribeInstances(POLLING_LIMIT + 2, "Running", 16);
    ArgumentCaptor<StartInstancesRequest> captor = ArgumentCaptor.forClass(StartInstancesRequest.class);

    Assertions.assertThrows(PollerStoppedException.class, () -> underTest.start(authenticatedContext, List.of(), inputList));
    verify(amazonEC2Client, times(1)).startInstances(captor.capture());
    Assertions.assertTrue(captor.getValue().getInstanceIds().size() == inputList.size());
}
 
Example #8
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartEveryInstancesStartedAlready() {
    mockDescribeInstancesAllIsRunning(POLLING_LIMIT - 2);
    List<CloudVmInstanceStatus> result = underTest.start(authenticatedContext, List.of(), inputList);
    verify(amazonEC2Client, never()).startInstances(any(StartInstancesRequest.class));
    Assert.assertThat(result, hasItem(allOf(hasProperty("status", is(InstanceStatus.STARTED)))));
}
 
Example #9
Source File: AwsInstanceConnectorTest.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartSomeInstancesStarted() {
    mockDescribeInstancesOneIsRunningLastSuccess(POLLING_LIMIT - 2);
    ArgumentCaptor<StartInstancesRequest> captor = ArgumentCaptor.forClass(StartInstancesRequest.class);

    List<CloudVmInstanceStatus> result = underTest.start(authenticatedContext, List.of(), inputList);
    verify(amazonEC2Client, times(1)).startInstances(captor.capture());
    Assertions.assertTrue(captor.getValue().getInstanceIds().size() < inputList.size());
    Assert.assertThat(result, hasItem(allOf(hasProperty("status", is(InstanceStatus.STARTED)))));
}
 
Example #10
Source File: AwsInstanceConnector.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
@Retryable(
        value = SdkClientException.class,
        maxAttemptsExpression = "#{${cb.vm.retry.attempt:15}}",
        backoff = @Backoff(delayExpression = "#{${cb.vm.retry.backoff.delay:1000}}",
                multiplierExpression = "#{${cb.vm.retry.backoff.multiplier:2}}",
                maxDelayExpression = "#{${cb.vm.retry.backoff.maxdelay:10000}}")
)
@Override
public List<CloudVmInstanceStatus> start(AuthenticatedContext ac, List<CloudResource> resources, List<CloudInstance> vms) {
    return setCloudVmInstanceStatuses(ac, vms, "Running",
            (ec2Client, instances) -> ec2Client.startInstances(new StartInstancesRequest().withInstanceIds(instances)),
            "Failed to send start request to AWS: ");
}
 
Example #11
Source File: Ec2Util.java    From s3-bucket-loader with Apache License 2.0 5 votes vote down vote up
public void startInstance(AmazonEC2Client ec2Client, String instanceId) throws Exception {
	StartInstancesRequest startReq = new StartInstancesRequest();
	List<String> instanceIds = new ArrayList<String>();
	instanceIds.add(instanceId);
	startReq.setInstanceIds(instanceIds);
	logger.debug("Starting EC2 instance...." + Arrays.toString(instanceIds.toArray(new String[]{})));
	ec2Client.startInstances(startReq);
}
 
Example #12
Source File: InstanceImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public StartInstancesResult start(ResultCapture<StartInstancesResult>
        extractor) {

    StartInstancesRequest request = new StartInstancesRequest();
    return start(request, extractor);
}
 
Example #13
Source File: InstanceImpl.java    From aws-sdk-java-resources with Apache License 2.0 5 votes vote down vote up
@Override
public StartInstancesResult start(StartInstancesRequest request,
        ResultCapture<StartInstancesResult> extractor) {

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

    if (result == null) return null;
    return (StartInstancesResult) result.getData();
}
 
Example #14
Source File: AwsInstanceProcess.java    From primecloud-controller with GNU General Public License v2.0 5 votes vote down vote up
public void start(AwsProcessClient awsProcessClient, Long instanceNo) {
    AwsInstance awsInstance = awsInstanceDao.read(instanceNo);
    String instanceId = awsInstance.getInstanceId();

    // イベントログ出力
    Instance instance = instanceDao.read(instanceNo);
    processLogger.debug(null, instance, "AwsInstanceStart",
            new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId });

    // インスタンスの起動
    StartInstancesRequest request = new StartInstancesRequest();
    request.withInstanceIds(instanceId);
    StartInstancesResult result = awsProcessClient.getEc2Client().startInstances(request);
    List<InstanceStateChange> startingInstances = result.getStartingInstances();

    // API実行結果チェック
    if (startingInstances.size() == 0) {
        // インスタンス起動失敗時
        throw new AutoException("EPROCESS-000125", instanceId);

    } else if (startingInstances.size() > 1) {
        // 複数のインスタンスが起動した場合
        AutoException exception = new AutoException("EPROCESS-000127", instanceId);
        exception.addDetailInfo("result=" + startingInstances);
        throw exception;
    }

    // ログ出力
    if (log.isInfoEnabled()) {
        log.info(MessageUtils.getMessage("IPROCESS-100111", instanceId));
    }

    // データベース更新
    awsInstance.setStatus(startingInstances.get(0).getCurrentState().getName());
    awsInstanceDao.update(awsInstance);
}
 
Example #15
Source File: EC2CommunicationTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void testStartInstance() throws Exception {
    ec2comm.startInstance("instance1");
    ArgumentCaptor<StartInstancesRequest> arg1 = ArgumentCaptor
            .forClass(StartInstancesRequest.class);
    verify(ec2).startInstances(arg1.capture());
    StartInstancesRequest val = arg1.getValue();

    assertEquals(1, val.getInstanceIds().size());
    assertEquals("instance1", val.getInstanceIds().get(0));
}
 
Example #16
Source File: EC2ProcessorTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void process_START_REQUESTED() throws Exception {
    // given
    ph.setOperation(Operation.EC2_OPERATION);
    ph.setState(FlowState.START_REQUESTED);

    // when
    InstanceStatus result = ec2proc.process();

    // then
    assertFalse(result.isReady());
    assertEquals(FlowState.STARTING, ph.getState());
    verify(ec2).startInstances(any(StartInstancesRequest.class));
}
 
Example #17
Source File: EC2ProcessorTest.java    From development with Apache License 2.0 5 votes vote down vote up
@Test
public void process_ACTIVATION_REQUESTED() throws Exception {
    // given
    ph.setOperation(Operation.EC2_ACTIVATION);
    ph.setState(FlowState.ACTIVATION_REQUESTED);

    // when
    InstanceStatus result = ec2proc.process();

    // then
    assertFalse(result.isReady());
    assertEquals(FlowState.STARTING, ph.getState());
    verify(ec2).startInstances(any(StartInstancesRequest.class));
}
 
Example #18
Source File: InstanceImpl.java    From aws-sdk-java-resources with Apache License 2.0 4 votes vote down vote up
@Override
public StartInstancesResult start(StartInstancesRequest request) {
    return start(request, null);
}
 
Example #19
Source File: EC2Mockup.java    From development with Apache License 2.0 4 votes vote down vote up
public void createStartInstanceException(AmazonClientException ase) {
    doThrow(ase).when(ec2).startInstances(any(StartInstancesRequest.class));
}
 
Example #20
Source File: EC2Application.java    From tutorials with MIT License 4 votes vote down vote up
public static void main(String[] args) {
   
    // Set up the client
    AmazonEC2 ec2Client = AmazonEC2ClientBuilder.standard()
        .withCredentials(new AWSStaticCredentialsProvider(credentials))
        .withRegion(Regions.US_EAST_1)
        .build();

    // Create a security group
    CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest().withGroupName("BaeldungSecurityGroup")
        .withDescription("Baeldung Security Group");
    ec2Client.createSecurityGroup(createSecurityGroupRequest);

    // Allow HTTP and SSH traffic
    IpRange ipRange1 = new IpRange().withCidrIp("0.0.0.0/0");

    IpPermission ipPermission1 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
        .withIpProtocol("tcp")
        .withFromPort(80)
        .withToPort(80);

    IpPermission ipPermission2 = new IpPermission().withIpv4Ranges(Arrays.asList(new IpRange[] { ipRange1 }))
        .withIpProtocol("tcp")
        .withFromPort(22)
        .withToPort(22);

    AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest()
        .withGroupName("BaeldungSecurityGroup")
        .withIpPermissions(ipPermission1, ipPermission2);

    ec2Client.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest);

    // Create KeyPair
    CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest()
        .withKeyName("baeldung-key-pair");
    CreateKeyPairResult createKeyPairResult = ec2Client.createKeyPair(createKeyPairRequest);
    String privateKey = createKeyPairResult
        .getKeyPair()
        .getKeyMaterial(); // make sure you keep it, the private key, Amazon doesn't store the private key

    // See what key-pairs you've got
    DescribeKeyPairsRequest describeKeyPairsRequest = new DescribeKeyPairsRequest();
    DescribeKeyPairsResult describeKeyPairsResult = ec2Client.describeKeyPairs(describeKeyPairsRequest);

    // Launch an Amazon Instance
    RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withImageId("ami-97785bed") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AMIs.html | https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/usingsharedamis-finding.html
        .withInstanceType("t2.micro") // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html
        .withMinCount(1)
        .withMaxCount(1)
        .withKeyName("baeldung-key-pair") // optional - if not present, can't connect to instance
        .withSecurityGroups("BaeldungSecurityGroup");

    String yourInstanceId = ec2Client.runInstances(runInstancesRequest).getReservation().getInstances().get(0).getInstanceId();

    // Start an Instance
    StartInstancesRequest startInstancesRequest = new StartInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.startInstances(startInstancesRequest);

    // Monitor Instances
    MonitorInstancesRequest monitorInstancesRequest = new MonitorInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.monitorInstances(monitorInstancesRequest);

    UnmonitorInstancesRequest unmonitorInstancesRequest = new UnmonitorInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.unmonitorInstances(unmonitorInstancesRequest);

    // Reboot an Instance

    RebootInstancesRequest rebootInstancesRequest = new RebootInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.rebootInstances(rebootInstancesRequest);

    // Stop an Instance
    StopInstancesRequest stopInstancesRequest = new StopInstancesRequest()
        .withInstanceIds(yourInstanceId);

    ec2Client.stopInstances(stopInstancesRequest)
        .getStoppingInstances()
        .get(0)
        .getPreviousState()
        .getName();

    // Describe an Instance
    DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
    DescribeInstancesResult response = ec2Client.describeInstances(describeInstancesRequest);
    System.out.println(response.getReservations()
        .get(0)
        .getInstances()
        .get(0)
        .getKernelId());
}
 
Example #21
Source File: EC2Communication.java    From development with Apache License 2.0 4 votes vote down vote up
public void startInstance(String instanceId) {
    getEC2().startInstances(
            new StartInstancesRequest().withInstanceIds(instanceId));
}
 
Example #22
Source File: Instance.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>Start</code> action and use a ResultCapture to
 * retrieve the low-level client response.
 *
 * <p>
 * The following request parameters will be populated from the data of this
 * <code>Instance</code> resource, and any conflicting parameter value set
 * in the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>InstanceIds.0</code></b>
 *         - mapped from the <code>Id</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return The response of the low-level client operation associated with
 *         this resource action.
 * @see StartInstancesRequest
 */
StartInstancesResult start(StartInstancesRequest request,
        ResultCapture<StartInstancesResult> extractor);
 
Example #23
Source File: Instance.java    From aws-sdk-java-resources with Apache License 2.0 2 votes vote down vote up
/**
 * Performs the <code>Start</code> action.
 *
 * <p>
 * The following request parameters will be populated from the data of this
 * <code>Instance</code> resource, and any conflicting parameter value set
 * in the request will be overridden:
 * <ul>
 *   <li>
 *     <b><code>InstanceIds.0</code></b>
 *         - mapped from the <code>Id</code> identifier.
 *   </li>
 * </ul>
 *
 * <p>
 *
 * @return The response of the low-level client operation associated with
 *         this resource action.
 * @see StartInstancesRequest
 */
StartInstancesResult start(StartInstancesRequest request);