Example usage for com.amazonaws.services.cloudwatch.model PutMetricAlarmRequest PutMetricAlarmRequest

List of usage examples for com.amazonaws.services.cloudwatch.model PutMetricAlarmRequest PutMetricAlarmRequest

Introduction

In this page you can find the example usage for com.amazonaws.services.cloudwatch.model PutMetricAlarmRequest PutMetricAlarmRequest.

Prototype

PutMetricAlarmRequest

Source Link

Usage

From source file:AwsAuto.java

License:Open Source License

public static void main(String[] args) throws Exception {

    // initialize/determine parameters
    String instanceType = "m3.medium";
    String loadGeneratorAmi = "ami-8ac4e9e0";
    String dataCenterAmi = "ami-349fbb5e";
    String bidPrice = "0.1";
    String loadGeneratorDns = null; // load generator DNS
    String dashboardUrl = null; // the URL where we check our performance
    String testId = null;/*from   w  w w  . j  a v  a  2s. co m*/

    // create project tag for instances
    ArrayList<com.amazonaws.services.ec2.model.Tag> loadGeneratorTags = new ArrayList<>();
    com.amazonaws.services.ec2.model.Tag loadGeneratorTag = new com.amazonaws.services.ec2.model.Tag("Project",
            "2.1");
    loadGeneratorTags.add(loadGeneratorTag);

    // create project tag for auto-scaling
    com.amazonaws.services.autoscaling.model.Tag asgTag = new com.amazonaws.services.autoscaling.model.Tag();
    asgTag.setKey("Project");
    asgTag.setValue("2.1");

    // create project tag for load balancer
    ArrayList<com.amazonaws.services.elasticloadbalancing.model.Tag> loadBalancerTags = new ArrayList<>();
    com.amazonaws.services.elasticloadbalancing.model.Tag loadBalancerTag = new com.amazonaws.services.elasticloadbalancing.model.Tag();
    loadBalancerTag.setKey("Project");
    loadBalancerTag.setValue("2.1");
    loadBalancerTags.add(loadBalancerTag);

    /**
     * =========================================================================
     * ================= Create security groups
     * =========================================================================
     * =================
     */

    String loadGeneratorSecurityName = "LoadGeneratorSGP2";
    String allPurposeSecurityName = "AllPurposeSGP2";
    SecurityGroup loadGeneratorSecurityGroup = new SecurityGroup(loadGeneratorSecurityName);
    SecurityGroup allPurposeSecurityGroup = new SecurityGroup(allPurposeSecurityName);

    /**
     * =========================================================================
     * ================= Grant permission and credentials
     * =========================================================================
     * =================
     */

    AWSCredentials credentials = null;
    try {
        credentials = new ProfileCredentialsProvider("School").getCredentials();
    } catch (Exception e) {
        throw new AmazonClientException("Cannot load the credentials from the credential profiles file. "
                + "Please make sure that your credentials file is at the correct "
                + "location (C:\\Users\\Jiabei\\.aws\\credentials), and is in valid format.", e);
    }

    // set region
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);
    Region usEast1 = Region.getRegion(Regions.US_EAST_1);
    ec2.setRegion(usEast1);

    /**
     * =========================================================================
     * ================= Create a load generator and submit password
     * =========================================================================
     * =================
     */

    Requests requestsLg = new Requests(instanceType, loadGeneratorAmi, bidPrice, loadGeneratorSecurityName,
            loadGeneratorTags);
    loadGeneratorDns = requestsLg.submitRequests();
    String submissionUrl = "http://" + loadGeneratorDns
            + "/password?passwd=0WSb4ufhYI7SkxfLWnnIWU0MC1NdcNKT&andrewId=jiabeip";
    sendGET(submissionUrl);

    try {

        /**
         * =======================================================================
         * =================== Create a load balancer
         * =======================================================================
         * ===================
         */

        String loadBalancerDns = null;
        String loadBalancerName = "LoadBalancerProj2";
        String healthCheckPage = "/heartbeat?lg=" + loadGeneratorDns;
        AmazonElasticLoadBalancingClient loadBalancerClient = new AmazonElasticLoadBalancingClient(credentials);

        // configure a request
        CreateLoadBalancerRequest loadBalancerRequest = new CreateLoadBalancerRequest()
                .withAvailabilityZones("us-east-1b").withListeners(new Listener("HTTP", 80, 80))
                .withLoadBalancerName(loadBalancerName).withSecurityGroups(allPurposeSecurityGroup.getGroupId())
                .withTags(loadBalancerTags);

        CreateLoadBalancerResult loadBalancerResult = loadBalancerClient
                .createLoadBalancer(loadBalancerRequest);
        loadBalancerDns = loadBalancerResult.getDNSName();

        // configure health check setting
        HealthCheck loadBalancerHealthCheck = new HealthCheck().withTarget("HTTP:80" + healthCheckPage)
                .withTimeout(5).withInterval(30).withUnhealthyThreshold(2).withHealthyThreshold(10);

        ConfigureHealthCheckRequest healthCheckRequest = new ConfigureHealthCheckRequest()
                .withLoadBalancerName(loadBalancerName).withHealthCheck(loadBalancerHealthCheck);

        // attach health check setting to load balancer
        ConfigureHealthCheckResult healthCheckResult = loadBalancerClient
                .configureHealthCheck(healthCheckRequest);

        System.out.println("Load balancer created!\nDNS: " + loadBalancerDns);

        /**
         * =======================================================================
         * =================== Create launch configuration
         * =======================================================================
         * ===================
         */

        String launchConfigName = "LaunchConfigProj2";
        String autoScalingGroupName = "AutoScalingGroupProj2";

        AmazonAutoScalingClient autoScalingGroupClient = new AmazonAutoScalingClient(credentials);
        AmazonCloudWatchClient cloudWatchClient = new AmazonCloudWatchClient(credentials);

        System.out.println("Creating launch configuration...");

        // configure the request
        CreateLaunchConfigurationRequest launchConfigRequest = new CreateLaunchConfigurationRequest()
                .withImageId(dataCenterAmi).withInstanceType(instanceType)
                .withLaunchConfigurationName(launchConfigName)
                .withSecurityGroups(allPurposeSecurityGroup.getGroupId()).withSpotPrice(bidPrice)
                .withKeyName("primary");

        // enable detail monitoring
        InstanceMonitoring monitor = new InstanceMonitoring();
        monitor.setEnabled(true);
        launchConfigRequest.setInstanceMonitoring(monitor);

        // attach the configuration to the ASG client
        autoScalingGroupClient.createLaunchConfiguration(launchConfigRequest);

        System.out.println("Configuration complete!\nCreating auto-scaling group...");

        /**
         * =======================================================================
         * =================== Create auto-scaling group
         * =======================================================================
         * ===================
         */

        // configure ASG request
        CreateAutoScalingGroupRequest asgRequest = new CreateAutoScalingGroupRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withAvailabilityZones("us-east-1b")
                .withLoadBalancerNames(loadBalancerName).withNewInstancesProtectedFromScaleIn(false)
                .withTags(asgTag).withDefaultCooldown(120).withMinSize(1).withMaxSize(8).withDesiredCapacity(1) // Start
                // from
                // one
                .withHealthCheckGracePeriod(120).withHealthCheckType("ELB")
                .withLaunchConfigurationName(launchConfigName);

        // attach group configuration to ASG client
        autoScalingGroupClient.createAutoScalingGroup(asgRequest);

        /**
         * =======================================================================
         * =================== Create scaling up policy for ASG
         * =======================================================================
         * ===================
         */

        StepAdjustment upRule1 = new StepAdjustment().withMetricIntervalLowerBound(0.0)
                .withMetricIntervalUpperBound(25.0).withScalingAdjustment(1);

        StepAdjustment upRule2 = new StepAdjustment().withMetricIntervalLowerBound(25.0)
                .withMetricIntervalUpperBound(30.0).withScalingAdjustment(2);

        StepAdjustment upRule3 = new StepAdjustment().withMetricIntervalLowerBound(30.0)
                .withMetricIntervalUpperBound(null).withScalingAdjustment(3);

        String upPolicyName = "Scaling Up";

        PutScalingPolicyRequest scalingUpPolicy = new PutScalingPolicyRequest()
                .withAdjustmentType("ChangeInCapacity").withPolicyType("StepScaling")
                .withStepAdjustments(upRule1, upRule2, upRule3).withAutoScalingGroupName(autoScalingGroupName)
                .withPolicyName(upPolicyName).withEstimatedInstanceWarmup(120);

        StepAdjustment downRule1 = new StepAdjustment().withMetricIntervalLowerBound(-20.0)
                .withMetricIntervalUpperBound(-0.0).withScalingAdjustment(-1);

        StepAdjustment downRule2 = new StepAdjustment().withMetricIntervalLowerBound(-30.0)
                .withMetricIntervalUpperBound(-20.0).withScalingAdjustment(-2);

        StepAdjustment downRule3 = new StepAdjustment().withMetricIntervalLowerBound(null)
                .withMetricIntervalUpperBound(-30.0).withScalingAdjustment(-3);

        String downPolicyName = "Scaling Down";

        PutScalingPolicyRequest scalingDownPolicy = new PutScalingPolicyRequest().withAdjustmentType("")
                .withPolicyType("ChangeInCapacity").withStepAdjustments(downRule1, downRule2, downRule3)
                .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(downPolicyName)
                .withEstimatedInstanceWarmup(60);

        // attach policies to ASG and get ARN for setting alarm
        PutScalingPolicyResult scaleUpResult = autoScalingGroupClient.putScalingPolicy(scalingUpPolicy);
        String upArn = scaleUpResult.getPolicyARN();
        PutScalingPolicyResult scaleDownResult = autoScalingGroupClient.putScalingPolicy(scalingDownPolicy);
        String downArn = scaleDownResult.getPolicyARN();

        /**
         * =======================================================================
         * =================== Create alarms for policies
         * =======================================================================
         * ===================
         */

        String upAlarmName = "UpAlarm_Mild";
        String downAlarmName = "DownAlarm_Mild";
        Dimension dimension = new Dimension();
        dimension.setName("AutoScalingGroupName");
        dimension.setValue(autoScalingGroupName);

        PutMetricAlarmRequest upAlarmRequest = new PutMetricAlarmRequest().withAlarmName(upAlarmName)
                .withMetricName("CPUUtilization").withNamespace("AWS/EC2").withDimensions(dimension)
                .withStatistic(Statistic.SampleCount)
                .withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold).withThreshold(65.0)
                .withEvaluationPeriods(1).withPeriod(120).withAlarmActions(upArn);

        PutMetricAlarmRequest downAlarmRequest = new PutMetricAlarmRequest().withAlarmName(downAlarmName)
                .withNamespace("AWS/EC2").withDimensions(dimension).withMetricName("CPUUtilization")
                .withStatistic(Statistic.Average)
                .withComparisonOperator(ComparisonOperator.LessThanOrEqualToThreshold).withThreshold(60.0)
                .withEvaluationPeriods(1).withPeriod(120).withAlarmActions(downArn);

        cloudWatchClient.putMetricAlarm(upAlarmRequest);
        cloudWatchClient.putMetricAlarm(downAlarmRequest);

        System.out.println("All settings complete! \nReady for warmup...");

        /**
         * =======================================================================
         * =================== Warm up ELB
         * =======================================================================
         * ===================
         */

        String warmUpUrl = "http://" + loadGeneratorDns + "/warmup?dns=" + loadBalancerDns;
        sendGET(warmUpUrl);
        System.out.println("Warmup link: " + warmUpUrl);

        try {
            Thread.sleep(15 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Warmup complete!\nReady for battle...");

        /**
         * =======================================================================
         * =================== Start the test
         * =======================================================================
         * ===================
         */

        String testUrl = "http://" + loadGeneratorDns + "/junior?dns=" + loadBalancerDns;
        testId = sendGET(testUrl);
        System.out.println("Test ID is: " + testId);

        System.out.println("Test link: " + testUrl);

        try {
            Thread.sleep(60 * 60 * 1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("Test finished!");

        /**
         * =======================================================================
         * =================== Delete resources
         * =======================================================================
         * ===================
         */

        // clear ASG
        UpdateAutoScalingGroupRequest asgClearRequest = new UpdateAutoScalingGroupRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withMaxSize(0).withMinSize(0);
        autoScalingGroupClient.updateAutoScalingGroup(asgClearRequest);

        // delete policies
        DeletePolicyRequest upPolicyDeleteRequest = new DeletePolicyRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(upPolicyName);
        autoScalingGroupClient.deletePolicy(upPolicyDeleteRequest);

        DeletePolicyRequest downPolicyDeleteRequest = new DeletePolicyRequest()
                .withAutoScalingGroupName(autoScalingGroupName).withPolicyName(downPolicyName);
        autoScalingGroupClient.deletePolicy(downPolicyDeleteRequest);
        System.out.println("Policies deleted...");

        // delete alarms
        DeleteAlarmsRequest alarmsDeleteRequest = new DeleteAlarmsRequest().withAlarmNames(upAlarmName,
                downAlarmName);
        cloudWatchClient.deleteAlarms(alarmsDeleteRequest);
        System.out.println("Alarms deleted...");

        // delete load balancer
        DeleteLoadBalancerRequest lgDeleteRequest = new DeleteLoadBalancerRequest()
                .withLoadBalancerName(loadBalancerName);
        loadBalancerClient.deleteLoadBalancer(lgDeleteRequest);
        System.out.println("Load generator deleted...");

        // delete ASG
        DeleteAutoScalingGroupRequest asgDeleteRequest = new DeleteAutoScalingGroupRequest()
                .withForceDelete(true).withAutoScalingGroupName(autoScalingGroupName);
        autoScalingGroupClient.deleteAutoScalingGroup(asgDeleteRequest);
        System.out.println("ASG deleted...");

        // delete launch configuration
        DeleteLaunchConfigurationRequest launchConfigDeleteRequest = new DeleteLaunchConfigurationRequest()
                .withLaunchConfigurationName(launchConfigName);
        autoScalingGroupClient.deleteLaunchConfiguration(launchConfigDeleteRequest);
        System.out.println("Launch configuration deleted...");

        // delete security group
        DeleteSecurityGroupRequest sgDeleteRequest = new DeleteSecurityGroupRequest()
                .withGroupName(allPurposeSecurityName);
        ec2.deleteSecurityGroup(sgDeleteRequest);
        System.out.println("Security group deleted...");

        /**
         * =======================================================================
         * =================== All done
         * =======================================================================
         * ===================
         */
        System.out.println("All done :)");

    } catch (AmazonServiceException ase) {
        // Write out any exceptions that may have occurred.
        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());

    } catch (Exception e) {
        System.out.println("Unexcepted error!");
        System.out.println(e.getMessage());
    }

}

From source file:virtualIT.java

License:Open Source License

private static void createTriggers(int userId) {
    System.out.println("Creating Trigger");
    Dimension dimension = new Dimension();
    dimension.setName("AutoScalingGroupName");
    dimension.setValue(virtualIT.autoScalingGroupName);

    PutMetricAlarmRequest putMetricBusyAlarmRequest = new PutMetricAlarmRequest();
    putMetricBusyAlarmRequest.withAlarmName(BUSY_ALARM_NAME)
            .withComparisonOperator("GreaterThanOrEqualToThreshold").withUnit("Seconds")
            .withEvaluationPeriods(EVALUATION_PERIOD).withMetricName(METRIC_NAME).withNamespace(NAMESPACE)
            .withPeriod(EC2_METRIC_SUBMIT_PERIOD).withStatistic(STATISTIC).withThreshold(THRESHOLD)
            .withAlarmActions(SCALE_UP_POLICY_ARN).withDimensions(dimension);

    PutMetricAlarmRequest putMetricIdleAlarmRequest = new PutMetricAlarmRequest();
    putMetricIdleAlarmRequest.withAlarmName(IDLE_ALARM_NAME)
            .withComparisonOperator("LessThanOrEqualToThreshold").withUnit("Seconds")
            .withEvaluationPeriods(EVALUATION_PERIOD).withMetricName(METRIC_NAME).withNamespace(NAMESPACE)
            .withPeriod(EC2_METRIC_SUBMIT_PERIOD).withStatistic(STATISTIC).withThreshold(THRESHOLD)
            .withAlarmActions(SCALE_DOWN_POLICY_ARN).withDimensions(dimension);

    cloudWatch.putMetricAlarm(putMetricBusyAlarmRequest);
    cloudWatch.putMetricAlarm(putMetricIdleAlarmRequest);

}

From source file:aws.example.cloudwatch.PutMetricAlarm.java

License:Open Source License

public static void main(String[] args) {

    final String USAGE = "To run this example, supply an alarm name and instance id\n"
            + "Ex: DeleteAlarm <alarm-name> <instance-id>\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);/*from w w  w.j  a v a  2s  . c o  m*/
    }

    String alarmName = args[0];
    String instanceId = args[1];

    final AmazonCloudWatch cw = AmazonCloudWatchClientBuilder.defaultClient();

    Dimension dimension = new Dimension().withName("InstanceId").withValue(instanceId);

    PutMetricAlarmRequest request = new PutMetricAlarmRequest().withAlarmName(alarmName)
            .withComparisonOperator(ComparisonOperator.GreaterThanThreshold).withEvaluationPeriods(1)
            .withMetricName("CPUUtilization").withNamespace("AWS/EC2").withPeriod(60)
            .withStatistic(Statistic.Average).withThreshold(70.0).withActionsEnabled(false)
            .withAlarmDescription("Alarm when server CPU utilization exceeds 70%")
            .withUnit(StandardUnit.Seconds).withDimensions(dimension);

    PutMetricAlarmResult response = cw.putMetricAlarm(request);

    System.out.printf("Successfully created alarm with name %s", alarmName);

}

