View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.chaos.policies;
20  
21  import java.util.ArrayList;
22  import java.util.Arrays;
23  import java.util.List;
24  
25  import org.apache.hadoop.hbase.chaos.actions.Action;
26  import org.apache.hadoop.hbase.chaos.monkies.PolicyBasedChaosMonkey;
27  import org.apache.hadoop.hbase.util.Pair;
28  import org.apache.hadoop.util.StringUtils;
29  
30  /**
31   * A policy, which picks a random action according to the given weights,
32   * and performs it every configurable period.
33   */
34  public class PeriodicRandomActionPolicy extends PeriodicPolicy {
35    private List<Pair<Action, Integer>> actions;
36  
37    public PeriodicRandomActionPolicy(long periodMs, List<Pair<Action, Integer>> actions) {
38      super(periodMs);
39      this.actions = actions;
40    }
41  
42    public PeriodicRandomActionPolicy(long periodMs, Pair<Action, Integer>... actions) {
43      // We don't expect it to be modified.
44      this(periodMs, Arrays.asList(actions));
45    }
46  
47    public PeriodicRandomActionPolicy(long periodMs, Action... actions) {
48      super(periodMs);
49      this.actions = new ArrayList<Pair<Action, Integer>>(actions.length);
50      for (Action action : actions) {
51        this.actions.add(new Pair<Action, Integer>(action, 1));
52      }
53    }
54  
55    @Override
56    protected void runOneIteration() {
57      Action action = PolicyBasedChaosMonkey.selectWeightedRandomItem(actions);
58      try {
59        action.perform();
60      } catch (Exception ex) {
61        LOG.warn("Exception occured during performing action: "
62            + StringUtils.stringifyException(ex));
63      }
64    }
65  
66    @Override
67    public void init(PolicyContext context) throws Exception {
68      super.init(context);
69      for (Pair<Action, Integer> action : actions) {
70        action.getFirst().init(this.context);
71      }
72    }
73  }