Exemple #1
0
  public HashMap<Region, List> listRegionInstances(AWSCredentials awsCreds) {

    AmazonEC2Client ec2Client = new AmazonEC2Client(awsCreds);
    List<Region> regions = new ArrayList();

    DescribeRegionsResult descRegionsResult = ec2Client.describeRegions();
    if (descRegionsResult != null) {
      regions = descRegionsResult.getRegions();
    }

    HashMap<Region, List> regionInstances = new HashMap();

    ExecutorService listInstanceExecutor = Executors.newFixedThreadPool(8);
    for (Region region : regions) {
      List<Instance> instances = new ArrayList();
      regionInstances.put(region, instances);

      Runnable worker = new ListInstanceRunnable(awsCreds, region, instances);
      listInstanceExecutor.execute(worker);
    }

    listInstanceExecutor.shutdown();
    try {
      listInstanceExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (InterruptedException e) {
      LOG.error("Caught InterruptedException: " + e.getMessage());
    }

    return regionInstances;
  }
  protected AmazonEC2Client getAmazonEC2Client(
      String accessKey, String secretKey, String endpoint) {

    AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);

    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(awsCredentials);

    amazonEC2Client.setEndpoint(endpoint);

    return amazonEC2Client;
  }
Exemple #3
0
 public ListInstanceRunnable(AWSCredentials awsCreds, Region region, List<Instance> instances) {
   this.region = region;
   this.instances = instances;
   ec2Client = new AmazonEC2Client(awsCreds);
   ec2Client.setEndpoint(region.getEndpoint());
   LOG.debug("Set endpoint to " + region.getEndpoint());
 }
  public synchronized AmazonEC2 client() {
    if (client != null) {
      return client;
    }

    ClientConfiguration clientConfiguration = new ClientConfiguration();
    String protocol = componentSettings.get("protocol", "http").toLowerCase();
    if ("http".equals(protocol)) {
      clientConfiguration.setProtocol(Protocol.HTTP);
    } else if ("https".equals(protocol)) {
      clientConfiguration.setProtocol(Protocol.HTTPS);
    } else {
      throw new ElasticSearchIllegalArgumentException(
          "No protocol supported [" + protocol + "], can either be [http] or [https]");
    }
    String account = componentSettings.get("access_key", settings.get("cloud.account"));
    String key = componentSettings.get("secret_key", settings.get("cloud.key"));

    if (account == null) {
      throw new ElasticSearchIllegalArgumentException("No s3 access_key defined for s3 gateway");
    }
    if (key == null) {
      throw new ElasticSearchIllegalArgumentException("No s3 secret_key defined for s3 gateway");
    }

    this.client = new AmazonEC2Client(new BasicAWSCredentials(account, key), clientConfiguration);

    if (componentSettings.get("endpoint") != null) {
      client.setEndpoint(componentSettings.get("endpoint"));
    }

    return this.client;
  }
Exemple #5
0
  public static void main(String[] args) {
    System.out.println("Hello, World!");
    AmazonEC2Client ec2 = new AmazonEC2Client();
    Region usWest2 = Region.getRegion(Regions.US_WEST_2);
    ec2.setRegion(usWest2);
    RunInstancesRequest req = new RunInstancesRequest();
    req.setImageId("ami-5189a661");
    req.setInstanceType("t2.micro");
    req.setKeyName("aws_pt-user");

    req.setMinCount(1);
    req.setMaxCount(1);

    RunInstancesResult result = ec2.runInstances(req);
    System.out.println(result.toString());
  }
 private void createTag(AmazonEC2Client ec2, Instance instance) {
   // Create Tags
   Tag tag = new Tag("Project", "2.3");
   CreateTagsRequest createTagsRequest = new CreateTagsRequest();
   createTagsRequest.withResources(instance.getInstanceId()).withTags(tag);
   ec2.createTags(createTagsRequest);
 }
Exemple #7
0
 private AmazonService() {
   AWSCredentials credentials =
       new BasicAWSCredentials(
           configuration.requiredOption("amazon.access.key"),
           configuration.requiredOption("amazon.secret.key"));
   amazonClient = new AmazonEC2Client(credentials);
   amazonClient.setEndpoint(configuration.requiredOption("amazon.endpoint"));
 }
