use of com.amazonaws.services.ec2.model.VolumeAttachment in project SimianArmy by Netflix.
the class VolumeTaggingMonkey method tagVolumesWithLatestAttachment.
private void tagVolumesWithLatestAttachment(AWSClient awsClient) {
List<Volume> volumes = awsClient.describeVolumes();
LOGGER.info(String.format("Trying to tag %d volumes for Janitor Monkey meta data.", volumes.size()));
Date now = calendar.now().getTime();
for (Volume volume : volumes) {
String owner = null, instanceId = null;
Date lastDetachTime = null;
List<VolumeAttachment> attachments = volume.getAttachments();
List<Tag> tags = volume.getTags();
// by Janitor monkey.
if ("donotmark".equals(getTagValue(JanitorMonkey.JANITOR_TAG, tags))) {
LOGGER.info(String.format("The volume %s is tagged as not handled by Janitor", volume.getVolumeId()));
continue;
}
Map<String, String> janitorMetadata = parseJanitorTag(tags);
// finding the instance attached most recently.
VolumeAttachment latest = null;
for (VolumeAttachment attachment : attachments) {
if (latest == null || latest.getAttachTime().before(attachment.getAttachTime())) {
latest = attachment;
}
}
if (latest != null) {
instanceId = latest.getInstanceId();
owner = getOwnerEmail(instanceId, janitorMetadata, tags, awsClient);
}
if (latest == null || "detached".equals(latest.getState())) {
if (janitorMetadata.get(JanitorMonkey.DETACH_TIME_TAG_KEY) == null) {
// There is no attached instance and the last detached time is not set.
// Use the current time as the last detached time.
LOGGER.info(String.format("Setting the last detached time to %s for volume %s", now, volume.getVolumeId()));
lastDetachTime = now;
} else {
LOGGER.debug(String.format("The volume %s was already marked as detached at time %s", volume.getVolumeId(), janitorMetadata.get(JanitorMonkey.DETACH_TIME_TAG_KEY)));
}
} else {
// The volume is currently attached to an instance
lastDetachTime = null;
}
String existingOwner = janitorMetadata.get(BasicSimianArmyContext.GLOBAL_OWNER_TAGKEY);
if (owner == null && existingOwner != null) {
// Save the current owner in the tag when we are not able to find a owner.
owner = existingOwner;
}
if (needsUpdate(janitorMetadata, owner, instanceId, lastDetachTime)) {
Event evt = updateJanitorMetaTag(volume, instanceId, owner, lastDetachTime, awsClient);
if (evt != null) {
context().recorder().recordEvent(evt);
}
}
}
}
Aggregations