001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.reef.poison.context; 020 021import org.apache.reef.evaluator.context.events.ContextStart; 022import org.apache.reef.poison.PoisonException; 023import org.apache.reef.poison.PoisonedAlarmHandler; 024import org.apache.reef.poison.params.CrashProbability; 025import org.apache.reef.poison.params.CrashTimeout; 026import org.apache.reef.tang.annotations.Parameter; 027import org.apache.reef.wake.EventHandler; 028import org.apache.reef.wake.time.Clock; 029 030import javax.inject.Inject; 031import java.util.Random; 032import java.util.logging.Level; 033import java.util.logging.Logger; 034 035/** 036 * Fault-injected handler for ContextStart. 037 */ 038public final class PoisonedContextStartHandler implements EventHandler<ContextStart> { 039 040 private static final Logger LOG = Logger.getLogger(PoisonedContextStartHandler.class.getName()); 041 042 private final Random random = new Random(); 043 044 private final double crashProbability; 045 private final int timeOut; 046 private final Clock clock; 047 048 @Inject 049 public PoisonedContextStartHandler( 050 @Parameter(CrashProbability.class) final double crashProbability, 051 @Parameter(CrashTimeout.class) final int timeOut, 052 final Clock clock) { 053 054 this.crashProbability = crashProbability; 055 this.timeOut = timeOut; 056 this.clock = clock; 057 } 058 059 @Override 060 public void onNext(final ContextStart contextStart) { 061 062 LOG.log(Level.INFO, "Starting Context poison injector with prescribed dose: {0} units", 063 this.crashProbability); 064 065 if (this.random.nextDouble() <= this.crashProbability) { 066 067 final int timeToCrash = this.random.nextInt(this.timeOut) * 1000; 068 LOG.log(Level.INFO, "Dosage lethal! Crashing in {0} msec.", timeToCrash); 069 070 if (timeToCrash == 0) { 071 throw new PoisonException("Crashed at: " + System.currentTimeMillis()); 072 } else { 073 this.clock.scheduleAlarm(timeToCrash, new PoisonedAlarmHandler()); 074 } 075 076 } else { 077 LOG.info("Dosage not lethal"); 078 } 079 } 080}