Exemple #8
0
 public void run() {
   LOG.debug("Running describeInstances() in " + region.getRegionName());
   List<Reservation> reservations = ec2Client.describeInstances().getReservations();
   for (Reservation reservation : reservations) {
     instances.addAll(reservation.getInstances());
   }
   LOG.debug("Completed describeInstances() in " + region.getRegionName());
 }
Exemple #9
0
 public void createECAccordingAMI(String ami) {
   amazonClient.runInstances(
       new RunInstancesRequest()
           .withImageId(ami)
           .withMinCount(1)
           .withMaxCount(1)
           .withInstanceType(
               InstanceType.fromValue(configuration.requiredOption("amazon.instance.type"))));
 }
  public AmazonEC2Client getEc2Client() {
    AmazonEC2Client client =
        getAwsCredentials() == null
            ? new AmazonEC2Client()
            : new AmazonEC2Client(getAwsCredentials());

    String endpoint =
        Strings.isNullOrEmpty(this.getEc2EndPoint())
            ? System.getenv("AWS_EC2_ENDPOINT")
            : this.getEc2EndPoint();

    if (Strings.isNullOrEmpty(endpoint)) {
      endpoint = Constants.AWS_EC2_ENDPOINT;
    }
    client.setEndpoint(endpoint);
    logger.log(Level.SEVERE, "AWS EC2 Endpoint: " + endpoint);

    return client;
  }
  public Instance startInstance(AWSCredentials credentials) {
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);

    RunInstancesRequest runInstancesRequest =
        new RunInstancesRequest()
            .withImageId("")
            .withInstanceType("m1.small")
            .withMinCount(1)
            .withMaxCount(1);

    RunInstancesResult runInstancesResult = amazonEC2Client.runInstances(runInstancesRequest);

    Reservation reservation = runInstancesResult.getReservation();
    List<Instance> instances = reservation.getInstances();

    // there will be exactly one instance in this list, otherwise
    // runInstances() would have thrown an exception
    return instances.get(0);
  }
Exemple #12
0
  private static void putCache() throws CacheException {
    if (amazon == null) amazon = JCS.getInstance("Instances");
    synchronized (AmazonService.class) {
      amazon.clear();
      DescribeInstancesResult result = amazonClient.describeInstances();
      for (Reservation r : result.getReservations()) {
        for (Instance i : r.getInstances()) {
          amazon.putInGroup(i.getInstanceId(), "Instances", i);
        }
      }

      DescribeImagesRequest ir = new DescribeImagesRequest().withOwners("self");
      DescribeImagesResult images = amazonClient.describeImages(ir);
      for (Image r : images.getImages()) {
        amazon.putInGroup(r.getImageId(), "AMIs", r);
      }
      log.debug("put cache finished");
    }
  }
  public static AmazonEC2Client getEc2Client(
      String accessKeyId, String secretAccessKey, String ec2EndPoint) {
    AmazonEC2Client client;

    if (Strings.isNullOrEmpty(accessKeyId) || Strings.isNullOrEmpty(secretAccessKey)) {
      logger.log(Level.SEVERE, "No Access Key provided");
      client = new AmazonEC2Client();
    } else {
      client = new AmazonEC2Client(new BasicAWSCredentials(accessKeyId, secretAccessKey));
    }

    String endpoint =
        Strings.isNullOrEmpty(ec2EndPoint) ? System.getenv("AWS_EC2_ENDPOINT") : ec2EndPoint;

    if (Strings.isNullOrEmpty(endpoint)) {
      endpoint = Constants.AWS_EC2_ENDPOINT;
    }
    client.setEndpoint(endpoint);
    logger.log(Level.SEVERE, "AWS EC2 Endpoint: " + endpoint);

    return client;
  }
