List of usage examples for com.amazonaws.services.cloudwatch.model Datapoint getAverage
public Double getAverage()
The average of the metric values that correspond to the data point.
From source file:HW1.java
License:Open Source License
public static void main(String[] args) throws Exception { AWSCredentials credentials = new PropertiesCredentials( HW1.class.getResourceAsStream("AwsCredentials.properties")); /********************************************* * /*from w w w . j a v a 2s . c o m*/ * #1 Create Amazon Client object * *********************************************/ System.out.println("#1 Create Amazon Client object"); ec2 = new AmazonEC2Client(credentials); ec2.setEndpoint("https://us-east-1.ec2.amazonaws.com"); System.out.println("Please enter required group name and key name... (consider them to be the same)"); Scanner scan = new Scanner(System.in); final String keyGroupName = scan.nextLine(); /* create security group */ CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest(); createSecurityGroupRequest.withGroupName(keyGroupName).withDescription("My Java Security Group"); CreateSecurityGroupResult createSecurityGroupResult = ec2.createSecurityGroup(createSecurityGroupRequest); /* set ip settings */ IpPermission ipPermission = new IpPermission(); /* authorize tcp, ssh 22 */ ipPermission.withIpRanges("0.0.0.0/0").withIpProtocol("tcp").withFromPort(22) /* authorize http 80 */ .withToPort(80); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest(); authorizeSecurityGroupIngressRequest.withGroupName(keyGroupName).withIpPermissions(ipPermission); ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); /* create key pair */ CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest(); createKeyPairRequest.withKeyName(keyGroupName); CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest); KeyPair keyPair = new KeyPair(); keyPair = createKeyPairResult.getKeyPair(); String privateKey = keyPair.getKeyMaterial(); PrintWriter file = new PrintWriter("/Users/will/.ssh/" + keyGroupName + ".pem"); file.print(privateKey); file.close(); Runtime.getRuntime().exec("chmod 400 /Users/will/.ssh/" + keyGroupName + ".pem"); try { /********************************************* * * #2 Create two Instances * *********************************************/ System.out.println(); System.out.println("#2 Create two new Instances"); int ready_num = 0; String insDNS1 = new String(); String insDNS2 = new String(); String insId1 = new String(); String insId2 = new String(); String insZone1 = new String(); String insZone2 = new String(); String imageId = "ami-76f0061f"; //Basic 32-bit Amazon Linux AMI int minInstanceCount = 2; // create 2 instance int maxInstanceCount = 2; /* create instances */ RunInstancesRequest rir = new RunInstancesRequest(imageId, minInstanceCount, maxInstanceCount); rir.withKeyName(keyGroupName).withSecurityGroups(keyGroupName); ec2.runInstances(rir); /* waiting for instance to start */ System.out.println("Created instance, wait for pending..."); DescribeInstancesResult describeInstancesRequest; List<Reservation> reservations; List<Instance> allInstances = new ArrayList<Instance>(); while (ready_num < 2) { describeInstancesRequest = ec2.describeInstances(); reservations = describeInstancesRequest.getReservations(); for (Reservation reservation : reservations) { for (Instance ins : reservation.getInstances()) { if (ins.getState().getName().compareTo("running") == 0 && ins.getPublicIpAddress() != null) { if (allInstances.size() == 0 || (allInstances.size() > 0 && allInstances.get(0).getInstanceId().compareTo(ins.getInstanceId()) != 0)) { ready_num++; allInstances.add(ins); } } } } } System.out.println("You have " + allInstances.size() + " Amazon EC2 instance(s)."); insId1 = allInstances.get(0).getInstanceId(); insId2 = allInstances.get(1).getInstanceId(); insDNS1 = allInstances.get(0).getPublicIpAddress(); insDNS2 = allInstances.get(1).getPublicIpAddress(); insZone1 = allInstances.get(0).getPlacement().getAvailabilityZone(); insZone2 = allInstances.get(1).getPlacement().getAvailabilityZone(); for (Instance ins : allInstances) { System.out.println("New instance has been created: " + ins.getInstanceId()); } System.out.println("Both instances are running now:"); System.out.println("Instance id1: " + insId1); System.out.println("IP: " + insDNS1); System.out.println("Zone: " + insZone1); System.out.println("Instance id1: " + insId2); System.out.println("IP: " + insDNS2); System.out.println("Zone: " + insZone2); System.out.println(); /********************************************* * #3 Check OR Create two volumes *********************************************/ System.out.println(); System.out.println("#3 Create volumes"); String volume_name1 = createVolume(insZone1, null); String volume_name2 = createVolume(insZone2, null); /********************************************* * #4 Attach the volume to the instance *********************************************/ System.out.println(); System.out.println("#4 Attach the volume to the instance"); System.out.println("Wait for volumes to be available..."); Thread.sleep(20000); /* attach instances to existing volume */ attachVolume(insId1, volume_name1); attachVolume(insId2, volume_name2); /************************************************ * #5 S3 bucket and object ***************************************************/ System.out.println(); System.out.println("#5 S3 bucket and object"); s3 = new AmazonS3Client(credentials); /* create bucket */ String bucketName = "cloud-hw1-bucket"; s3.createBucket(bucketName); /* set key */ String key = "object-hw1.txt"; /* set value */ File new_file = File.createTempFile("temp", ".txt"); new_file.deleteOnExit(); Writer writer = new OutputStreamWriter(new FileOutputStream(new_file)); writer.write("This is the file stored on the S3 storage on the first day!!!."); writer.close(); /* put object - bucket, key, value(file) */ s3.putObject(new PutObjectRequest(bucketName, key, new_file)); System.out.println("Successfully put file temp.txt to S3, we will read it tomorrow..."); System.out.println(); /*********************************** * #3 Monitoring (CloudWatch) *********************************/ System.out.println(); System.out.println("#6 set up cloudwatch"); try { /* create CloudWatch client */ AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(credentials); /* create request message1 */ GetMetricStatisticsRequest statRequest1 = new GetMetricStatisticsRequest(); GetMetricStatisticsRequest statRequest2 = new GetMetricStatisticsRequest(); /* set up request message */ statRequest1.setNamespace("AWS/EC2"); //namespace statRequest2.setNamespace("AWS/EC2"); //namespace statRequest1.setPeriod(60); //period of data statRequest2.setPeriod(60); //period of data ArrayList<String> stats = new ArrayList<String>(); /* Use one of these strings: Average, Maximum, Minimum, SampleCount, Sum */ stats.add("Average"); stats.add("Sum"); statRequest1.setStatistics(stats); statRequest2.setStatistics(stats); /* Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations */ statRequest1.setMetricName("CPUUtilization"); statRequest2.setMetricName("CPUUtilization"); /* set time */ GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // 1 second ago Date endTime = calendar.getTime(); calendar.add(GregorianCalendar.MINUTE, -10); // 10 minutes ago Date startTime = calendar.getTime(); statRequest1.setStartTime(startTime); statRequest1.setEndTime(endTime); statRequest2.setStartTime(startTime); statRequest2.setEndTime(endTime); /* specify an instance */ ArrayList<Dimension> dimensions1 = new ArrayList<Dimension>(); dimensions1.add(new Dimension().withName("InstanceId").withValue(insId1)); ArrayList<Dimension> dimensions2 = new ArrayList<Dimension>(); dimensions2.add(new Dimension().withName("InstanceId").withValue(insId2)); statRequest1.setDimensions(dimensions1); statRequest2.setDimensions(dimensions2); System.out.println("Set up cloud watch for instance: " + insId1 + " and instance: " + insId2); /* !!!!!!!!!!!!here set for 10 loops for now */ /* get statistics */ for (int i = 0; i < 10; i++) { GetMetricStatisticsResult statResult1 = cloudWatch.getMetricStatistics(statRequest1); GetMetricStatisticsResult statResult2 = cloudWatch.getMetricStatistics(statRequest2); /* display */ System.out.println("Instance 1: " + statResult1.toString()); List<Datapoint> dataList = statResult1.getDatapoints(); Double averageCPU = null; Date timeStamp = null; for (Datapoint d : dataList) { averageCPU = d.getAverage(); timeStamp = d.getTimestamp(); System.out .println("Instance 1 average CPU utlilization for last 10 minutes: " + averageCPU); System.out.println("Instance 1 total CPU utlilization for last 10 minutes: " + d.getSum()); } System.out.println(); System.out.println("Instance 2: " + statResult1.toString()); dataList = statResult2.getDatapoints(); for (Datapoint d : dataList) { averageCPU = d.getAverage(); timeStamp = d.getTimestamp(); System.out .println("Instance 2 average CPU utlilization for last 10 minutes: " + averageCPU); System.out.println("Instance 2 total CPU utlilization for last 10 minutes: " + d.getSum()); } } } 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()); } /*********************************** * # Copy script to * instance and run *********************************/ System.out.println(); System.out.println("Waiting for init and automatically SSH..."); /* call runtime exec to run scp */ execCmdRuby(insDNS1, keyGroupName); /*********************************** * # Save instances to image *********************************/ System.out.println(); System.out.println("******* Approaching 5:00 pm, create ami for instances *********"); String imageId1; String imageId2; String snapshot1; String snapshot2; imageId1 = createAmiFromInstance(insId1, "image1", true); imageId2 = createAmiFromInstance(insId2, "image2", true); System.out.println("Created first image id: " + imageId1); System.out.println("Created second image id: " + imageId2); snapshot1 = createSnapShotFromVolume(volume_name1); snapshot2 = createSnapShotFromVolume(volume_name2); System.out.println("Created first snapshot id: " + snapshot1); System.out.println("Created second snapshot id: " + snapshot2); /********************************************* * * # Stop Instances * *********************************************/ System.out.println(); System.out.println("#7 Stop & terminate the Instance"); List<String> instanceIds = new LinkedList<String>(); instanceIds.add(insId1); instanceIds.add(insId2); /* stop instances */ StopInstancesRequest stopIR = new StopInstancesRequest(instanceIds); ec2.stopInstances(stopIR); TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds); ec2.terminateInstances(tir); /********************************************* * * # Detach volumes * *********************************************/ System.out.println(); System.out.println("Detach the volumes from the instances..."); deatchVolume(insId1, volume_name1); deatchVolume(insId2, volume_name2); /********************************************* * * # Delete Volumes * *********************************************/ System.out.println(); while (true) { if (getVolumeState(volume_name1).compareTo("available") == 0 && getVolumeState(volume_name2).compareTo("available") == 0) break; } System.out.println("Delete volumes..."); Thread.sleep(10000); deleteVolume(volume_name1); deleteVolume(volume_name2); /********************************************* * * # Second day restore instances and volumes * *********************************************/ System.out.println(); System.out.println("#8 Second day start up instances from stored amis..."); String newInsId1 = ""; String newInsId2 = ""; String newInsIP1 = ""; String newInsIP2 = ""; String newInsZone1 = ""; String newInsZone2 = ""; newInsId1 = createInstanceFromImageId(imageId1, keyGroupName); newInsId2 = createInstanceFromImageId(imageId2, keyGroupName); System.out.println("Second day first instance has been restored with id: " + newInsId1); System.out.println("Second day second instance has been restored with id: " + newInsId2); newInsZone1 = getInstanceZone(newInsId1); newInsZone2 = getInstanceZone(newInsId2); System.out.println("New instance 1 zone: " + newInsZone1); System.out.println("New instance 2 zone: " + newInsZone2); newInsIP1 = getInstanceIP(newInsId1); newInsIP2 = getInstanceIP(newInsId2); System.out.println("New instance 1 IP: " + newInsIP1); System.out.println("New instance 2 IP: " + newInsIP2); Thread.sleep(120000); /* exec read */ System.out.println(); System.out.println("Now start to read the file stored yesterday..."); execCmdRead(newInsIP1, keyGroupName); /********************************************* * * #9 Read data from S3 * *********************************************/ /* get the object from the first day */ System.out.println(); System.out.println("#9 Reading data from S3 stored on the first day"); S3Object object = s3.getObject(new GetObjectRequest(bucketName, key)); BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent())); String data = null; while ((data = reader.readLine()) != null) { System.out.println(data); } /********************************************* * * #10 shutdown client object * *********************************************/ System.out.println("#10 shutdown client objects"); ec2.shutdown(); s3.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()); } }
From source file:virtualIT.java
License:Open Source License
private void cloudWatchMonitor(int userId) throws InterruptedException { String instanceId = mapUserInst.get(userId); //create request message GetMetricStatisticsRequest statRequest = new GetMetricStatisticsRequest(); //set up request message statRequest.setNamespace("AWS/EC2"); //namespace statRequest.setPeriod(60); //period of data ArrayList<String> stats = new ArrayList<String>(); //Use one of these strings: Average, Maximum, Minimum, SampleCount, Sum stats.add("Average"); stats.add("Sum"); statRequest.setStatistics(stats);// w w w. ja va2 s . c o m //Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations statRequest.setMetricName("CPUUtilization"); // set time GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // 1 second ago Date endTime = calendar.getTime(); calendar.add(GregorianCalendar.MINUTE, -10); // 10 minutes ago Date startTime = calendar.getTime(); statRequest.setStartTime(startTime); statRequest.setEndTime(endTime); //specify an instance ArrayList<Dimension> dimensions = new ArrayList<Dimension>(); dimensions.add(new Dimension().withName("InstanceId").withValue(instanceId)); statRequest.setDimensions(dimensions); //get statistics cloudWatch.getMetricStatistics(statRequest); Thread.currentThread().sleep(1000000); GetMetricStatisticsResult statResult = cloudWatch.getMetricStatistics(statRequest); //display System.out.println(statResult.toString()); List<Datapoint> dataList = statResult.getDatapoints(); Double averageCPU = null; Date timeStamp = null; for (Datapoint data : dataList) { averageCPU = data.getAverage(); timeStamp = data.getTimestamp(); System.out.println("Average CPU utlilization for last 10 minutes: " + averageCPU); System.out.println("Totl CPU utlilization for last 10 minutes: " + data.getSum()); } if (!mapUserCpu.containsKey(userId)) { mapUserCpu.put(userId, averageCPU); } else { mapUserCpu.remove(userId); /************** * update * / */ mapUserCpu.put(userId, averageCPU); } }
From source file:Assignment1.java
License:Open Source License
public static void main(String[] args) throws Exception { AWSCredentials credentials = new PropertiesCredentials( Assignment1.class.getResourceAsStream("AwsCredentials.properties")); /********************************************* * #1 Create Amazon Client object/* ww w . j av a 2 s . c om*/ **********************************************/ ec2 = new AmazonEC2Client(credentials); // We assume that we've already created an instance. Use the id of the instance. //String instanceId = "i-4e6c2a3d"; //put your own instance id to test this code. try { CreateSecurityGroupRequest createSecurityGroupRequest = new CreateSecurityGroupRequest(); createSecurityGroupRequest.withGroupName("mini").withDescription("My Java Security Group"); CreateSecurityGroupResult createSecurityGroupResult = ec2 .createSecurityGroup(createSecurityGroupRequest); IpPermission ipPermission = new IpPermission(); ipPermission.withIpRanges("0.0.0.0/0", "150.150.150.150/32").withIpProtocol("tcp").withFromPort(22) .withToPort(22); AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest = new AuthorizeSecurityGroupIngressRequest(); authorizeSecurityGroupIngressRequest.withGroupName("mini").withIpPermissions(ipPermission); ec2.authorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); CreateKeyPairRequest createKeyPairRequest = new CreateKeyPairRequest(); createKeyPairRequest.withKeyName("E3instance_key"); CreateKeyPairResult createKeyPairResult = ec2.createKeyPair(createKeyPairRequest); KeyPair keyPair = new KeyPair(); keyPair = createKeyPairResult.getKeyPair(); String privateKey = keyPair.getKeyMaterial(); System.out.print(privateKey); /********************************************* * * #1.1 Describe Key Pair * *********************************************/ System.out.println("\n#1.1 Describe Key Pair"); DescribeKeyPairsResult dkr = ec2.describeKeyPairs(); System.out.println(dkr.toString()); /********************************************* * * #1.2 Create an Instance * *********************************************/ RunInstancesRequest runInstancesRequest = new RunInstancesRequest(); runInstancesRequest.withImageId("ami-ab844dc2").withInstanceType("t1.micro").withMinCount(2) .withMaxCount(2).withKeyName("E3instance_key").withSecurityGroups("mini"); RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest); System.out.println("\n#1.2 Create an Instance"); List<Instance> resultInstance = runInstancesResult.getReservation().getInstances(); String createdInstanceId = null; for (Instance ins : resultInstance) { createdInstanceId = ins.getInstanceId(); System.out.println("New instance has been created: " + ins.getInstanceId()); } String myinstanceZone = resultInstance.get(0).getPlacement().getAvailabilityZone(); String myinstanceZone1 = resultInstance.get(1).getPlacement().getAvailabilityZone(); String myinstanceID = resultInstance.get(0).getInstanceId(); String myinstanceID1 = resultInstance.get(1).getInstanceId(); Thread.sleep(1000 * 1 * 60); /********************************************* * #2.1 Create a volume *********************************************/ //create a volume CreateVolumeRequest cvr = new CreateVolumeRequest(); CreateVolumeRequest cvr1 = new CreateVolumeRequest(); cvr.setAvailabilityZone(myinstanceZone); cvr1.setAvailabilityZone(myinstanceZone1); cvr.setSize(10); //size = 10 gigabytes cvr1.setSize(10); CreateVolumeResult volumeResult = ec2.createVolume(cvr); CreateVolumeResult volumeResult1 = ec2.createVolume(cvr1); String createdVolumeId = volumeResult.getVolume().getVolumeId(); String createdVolumeId1 = volumeResult1.getVolume().getVolumeId(); String[] volumeID = new String[2]; volumeID[0] = createdVolumeId; volumeID[1] = createdVolumeId1; System.out.println("\n#2.1 Create a volume for each instance"); Thread.sleep(1000 * 1 * 60); /********************************************* * #2.2 Attach the volume to the instance *********************************************/ AttachVolumeRequest avr = new AttachVolumeRequest(); AttachVolumeRequest avr1 = new AttachVolumeRequest(); avr.setInstanceId(myinstanceID); avr1.setInstanceId(myinstanceID1); avr.setVolumeId(createdVolumeId); avr1.setVolumeId(createdVolumeId1); avr.setDevice("/dev/sda2"); avr1.setDevice("/dev/sda2"); //avr.setVolumeId(createdVolumeId); //avr.setInstanceId(createdInstanceId); //avr.setDevice("/dev/sdf"); ec2.attachVolume(avr); ec2.attachVolume(avr1); System.out.println("\n#2.2 Attach the volume"); System.out.println("EBS volume has been attached and the volume ID is: " + createdVolumeId); System.out.println("EBS volume has been attached and the volume ID is: " + createdVolumeId1); Thread.sleep(1000 * 2 * 60); /*********************************** * #2.3 Monitoring (CloudWatch) *********************************/ //create CloudWatch client AmazonCloudWatchClient cloudWatch = new AmazonCloudWatchClient(credentials); //create request message GetMetricStatisticsRequest statRequest = new GetMetricStatisticsRequest(); //set up request message statRequest.setNamespace("AWS/EC2"); //namespace statRequest.setPeriod(60); //period of data ArrayList<String> stats = new ArrayList<String>(); //Use one of these strings: Average, Maximum, Minimum, SampleCount, Sum stats.add("Average"); stats.add("Sum"); statRequest.setStatistics(stats); //Use one of these strings: CPUUtilization, NetworkIn, NetworkOut, DiskReadBytes, DiskWriteBytes, DiskReadOperations statRequest.setMetricName("CPUUtilization"); // set time GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // 1 second ago Date endTime = calendar.getTime(); calendar.add(GregorianCalendar.MINUTE, -10); // 10 minutes ago Date startTime = calendar.getTime(); statRequest.setStartTime(startTime); statRequest.setEndTime(endTime); //specify an instance ArrayList<Dimension> dimensions = new ArrayList<Dimension>(); String monitorInstanceId = null; int i = 0; String[] idleInstance = new String[2]; for (Instance ins : resultInstance) { monitorInstanceId = ins.getInstanceId(); dimensions.add(new Dimension().withName("InstanceId").withValue(monitorInstanceId)); statRequest.setDimensions(dimensions); Thread.sleep(1000 * 3 * 60); //get statistics GetMetricStatisticsResult statResult = cloudWatch.getMetricStatistics(statRequest); //display System.out.println(statResult.toString()); List<Datapoint> dataList = statResult.getDatapoints(); Double averageCPU = null; Date timeStamp = null; for (Datapoint data : dataList) { averageCPU = data.getAverage(); timeStamp = data.getTimestamp(); System.out.println("Average CPU utlilization for last 1 minutes: " + averageCPU); //System.out.println("Total CPU utlilization for last 1 minutes: "+data.getSum()); //Calendar vmTime=GregorianCalendar.getInstance(); //vmTime.setTime(timeStamp); //vmTime.get(Calendar.HOUR_OF_DAY); if (averageCPU < 50 && i < 2) { idleInstance[i] = monitorInstanceId; i++; } } } System.out.println("\n" + i + " instance(s) idling."); /********************************************* * #2.4 Detach the volume from the instance *********************************************/ DetachVolumeRequest dvr = new DetachVolumeRequest(); DetachVolumeRequest dvr1 = new DetachVolumeRequest(); dvr.setVolumeId(createdVolumeId); dvr1.setVolumeId(createdVolumeId1); dvr.setInstanceId(myinstanceID); dvr1.setInstanceId(myinstanceID1); dvr.setDevice("/dev/sda2"); dvr1.setDevice("/dev/sda2"); ec2.detachVolume(dvr); ec2.detachVolume(dvr1); System.out.println("\n#2.4 Detach the volume"); Thread.sleep(1000 * 1 * 60); /********************************************* * #2.5 Create new AMI for idle instance *********************************************/ String[] idleAMIID = new String[2]; int j = 0; for (j = 0; j < idleInstance.length; j++) { CreateImageRequest Im = new CreateImageRequest(idleInstance[j], "image" + j); //CreateImageRequest Im1=new CreateImageRequest(myinstanceID1, "image1"); Im.setInstanceId(idleInstance[j]); //Im1.setInstanceId(myinstanceID1); CreateImageResult myAMI = ec2.createImage(Im); idleAMIID[j] = myAMI.getImageId(); //CreateImageResult myAMI1= ec2.createImage(Im1); System.out.println("\n#2.5 Create new AMI"); } Thread.sleep(1000 * 1 * 60); /********************************************* * * # Terminate an Instance * *********************************************/ //System.out.println("#8 Terminate the Instance"); // TerminateInstancesRequest tir = new TerminateInstancesRequest(instanceIds); //ec2.terminateInstances(tir); /********************************************* * #2.6 Create new VMs *********************************************/ RunInstancesRequest runNewInstancesRequest = new RunInstancesRequest(); int m; String[] newCreatedInstanceId = new String[2]; for (m = 0; m < j; m++)//j is the number of AMI created { runNewInstancesRequest.withImageId(idleAMIID[m]).withInstanceType("t1.micro").withMinCount(1) .withMaxCount(1).withKeyName("E3instance_key").withSecurityGroups("mini"); RunInstancesResult runNewInstancesResult = ec2.runInstances(runNewInstancesRequest); List<Instance> newResultInstance = runNewInstancesResult.getReservation().getInstances(); String newInstanceId = null; for (Instance ins : newResultInstance) { newInstanceId = ins.getInstanceId(); } newCreatedInstanceId[m] = newInstanceId; System.out.println("Using AMI, a new instance has been created: " + newCreatedInstanceId[m]); } Thread.sleep(1000 * 1 * 60); //System.out.println("\n#2.6 Create "+ m + " instance using AMI"); /********************************************* * #2.7 Attach the volume to the new instance *********************************************/ int n; for (n = 0; n < idleInstance.length; n++) { AttachVolumeRequest new_avr = new AttachVolumeRequest(); //AttachVolumeRequest new_avr1 = new AttachVolumeRequest(); new_avr.setInstanceId(newCreatedInstanceId[n]); //avr1.setInstanceId(myinstanceID1); new_avr.setVolumeId(volumeID[n]); //avr1.setVolumeId(createdVolumeId1); new_avr.setDevice("/dev/sda2"); //avr1.setDevice("/dev/sda2"); //avr.setVolumeId(createdVolumeId); //avr.setInstanceId(createdInstanceId); //avr.setDevice("/dev/sdf"); ec2.attachVolume(new_avr); //ec2.attachVolume(avr1); System.out.println("\n#2.7 Re-attach the volume"); System.out.println("EBS volume has been attached and the volume ID is: " + volumeID[n]); //System.out.println("EBS volume has been attached and the volume ID is: "+createdVolumeId1); Thread.sleep(1000 * 1 * 60); } /************************************************ * #3 S3 bucket and object ***************************************************/ s3 = new AmazonS3Client(credentials); //create bucket String bucketName = "lucinda.duan"; s3.createBucket(bucketName); //set key String key = "object-name.txt"; //set value File file = File.createTempFile("temp", ".txt"); file.deleteOnExit(); Writer writer = new OutputStreamWriter(new FileOutputStream(file)); writer.write("This is a sample sentence.\r\nYes!"); writer.close(); //put object - bucket, key, value(file) s3.putObject(new PutObjectRequest(bucketName, key, file)); //get object S3Object object = s3.getObject(new GetObjectRequest(bucketName, key)); BufferedReader reader = new BufferedReader(new InputStreamReader(object.getObjectContent())); String data = null; while ((data = reader.readLine()) != null) { System.out.println(data); } /********************************************* * #4 shutdown client object *********************************************/ // ec2.shutdown(); // s3.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()); } }
From source file:com.appdynamics.extensions.cloudwatch.metricsmanager.MetricsManager.java
License:Apache License
protected Double getValue(String namespace, String metricName, Datapoint data) { MetricType type = getMetricType(namespace, metricName); Double value = null;/*from w w w . ja v a2 s .c om*/ switch (type) { case AVE: value = data.getAverage(); break; case MAX: value = data.getMaximum(); break; case MIN: value = data.getMinimum(); break; case SUM: value = data.getSum(); break; case SAMPLE_COUNT: value = data.getSampleCount(); break; } return value; }
From source file:com.blubb.andcw.ChartBuilder.java
License:Apache License
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Metric m = new Metric().withMetricName((String) getIntent().getExtras().get("metric")) .withNamespace((String) getIntent().getExtras().get("namespace")); Dimension d = new Dimension().withName((String) getIntent().getExtras().get("dimension")) .withValue((String) getIntent().getExtras().get("dimensionvalue")); TimeSeries series = new TimeSeries(m.getMetricName() + " - " + d.getName() + " " + d.getValue()); AWSCredentials awsc = getAWSCredentials(); AmazonCloudWatchAsyncClient acw = new AmazonCloudWatchAsyncClient(awsc); long offset = new Date().getTime() - 1000 * 3600 * 24; GetMetricStatisticsRequest gmsr = new GetMetricStatisticsRequest().withStartTime(new Date(offset)) .withMetricName(m.getMetricName()).withNamespace(m.getNamespace()).withDimensions(d).withPeriod(300) .withStatistics("Average").withEndTime(new Date()); Log.i("AndCW req", gmsr.toString()); Future<GetMetricStatisticsResult> res = acw.getMetricStatisticsAsync(gmsr); TreeSet<Datapoint> data = new TreeSet<Datapoint>(new Comparator<Datapoint>() { public int compare(Datapoint lhs, Datapoint rhs) { return lhs.getTimestamp().compareTo(rhs.getTimestamp()); }//from ww w. java 2 s . c o m }); try { data.addAll((List<Datapoint>) res.get().getDatapoints()); // FIXME } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } for (Datapoint dp : data) { series.add(dp.getTimestamp(), dp.getAverage()); } XYSeriesRenderer renderer = new XYSeriesRenderer(); mRenderer.addSeriesRenderer(renderer); renderer.setPointStyle(PointStyle.CIRCLE); renderer.setFillPoints(true); mDataset.addSeries(series); mRenderer.setApplyBackgroundColor(true); mRenderer.setBackgroundColor(Color.argb(100, 50, 50, 50)); mRenderer.setAxisTitleTextSize(16); mRenderer.setChartTitleTextSize(20); mRenderer.setLabelsTextSize(15); mRenderer.setLegendTextSize(15); mRenderer.setMargins(new int[] { 20, 30, 15, 0 }); mRenderer.setZoomButtonsVisible(true); mRenderer.setPointSize(1); mChartView = ChartFactory.getTimeChartView(this, mDataset, mRenderer, null); setContentView(mChartView); }
From source file:com.pinterest.arcee.autoscaling.AwsAlarmManager.java
License:Apache License
@Override public List<MetricDatumBean> getMetricsStatistics(String groupName, String metricName, String startFrom) throws Exception { GetMetricStatisticsRequest request = new GetMetricStatisticsRequest().withStatistics("Average"); request.setNamespace(METRIC_NAMESPACE); request.setMetricName(metricName);/* w ww .j ava 2 s . co m*/ request.setDimensions(Arrays.asList(getDimention(groupName))); request.setPeriod(60); // minimum period request.setStartTime(getDate(startFrom)); request.setEndTime(new Date()); List<Datapoint> datapoints = acwClient.getMetricStatistics(request).getDatapoints(); List<MetricDatumBean> metricDataPoints = new ArrayList<>(); for (Datapoint datapoint : datapoints) { MetricDatumBean dp = new MetricDatumBean(); dp.setTimestamp(datapoint.getTimestamp().getTime()); dp.setValue(datapoint.getAverage()); metricDataPoints.add(dp); } return metricDataPoints; }
From source file:com.vmware.photon.controller.model.adapters.awsadapter.AWSStatsService.java
License:Open Source License
private void persistStat(StatelessService service, Datapoint datapoint, String metricName, AWSStatsDataHolder statsData) {//from w w w. j a va2s. c o m ResourceMetricService.ResourceMetric stat = new ResourceMetricService.ResourceMetric(); // Set the documentSelfLink to <computeId>-<metricName> stat.documentSelfLink = UriUtils.getLastPathSegment(statsData.computeDesc.documentSelfLink) + "-" + metricName; stat.value = datapoint.getAverage(); stat.timestampMicrosUtc = TimeUnit.MILLISECONDS.toMicros(datapoint.getTimestamp().getTime()); service.getHost().sendRequest(Operation.createPost(statsData.persistStatsUri) .setReferer(AWSStatsService.SELF_LINK).setBodyNoCloning(stat)); }
From source file:eu.optimis.monitoring.amazoncollector.MeasurementsHelper.java
License:Apache License
private Measurement getCWMeasurement(String metric_name, String optimis_metric_name, boolean custom, String instance_id, String service_id) { AmazonCloudWatch cw = getAmazonCloudWatchClient(); String ns = custom ? "System/Linux" : "AWS/EC2"; List<Dimension> dimensions = new LinkedList<Dimension>(); Dimension dim = new Dimension(); dim.setName("InstanceId"); dim.setValue(instance_id);//from www .j a v a 2 s .c om dimensions.add(dim); GetMetricStatisticsRequest req = new GetMetricStatisticsRequest(); req.setStartTime(new Date(System.currentTimeMillis() - HOUR_AND_HALF_AGO - PERIOD)); req.setEndTime(new Date(System.currentTimeMillis() - HOUR_AND_HALF_AGO)); req.setMetricName(metric_name); req.setNamespace(ns); List<String> statistics = new LinkedList<String>(); statistics.add(Statistic.Average.toString()); req.setStatistics(statistics); req.setPeriod((int) PERIOD / 1000); req.setDimensions(dimensions); GetMetricStatisticsResult res = cw.getMetricStatistics(req); if (res.getDatapoints().isEmpty()) return null; Datapoint dp = res.getDatapoints().get(0); return new Measurement(optimis_metric_name, dp.getAverage().toString(), dp.getUnit(), new Date(), instance_id, service_id); }
From source file:imperial.modaclouds.monitoring.datacollectors.monitors.CloudWatchMonitor.java
License:BSD License
/** * Retrieve monitoring value from metric names. *//*w w w .j a v a 2 s .co m*/ public MeasureSet retrieveMeasureSet(ArrayList<String> measureNames) throws ParseException { GetMetricStatisticsRequest getMetricRequest = new GetMetricStatisticsRequest(); // Dimension Set ArrayList<Dimension> dimensions = new ArrayList<Dimension>(); Dimension dim = new Dimension(); dim.setName("InstanceId"); dim.setValue(instanceID); dimensions.add(dim); // Time Set //TimeZone zone = TimeZone.getDefault(); //int timeOffset = zone.getOffset(new Date().getTime()) / (1000 * 3600); //String dateFormatString = "%1$tY-%1$tm-%1$tdT%1tH:%1$tM:%1$tSZ"; GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // Static Set ArrayList<String> stats = new ArrayList<String>(); stats.add("Average"); //stats.add("Maximum"); getMetricRequest.setStatistics(stats); getMetricRequest.setNamespace("AWS/EC2"); getMetricRequest.setPeriod(60); getMetricRequest.setDimensions(dimensions); getMetricRequest.setEndTime(calendar.getTime()); calendar.add(GregorianCalendar.MINUTE, -10); getMetricRequest.setStartTime(calendar.getTime()); HashMap<Long, MeasureSet> measureSets = new HashMap<Long, MeasureSet>(); for (String measureName : measureNames) { getMetricRequest.setMetricName(measureName); GetMetricStatisticsResult metricStatistics = cloudWatchClient.getMetricStatistics(getMetricRequest); List<Datapoint> datapoints = metricStatistics.getDatapoints(); for (Datapoint point : datapoints) { Calendar cal = new GregorianCalendar(); cal.setTime(point.getTimestamp()); //cal.add(GregorianCalendar.HOUR, timeOffset); MeasureSet measureSet = measureSets.get(cal.getTimeInMillis()); if (measureSet == null) { measureSet = new MeasureSet(); measureSet.timestamp = cal; measureSets.put(cal.getTimeInMillis(), measureSet); } measureSet.setMeasure(measureName, point.getAverage()); } } ArrayList<MeasureSet> sortedMeasureSets = new ArrayList<MeasureSet>(measureSets.values()); if (sortedMeasureSets.size() == 0) { return null; } else { Collections.sort(sortedMeasureSets); return sortedMeasureSets.get(sortedMeasureSets.size() - 1); } }
From source file:imperial.modaclouds.monitoring.datacollectors.monitors.CostMonitor.java
License:BSD License
/** * Retrieve monitoring value from metric names. *//*from ww w . j ava 2s . com*/ public MeasureSet retrieveMeasureSet(ArrayList<String> measureNames) throws ParseException { GetMetricStatisticsRequest getMetricRequest = new GetMetricStatisticsRequest(); // Dimension Set ArrayList<Dimension> dimensions = new ArrayList<Dimension>(); Dimension dim = new Dimension(); //dim.setName("InstanceId"); //dim.setValue(instanceID); dim.setName("Currency"); dim.setValue("USD"); dimensions.add(dim); // Time Set //TimeZone zone = TimeZone.getDefault(); //int timeOffset = zone.getOffset(new Date().getTime()) / (1000 * 3600); //String dateFormatString = "%1$tY-%1$tm-%1$tdT%1tH:%1$tM:%1$tSZ"; GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); calendar.add(GregorianCalendar.SECOND, -1 * calendar.get(GregorianCalendar.SECOND)); // Static Set ArrayList<String> stats = new ArrayList<String>(); stats.add("Average"); //stats.add("Maximum"); getMetricRequest.setStatistics(stats); getMetricRequest.setNamespace("AWS/Billing"); getMetricRequest.setPeriod(3600); getMetricRequest.setDimensions(dimensions); getMetricRequest.setEndTime(calendar.getTime()); calendar.add(GregorianCalendar.HOUR, -10); getMetricRequest.setStartTime(calendar.getTime()); HashMap<Long, MeasureSet> measureSets = new HashMap<Long, MeasureSet>(); for (String measureName : measureNames) { getMetricRequest.setMetricName(measureName); GetMetricStatisticsResult metricStatistics = cloudWatchClient.getMetricStatistics(getMetricRequest); List<Datapoint> datapoints = metricStatistics.getDatapoints(); for (Datapoint point : datapoints) { Calendar cal = new GregorianCalendar(); cal.setTime(point.getTimestamp()); //cal.add(GregorianCalendar.HOUR, timeOffset); MeasureSet measureSet = measureSets.get(cal.getTimeInMillis()); if (measureSet == null) { measureSet = new MeasureSet(); measureSet.timestamp = cal; measureSets.put(cal.getTimeInMillis(), measureSet); } measureSet.setMeasure(measureName, point.getAverage()); } } ArrayList<MeasureSet> sortedMeasureSets = new ArrayList<MeasureSet>(measureSets.values()); if (sortedMeasureSets.size() == 0) { return null; } else { Collections.sort(sortedMeasureSets); return sortedMeasureSets.get(sortedMeasureSets.size() - 1); } }