@Override
    public void run() {
      // set up new data center
      RunInstancesRequest dataCenterRequest = createDataCenterRequest();
      RunInstancesResult runDataCenterResult = ec2.runInstances(dataCenterRequest);
      Instance dataCenterInstance = runDataCenterResult.getReservation().getInstances().get(0);
      String dataCenterId = dataCenterInstance.getInstanceId();
      createTag(ec2, dataCenterInstance);

      // wait for 1 min for the data center running
      try {
        Thread.sleep(60 * 1000);
      } catch (InterruptedException e1) {
        e1.printStackTrace();
      }

      // wait for data center ready for the web server
      String testSentence = null;
      while (testSentence == null) {
        System.out.println("RunInstance Thread: Waiting for data center ready");

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

        List<Instance> allInstances = listInstance(ec2);
        for (Instance inst : allInstances) {
          if (inst.getInstanceId().equals(dataCenterId)) {
            dataCenterInstance = inst;
            break;
          }
        }

        String randomUserUrl = "http://" + dataCenterInstance.getPublicDnsName() + "/lookup/random";
        try {
          testSentence = sendGet(randomUserUrl);
        } catch (Exception e) {
          // Do nothing
        }
      }

      String newDataCenterUrl = "http://" + dataCenterInstance.getPublicDnsName();

      // update the data center to in-service instances
      for (int i = 0; i < 3; i++) {
        if (instances[i].getUrl() == null) {
          instances[i].changeUrl(newDataCenterUrl);
          isHealthy[i] = true;
          updataHealthCount();
        }
      }
      // complete adding instance
      isAddingInstance = false;
    }
 /** Test of launchMaster method, of class HadoopCluster. */
 @Test
 public void testLaunchMaster() {
   System.out.println("launchMaster");
   try {
     RunInstancesResult result = cluster.launchMaster(TEST_SIZE);
     out.println(result.toString());
   } catch (IOException e) {
     fail("Failed to read user data.");
   }
 }
 /** Test of launchSlaves method, of class HadoopCluster. */
 @Test
 public void testLaunchSlaves() {
   System.out.println("launchSlaves");
   int howMany = 2;
   String size = "m1.large";
   try {
     RunInstancesResult result = cluster.launchSlaves(howMany, size);
     out.println(result.toString());
   } catch (IOException e) {
     fail(e.getMessage());
   } catch (MasterTimeoutException e) {
     fail("timed out waiting for master to get internal dns.");
   }
 }
