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, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.chaos.policies;
019
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.List;
023import org.apache.hadoop.hbase.chaos.actions.Action;
024import org.apache.hadoop.hbase.chaos.monkies.PolicyBasedChaosMonkey;
025import org.apache.hadoop.hbase.util.Pair;
026import org.apache.hadoop.util.StringUtils;
027
028/**
029 * A policy, which picks a random action according to the given weights, and performs it every
030 * configurable period.
031 */
032public class PeriodicRandomActionPolicy extends PeriodicPolicy {
033  private List<Pair<Action, Integer>> actions;
034
035  public PeriodicRandomActionPolicy(long periodMs, List<Pair<Action, Integer>> actions) {
036    super(periodMs);
037    this.actions = actions;
038  }
039
040  public PeriodicRandomActionPolicy(long periodMs, Pair<Action, Integer>... actions) {
041    // We don't expect it to be modified.
042    this(periodMs, Arrays.asList(actions));
043  }
044
045  public PeriodicRandomActionPolicy(long periodMs, Action... actions) {
046    super(periodMs);
047    this.actions = new ArrayList<>(actions.length);
048    for (Action action : actions) {
049      this.actions.add(new Pair<>(action, 1));
050    }
051  }
052
053  @Override
054  protected void runOneIteration() {
055    Action action = PolicyBasedChaosMonkey.selectWeightedRandomItem(actions);
056    try {
057      action.perform();
058    } catch (Exception ex) {
059      LOG.warn("Exception performing action: " + StringUtils.stringifyException(ex));
060    }
061  }
062
063  @Override
064  public void init(PolicyContext context) throws Exception {
065    super.init(context);
066    for (Pair<Action, Integer> action : actions) {
067      action.getFirst().init(this.context);
068    }
069  }
070}