Exemple #14
0
  private AmazonEC2Client getClientForAccount(final String accountId, final Region region) {
    AWSSecurityTokenServiceClient stsClient =
        new AWSSecurityTokenServiceClient(new ProfileCredentialsProvider());

    AssumeRoleRequest assumeRequest =
        new AssumeRoleRequest()
            .withRoleArn("arn:aws:iam::ACCOUNT_ID:role/fullstop-role")
            .withDurationSeconds(3600)
            .withRoleSessionName("fullstop-role");

    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);

    BasicSessionCredentials temporaryCredentials =
        new BasicSessionCredentials(
            assumeResult.getCredentials().getAccessKeyId(),
            assumeResult.getCredentials().getSecretAccessKey(),
            assumeResult.getCredentials().getSessionToken());

    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(temporaryCredentials);
    amazonEC2Client.setRegion(region);

    return amazonEC2Client;
  }
Exemple #15
0
  @Test(expected = AmazonServiceException.class)
  public void testDeleteVPC() throws Exception {

    // Create a VPC that can be deleted through API_DeleteVPC procedure
    CreateVpcResult createVpcResult = m_ec2Client.createVpc(new CreateVpcRequest("10.0.0.0/20"));
    Vpc vpc = createVpcResult.getVpc();
    m_vpcId = vpc.getVpcId();

    long jobTimeoutMillis = 5 * 60 * 1000;

    JSONObject jo = new JSONObject();

    jo.put("projectName", "EC-EC2-" + StringConstants.PLUGIN_VERSION);
    jo.put("procedureName", "API_DeleteVPC");

    HashMap actualParameters = new HashMap();

    actualParameters.put("config", "ec2cfg");
    actualParameters.put("vpcId", m_vpcId);
    actualParameters.put("propResult", "/myJob");

    JSONArray actualParameterArray = TestUtil.getJSONActualParameterArray(actualParameters);

    jo.put("actualParameter", actualParameterArray);

    String jobId = TestUtil.callRunProcedure(jo);

    String response = TestUtil.waitForJob(jobId, jobTimeoutMillis);

    // Check job status
    assertEquals("Job completed with errors", "success", response);

    // Following method invocation must throw com.amazonaws.AmazonServiceException
    DescribeVpcsResult describeVpcsResult =
        m_ec2Client.describeVpcs(new DescribeVpcsRequest().withVpcIds(m_vpcId));
  }
Exemple #16
0
  @AfterClass
  public static void cleanup() {

    /*
       Delete the VPC created just as a precaution if testDeleteVPC test fails.
       If the test testDeleteVPC executes successfully, there will not be any VPC with vpcId.
       In that case deleteVpc() will throw an exception which is expected and hence catching it here.
    */
    try {
      m_ec2Client.deleteVpc(new DeleteVpcRequest(m_vpcId));
    } catch (com.amazonaws.AmazonServiceException e) {
      System.out.println(
          "API_DeleteVPC deleted " + m_vpcId + " successfully.No need of separate cleanup.");
    }
  }
