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