From source file:be.dataminded.nifi.plugins.PutCloudWatchCountMetricAndAlarm.java

License:Apache License

@Override
public void onTrigger(ProcessContext context, ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/*w  w  w  . j  a  va2s  . c om*/
    if (flowFile == null) {
        return;
    }

    long totalTableCount = 0;
    long sumCount = 0;
    String tableName = "";
    String schemaName = "";
    String source = "";
    String tenantName = "";

    try (InputStream inputStream = session.read(flowFile)) {

        StringWriter writer = new StringWriter();
        IOUtils.copy(inputStream, writer, "UTF-8");
        String flowFileContent = writer.toString();

        // The MergeContent controller will be configured to append the JSON content with commas
        // We have to surround this list with square brackets to become a valid JSON Array
        String jsonContent = "[" + flowFileContent + "]";

        JSONArray jsonArray = new JSONArray(jsonContent);

        Iterator iterator = jsonArray.iterator();

        ArrayList<Long> counts = new ArrayList<>();

        while (iterator.hasNext()) {
            JSONObject o = (JSONObject) iterator.next();
            counts.add(o.getLong(context.getProperty(NAME_ELEMENT_TO_SUM).getValue()));
        }
        sumCount = counts.stream().mapToLong(Long::longValue).sum();

        JSONObject firstElement = (JSONObject) jsonArray.get(0);
        totalTableCount = firstElement.getLong(context.getProperty(NAME_ELEMENT_TOTAL_COUNT).getValue());
        tableName = firstElement.getString(TABLE_NAME);
        schemaName = firstElement.getString(SCHEMA_NAME);
        source = firstElement.getString(SOURCE_NAME);
        tenantName = firstElement.getString(TENANT_NAME);

    } catch (IOException e) {
        logger.error("Something went wrong when trying to read the flowFile body: " + e.getMessage());
    } catch (org.json.JSONException e) {
        logger.error("Something when trying to parse the JSON body of the flowFile: " + e.getMessage());
    } catch (Exception e) {
        logger.error("something else went wrong in body processing of this FlowFile: " + e.getMessage());
        session.transfer(flowFile, REL_FAILURE);
    }

    try {

        String environment = context.getProperty(ENVIRONMENT).getValue();
        String alarmPrefix = context.getProperty(NAME_PREFIX_ALARM).getValue();

        Map<String, Long> metrics = new HashMap<>();
        // first metric: this is the total count of the records that were exported
        metrics.put("COUNT_", sumCount);
        // second metric: this is the difference between the records exported
        // and the total amount of records counted in the DB, should always be 0 !!!
        // we take a margin into account because we can't be sure there won't be any deletes
        // between counting and executing the queries
        long diff = Math.abs(totalTableCount - sumCount);
        double diffProcent = Math.round((diff / totalTableCount) * 1000);
        metrics.put("DIFF_", (long) diffProcent);

        ArrayList<Dimension> dimensions = new ArrayList<>();
        dimensions.add(new Dimension().withName("tableName").withValue(tableName));
        dimensions.add(new Dimension().withName("tenantName").withValue(tenantName));
        dimensions.add(new Dimension().withName("sourceName").withValue(source));
        dimensions.add(new Dimension().withName("schemaName").withValue(schemaName));
        dimensions.add(new Dimension().withName("environment").withValue(environment));

        for (Map.Entry<String, Long> metric : metrics.entrySet()) {
            MetricDatum datum = new MetricDatum();
            datum.setMetricName(metric.getKey() + tableName);
            datum.setValue((double) metric.getValue());
            datum.setUnit("Count");
            datum.setDimensions(dimensions);

            final PutMetricDataRequest metricDataRequest = new PutMetricDataRequest().withNamespace("NIFI")
                    .withMetricData(datum);

            putMetricData(metricDataRequest);
        }

        // the alarm we create is a static one that will check if the diff is zero
        String comparisonOperator = context.getProperty(ALARM_COMPARISON_OPERATOR).getValue();
        String alarmStatistic = context.getProperty(ALARM_STATISTIC).getValue();
        String alarmPeriod = context.getProperty(ALARM_PERIOD).getValue();
        String alarmEvaluatePeriods = context.getProperty(ALARM_EVALUATE_PERIODS).getValue();
        String alarmAction = context.getProperty(ALARM_ACTION).getValue();

        PutMetricAlarmRequest putMetricAlarmRequest = new PutMetricAlarmRequest()
                .withMetricName("DIFF_" + tableName)
                .withAlarmName(environment + "_" + alarmPrefix + "_" + "DIFF_" + tableName)
                .withDimensions(dimensions).withComparisonOperator(comparisonOperator).withNamespace("NIFI")
                .withStatistic(alarmStatistic).withPeriod(Integer.parseInt(alarmPeriod))
                .withEvaluationPeriods(Integer.parseInt(alarmEvaluatePeriods)).withThreshold((double) 0)
                //.withTreatMissingData("notBreaching") // aws java SDK has to be upgraded for this
                .withAlarmDescription("The daily Count Alarm for table " + tableName).withActionsEnabled(true)
                .withAlarmActions(alarmAction);
        putAlarmData(putMetricAlarmRequest);

        session.transfer(flowFile, REL_SUCCESS);
        getLogger().info("Successfully published cloudwatch metric for {}", new Object[] { flowFile });
    } catch (final Exception e) {
        getLogger().error("Failed to publish cloudwatch metric for {} due to {}", new Object[] { flowFile, e });
        flowFile = session.penalize(flowFile);
        session.transfer(flowFile, REL_FAILURE);
    }

}