Exemple #17
0
  @Override
  // @HystrixCommand(fallback = my coole exception)
  // command for account id and client type -> generate new credentials
  public void processEvent(final CloudTrailEvent event) {

    String parameters = event.getEventData().getRequestParameters();
    String instanceId = getFromParameters(parameters);

    AmazonEC2Client client =
        getClientForAccount(
            event.getEventData().getUserIdentity().getAccountId(),
            Region.getRegion(Regions.fromName(event.getEventData().getAwsRegion())));

    DescribeInstancesRequest request = new DescribeInstancesRequest();
    request.setInstanceIds(Collections.singleton(instanceId));

    // try
    DescribeInstancesResult result = client.describeInstances(request);
    // catch credentials are old
    // throw new my coole exception ( account id, CLIENTTYPE.EC2, exception) -> this will trigger
    // hystrix

    LOG.info("SAVING RESULT INTO MAGIC DB", result);
  }
 public Future<TerminateInstancesResult> terminateInstancesAsync(
     AmazonEC2Client client, Instance... instances) {
   List<String> ids =
       Arrays.stream(instances).map(i -> i.getInstanceId()).collect(Collectors.toList());
   TerminateInstancesRequest request = new TerminateInstancesRequest(ids);
   Future<TerminateInstancesResult> f =
       circuitBreaker.callWithCircuitBreaker(
           () -> Futures.future(() -> client.terminateInstances(request), executionContext));
   PartialFunction<Throwable, Future<TerminateInstancesResult>> recovery =
       new PFBuilder<Throwable, Future<TerminateInstancesResult>>()
           .match(
               AmazonClientException.class,
               ex -> ex.isRetryable(),
               ex -> terminateInstancesAsync(client, instances))
           .build();
   return f.recoverWith(recovery, executionContext);
 }
 private List<Instance> listInstance(AmazonEC2Client ec2) {
   List<Instance> testInstances = new ArrayList<Instance>();
   List<Reservation> reservations = ec2.describeInstances().getReservations();
   int reservationCount = reservations.size();
   for (int i = 0; i < reservationCount; i++) {
     List<Instance> instances = reservations.get(i).getInstances();
     int instanceCount = instances.size();
     // Print the instance IDs of every instance in the reservation.
     for (int j = 0; j < instanceCount; j++) {
       Instance instance = instances.get(j);
       if (instance.getState().getName().equals("running")) {
         testInstances.add(instance);
       }
     }
   }
   return testInstances;
 }
  /**
   * Perform operations necessary to complete a full integration test.
   *
   * @return: String groupId
   */
  public String integrationTest(AmazonEC2Client computeClient)
      throws AmazonServiceException, AmazonClientException {
    final String suffix = UUID.randomUUID().toString().substring(0, 8);
    final String groupName = this.getTestGroupName(suffix);
    final String groupDescription = this.getTestGoupDescription(suffix);
    CreateSecurityGroupResult createResult = null;
    final com.amazonaws.services.ec2.model.CreateSecurityGroupRequest ec2request =
        new com.amazonaws.services.ec2.model.CreateSecurityGroupRequest();
    ec2request.setGroupName(groupName);
    ec2request.setDescription(groupDescription);

    logger.info("Creating Security Group");
    createResult = computeClient.createSecurityGroup(ec2request);
    mSecurityGroups.add(groupName);
    final String groupId = createResult.getGroupId();
    assertNotNull("Expect a group id.", groupId);

    return groupId;
  }