Beispiel #4
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());
  }
  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);
  }
  public RunInstancesResult unmarshall(StaxUnmarshallerContext context) throws Exception {
    RunInstancesResult runInstancesResult = new RunInstancesResult();
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) targetDepth += 1;

    while (true) {
      XMLEvent xmlEvent = context.nextEvent();
      if (xmlEvent.isEndDocument()) return runInstancesResult;

      if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {

        runInstancesResult.setReservation(
            ReservationStaxUnmarshaller.getInstance().unmarshall(context));
        continue;
      } else if (xmlEvent.isEndElement()) {
        if (context.getCurrentDepth() < originalDepth) {
          return runInstancesResult;
        }
      }
    }
  }
  public RunInstancesResult unmarshall(StaxUnmarshallerContext context) throws Exception {
    RunInstancesResult runInstancesResult = new RunInstancesResult();
    int originalDepth = context.getCurrentDepth();
    int targetDepth = originalDepth + 1;

    if (context.isStartOfDocument()) targetDepth += 1;

    while (true) {
      int xmlEvent = context.nextEvent();
      if (xmlEvent == XmlPullParser.END_DOCUMENT) return runInstancesResult;

      if (xmlEvent == XmlPullParser.START_TAG) {
        if (context.testExpression("", targetDepth)) {
          runInstancesResult.setReservation(
              ReservationStaxUnmarshaller.getInstance().unmarshall(context));
          continue;
        }
      } else if (xmlEvent == XmlPullParser.END_TAG) {
        if (context.getCurrentDepth() < originalDepth) {
          return runInstancesResult;
        }
      }
    }
  }
  public static void start() {
    AWSCredentials credentials = null;
    try {
      credentials =
          new PropertiesCredentials(
              CreateInitialVMs.class.getResourceAsStream("AwsCredentials.properties"));
    } catch (IOException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }

    /**
     * *******************************************
     *
     * <p>#1 Create Amazon Client object
     *
     * <p>*******************************************
     */
    System.out.println("#1 Create Amazon Client object");
    ec2 = new AmazonEC2Client(credentials);

    try {

      /**
       * *******************************************
       *
       * <p>#6 Create an Instance
       *
       * <p>*******************************************
       */
      System.out.println("#5 Create an Instance");

      String imageId = "ami-76f0061f"; // Basic 32-bit Amazon Linux AMI
      int minInstanceCount = 1;
      int maxInstanceCount = 2; // create 2 instances
      String keyPairName = "testElastic";
      String securityGroupName = "Prachi";
      ArrayList<String> securityGroup = new ArrayList<String>();
      securityGroup.add(securityGroupName);

      RunInstancesRequest rir =
          new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount);
      rir.setKeyName(keyPairName);
      rir.setSecurityGroups(securityGroup);
      Placement p = new Placement();
      p.setAvailabilityZone("us-east-1a");
      rir.setPlacement(p);

      RunInstancesResult result = ec2.runInstances(rir);

      // get instanceId from the result
      List<Instance> resultInstance = result.getReservation().getInstances();
      String createdInstanceId = null;
      for (Instance ins : resultInstance) {
        createdInstanceId = ins.getInstanceId();

        System.out.println("State of instance " + ins.getInstanceId() + " : ");
        while (true) {
          try {
            Thread.sleep(1000);
          } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          System.out.print(ins.getState().getName() + "\n");

          ins = updatedInstance(ins);
          // if(ins.getPublicIpAddress()!= null){
          // if(ins.getState().getName().equals("running")){
          if (ins.getPublicIpAddress() != null && ins.getState().getName().equals("running")) {
            break;
          }
        }

        System.out.println("State: " + ins.getState().getName());

        System.out.println("New instance has been created: " + ins.getInstanceId());
        System.out.println("Instance Key: " + ins.getKeyName());
        System.out.println("Public DNS Name: " + ins.getPublicDnsName());
        System.out.println("Public DNS IP Address: " + ins.getPublicIpAddress());
        System.out.println("Instance ID: " + ins.getInstanceId());

        VMNode vmn = new VMNode();

        vmn.setInstanceId(ins.getInstanceId());

        /**
         * ******************************************* Allocate elastic IP addresses.
         * *******************************************
         */
        System.out.println("Public IP before association: " + ins.getPublicIpAddress());

        ins = allocateElasticIP(ins);

        vmn.setElasticIp(ins.getPublicIpAddress());

        System.out.println("Public IP after association: " + ins.getPublicIpAddress());

        /**
         * ******************************************* Create a volume
         * *******************************************
         */
        String createdVolumeId = createVolume();

        /**
         * ******************************************* Attach the volume to the instance
         * *******************************************
         */
        attachVolume(createdInstanceId, createdVolumeId);

        vmn.setVolumeId(createdVolumeId);

        /**
         * ******************************************* Detach the volume from the instance
         * *******************************************
         */
        detachVolume(createdInstanceId, createdVolumeId);

        /**
         * ********************************* Create an AMI from an instance
         * *******************************
         */
        String createdImageId = createAmi(createdInstanceId);

        vmn.setAmiId(createdImageId);
        nodes.add(vmn);

        /** ********************************* Stop the instance ******************************* */
        // stopInstance(ins.getInstanceId());
        // Diassociate Elastic IP from instance
        disassociateElasticIp(ins.getPublicIpAddress());
      }

      System.out.println("Listing Nodes: ");
      for (VMNode n : nodes) {
        System.out.println("Instance ID: " + n.getInstanceid());
        System.out.println("Elastic IP: " + n.getElasticIp());
        System.out.println("Volume ID: " + n.getVolumeId());
        System.out.println("AMI ID: " + n.getAmiId());
        System.out.println();
      }

      /**
       * *******************************************
       *
       * <p>#10 shutdown client object
       *
       * <p>*******************************************
       */
      ec2.shutdown();

    } catch (AmazonServiceException ase) {
      System.out.println("Caught Exception: " + ase.getMessage());
      System.out.println("Reponse Status Code: " + ase.getStatusCode());
      System.out.println("Error Code: " + ase.getErrorCode());
      System.out.println("Request ID: " + ase.getRequestId());
    }
  }