From source file:cloudwatch.src.main.java.aws.example.cloudwatch.PutMetricAlarm.java

License:Open Source License

public static void main(String[] args) {

    final String USAGE = "To run this example, supply an alarm name and instance id\n"
            + "Ex: DeleteAlarm <alarm-name> <instance-id>\n";

    if (args.length != 2) {
        System.out.println(USAGE);
        System.exit(1);/*from   w  w  w .  ja va  2s  . co m*/
    }

    String alarmName = args[0];
    String instanceId = args[1];

    final AmazonCloudWatch cloudWatch = AmazonCloudWatchClientBuilder.defaultClient();

    Dimension dimension = new Dimension().withName("InstanceId").withValue(instanceId);

    PutMetricAlarmRequest request = new PutMetricAlarmRequest().withAlarmName(alarmName)
            .withComparisonOperator(ComparisonOperator.GreaterThanThreshold).withEvaluationPeriods(1)
            .withMetricName("CPUUtilization").withNamespace("AWS/EC2").withPeriod(60)
            .withStatistic(Statistic.Average).withThreshold(70.0).withActionsEnabled(false)
            .withAlarmDescription("Alarm when server CPU utilization exceeds 70%")
            .withUnit(StandardUnit.Seconds).withDimensions(dimension);

    PutMetricAlarmResult response = cloudWatch.putMetricAlarm(request);

    System.out.printf("Successfully created alarm with name %s", alarmName);

}