Exemple #21
0
  public void run() {
    logger.debug("started GridManager");
    System.out.println("started GridManager");
    AmazonSQSClient sqsClient = new AmazonSQSClient(papa.getCredentials());
    AmazonEC2Client ec2Client = new AmazonEC2Client(papa.getCredentials());

    // Get current imageID from the metadata table
    String imageID = Constants.imageID; // get the default imageID from Constants
    try {
      Connection conn = PooledConnectionFactory.INSTANCE.getCumulusConnection();
      Statement stmt = conn.createStatement();
      String imageQuery = "SELECT mvalue FROM cumulus.metadata WHERE mkey='imageID';";
      ResultSet results = stmt.executeQuery(imageQuery);
      results.next(); // move the cursor into the results
      imageID = results.getString(1);
    } catch (SQLException e) {
      logger.warn(e);
    }
    if (imageID == null
        || imageID.equals("")) { // if we get an empty imageID revert to the hardcoded one
      imageID = Constants.imageID;
    }
    logger.debug(imageID);
    System.out.println(imageID);

    while (true) { // loop from startup to shutdown
      // check the number of messages in the queue.
      GetQueueAttributesRequest sqsRequest =
          new GetQueueAttributesRequest(papa.getDispatchQueue())
              .withAttributeNames("ApproximateNumberOfMessages");
      Integer sqsResult = null;
      try {
        sqsResult =
            Integer.valueOf(
                sqsClient
                    .getQueueAttributes(sqsRequest)
                    .getAttributes()
                    .get("ApproximateNumberOfMessages"));
      } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.err.println("Error getting list of instances");
        System.err.println("Caught Exception: " + e.getMessage());
        System.err.println("Reponse Status Code: " + e.getStatusCode());
        System.err.println("Error Code: " + e.getErrorCode());
        System.err.println("Request ID: " + e.getRequestId());
      } catch (AmazonClientException e) {
        logger.warn(e);
        continue; // if the error is due to being unable to connect to sqs it is likely transient,
                  // and we should keep going until SQS comes back
      } catch (Exception e) {
        // caught another exception
        System.err.println(e);
        System.err.println("Did not exit cleanly");
        // System.exit(1);
      }
      if (sqsResult == null) {
        System.err.println(
            "Couldn't get the number of items in the queue reverting to static functioning");
        logger.error(
            "Couldn't get the number of items in the queue reverting to static functioning");
        break;
      }
      System.out.println("Queue size=" + sqsResult);
      // check the number of running instances.
      DescribeInstancesRequest describeInstancesRequest = new DescribeInstancesRequest();
      // get the number of running instances with our image ID
      describeInstancesRequest.withFilters(
          new Filter("image-id").withValues(imageID),
          new Filter("instance-state-name").withValues("running"));
      logger.debug("Getting list of active cumulus drones");
      Integer numInstances = null;
      Integer numSpotRequests = null;
      Initializer.serialize("/tmp/dump.obj", papa.unitsOnServer); // TODO test this.
      // check number of open spot requests
      DescribeSpotInstanceRequestsRequest describeSpotInstancesRequest =
          new DescribeSpotInstanceRequestsRequest();
      describeSpotInstancesRequest.withFilters(new Filter("state").withValues("open"));
      try {
        // Parse returned instances
        DescribeInstancesResult describeInstancesResult =
            ec2Client.describeInstances(describeInstancesRequest);
        if (describeInstancesResult.getReservations().size() == 0) {
          numInstances = 0;
        } else {
          Integer totalInstances = 0;
          for (Reservation i : describeInstancesResult.getReservations()) {
            totalInstances += i.getInstances().size();
          }
          numInstances = totalInstances;
        }
        // Parse returned open spot requests
        DescribeSpotInstanceRequestsResult describeSpotReservationsResult =
            ec2Client.describeSpotInstanceRequests(describeSpotInstancesRequest);
        if (describeSpotReservationsResult.getSpotInstanceRequests().size() == 0) {
          numSpotRequests = 0;
        } else {
          Integer totalInstances = 0;
          for (SpotInstanceRequest i : describeSpotReservationsResult.getSpotInstanceRequests()) {
            totalInstances++;
          }
          numSpotRequests = totalInstances;
        }

        // System.out.println("num instances="+numInstances);
      } catch (AmazonServiceException e) {
        // Write out any exceptions that may have occurred.
        System.err.println("Error getting list of instances");
        System.err.println("Caught Exception: " + e.getMessage());
        System.err.println("Reponse Status Code: " + e.getStatusCode());
        System.err.println("Error Code: " + e.getErrorCode());
        System.err.println("Request ID: " + e.getRequestId());
        // System.exit(1);
      } catch (Exception e) {
        // caught another exception
        System.err.println(e);
        System.err.println("Did not exit cleanly");
        // System.exit(1);
      }
      if (numInstances == null || numSpotRequests == null) {
        logger.error(
            "Couldn't get the number of machines or requests reverting to static functioning");
        break;
      }
      System.out.println("num instances=" + (numInstances + numSpotRequests));

      // if queue is longer than the number of instances * idealMaxUnitsPerInstance
      Integer idealMaxUnitsPerInstance = Integer.valueOf(Constants.idealMaxUnitsPerInstance);
      if (sqsResult
          > (numInstances + numSpotRequests)
              * idealMaxUnitsPerInstance) { // we count pending spot instances too.
        Integer numToCreate = (sqsResult / idealMaxUnitsPerInstance) - numInstances + 1;
        // check current pricing of spot instances
        DescribeSpotPriceHistoryRequest historyRequest =
            new DescribeSpotPriceHistoryRequest()
                .withAvailabilityZone("us-east-1c")
                .withInstanceTypes(Constants.instanceType)
                .withProductDescriptions("Linux/UNIX (Amazon VPC)")
                .withStartTime(new Date(System.currentTimeMillis()));
        DescribeSpotPriceHistoryResult result = ec2Client.describeSpotPriceHistory(historyRequest);
        Double nowPrice = Double.valueOf(result.getSpotPriceHistory().get(0).getSpotPrice());
        // If spot price is < constants.spotPrice launch numToCreate*Constants.percentSpot spot
        // instances
        Integer spotToCreate = 0;
        if (nowPrice < Double.valueOf(Constants.spotPrice)) {
          Double percentSpot = Double.valueOf(Constants.percentSpot);
          spotToCreate = (int) (numToCreate * percentSpot);
          numToCreate = (int) (numToCreate * (1 - percentSpot));
        }
        try {
          System.out.println("regular instances: " + numToCreate);
          System.out.println("spot instances: " + spotToCreate);
          // Create regular and spot instances
          if (numToCreate > 0) {
            papa.createInstances(ec2Client, numToCreate, imageID);
          }
          if (spotToCreate > 0) {
            papa.createSpotInstances(ec2Client, spotToCreate, Constants.imageID); // FIXME
          }
          System.out.println("created instances");
        } catch (Exception e) {
          // Report ec2 exceptions
          logger.error(e);
          e.printStackTrace();
          continue;
        }
      }
      try {
        Thread.sleep(60000); // we wait for any new servers to start up
      } catch (InterruptedException e) {
        logger.error("Sqslistener was interrupted");
        if (papa.getShuttingDown()) {
          break;
        } else {
          continue;
        }
      }
    }
  }
 @Override
 protected void doClose() throws ElasticSearchException {
   if (client != null) {
     client.shutdown();
   }
 }
 private AmazonEC2 initClient() {
   AwsPluginExtension aws = project.getExtensions().getByType(AwsPluginExtension.class);
   AmazonEC2Client client = aws.createClient(AmazonEC2Client.class, profileName);
   client.setRegion(aws.getActiveRegion(region));
   return client;
 }
