Example usage for com.amazonaws.services.ec2 AmazonEC2Client createTags

List of usage examples for com.amazonaws.services.ec2 AmazonEC2Client createTags

Introduction

In this page you can find the example usage for com.amazonaws.services.ec2 AmazonEC2Client createTags.

Prototype

@Override
public CreateTagsResult createTags(CreateTagsRequest request) 

Source Link

Document

Adds or overwrites the specified tags for the specified Amazon EC2 resource or resources.

Usage

From source file:com.pearson.eidetic.aws.EC2ClientMethods.java

public static void createTags(AmazonEC2Client ec2Client, CreateTagsRequest createTagsRequest,
        Integer numRetries, Integer maxApiRequestsPerSecond, String uniqueAwsAccountIdentifier) {

    for (int i = 0; i <= numRetries; i++) {
        try {//www.ja  va  2s.com
            // if the initial download attempt failed, wait for i * 500ms 
            if (i > 0) {
                long sleepTimeInMilliseconds = 500 * i;
                Threads.sleepMilliseconds(sleepTimeInMilliseconds);
            }

            AtomicLong requestAttemptCounter = GlobalVariables.apiRequestAttemptCountersByAwsAccount
                    .get(uniqueAwsAccountIdentifier);
            long currentRequestCount = requestAttemptCounter.incrementAndGet();

            while (currentRequestCount > maxApiRequestsPerSecond) {
                Threads.sleepMilliseconds(50);
                currentRequestCount = requestAttemptCounter.incrementAndGet();
            }

            try {
                ec2Client.createTags(createTagsRequest);
                try {
                    GlobalVariables.apiRequestCountersByAwsAccount.get(uniqueAwsAccountIdentifier)
                            .incrementAndGet();
                } catch (Exception e) {
                    logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier + "\","
                            + createTagsRequest.toString() + System.lineSeparator() + e.toString()
                            + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
                }
                break;
            } catch (Exception e) {
                if (e.toString().contains("TagLimitExceeded")) {
                    break;
                }
                logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier + "\","
                        + createTagsRequest.toString() + System.lineSeparator() + e.toString()
                        + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
            }

        } catch (Exception e) {
            logger.error("awsAccountNickname=\"" + uniqueAwsAccountIdentifier + "\","
                    + createTagsRequest.toString() + System.lineSeparator() + e.toString()
                    + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
        }
    }

}

From source file:dsmwatcher.DSMWatcher.java

License:Open Source License

public void isolateInstance(Instance instance, AmazonEC2Client ec2) throws Exception {
    Subnet targetIRSubnet = null;//from   w  w  w. ja  v  a2  s. co  m
    handleAutoScaledInstance(instance); //check for autoscaling, if autoscaled instance detach first 
                                        // to prevent heathcheck failure and termination
    DescribeSubnetsRequest subnetRequest = new DescribeSubnetsRequest().withSubnetIds(instance.getSubnetId());
    List<Subnet> sourceSubnet = ec2.describeSubnets(subnetRequest).getSubnets();
    String targetAZStr = sourceSubnet.get(0).getAvailabilityZone();
    for (String IRSubnet : IRSubnets) {
        subnetRequest = new DescribeSubnetsRequest().withSubnetIds(IRSubnet);
        if (targetAZStr
                .compareTo(ec2.describeSubnets(subnetRequest).getSubnets().get(0).getAvailabilityZone()) == 0) {
            targetIRSubnet = ec2.describeSubnets(subnetRequest).getSubnets().get(0);
        }
    }
    if (targetIRSubnet == null) {
        error("Unable to find an isolation subnet for instance " + instance.getInstanceId());
        return;
    }
    List<InstanceNetworkInterface> ienis = instance.getNetworkInterfaces();
    for (InstanceNetworkInterface ieni : ienis) {
        String eniTag = "";
        List<GroupIdentifier> inititalSecGroups = ieni.getGroups();
        for (GroupIdentifier secGroup : inititalSecGroups) {
            eniTag += secGroup.getGroupId() + ",";
        }
        eniTag = eniTag.substring(0, eniTag.length() - 1);
        DescribeNetworkInterfacesRequest netReq = new DescribeNetworkInterfacesRequest()
                .withNetworkInterfaceIds(ieni.getNetworkInterfaceId());
        DescribeNetworkInterfacesResult netResult = ec2.describeNetworkInterfaces(netReq);
        List<com.amazonaws.services.ec2.model.NetworkInterface> enis = netResult.getNetworkInterfaces();
        for (com.amazonaws.services.ec2.model.NetworkInterface eni : enis) {
            List<Tag> tagSet = eni.getTagSet();
            Tag saveSGTag = new Tag().withKey("PreIsolationSG").withValue(eniTag);
            Tag isolationTag = new Tag().withKey("InIsolation").withValue("True");
            tagSet.add(saveSGTag);
            tagSet.add(isolationTag);
            CreateTagsRequest ctr = new CreateTagsRequest().withResources(eni.getNetworkInterfaceId())
                    .withTags(tagSet);
            ec2.createTags(ctr);
            ModifyNetworkInterfaceAttributeRequest netReqest = new ModifyNetworkInterfaceAttributeRequest()
                    .withNetworkInterfaceId(eni.getNetworkInterfaceId()).withGroups(denyAllSG);
            ec2.modifyNetworkInterfaceAttribute(netReqest);
        }
    }
    CreateNetworkInterfaceRequest newENIReq = new CreateNetworkInterfaceRequest()
            .withSubnetId(targetIRSubnet.getSubnetId()).withGroups(IRSecGrp);
    CreateNetworkInterfaceResult newENIResult = ec2.createNetworkInterface(newENIReq);
    AttachNetworkInterfaceRequest attachReq = new AttachNetworkInterfaceRequest()
            .withNetworkInterfaceId(newENIResult.getNetworkInterface().getNetworkInterfaceId())
            .withInstanceId(instance.getInstanceId())
            .withDeviceIndex(instance.getNetworkInterfaces().size() + 1);
    AttachNetworkInterfaceResult attachResults = ec2.attachNetworkInterface(attachReq);
    NetworkInterfaceAttachmentChanges attachTerm = new NetworkInterfaceAttachmentChanges()
            .withAttachmentId(attachResults.getAttachmentId()).withDeleteOnTermination(true);
    ModifyNetworkInterfaceAttributeRequest setDeleteOnTerm = new ModifyNetworkInterfaceAttributeRequest()
            .withAttachment(attachTerm)
            .withNetworkInterfaceId(newENIResult.getNetworkInterface().getNetworkInterfaceId());
    ec2.modifyNetworkInterfaceAttribute(setDeleteOnTerm);
    CreateTagsRequest tagNewENIReq = new CreateTagsRequest();
    List<Tag> isolationENITags = newENIResult.getNetworkInterface().getTagSet();
    Tag newENITag = new Tag().withKey("IRENI").withValue("True");
    isolationENITags.add(newENITag);
    tagNewENIReq.setTags(isolationENITags);
    tagNewENIReq.withResources(newENIResult.getNetworkInterface().getNetworkInterfaceId());
    ec2.createTags(tagNewENIReq);
}

From source file:n3phele.factory.ec2.VirtualServerResource.java

License:Open Source License

/**
 * Updates virtual server object and data store state
 * //from w ww  .  java 2  s  .  co  m
 * @param item
 *            object to update
 * @param reference
 *            reference UUID used for notifications
 * @param sequence
 *            notification sequence number
 */

private void updateVirtualServer(VirtualServer item, UUID reference, int sequence)
        throws IllegalArgumentException {
    AmazonEC2Client client = null;
    client = getEC2Client(item.getAccessKey(), item.getEncryptedKey(), item.getLocation());
    String instanceId = item.getInstanceId();
    boolean madeIntoZombie = item.isZombie();
    if (!madeIntoZombie && (instanceId == null || instanceId.length() == 0)) {
        String spotId = item.getSpotId();
        if (spotId == null || spotId.length() == 0) {
            if ("Initializing".equals(item.getStatus())) {
                // Update has been called on an item under construction --
                // ignore
                log.warning("Ignoring partially formed item " + item.getUri());
                return;
            } else {
                log.severe("Improper item " + item);
            }
        }

        DescribeSpotInstanceRequestsResult update = null;
        try {
            update = client.describeSpotInstanceRequests(
                    new DescribeSpotInstanceRequestsRequest().withSpotInstanceRequestIds(spotId));
        } catch (AmazonServiceException e) {
            log.log(Level.WARNING, "EC2 error " + e.getErrorCode(), e);
            throw new WebApplicationException(e, Status.BAD_REQUEST);
        }
        instanceId = update.getSpotInstanceRequests().get(0).getInstanceId();
        item.setInstanceId(instanceId);
        //
        // After cleaning up an object, we leave it around with status ==
        // TERMINATED
        // for one refresh so that others can see the state chance via
        // polling.
        // If we come across an object with state terminated, and the
        // underlying object
        // is canceled or closed, then this is the second time the item has
        // been
        // refreshed, so now we remove the object.
        //
        if ((instanceId == null || instanceId.length() == 0) // pure spot
                // request
                && item.getStatus().equals(InstanceStateName.Terminated.toString())
                && (update.getSpotInstanceRequests().get(0).getState().equals("cancelled")
                        || update.getSpotInstanceRequests().get(0).getState().equals("closed"))) {
            delete(item);
            return;
        }

        updateStatus(item, update.getSpotInstanceRequests().get(0).getState(), reference, sequence);
        update(item);
        if (item.getStatus().equals("cancelled")) {
            log.warning("Spot Instance " + item.getUri() + " cancelled .. purging");
            try {
                deleteInstance(item, reference, sequence); // will set
                // object to
                // terminated
            } catch (Exception e) {
                log.log(Level.SEVERE, "Failed to clean up cancelled spot instance", e);
                updateStatus(item, InstanceStateName.Terminated.toString(), reference, sequence);
                delete(item);
                return;
            }

        }
        if (item.getStatus().equals("closed")
                && ((item.getInstanceId() == null) || (item.getInstanceId().length() == 0))) {
            log.warning("Spot Instance " + item.getUri() + " not fulfilled .. purging");
            updateStatus(item, InstanceStateName.Terminated.toString(), reference, sequence);
            delete(item);
            return;
        }

    }
    if (madeIntoZombie) {
        if (updateStatus(item, "terminated", reference, sequence))
            update(item);
        if (item.getStatus().equals("terminated")) {
            log.warning("Instance " + item.getName() + " terminated .. purging");
            delete(item);
            return;
        }

    } else if (instanceId != null && instanceId.length() > 0) {
        DescribeInstancesResult update = client
                .describeInstances(new DescribeInstancesRequest().withInstanceIds(item.getInstanceId()));
        if (update.getReservations() != null && update.getReservations().size() > 0) {
            Instance ec2Instance = update.getReservations().get(0).getInstances().get(0);
            String newStatus = ec2Instance.getState().getName();

            if (!item.getStatus().equals(InstanceStateName.Running.toString())
                    && InstanceStateName.Running.toString().equals(newStatus)) {
                item.setOutputParameters(Extractor.extract(ec2Instance));
                try {
                    client.createTags(new CreateTagsRequest().withResources(ec2Instance.getInstanceId())
                            .withTags(new Tag("Name", item.getName()),
                                    new Tag("n3phele-factory", Resource.get("factoryName", "ec2Factory")),
                                    new Tag("n3phele-uri", item.getUri().toString())));
                } catch (Exception ex) {
                    log.log(Level.WARNING, "Cant set tag for " + ec2Instance.getInstanceId()
                            + " associated with " + item.getName(), ex);
                }
            }

            if (updateStatus(item, newStatus, reference, sequence))
                update(item);
            if (item.getStatus().equals("terminated")) {
                log.warning("Instance " + ec2Instance.getInstanceId() + " terminated .. purging");
                delete(item);
                return;
            }
        } else {
            log.warning("Instance " + item.getInstanceId() + " not found, assumed terminated .. purging");
            updateStatus(item, InstanceStateName.Terminated.toString(), reference, sequence);
            delete(item);
            return;
        }
    }
}

From source file:org.elasticdroid.model.ControlInstancesModel.java

License:Open Source License

/**
 * Create/override tags of key name for the instances.
 * @param instances: list of instances/*from w  ww .j a va 2s. com*/
 * @return
 * <ul>
 *    <li> true: to indicate success in reassigning the tags </li>
 *    <li>IllegalArgumentException: If the number of instances != number of tags</li>
 * <li>AmazonServicesException: Serverside issues with AWS</li>
 * <li>AmazonClientException: (Probably) connectivity issues</li>
 * </ul>
 */
public Object tagInstance(List<String> instances) {
    if (instances.size() != ec2Tags.size()) {
        return new IllegalArgumentException("The number of instances should be equal to be " + "the number");
    }
    //create credentials using the BasicAWSCredentials class
    BasicAWSCredentials credentials = new BasicAWSCredentials(connectionData.get("accessKey"),
            connectionData.get("secretAccessKey"));
    //create Amazon EC2 Client object, and set tye end point to the region. params[3]
    //contains endpoint
    AmazonEC2Client amazonEC2Client = new AmazonEC2Client(credentials);

    //override the default connection endpoint if provided.
    if (connectionData.get("endpoint") != null) {
        amazonEC2Client.setEndpoint(connectionData.get("endpoint"));
    }

    //create a TagsRequest
    for (String instance : instances) {
        Log.v(TAG, "Tagging " + instance);
    }
    CreateTagsRequest request = new CreateTagsRequest(instances, ec2Tags);

    //okay, tag the instance
    try {
        amazonEC2Client.createTags(request);
    } catch (AmazonServiceException amazonServiceException) {
        return amazonServiceException;
    } catch (AmazonClientException amazonClientException) {
        return amazonClientException;
    }

    return new Boolean(true); //return true to indicate success!
}

From source file:rollsPOC2.util.AWSHelper.java

public static Instance createOrFindEC2Instance(String instanceName) throws Exception {
    Instance instance = findEC2Instance(instanceName);
    if (instance == null || instance.getState().getName().equals("terminated")
            || instance.getState().getName().equals("shutting-down")) {
        while (instance != null && instance.getState().getName().equals("shutting-down")) {
            System.out.println("Waiting for previous EC2 instance to terminate");
            Thread.sleep(10000l);
            instance = findEC2Instance(instanceName);
        }//from w  w  w .  ja v  a2  s  . c  o m
        String userDataScript = Base64.getUrlEncoder().encodeToString(Files.readAllBytes(
                Paths.get(instanceName.getClass().getResource("/scripts/postinstall-script.sh").toURI())));

        AmazonEC2Client ec2 = AppServices.getEC2Client();
        RunInstancesRequest runInstancesRequest = new RunInstancesRequest().withKeyName("bjss")
                .withImageId("ami-2d39803a").withUserData(userDataScript).withMinCount(1).withMaxCount(1)
                .withInstanceType("t2.small").withSecurityGroupIds("IPAASDemo");

        RunInstancesResult runInstancesResult = ec2.runInstances(runInstancesRequest);
        String instanceId = runInstancesResult.getReservation().getInstances().get(0).getInstanceId();
        CreateTagsRequest createTagsRequest = new CreateTagsRequest().withResources(instanceId)
                .withTags(new Tag("Name", "IPAASDemo"));
        ec2.createTags(createTagsRequest);
        instance = findEC2Instance(instanceName);
        while (instance != null && instance.getState().getName().equals("pending")) {
            System.out.println("Waiting for EC2 instance to start");
            Thread.sleep(10000l);
            instance = findEC2Instance(instanceName);
        }
    }

    return findEC2Instance(instanceName);
}