Search in sources :

Example 1 with Event

use of com.netflix.simianarmy.MonkeyRecorder.Event 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);
            }
        }
    }
}
Also used : VolumeAttachment(com.amazonaws.services.ec2.model.VolumeAttachment) Volume(com.amazonaws.services.ec2.model.Volume) Event(com.netflix.simianarmy.MonkeyRecorder.Event) Tag(com.amazonaws.services.ec2.model.Tag) Date(java.util.Date)

Example 2 with Event

use of com.netflix.simianarmy.MonkeyRecorder.Event in project SimianArmy by Netflix.

the class BasicJanitorMonkey method optInOrOutResource.

private Event optInOrOutResource(String resourceId, boolean optIn, String resourceRegion) {
    if (resourceRegion == null) {
        resourceRegion = region;
    }
    Resource resource = resourceTracker.getResource(resourceId, resourceRegion);
    if (resource == null) {
        return null;
    }
    EventTypes eventType = optIn ? EventTypes.OPT_IN_RESOURCE : EventTypes.OPT_OUT_RESOURCE;
    long timestamp = calendar.now().getTimeInMillis();
    // The same resource can have multiple events, so we add the timestamp to the id.
    Event evt = recorder.newEvent(Type.JANITOR, eventType, resource, resourceId + "@" + timestamp);
    recorder.recordEvent(evt);
    resource.setOptOutOfJanitor(!optIn);
    resourceTracker.addOrUpdate(resource);
    return evt;
}
Also used : Event(com.netflix.simianarmy.MonkeyRecorder.Event)

Example 3 with Event

use of com.netflix.simianarmy.MonkeyRecorder.Event in project SimianArmy by Netflix.

the class BasicScheduler method start.

/** {@inheritDoc} */
@Override
public void start(Monkey monkey, Runnable command) {
    long cycle = TimeUnit.MILLISECONDS.convert(frequency(), frequencyUnit());
    // go back 1 cycle to see if we have any events
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MILLISECOND, (int) (-1 * cycle));
    Date then = cal.getTime();
    List<Event> events = monkey.context().recorder().findEvents(monkey.type(), Collections.<String, String>emptyMap(), then);
    if (events.isEmpty()) {
        // no events so just run now
        futures.put(monkey.type().name(), scheduler.scheduleWithFixedDelay(command, 0, frequency(), frequencyUnit()));
    } else {
        // we have events, so set the start time to the time left in what would have been the last cycle
        Date eventTime = events.get(0).eventTime();
        Date now = new Date();
        long init = cycle - (now.getTime() - eventTime.getTime());
        LOGGER.info("Detected previous events within cycle, setting " + monkey.type().name() + " start to " + new Date(now.getTime() + init));
        futures.put(monkey.type().name(), scheduler.scheduleWithFixedDelay(command, init, cycle, TimeUnit.MILLISECONDS));
    }
}
Also used : Calendar(java.util.Calendar) Event(com.netflix.simianarmy.MonkeyRecorder.Event) Date(java.util.Date)

Example 4 with Event

use of com.netflix.simianarmy.MonkeyRecorder.Event in project SimianArmy by Netflix.

the class BasicSimianArmyContext method getEventReport.

@Override
public String getEventReport() {
    StringBuilder report = new StringBuilder();
    for (Event event : this.eventReport) {
        report.append(String.format("%s %s (", event.eventType(), event.id()));
        boolean isFirst = true;
        for (Entry<String, String> field : event.fields().entrySet()) {
            if (!isFirst) {
                report.append(", ");
            } else {
                isFirst = false;
            }
            report.append(String.format("%s:%s", field.getKey(), field.getValue()));
        }
        report.append(")\n");
    }
    return report.toString();
}
Also used : Event(com.netflix.simianarmy.MonkeyRecorder.Event)

Example 5 with Event

use of com.netflix.simianarmy.MonkeyRecorder.Event in project SimianArmy by Netflix.

the class BasicChaosMonkey method terminateInstance.

protected Event terminateInstance(InstanceGroup group, String inst, ChaosType chaosType) {
    Validate.notNull(group);
    Validate.notEmpty(inst);
    String prop = NS + "leashed";
    if (cfg.getBoolOrElse(prop, true)) {
        LOGGER.info("leashed ChaosMonkey prevented from killing {} from group {} [{}], set {}=false", new Object[] { inst, group.name(), group.type(), prop });
        reportEventForSummary(EventTypes.CHAOS_TERMINATION_SKIPPED, group, inst);
        return null;
    } else {
        try {
            Event evt = recordTermination(group, inst, chaosType);
            sendTerminationNotification(group, inst, chaosType);
            SshConfig sshConfig = new SshConfig(cfg);
            ChaosInstance chaosInstance = new ChaosInstance(context().cloudClient(), inst, sshConfig);
            chaosType.apply(chaosInstance);
            LOGGER.info("Terminated {} from group {} [{}] with {}", new Object[] { inst, group.name(), group.type(), chaosType.getKey() });
            reportEventForSummary(EventTypes.CHAOS_TERMINATION, group, inst);
            return evt;
        } catch (NotFoundException e) {
            LOGGER.warn("Failed to terminate " + inst + ", it does not exist. Perhaps it was already terminated");
            reportEventForSummary(EventTypes.CHAOS_TERMINATION_SKIPPED, group, inst);
            return null;
        } catch (Exception e) {
            handleTerminationError(inst, e);
            reportEventForSummary(EventTypes.CHAOS_TERMINATION_SKIPPED, group, inst);
            return null;
        }
    }
}
Also used : Event(com.netflix.simianarmy.MonkeyRecorder.Event)

Aggregations

Event (com.netflix.simianarmy.MonkeyRecorder.Event)14 Date (java.util.Date)3 HashMap (java.util.HashMap)3 Map (java.util.Map)3 Calendar (java.util.Calendar)2 Response (javax.ws.rs.core.Response)2 Tag (com.amazonaws.services.ec2.model.Tag)1 Volume (com.amazonaws.services.ec2.model.Volume)1 VolumeAttachment (com.amazonaws.services.ec2.model.VolumeAttachment)1 FeatureNotEnabledException (com.netflix.simianarmy.FeatureNotEnabledException)1 InstanceGroupNotFoundException (com.netflix.simianarmy.InstanceGroupNotFoundException)1 NotFoundException (com.netflix.simianarmy.NotFoundException)1 BasicRecorderEvent (com.netflix.simianarmy.basic.BasicRecorderEvent)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 List (java.util.List)1 GET (javax.ws.rs.GET)1 JsonGenerator (org.codehaus.jackson.JsonGenerator)1