Exemple #24
0
 public void stopEC2(String... ec2id) {
   StopInstancesRequest stopInstancesRequest = new StopInstancesRequest();
   amazonClient.stopInstances(stopInstancesRequest.withInstanceIds(ec2id));
 }
Exemple #25
0
 public void startEC2(String... ec2id) {
   StartInstancesRequest startInstances = new StartInstancesRequest();
   amazonClient.startInstances(startInstances.withInstanceIds(ec2id));
 }
Exemple #26
0
 public void saveEC2ToAMI(String name, String description, String ec2id) {
   CreateImageRequest createImageRequest = new CreateImageRequest();
   amazonClient.createImage(
       createImageRequest.withInstanceId(ec2id).withDescription(description).withName(name));
 }
Exemple #27
0
 public void deleteAMI(String ami) {
   DeregisterImageRequest request = new DeregisterImageRequest(ami);
   amazonClient.deregisterImage(request);
 }
  public synchronized AmazonEC2 client() {
    if (client != null) {
      return client;
    }

    ClientConfiguration clientConfiguration = new ClientConfiguration();
    // the response metadata cache is only there for diagnostics purposes,
    // but can force objects from every response to the old generation.
    clientConfiguration.setResponseMetadataCacheSize(0);
    String protocol =
        settings
            .get(CLOUD_EC2.PROTOCOL, settings.get(CLOUD_AWS.PROTOCOL, "https"))
            .toLowerCase(Locale.ROOT);
    if ("http".equals(protocol)) {
      clientConfiguration.setProtocol(Protocol.HTTP);
    } else if ("https".equals(protocol)) {
      clientConfiguration.setProtocol(Protocol.HTTPS);
    } else {
      throw new IllegalArgumentException(
          "No protocol supported [" + protocol + "], can either be [http] or [https]");
    }
    String account = settings.get(CLOUD_EC2.KEY, settings.get(CLOUD_AWS.KEY));
    String key = settings.get(CLOUD_EC2.SECRET, settings.get(CLOUD_AWS.SECRET));

    String proxyHost = settings.get(CLOUD_EC2.PROXY_HOST, settings.get(CLOUD_AWS.PROXY_HOST));
    if (proxyHost != null) {
      String portString =
          settings.get(CLOUD_EC2.PROXY_PORT, settings.get(CLOUD_AWS.PROXY_PORT, "80"));
      Integer proxyPort;
      try {
        proxyPort = Integer.parseInt(portString, 10);
      } catch (NumberFormatException ex) {
        throw new IllegalArgumentException(
            "The configured proxy port value [" + portString + "] is invalid", ex);
      }
      clientConfiguration.withProxyHost(proxyHost).setProxyPort(proxyPort);
    }

    // #155: we might have 3rd party users using older EC2 API version
    String awsSigner = settings.get(CLOUD_EC2.SIGNER, settings.get(CLOUD_AWS.SIGNER));
    if (awsSigner != null) {
      logger.debug("using AWS API signer [{}]", awsSigner);
      try {
        AwsSigner.configureSigner(awsSigner, clientConfiguration);
      } catch (IllegalArgumentException e) {
        logger.warn(
            "wrong signer set for [{}] or [{}]: [{}]",
            CLOUD_EC2.SIGNER,
            CLOUD_AWS.SIGNER,
            awsSigner);
      }
    }

    AWSCredentialsProvider credentials;

    if (account == null && key == null) {
      credentials =
          new AWSCredentialsProviderChain(
              new EnvironmentVariableCredentialsProvider(),
              new SystemPropertiesCredentialsProvider(),
              new InstanceProfileCredentialsProvider());
    } else {
      credentials =
          new AWSCredentialsProviderChain(
              new StaticCredentialsProvider(new BasicAWSCredentials(account, key)));
    }

    this.client = new AmazonEC2Client(credentials, clientConfiguration);

    if (settings.get(CLOUD_EC2.ENDPOINT) != null) {
      String endpoint = settings.get(CLOUD_EC2.ENDPOINT);
      logger.debug("using explicit ec2 endpoint [{}]", endpoint);
      client.setEndpoint(endpoint);
    } else if (settings.get(CLOUD_AWS.REGION) != null) {
      String region = settings.get(CLOUD_AWS.REGION).toLowerCase(Locale.ROOT);
      String endpoint;
      if (region.equals("us-east-1") || region.equals("us-east")) {
        endpoint = "ec2.us-east-1.amazonaws.com";
      } else if (region.equals("us-west") || region.equals("us-west-1")) {
        endpoint = "ec2.us-west-1.amazonaws.com";
      } else if (region.equals("us-west-2")) {
        endpoint = "ec2.us-west-2.amazonaws.com";
      } else if (region.equals("ap-southeast") || region.equals("ap-southeast-1")) {
        endpoint = "ec2.ap-southeast-1.amazonaws.com";
      } else if (region.equals("ap-southeast-2")) {
        endpoint = "ec2.ap-southeast-2.amazonaws.com";
      } else if (region.equals("ap-northeast") || region.equals("ap-northeast-1")) {
        endpoint = "ec2.ap-northeast-1.amazonaws.com";
      } else if (region.equals("eu-west") || region.equals("eu-west-1")) {
        endpoint = "ec2.eu-west-1.amazonaws.com";
      } else if (region.equals("eu-central") || region.equals("eu-central-1")) {
        endpoint = "ec2.eu-central-1.amazonaws.com";
      } else if (region.equals("sa-east") || region.equals("sa-east-1")) {
        endpoint = "ec2.sa-east-1.amazonaws.com";
      } else if (region.equals("cn-north") || region.equals("cn-north-1")) {
        endpoint = "ec2.cn-north-1.amazonaws.com.cn";
      } else {
        throw new IllegalArgumentException(
            "No automatic endpoint could be derived from region [" + region + "]");
      }
      logger.debug("using ec2 region [{}], with endpoint [{}]", region, endpoint);
      client.setEndpoint(endpoint);
    }

    return this.client;
  }
Exemple #29
0
 public void terminateEC2(String... ec2id) {
   TerminateInstancesRequest terminateInstancesRequest = new TerminateInstancesRequest();
   amazonClient.terminateInstances(terminateInstancesRequest.withInstanceIds(ec2id));
 }
Exemple #30
0
 public void rebootEC2(String... ec2id) {
   amazonClient.rebootInstances(new RebootInstancesRequest().withInstanceIds(ec2id));
 }