@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)); }
@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)); }
@Override public void process(Instance instance) { ec2UserClient.amazonEC2Async().startInstancesAsync( new StartInstancesRequest().withInstanceIds(instance.getInstanceId()), new AsyncHandler<StartInstancesRequest, StartInstancesResult>() { @Override public void onError(Exception exception) { log.warn("something went wrong starting the server {}", exception.getLocalizedMessage()); } @Override public void onSuccess(StartInstancesRequest request, StartInstancesResult result) { onSuccessStart(instance); } }); }
StartInstancesResult startInstance(InstanceRequest instanceRequest, Context context) { AmazonEC2Async client = createEC2Client(); try { StartInstancesRequest req = new StartInstancesRequest(); req.setInstanceIds(Arrays.asList(instanceRequest.getInstanceId())); Future<StartInstancesResult> result = client.startInstancesAsync(req); while (!result.isDone()) { Thread.sleep(100); } return result.get(); } catch (Exception e) { throw new RuntimeException("unexpected error has occured in the start instance request.", e); } finally { client.shutdown(); } }
private void startInstance(AmazonEC2AsyncClient client, DefaultAdapterContext c) { StartInstancesRequest startRequest = new StartInstancesRequest(); startRequest.withInstanceIds(c.child.id); client.startInstancesAsync(startRequest, new AWSAsyncHandler<StartInstancesRequest, StartInstancesResult>() { @Override protected void handleError(Exception e) { c.taskManager.patchTaskToFailure(e); } @Override protected void handleSuccess(StartInstancesRequest request, StartInstancesResult result) { AWSUtils.waitForTransitionCompletion(getHost(), result.getStartingInstances(), "running", client, (is, e) -> { if (e == null) { c.taskManager.finishTask(); } else { c.taskManager.patchTaskToFailure(e); } }); } }); }
private void startInstances(AmazonEC2Client ec2Client, Exchange exchange) { Collection instanceIds; StartInstancesRequest request = new StartInstancesRequest(); 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"); } StartInstancesResult result; try { result = ec2Client.startInstances(request); } catch (AmazonServiceException ase) { LOG.trace("Start Instances command returned the error code {}", ase.getErrorCode()); throw ase; } LOG.trace("Starting instances with Ids [{}] ", Arrays.toString(instanceIds.toArray())); Message message = getMessageForResponse(exchange); message.setBody(result); }
@Override public StartInstancesResult startInstances(StartInstancesRequest startInstancesRequest) { StartInstancesResult result = new StartInstancesResult(); if (startInstancesRequest.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.Stopped); InstanceState newState = new InstanceState(); newState.setCode(16); newState.setName(InstanceStateName.Running); sc.setPreviousState(previousState); sc.setCurrentState(newState); sc.setInstanceId("test-1"); coll.add(sc); result.setStartingInstances(coll); } else { throw new AmazonServiceException("The image-id doesn't exists"); } return result; }
@Test public void testStartInstance() { final DescribeInstanceStatusRequest describeInstanceStatusRequest = new DescribeInstanceStatusRequest().withIncludeAllInstances(true).withInstanceIds(INSTANCE_ID); final DescribeInstanceStatusResult describeInstanceStatusResult = new DescribeInstanceStatusResult().withInstanceStatuses(new InstanceStatus().withInstanceState(new InstanceState().withName(InstanceStateName.Stopped))); final StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(INSTANCE_ID); final StartInstancesResult startInstancesResult = new StartInstancesResult().withStartingInstances(new InstanceStateChange().withCurrentState(new InstanceState().withName(InstanceStateName.Running))); Mockito.doReturn(describeInstanceStatusResult).when(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); Mockito.doReturn(startInstancesResult).when(amazonEC2Client).startInstances(startInstancesRequest); amazonEC2Service.startInstance(INSTANCE_ID); final InOrder inOrder = Mockito.inOrder(amazonEC2Client); inOrder.verify(amazonEC2Client).describeInstanceStatus(describeInstanceStatusRequest); inOrder.verify(amazonEC2Client).startInstances(startInstancesRequest); }
/** * 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(); }
@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)); }
@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)); }
@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)); }
/** * start the instance and on success updates the disk and compute state to reflect the detach information. */ private void startInstance(AmazonEC2AsyncClient client, DiskContext c, DeferredResult<DiskContext> dr) { StartInstancesRequest startRequest = new StartInstancesRequest(); startRequest.withInstanceIds(c.baseAdapterContext.child.id); client.startInstancesAsync(startRequest, new AWSAsyncHandler<StartInstancesRequest, StartInstancesResult>() { @Override protected void handleError(Exception e) { dr.fail(e); } @Override protected void handleSuccess(StartInstancesRequest request, StartInstancesResult result) { AWSUtils.waitForTransitionCompletion(getHost(), result.getStartingInstances(), "running", client, (is, e) -> { if (e != null) { dr.fail(e); return; } logInfo(() -> String.format( "[AWSComputeDiskDay2Service] Successfully started the " + "instance %s", result.getStartingInstances().get(0).getInstanceId())); updateComputeAndDiskState(dr, c); }); } }); }
public static InstanceStateChange startInstance(AmazonEC2 ec2, String instanceId) { StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceId); StartInstancesResult startInstancesResult = ec2.startInstances(startInstancesRequest); List<InstanceStateChange> instanceStateChange = startInstancesResult.getStartingInstances(); for (InstanceStateChange stateChange : instanceStateChange) { return stateChange; } return null; }
/** * Check the instance status and order to start it if it's stopped. * * @param instanceId Instance du start */ public void startInstance(final String instanceId) { LOG.entry(); LOG.info("Starting instance {}", instanceId); // Check the instance state final InstanceStateName instanteState = getInstanceStatus(instanceId); if (InstanceStateName.Stopped != instanteState) { final String message = "Instance " + instanceId + " is not stopped, current state: " + instanteState; LOG.error(message); final AmazonClientException exception = new AmazonClientException(message); LOG.exit(exception); throw exception; } // Start instance order final StartInstancesRequest startInstancesRequest = new StartInstancesRequest().withInstanceIds(instanceId); final StartInstancesResult startInstancesResult = amazonEC2Client.startInstances(startInstancesRequest); final List<InstanceStateChange> instanceStateChangeList = startInstancesResult.getStartingInstances(); for (final InstanceStateChange instanceStateChange : instanceStateChangeList) { LOG.info("Instance {} has changing state: {} -> {}", instanceStateChange.getInstanceId(), instanceStateChange.getPreviousState(), instanceStateChange.getCurrentState()); } LOG.info("Instance {} is starting", instanceId); LOG.exit(); }
public void startInstances(String ... instanceIds) { LOG.info("Starting up the instances [{}]", Arrays.toString(instanceIds)); List<InstanceStateChange> startingInstances = ec2_.startInstances(new StartInstancesRequest().withInstanceIds(instanceIds)).getStartingInstances(); for (InstanceStateChange state: startingInstances) { LOG.info("The state of the instance [{}] changed from [{}] to [{}]", state.getInstanceId(), state.getPreviousState().getName(), state.getCurrentState().getName()); } // waitForEc2Instance(instanceToWaitRunningState); }
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); }
@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(); }
@Override public StartInstancesResult start(ResultCapture<StartInstancesResult> extractor) { StartInstancesRequest request = new StartInstancesRequest(); return start(request, extractor); }
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); }
/** * http://shlomoswidler.com/2009/07/ec2-instance-life-cycle.html */ public void instanceStart(final String instanceId) throws Exception { final Instance instance = findInstance(instanceId); final InstanceStateName state = stateFrom(instance); logger.info("start: current state=" + state); switch (state) { case Running: return; case Pending: waitForIstanceState(instanceId, InstanceStateName.Running); return; case Stopped: break; case Stopping: waitForIstanceState(instanceId, InstanceStateName.Stopped); break; case ShuttingDown: case Terminated: throw new IllegalStateException("start: dead instance"); default: throw new IllegalStateException("start: unknown state"); } final StartInstancesRequest request = new StartInstancesRequest(); request.setInstanceIds(wrapList(instanceId)); final StartInstancesResult result = amazonClient .startInstances(request); waitForIstanceState(instanceId, InstanceStateName.Running); }
/** * 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(); }
@Override public StartInstancesResult startInstances(StartInstancesRequest startInstancesRequest) throws AmazonServiceException, AmazonClientException { throw new UnsupportedOperationException("Not supported in mock"); }
public void startInstance(String instanceId) { getEC2().startInstances( new StartInstancesRequest().withInstanceIds(instanceId)); }
public void createStartInstanceException(AmazonClientException ase) { doThrow(ase).when(ec2).startInstances(any(StartInstancesRequest.class)); }
@Override public void startInstance(String ec2InstanceId) throws InterruptedException { Instance instance = getSingleEc2InstanceById(ec2InstanceId); InstanceState state = instance.getState(); // different possible states: pending, running, shutting-down, // terminated, stopping, stopped String stateName = state.getName(); if (stateName.equalsIgnoreCase("pending")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is pending, no action was taken."); } else if (stateName.equalsIgnoreCase("running")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is running, no action was taken."); } else if (stateName.equalsIgnoreCase("shutting-down")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is shutting-down, no action was taken."); // TODO maybe we should wait for the instance to shutdown before // starting it again.. ? } else if (stateName.equalsIgnoreCase("terminated")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is terminated, no action was taken."); // TODO throw error ? } else if (stateName.equalsIgnoreCase("stopping")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is stopping, no action was taken."); // TODO maybe we should wait for the instance to stop before // starting it again.. ? what is the difference between // shutting-down and stopping ?? } else if (stateName.equalsIgnoreCase("stopped")) { log.info("startInstance: instance with id= " + ec2InstanceId + " state is stopped, the instance has been asked to start..."); StartInstancesRequest startRequest = new StartInstancesRequest() .withInstanceIds(ec2InstanceId); StartInstancesResult startResult = config.getAmazonEC2Client() .startInstances(startRequest); List<InstanceStateChange> stateChangeList = startResult .getStartingInstances(); waitForTransitionCompletion(stateChangeList, "running", ec2InstanceId); } }
public void startInstances(List<String> instanceIds) throws InterruptedException { if (instanceIds.isEmpty()) throw new Error("instanceIds must not be empty"); logger.info("start instances, instanceIds={}", instanceIds); ec2.startInstances(new StartInstancesRequest().withInstanceIds(instanceIds)); waitUntilRunning(instanceIds); }
public static void StartServer(String keys, JSONObject endpointsAPI, String serverId) { String accessKey = keys.split(";")[0]; String secretKey = keys.split(";")[1]; String regionEndpoint = (String) endpointsAPI.get("amazon-regionEndpoint"); try { // EC2 Client for given region and credentials AmazonEC2 ec2 = new AmazonEC2Client(new BasicAWSCredentials(accessKey, secretKey)); ec2.setEndpoint(regionEndpoint); StartInstancesRequest req = new StartInstancesRequest(); ArrayList<String> list = new ArrayList<String>(); list.add(serverId); req.setInstanceIds(list); System.out.println("Starting Instance " + serverId); ec2.startInstances(req); return; } catch (AmazonServiceException ase) { System.out.println("Caught an AmazonServiceException, which means your request made it " + "to AWS, but was rejected with an error response for some reason."); System.out.println("Error Message: " + ase.getMessage()); System.out.println("HTTP Status Code: " + ase.getStatusCode()); System.out.println("AWS Error Code: " + ase.getErrorCode()); System.out.println("Error Type: " + ase.getErrorType()); System.out.println("Request ID: " + ase.getRequestId()); return; } catch (AmazonClientException ace) { System.out.println("Caught an AmazonClientException, which means the client encountered " + "a serious internal problem while trying to communicate with AWS, " + "such as not being able to access the network."); System.out.println("Error Message: " + ace.getMessage()); return; } }
@Override public StartInstancesResult start(StartInstancesRequest request) { return start(request, null); }
/** * 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);
/** * 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);