From source file:com.intuit.tank.vmManager.environment.amazon.CloudwatchInstance.java

License:Open Source License

/**
 * //w  w  w.j  a v  a  2s  .c o m
 * @param instances
 * @param email
 * @param jobId
 */
public void addWatch(Collection<String> instances, String email, String jobId) {

    String alarmName = getAlarmName(email, jobId);
    for (MetricAlarm a : asynchCloudWatchClient.describeAlarms().getMetricAlarms()) {
        if (a.getAlarmName().equalsIgnoreCase(alarmName)) {
            logger.info("Alarm for job " + jobId + " and email " + email + " already exists.");
            return;
        }
    }
    List<Dimension> dimensions = new ArrayList<Dimension>();
    for (String instanceId : instances) {
        Dimension d = new Dimension().withName("InstanceId").withValue(instanceId);
        dimensions.add(d);

    }
    PutMetricAlarmRequest request = new PutMetricAlarmRequest().withActionsEnabled(true)
            .withAlarmName(alarmName).withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold)
            .withDimensions(dimensions).withAlarmActions(getOrCreateNotification(email))
            .withEvaluationPeriods(1).withPeriod(60).withThreshold(60.0D).withStatistic(Statistic.Average)
            .withMetricName("CPUUtilization").withNamespace("AWS/EC2");
    asynchCloudWatchClient.putMetricAlarm(request);
    logger.info("Created alarm " + alarmName);
}

