View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.wal;
20  
21  import static org.apache.hadoop.hbase.wal.DefaultWALProvider.META_WAL_PROVIDER_ID;
22  import static org.apache.hadoop.hbase.wal.DefaultWALProvider.WAL_FILE_NAME_DELIMITER;
23  
24  import java.io.IOException;
25  import java.util.Collections;
26  import java.util.List;
27  import java.util.concurrent.ConcurrentHashMap;
28  import java.util.concurrent.ConcurrentMap;
29  import java.util.concurrent.locks.Lock;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.apache.hadoop.conf.Configuration;
34  import org.apache.hadoop.hbase.classification.InterfaceAudience;
35  // imports for classes still in regionserver.wal
36  import org.apache.hadoop.hbase.regionserver.wal.WALActionsListener;
37  import org.apache.hadoop.hbase.util.Bytes;
38  import org.apache.hadoop.hbase.util.IdReadWriteLock;
39  
40  /**
41   * A WAL Provider that returns a WAL per group of regions.
42   *
43   * This provider follows the decorator pattern and mainly holds the logic for WAL grouping.
44   * WAL creation/roll/close is delegated to {@link #DELEGATE_PROVIDER}
45   *
46   * Region grouping is handled via {@link RegionGroupingStrategy} and can be configured via the
47   * property "hbase.wal.regiongrouping.strategy". Current strategy choices are
48   * <ul>
49   *   <li><em>defaultStrategy</em> : Whatever strategy this version of HBase picks. currently
50   *                                  "bounded".</li>
51   *   <li><em>identity</em> : each region belongs to its own group.</li>
52   *   <li><em>bounded</em> : bounded number of groups and region evenly assigned to each group.</li>
53   * </ul>
54   * Optionally, a FQCN to a custom implementation may be given.
55   */
56  @InterfaceAudience.Private
57  public class RegionGroupingProvider implements WALProvider {
58    private static final Log LOG = LogFactory.getLog(RegionGroupingProvider.class);
59  
60    /**
61     * Map identifiers to a group number.
62     */
63    public static interface RegionGroupingStrategy {
64  
65      /**
66       * Given an identifier and a namespace, pick a group.
67       */
68      String group(final byte[] identifier, byte[] namespace);
69      void init(Configuration config, String providerId);
70    }
71  
72    /**
73     * Maps between configuration names for strategies and implementation classes.
74     */
75    static enum Strategies {
76      defaultStrategy(BoundedGroupingStrategy.class),
77      identity(IdentityGroupingStrategy.class),
78      bounded(BoundedGroupingStrategy.class),
79      namespace(NamespaceGroupingStrategy.class);
80  
81      final Class<? extends RegionGroupingStrategy> clazz;
82      Strategies(Class<? extends RegionGroupingStrategy> clazz) {
83        this.clazz = clazz;
84      }
85    }
86  
87    /**
88     * instantiate a strategy from a config property.
89     * requires conf to have already been set (as well as anything the provider might need to read).
90     */
91    RegionGroupingStrategy getStrategy(final Configuration conf, final String key,
92        final String defaultValue) throws IOException {
93      Class<? extends RegionGroupingStrategy> clazz;
94      try {
95        clazz = Strategies.valueOf(conf.get(key, defaultValue)).clazz;
96      } catch (IllegalArgumentException exception) {
97        // Fall back to them specifying a class name
98        // Note that the passed default class shouldn't actually be used, since the above only fails
99        // when there is a config value present.
100       clazz = conf.getClass(key, IdentityGroupingStrategy.class, RegionGroupingStrategy.class);
101     }
102     LOG.info("Instantiating RegionGroupingStrategy of type " + clazz);
103     try {
104       final RegionGroupingStrategy result = clazz.newInstance();
105       result.init(conf, providerId);
106       return result;
107     } catch (InstantiationException exception) {
108       LOG.error("couldn't set up region grouping strategy, check config key " +
109           REGION_GROUPING_STRATEGY);
110       LOG.debug("Exception details for failure to load region grouping strategy.", exception);
111       throw new IOException("couldn't set up region grouping strategy", exception);
112     } catch (IllegalAccessException exception) {
113       LOG.error("couldn't set up region grouping strategy, check config key " +
114           REGION_GROUPING_STRATEGY);
115       LOG.debug("Exception details for failure to load region grouping strategy.", exception);
116       throw new IOException("couldn't set up region grouping strategy", exception);
117     }
118   }
119 
120   public static final String REGION_GROUPING_STRATEGY = "hbase.wal.regiongrouping.strategy";
121   public static final String DEFAULT_REGION_GROUPING_STRATEGY = Strategies.defaultStrategy.name();
122 
123   /** delegate provider for WAL creation/roll/close */
124   public static final String DELEGATE_PROVIDER = "hbase.wal.regiongrouping.delegate.provider";
125   public static final String DEFAULT_DELEGATE_PROVIDER = WALFactory.Providers.defaultProvider
126       .name();
127 
128   private static final String META_WAL_GROUP_NAME = "meta";
129 
130   /** A group-provider mapping, make sure one-one rather than many-one mapping */
131   private final ConcurrentMap<String, WALProvider> cached = new ConcurrentHashMap<>();
132 
133   private final IdReadWriteLock createLock = new IdReadWriteLock();
134 
135   private RegionGroupingStrategy strategy = null;
136   private WALFactory factory = null;
137   private List<WALActionsListener> listeners = null;
138   private String providerId = null;
139   private Class<? extends WALProvider> providerClass;
140 
141   @Override
142   public void init(final WALFactory factory, final Configuration conf,
143       final List<WALActionsListener> listeners, final String providerId) throws IOException {
144     if (null != strategy) {
145       throw new IllegalStateException("WALProvider.init should only be called once.");
146     }
147     this.factory = factory;
148     this.listeners = null == listeners ? null : Collections.unmodifiableList(listeners);
149     StringBuilder sb = new StringBuilder().append(factory.factoryId);
150     if (providerId != null) {
151       if (providerId.startsWith(WAL_FILE_NAME_DELIMITER)) {
152         sb.append(providerId);
153       } else {
154         sb.append(WAL_FILE_NAME_DELIMITER).append(providerId);
155       }
156     }
157     this.providerId = sb.toString();
158     this.strategy = getStrategy(conf, REGION_GROUPING_STRATEGY, DEFAULT_REGION_GROUPING_STRATEGY);
159     this.providerClass = factory.getProviderClass(DELEGATE_PROVIDER, DEFAULT_DELEGATE_PROVIDER);
160   }
161 
162   private WALProvider createProvider(String group) throws IOException {
163     if (META_WAL_PROVIDER_ID.equals(providerId)) {
164       return factory.createProvider(providerClass, listeners, META_WAL_PROVIDER_ID);
165     } else {
166       return factory.createProvider(providerClass, listeners, group);
167     }
168   }
169 
170   private WAL getWAL(final String group) throws IOException {
171     WALProvider provider = cached.get(group);
172     if (provider == null) {
173       Lock lock = createLock.getLock(group.hashCode()).writeLock();
174       lock.lock();
175       try {
176         provider = cached.get(group);
177         if (provider == null) {
178           provider = createProvider(group);
179           cached.put(group, provider);
180         }
181       } finally {
182         lock.unlock();
183       }
184     }
185     return provider.getWAL(null, null);
186   }
187 
188   @Override
189   public WAL getWAL(final byte[] identifier, byte[] namespace) throws IOException {
190     final String group;
191     if (META_WAL_PROVIDER_ID.equals(this.providerId)) {
192       group = META_WAL_GROUP_NAME;
193     } else {
194       group = strategy.group(identifier, namespace);
195     }
196     return getWAL(group);
197   }
198 
199   @Override
200   public void shutdown() throws IOException {
201     // save the last exception and rethrow
202     IOException failure = null;
203     for (WALProvider provider: cached.values()) {
204       try {
205         provider.shutdown();
206       } catch (IOException e) {
207         LOG.error("Problem shutting down wal provider '" + provider + "': " + e.getMessage());
208         if (LOG.isDebugEnabled()) {
209           LOG.debug("Details of problem shutting down wal provider '" + provider + "'", e);
210         }
211         failure = e;
212       }
213     }
214     if (failure != null) {
215       throw failure;
216     }
217   }
218 
219   @Override
220   public void close() throws IOException {
221     // save the last exception and rethrow
222     IOException failure = null;
223     for (WALProvider provider : cached.values()) {
224       try {
225         provider.close();
226       } catch (IOException e) {
227         LOG.error("Problem closing wal provider '" + provider + "': " + e.getMessage());
228         if (LOG.isDebugEnabled()) {
229           LOG.debug("Details of problem closing wal provider '" + provider + "'", e);
230         }
231         failure = e;
232       }
233     }
234     if (failure != null) {
235       throw failure;
236     }
237   }
238 
239   static class IdentityGroupingStrategy implements RegionGroupingStrategy {
240     @Override
241     public void init(Configuration config, String providerId) {}
242     @Override
243     public String group(final byte[] identifier, final byte[] namespace) {
244       return "identity-" + Bytes.toString(identifier);
245     }
246   }
247 
248   @Override
249   public long getNumLogFiles() {
250     long numLogFiles = 0;
251     for (WALProvider provider : cached.values()) {
252       numLogFiles += provider.getNumLogFiles();
253     }
254     return numLogFiles;
255   }
256 
257   @Override
258   public long getLogFileSize() {
259     long logFileSize = 0;
260     for (WALProvider provider : cached.values()) {
261       logFileSize += provider.getLogFileSize();
262     }
263     return logFileSize;
264   }
265 }