@Override public void process(AmazonEC2Async amazonEC2Async, Instance instance) { amazonEC2Async.stopInstancesAsync( new StopInstancesRequest().withInstanceIds(instance.getInstanceId()), new AsyncHandler<StopInstancesRequest, StopInstancesResult>() { @Override public void onError(Exception exception) { log.warn("something went wrong stopping the server {}", exception.getLocalizedMessage()); } @Override public void onSuccess(StopInstancesRequest request, StopInstancesResult result) { onSuccessStop(instance); } }); }
@Override public void process(Instance instance) { ec2UserClient.amazonEC2Async().stopInstancesAsync( new StopInstancesRequest().withInstanceIds(instance.getInstanceId()), new AsyncHandler<StopInstancesRequest, StopInstancesResult>() { @Override public void onError(Exception exception) { log.warn("something went wrong stopping the server {}", exception.getLocalizedMessage()); } @Override public void onSuccess(StopInstancesRequest request, StopInstancesResult result) { onSuccessStop(instance); } }); }
StopInstancesResult stopInstance(InstanceRequest instanceRequest, Context context) { AmazonEC2Async client = createEC2Client(); try { StopInstancesRequest req = new StopInstancesRequest(); req.setInstanceIds(Arrays.asList(instanceRequest.getInstanceId())); Future<StopInstancesResult> result = client.stopInstancesAsync(req); while (!result.isDone()) { Thread.sleep(100); } return result.get(); } catch (Exception e) { throw new RuntimeException("unexpected error has occured in the stop instance request.", e); } finally { client.shutdown(); } }
private void stopInstances(AmazonEC2Client ec2Client, Exchange exchange) { Collection instanceIds; StopInstancesRequest request = new StopInstancesRequest(); if (ObjectHelper.isNotEmpty(exchange.getIn().getHeader(EC2Constants.INSTANCES_IDS))) { instanceIds = exchange.getIn().getHeader(EC2Constants.INSTANCES_IDS, Collection.class); request.withInstanceIds(instanceIds); } else { throw new IllegalArgumentException("Instances Ids must be specified"); } StopInstancesResult result; try { result = ec2Client.stopInstances(request); } catch (AmazonServiceException ase) { LOG.trace("Stop Instances command returned the error code {}", ase.getErrorCode()); throw ase; } LOG.trace("Stopping instances with Ids [{}] ", Arrays.toString(instanceIds.toArray())); Message message = getMessageForResponse(exchange); message.setBody(result); }
@Override public StopInstancesResult stopInstances(StopInstancesRequest stopInstancesRequest) { StopInstancesResult result = new StopInstancesResult(); if (stopInstancesRequest.getInstanceIds().get(0).equals("test-1")) { Collection<InstanceStateChange> coll = new ArrayList<InstanceStateChange>(); InstanceStateChange sc = new InstanceStateChange(); InstanceState previousState = new InstanceState(); previousState.setCode(80); previousState.setName(InstanceStateName.Running); InstanceState newState = new InstanceState(); newState.setCode(16); newState.setName(InstanceStateName.Stopped); sc.setPreviousState(previousState); sc.setCurrentState(newState); sc.setInstanceId("test-1"); coll.add(sc); result.setStoppingInstances(coll); } else { throw new AmazonServiceException("The image-id doesn't exists"); } return result; }
private List<VMInformation> stopForRegion(VMRegion region, List<String> instanceIds) { List<VMInformation> result = new ArrayList<VMInformation>(); try { asynchEc2Client.setEndpoint(region.getEndpoint()); List<VMInformation> instances = describeInstances(instanceIds.toArray(new String[instanceIds.size()])); List<String> ids = new ArrayList<String>(); for (VMInformation info : instances) { ids.add(info.getInstanceId()); } if (ids.size() > 0) { StopInstancesRequest stopInstancesRequest = new StopInstancesRequest(ids); StopInstancesResult stopResult = asynchEc2Client.stopInstances(stopInstancesRequest); List<InstanceStateChange> stoppingInstances = stopResult.getStoppingInstances(); result = new AmazonDataConverter().processStateChange(stoppingInstances); } } catch (Exception ex) { LOG.error(ex.getMessage(), ex); throw new RuntimeException(ex); } return result; }
@Test public void testStopInstanceStopping() { final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID); final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running))); final StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(INSTANCE_ID); final StopInstancesResult stopInstancesResult = new StopInstancesResult().withStoppingInstances(new InstanceStateChange().withCurrentState(new InstanceState().withName(InstanceStateName.Stopping))); Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); Mockito.doReturn(stopInstancesResult).when(amazonEC2Client).stopInstances(stopInstancesRequest); amazonEC2Service.stopInstance(INSTANCE_ID); final InOrder inOrder = Mockito.inOrder(amazonEC2Client); inOrder.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); inOrder.verify(amazonEC2Client).stopInstances(stopInstancesRequest); }
@Test public void testStopInstanceStopped() { final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID); final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Running))); final StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(INSTANCE_ID); final StopInstancesResult stopInstancesResult = new StopInstancesResult().withStoppingInstances(new InstanceStateChange().withCurrentState(new InstanceState().withName(InstanceStateName.Stopped))); Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); Mockito.doReturn(stopInstancesResult).when(amazonEC2Client).stopInstances(stopInstancesRequest); amazonEC2Service.stopInstance(INSTANCE_ID); final InOrder inOrder = Mockito.inOrder(amazonEC2Client); inOrder.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); inOrder.verify(amazonEC2Client).stopInstances(stopInstancesRequest); }
/** * Stop specified instances (power-on the instances). * * @param instanceIDs * IDs of the instances to stop * @return a list of state changes for the instances */ public static List<InstanceStateChange> stopInstances(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 stop request with args as instance IDs to stop running instances StopInstancesRequest request = new StopInstancesRequest(); request.withInstanceIds(instanceIDs); StopInstancesResult result = amazonEC2Client.stopInstances(request); return result.getStoppingInstances(); }
private void reset(AmazonEC2AsyncClient client, ResourceOperationRequest pr, DefaultAdapterContext c) { if (!c.child.powerState.equals(ComputeService.PowerState.ON)) { logWarning(() -> String.format("Cannot perform a reset on this EC2 instance. " + "The machine should be in powered on state")); c.taskManager.patchTaskToFailure(new IllegalStateException("Incorrect power state. Expected the machine " + "to be powered on ")); return; } // The stop action for reset is a force stop. So we use the withForce method to set the force parameter to TRUE // This is similar to unplugging the machine from the power circuit. // The OS and the applications are forcefully stopped. StopInstancesRequest stopRequest = new StopInstancesRequest(); stopRequest.withInstanceIds(c.child.id).withForce(Boolean.TRUE); client.stopInstancesAsync(stopRequest, new AWSAsyncHandler<StopInstancesRequest, StopInstancesResult>() { @Override protected void handleError(Exception e) { c.taskManager.patchTaskToFailure(e); } @Override protected void handleSuccess(StopInstancesRequest request, StopInstancesResult result) { AWSUtils.waitForTransitionCompletion(getHost(), result.getStoppingInstances(), "stopped", client, (is, e) -> { if (e != null) { onError(e); return; } //Instances will be started only if they're successfully stopped startInstance(client,c); }); } }); }
/** * Stop instances on the AWS endpoint for the set of instance Ids that are passed in. * * @param client * @param host * @param instanceIdsToStop * @throws Throwable */ public static void stopVMsUsingEC2Client(AmazonEC2AsyncClient client, VerificationHost host, List<String> instanceIdsToStop) throws Throwable { StopInstancesRequest stopRequest = new StopInstancesRequest(instanceIdsToStop); AsyncHandler<StopInstancesRequest, StopInstancesResult> stopHandler = new AWSStopHandlerAsync( host); client.stopInstancesAsync(stopRequest, stopHandler); waitForInstancesToBeStopped(client, host, instanceIdsToStop); }
public static InstanceStateChange stopInstance(AmazonEC2 ec2, String instanceId) { StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(instanceId); StopInstancesResult stopInstancesResult = ec2.stopInstances(stopInstancesRequest); List<InstanceStateChange> instanceStateChange = stopInstancesResult.getStoppingInstances(); for (InstanceStateChange stateChange : instanceStateChange) { return stateChange; } return null; }
/** * Check the instance status and order to stop it if it's running. * * @param instanceId instance to stop */ public void stopInstance(final String instanceId) { LOG.entry(); LOG.info("Stoping instance {}", instanceId); // Check the instance state final InstanceStateName instanteState = getInstanceStatus(instanceId); if (InstanceStateName.Running != instanteState) { final String message = "Instance " + instanceId + " is not running, current status: " + instanteState; LOG.error(message); LOG.exit(message); throw new AmazonClientException(message); } // Stop instance order final StopInstancesRequest stopInstancesRequest = new StopInstancesRequest().withInstanceIds(instanceId); final StopInstancesResult stopInstancesResult = amazonEC2Client.stopInstances(stopInstancesRequest); final List<InstanceStateChange> instanceStateChangeList = stopInstancesResult.getStoppingInstances(); for (final InstanceStateChange instanceStateChange : instanceStateChangeList) { LOG.info("Instance {} has changing state: {} -> {}", instanceStateChange.getInstanceId(), instanceStateChange.getPreviousState(), instanceStateChange.getCurrentState()); } LOG.info("Instance {} is stoping", instanceId); LOG.exit(); }
public void stop(AwsProcessClient awsProcessClient, Long instanceNo) { AwsInstance awsInstance = awsInstanceDao.read(instanceNo); String instanceId = awsInstance.getInstanceId(); // イベントログ出力 Instance instance = instanceDao.read(instanceNo); processLogger.debug(null, instance, "AwsInstanceStop", new Object[] { awsProcessClient.getPlatform().getPlatformName(), instanceId }); // インスタンスの停止 StopInstancesRequest request = new StopInstancesRequest(); request.withInstanceIds(instanceId); StopInstancesResult result = awsProcessClient.getEc2Client().stopInstances(request); List<InstanceStateChange> stoppingInstances = result.getStoppingInstances(); // API実行結果チェック if (stoppingInstances.size() == 0) { // インスタンス停止失敗時 throw new AutoException("EPROCESS-000128", instanceId); } else if (stoppingInstances.size() > 1) { // 複数のインスタンスが停止した場合 AutoException exception = new AutoException("EPROCESS-000130", instanceId); exception.addDetailInfo("result=" + stoppingInstances); throw exception; } // ログ出力 if (log.isInfoEnabled()) { log.info(MessageUtils.getMessage("IPROCESS-100113", instanceId)); } // データベース更新 awsInstance.setStatus(stoppingInstances.get(0).getCurrentState().getName()); awsInstanceDao.update(awsInstance); }
@Override public StopInstancesResult stop(StopInstancesRequest request, ResultCapture<StopInstancesResult> extractor) { ActionResult result = resource.performAction("Stop", request, extractor); if (result == null) return null; return (StopInstancesResult) result.getData(); }
@Override public StopInstancesResult stop(ResultCapture<StopInstancesResult> extractor ) { StopInstancesRequest request = new StopInstancesRequest(); return stop(request, extractor); }
/** * http://shlomoswidler.com/2009/07/ec2-instance-life-cycle.html */ public void instanceStop(final String instanceId) throws Exception { final Instance instance = findInstance(instanceId); final InstanceStateName state = stateFrom(instance); logger.info("stop: current state=" + state); switch (state) { case Pending: waitForIstanceState(instanceId, InstanceStateName.Running); case Running: break; case Stopping: waitForIstanceState(instanceId, InstanceStateName.Stopped); case Stopped: case Terminated: case ShuttingDown: return; default: throw new IllegalStateException("start: unknown state"); } final StopInstancesRequest request = new StopInstancesRequest(); request.setInstanceIds(wrapList(instanceId)); final StopInstancesResult result = amazonClient.stopInstances(request); waitForIstanceState(instanceId, InstanceStateName.Stopped); }
/** * Stop instances. * * @param instanceIds * instances' IDs * @return list of instances change */ protected final List<InstanceStateChange> stopInstances( final Collection<String> instanceIds) { log.info("Stop instances:" + toString(instanceIds)); StopInstancesRequest request = new StopInstancesRequest(); request.setInstanceIds(instanceIds); StopInstancesResult result = amazonEC2Client.stopInstances(request); return result.getStoppingInstances(); }
@Override public StopInstancesResult stopInstances(StopInstancesRequest stopInstancesRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
@Override public void onSuccess(StopInstancesRequest request, StopInstancesResult result) { this.host.log("Successfully stopped instances from the AWS endpoint %s", result.getStoppingInstances().toString()); }
@Override public void stop(final String... instanceIds) { if (instanceIds != null && instanceIds.length > 0) { final long startTime = System.nanoTime(); StopInstancesResult stopInstancesResult = ec2_.stopInstances(new StopInstancesRequest().withInstanceIds(instanceIds)); List<Callable<org.excalibur.service.aws.ConfigurationService.InstanceStateType>> tasks = newArrayList(); for (final InstanceStateChange state: stopInstancesResult.getStoppingInstances()) { tasks.add(new Callable<org.excalibur.service.aws.ConfigurationService.InstanceStateType>() { BackoffLimitedRetryHandler backoffLimitedRetryHandler = new BackoffLimitedRetryHandler(); @Override public org.excalibur.service.aws.ConfigurationService.InstanceStateType call() throws Exception { InstanceState currentState = state.getCurrentState(); org.excalibur.service.aws.ConfigurationService.InstanceStateType finalState = org.excalibur.service.aws.ConfigurationService.InstanceStateType.STOPPED; int failureCount = 0; do { if ("stopping".equalsIgnoreCase(currentState.getName())) { backoffLimitedRetryHandler.imposeBackoffExponentialDelay(1000, 2, failureCount++, 1000, String.format("waiting instance%:s", state.getInstanceId())); currentState = ec2_ .describeInstanceStatus(new DescribeInstanceStatusRequest().withInstanceIds(state.getInstanceId())) .getInstanceStatuses().get(0).getInstanceState(); } } while (!finalState.getValue().equalsIgnoreCase(currentState.getName())); System.out.println(state.getInstanceId() + "=" + (System.nanoTime() - startTime)); return finalState; } }); } invokeAll(tasks); long end = System.nanoTime() - startTime; System.out.println(end); } }
@Override public StopInstancesResult stop(StopInstancesRequest request) { return stop(request, null); }
@Override public StopInstancesResult stop() { return stop((ResultCapture<StopInstancesResult>)null); }
/** * Performs the <code>Stop</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 StopInstancesRequest */ StopInstancesResult stop(StopInstancesRequest request);
/** * Performs the <code>Stop</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 StopInstancesRequest */ StopInstancesResult stop(StopInstancesRequest request, ResultCapture<StopInstancesResult> extractor);
/** * The convenient method form for the <code>Stop</code> action. * * @see #stop(StopInstancesRequest) */ StopInstancesResult stop();
/** * The convenient method form for the <code>Stop</code> action. * * @see #stop(StopInstancesRequest, ResultCapture) */ StopInstancesResult stop(ResultCapture<StopInstancesResult> extractor);