From source file:com.netflix.spinnaker.clouddriver.ecs.services.EcsCloudMetricService.java

License:Apache License

private PutMetricAlarmRequest buildPutMetricAlarmRequest(MetricAlarm metricAlarm, String serviceName,
        Set<String> insufficientActionPolicyArns, Set<String> okActionPolicyArns,
        Set<String> alarmActionPolicyArns) {
    return new PutMetricAlarmRequest().withAlarmName(metricAlarm.getAlarmName() + "-" + serviceName)
            .withEvaluationPeriods(metricAlarm.getEvaluationPeriods()).withThreshold(metricAlarm.getThreshold())
            .withActionsEnabled(metricAlarm.getActionsEnabled())
            .withAlarmDescription(metricAlarm.getAlarmDescription())
            .withComparisonOperator(metricAlarm.getComparisonOperator())
            .withDimensions(metricAlarm.getDimensions()).withMetricName(metricAlarm.getMetricName())
            .withUnit(metricAlarm.getUnit()).withPeriod(metricAlarm.getPeriod())
            .withNamespace(metricAlarm.getNamespace()).withStatistic(metricAlarm.getStatistic())
            .withEvaluateLowSampleCountPercentile(metricAlarm.getEvaluateLowSampleCountPercentile())
            .withTreatMissingData(metricAlarm.getTreatMissingData())
            .withExtendedStatistic(metricAlarm.getExtendedStatistic())
            .withInsufficientDataActions(insufficientActionPolicyArns).withOKActions(okActionPolicyArns)
            .withAlarmActions(alarmActionPolicyArns);
}

From source file:com.pinterest.arcee.autoscaling.AwsAlarmManager.java

License:Apache License

@Override
public void putAlarmToPolicy(String action, AsgAlarmBean asgAlarmBean) throws Exception {
    PutMetricAlarmRequest request = new PutMetricAlarmRequest();
    List<String> ARNs = new LinkedList<>();
    ARNs.add(action);//  ww  w.j ava  2  s.  c om
    request.setAlarmActions(ARNs);
    if (asgAlarmBean.getFrom_aws_metric()) {
        request.setNamespace(METRIC_NAMESPACE);
    } else {
        request.setNamespace(getNameSpace(asgAlarmBean.getGroup_name()));
    }
    request.setDimensions(Arrays.asList(getDimention(asgAlarmBean.getGroup_name())));
    request.setActionsEnabled(true);

    request.setComparisonOperator(ComparisonOperator.fromValue(asgAlarmBean.getComparator()));
    request.setEvaluationPeriods(asgAlarmBean.getEvaluation_time());
    request.setPeriod(60);
    request.setStatistic(Statistic.Average);

    request.setMetricName(asgAlarmBean.getMetric_name());
    request.setThreshold(asgAlarmBean.getThreshold());
    request.setAlarmName(getAlarmName(asgAlarmBean));

    acwClient.putMetricAlarm(request);
}

From source file:de.tuhrig.deployman.launch.Launcher.java

/**
 * Starts a auto scaling launch configuration. This method is a little but complicated, since the
 * process to start a auto scaling configuration involves some steps: - create a launch
 * configuration which defines the machines to start - create an auto scaling definition which
 * defines how many machines should be started if something happens. - create an auto scaling
 * policy to which we add a metric - create the metric which is checked by the auto scaling -
 * print the starting instances/*from  w  w w . ja  v a2 s.com*/
 */
private List<Instance> runAutoScalingLaunch(Formation formation) {
    this.console.write("Run auto scaling...");

    Machine machine = formation.getMachine();
    Scaling scaling = machine.getScaling();

    AmazonAutoScalingClient autoScaling = new AutoScaling().getClient();

    try {
        CreateLaunchConfigurationRequest request = createLaunchConfigurationRequest(formation);
        autoScaling.createLaunchConfiguration(request);
        this.console.write("Created launch configuration " + scaling.getName());
    } catch (AlreadyExistsException e) {
        this.console.write("Launch configuration " + scaling.getName() + " already exists"); //$NON-NLS-2$
    }

    //
    //
    //

    try {
        CreateAutoScalingGroupRequest request = createAutoScalingRequest(scaling);
        autoScaling.createAutoScalingGroup(request);
        this.console.write("Created auto scaling group " + scaling.getGroup());
    } catch (AlreadyExistsException e) {
        this.console.write("Auto scaling group " + scaling.getGroup() + " already exists"); //$NON-NLS-2$
    }

    //
    //
    //

    PutScalingPolicyRequest request = new PutScalingPolicyRequest().withAutoScalingGroupName(scaling.getGroup())
            .withPolicyName(scaling.getPolicy()).withScalingAdjustment(1)
            .withAdjustmentType("ChangeInCapacity");

    PutScalingPolicyResult result = autoScaling.putScalingPolicy(request);

    this.console.write("Put scaling policy " + scaling.getPolicy());

    //
    //
    //

    // Scale Up

    Dimension dimension = new Dimension().withName("AutoScalingGroupName").withValue(scaling.getGroup());

    List<String> actions = new ArrayList<>();
    actions.add(result.getPolicyARN());

    PutMetricAlarmRequest upRequest = new PutMetricAlarmRequest().withAlarmName(scaling.getAlarm())
            .withMetricName("CPUUtilization").withDimensions(dimension).withNamespace("AWS/EC2")
            .withComparisonOperator(ComparisonOperator.GreaterThanThreshold).withStatistic(Statistic.Average)
            .withUnit(StandardUnit.Percent).withThreshold(60d).withPeriod(300).withEvaluationPeriods(2)
            .withAlarmActions(actions);

    AmazonCloudWatchClient cloudWatch = new CloudWatch().getClient();
    cloudWatch.putMetricAlarm(upRequest);

    this.console.write("Put alarm " + scaling.getAlarm());
    this.console.newLine();

    List<Instance> instances = new ArrayList<>();

    for (AutoScalingInstanceDetails instance : autoScaling.describeAutoScalingInstances()
            .getAutoScalingInstances()) {

        if (instance.getAutoScalingGroupName().equals(scaling.getGroup())) {

            instances.add(new Ec2().getEC2InstanceById(instance.getInstanceId()));
        }
    }

    return instances;
}

From source file:org.onebusaway.aws.monitoring.impl.alarms.AlarmsTemplate.java

License:Apache License

protected PutMetricAlarmRequest getMetricAlarmRequest(MetricName metricName) {
    return new PutMetricAlarmRequest().withActionsEnabled(true).withMetricName(metricName.toString())
            .withAlarmName(getAlarmName(metricName.toString())).withPeriod(60).withEvaluationPeriods(3)
            .withStatistic(Statistic.Average)
            .withComparisonOperator(ComparisonOperator.GreaterThanOrEqualToThreshold).withNamespace(getEnv());

}