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  
20  package org.apache.hadoop.hbase.coprocessor;
21  
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.Collections;
25  import java.util.Comparator;
26  import java.util.HashSet;
27  import java.util.List;
28  import java.util.Set;
29  import java.util.SortedSet;
30  import java.util.TreeSet;
31  import java.util.UUID;
32  import java.util.concurrent.ExecutorService;
33  import java.util.concurrent.atomic.AtomicInteger;
34  
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.classification.InterfaceAudience;
38  import org.apache.hadoop.classification.InterfaceStability;
39  import org.apache.hadoop.conf.Configuration;
40  import org.apache.hadoop.fs.Path;
41  import org.apache.hadoop.hbase.Abortable;
42  import org.apache.hadoop.hbase.Coprocessor;
43  import org.apache.hadoop.hbase.CoprocessorEnvironment;
44  import org.apache.hadoop.hbase.DoNotRetryIOException;
45  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
46  import org.apache.hadoop.hbase.TableName;
47  import org.apache.hadoop.hbase.client.HTable;
48  import org.apache.hadoop.hbase.client.HTableInterface;
49  import org.apache.hadoop.hbase.client.HTableWrapper;
50  import org.apache.hadoop.hbase.util.Bytes;
51  import org.apache.hadoop.hbase.util.CoprocessorClassLoader;
52  import org.apache.hadoop.hbase.util.SortedCopyOnWriteSet;
53  import org.apache.hadoop.hbase.util.VersionInfo;
54  
55  /**
56   * Provides the common setup framework and runtime services for coprocessor
57   * invocation from HBase services.
58   * @param <E> the specific environment extension that a concrete implementation
59   * provides
60   */
61  @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.COPROC)
62  @InterfaceStability.Evolving
63  public abstract class CoprocessorHost<E extends CoprocessorEnvironment> {
64    public static final String REGION_COPROCESSOR_CONF_KEY =
65        "hbase.coprocessor.region.classes";
66    public static final String REGIONSERVER_COPROCESSOR_CONF_KEY =
67        "hbase.coprocessor.regionserver.classes";
68    public static final String USER_REGION_COPROCESSOR_CONF_KEY =
69        "hbase.coprocessor.user.region.classes";
70    public static final String MASTER_COPROCESSOR_CONF_KEY =
71        "hbase.coprocessor.master.classes";
72    public static final String WAL_COPROCESSOR_CONF_KEY =
73      "hbase.coprocessor.wal.classes";
74    public static final String ABORT_ON_ERROR_KEY = "hbase.coprocessor.abortonerror";
75    public static final boolean DEFAULT_ABORT_ON_ERROR = true;
76  
77    private static final Log LOG = LogFactory.getLog(CoprocessorHost.class);
78    protected Abortable abortable;
79    /** Ordered set of loaded coprocessors with lock */
80    protected SortedSet<E> coprocessors =
81        new SortedCopyOnWriteSet<E>(new EnvironmentPriorityComparator());
82    protected Configuration conf;
83    // unique file prefix to use for local copies of jars when classloading
84    protected String pathPrefix;
85    protected AtomicInteger loadSequence = new AtomicInteger();
86  
87    public CoprocessorHost(Abortable abortable) {
88      this.abortable = abortable;
89      this.pathPrefix = UUID.randomUUID().toString();
90    }
91  
92    /**
93     * Not to be confused with the per-object _coprocessors_ (above),
94     * coprocessorNames is static and stores the set of all coprocessors ever
95     * loaded by any thread in this JVM. It is strictly additive: coprocessors are
96     * added to coprocessorNames, by loadInstance() but are never removed, since
97     * the intention is to preserve a history of all loaded coprocessors for
98     * diagnosis in case of server crash (HBASE-4014).
99     */
100   private static Set<String> coprocessorNames =
101       Collections.synchronizedSet(new HashSet<String>());
102   public static Set<String> getLoadedCoprocessors() {
103       return coprocessorNames;
104   }
105 
106   /**
107    * Used to create a parameter to the HServerLoad constructor so that
108    * HServerLoad can provide information about the coprocessors loaded by this
109    * regionserver.
110    * (HBASE-4070: Improve region server metrics to report loaded coprocessors
111    * to master).
112    */
113   public Set<String> getCoprocessors() {
114     Set<String> returnValue = new TreeSet<String>();
115     for(CoprocessorEnvironment e: coprocessors) {
116       returnValue.add(e.getInstance().getClass().getSimpleName());
117     }
118     return returnValue;
119   }
120 
121   /**
122    * Load system coprocessors. Read the class names from configuration.
123    * Called by constructor.
124    */
125   protected void loadSystemCoprocessors(Configuration conf, String confKey) {
126     Class<?> implClass = null;
127 
128     // load default coprocessors from configure file
129     String[] defaultCPClasses = conf.getStrings(confKey);
130     if (defaultCPClasses == null || defaultCPClasses.length == 0)
131       return;
132 
133     int priority = Coprocessor.PRIORITY_SYSTEM;
134     List<E> configured = new ArrayList<E>();
135     for (String className : defaultCPClasses) {
136       className = className.trim();
137       if (findCoprocessor(className) != null) {
138         continue;
139       }
140       ClassLoader cl = this.getClass().getClassLoader();
141       Thread.currentThread().setContextClassLoader(cl);
142       try {
143         implClass = cl.loadClass(className);
144         configured.add(loadInstance(implClass, Coprocessor.PRIORITY_SYSTEM, conf));
145         LOG.info("System coprocessor " + className + " was loaded " +
146             "successfully with priority (" + priority++ + ").");
147       } catch (Throwable t) {
148         // We always abort if system coprocessors cannot be loaded
149         abortServer(className, t);
150       }
151     }
152 
153     // add entire set to the collection for COW efficiency
154     coprocessors.addAll(configured);
155   }
156 
157   /**
158    * Load a coprocessor implementation into the host
159    * @param path path to implementation jar
160    * @param className the main class name
161    * @param priority chaining priority
162    * @param conf configuration for coprocessor
163    * @throws java.io.IOException Exception
164    */
165   public E load(Path path, String className, int priority,
166       Configuration conf) throws IOException {
167     Class<?> implClass = null;
168     LOG.debug("Loading coprocessor class " + className + " with path " +
169         path + " and priority " + priority);
170 
171     ClassLoader cl = null;
172     if (path == null) {
173       try {
174         implClass = getClass().getClassLoader().loadClass(className);
175       } catch (ClassNotFoundException e) {
176         throw new IOException("No jar path specified for " + className);
177       }
178     } else {
179       cl = CoprocessorClassLoader.getClassLoader(
180         path, getClass().getClassLoader(), pathPrefix, conf);
181       try {
182         implClass = cl.loadClass(className);
183       } catch (ClassNotFoundException e) {
184         throw new IOException("Cannot load external coprocessor class " + className, e);
185       }
186     }
187 
188     //load custom code for coprocessor
189     Thread currentThread = Thread.currentThread();
190     ClassLoader hostClassLoader = currentThread.getContextClassLoader();
191     try{
192       // switch temporarily to the thread classloader for custom CP
193       currentThread.setContextClassLoader(cl);
194       E cpInstance = loadInstance(implClass, priority, conf);
195       return cpInstance;
196     } finally {
197       // restore the fresh (host) classloader
198       currentThread.setContextClassLoader(hostClassLoader);
199     }
200   }
201 
202   /**
203    * @param implClass Implementation class
204    * @param priority priority
205    * @param conf configuration
206    * @throws java.io.IOException Exception
207    */
208   public void load(Class<?> implClass, int priority, Configuration conf)
209       throws IOException {
210     E env = loadInstance(implClass, priority, conf);
211     coprocessors.add(env);
212   }
213 
214   /**
215    * @param implClass Implementation class
216    * @param priority priority
217    * @param conf configuration
218    * @throws java.io.IOException Exception
219    */
220   public E loadInstance(Class<?> implClass, int priority, Configuration conf)
221       throws IOException {
222     if (!Coprocessor.class.isAssignableFrom(implClass)) {
223       throw new IOException("Configured class " + implClass.getName() + " must implement "
224           + Coprocessor.class.getName() + " interface ");
225     }
226 
227     // create the instance
228     Coprocessor impl;
229     Object o = null;
230     try {
231       o = implClass.newInstance();
232       impl = (Coprocessor)o;
233     } catch (InstantiationException e) {
234       throw new IOException(e);
235     } catch (IllegalAccessException e) {
236       throw new IOException(e);
237     }
238     // create the environment
239     E env = createEnvironment(implClass, impl, priority, loadSequence.incrementAndGet(), conf);
240     if (env instanceof Environment) {
241       ((Environment)env).startup();
242     }
243     // HBASE-4014: maintain list of loaded coprocessors for later crash analysis
244     // if server (master or regionserver) aborts.
245     coprocessorNames.add(implClass.getName());
246     return env;
247   }
248 
249   /**
250    * Called when a new Coprocessor class is loaded
251    */
252   public abstract E createEnvironment(Class<?> implClass, Coprocessor instance,
253       int priority, int sequence, Configuration conf);
254 
255   public void shutdown(CoprocessorEnvironment e) {
256     if (e instanceof Environment) {
257       if (LOG.isDebugEnabled()) {
258         LOG.debug("Stop coprocessor " + e.getInstance().getClass().getName());
259       }
260       ((Environment)e).shutdown();
261     } else {
262       LOG.warn("Shutdown called on unknown environment: "+
263           e.getClass().getName());
264     }
265   }
266 
267   /**
268    * Find a coprocessor implementation by class name
269    * @param className the class name
270    * @return the coprocessor, or null if not found
271    */
272   public Coprocessor findCoprocessor(String className) {
273     for (E env: coprocessors) {
274       if (env.getInstance().getClass().getName().equals(className) ||
275           env.getInstance().getClass().getSimpleName().equals(className)) {
276         return env.getInstance();
277       }
278     }
279     return null;
280   }
281 
282   /**
283    * Find a coprocessor environment by class name
284    * @param className the class name
285    * @return the coprocessor, or null if not found
286    */
287   public CoprocessorEnvironment findCoprocessorEnvironment(String className) {
288     for (E env: coprocessors) {
289       if (env.getInstance().getClass().getName().equals(className) ||
290           env.getInstance().getClass().getSimpleName().equals(className)) {
291         return env;
292       }
293     }
294     return null;
295   }
296 
297   /**
298    * Retrieves the set of classloaders used to instantiate Coprocessor classes defined in external
299    * jar files.
300    * @return A set of ClassLoader instances
301    */
302   Set<ClassLoader> getExternalClassLoaders() {
303     Set<ClassLoader> externalClassLoaders = new HashSet<ClassLoader>();
304     final ClassLoader systemClassLoader = this.getClass().getClassLoader();
305     for (E env : coprocessors) {
306       ClassLoader cl = env.getInstance().getClass().getClassLoader();
307       if (cl != systemClassLoader ){
308         //do not include system classloader
309         externalClassLoaders.add(cl);
310       }
311     }
312     return externalClassLoaders;
313   }
314 
315   /**
316    * Environment priority comparator.
317    * Coprocessors are chained in sorted order.
318    */
319   static class EnvironmentPriorityComparator
320       implements Comparator<CoprocessorEnvironment> {
321     public int compare(final CoprocessorEnvironment env1,
322         final CoprocessorEnvironment env2) {
323       if (env1.getPriority() < env2.getPriority()) {
324         return -1;
325       } else if (env1.getPriority() > env2.getPriority()) {
326         return 1;
327       }
328       if (env1.getLoadSequence() < env2.getLoadSequence()) {
329         return -1;
330       } else if (env1.getLoadSequence() > env2.getLoadSequence()) {
331         return 1;
332       }
333       return 0;
334     }
335   }
336 
337   /**
338    * Encapsulation of the environment of each coprocessor
339    */
340   public static class Environment implements CoprocessorEnvironment {
341 
342     /** The coprocessor */
343     public Coprocessor impl;
344     /** Chaining priority */
345     protected int priority = Coprocessor.PRIORITY_USER;
346     /** Current coprocessor state */
347     Coprocessor.State state = Coprocessor.State.UNINSTALLED;
348     /** Accounting for tables opened by the coprocessor */
349     protected List<HTableInterface> openTables =
350       Collections.synchronizedList(new ArrayList<HTableInterface>());
351     private int seq;
352     private Configuration conf;
353 
354     /**
355      * Constructor
356      * @param impl the coprocessor instance
357      * @param priority chaining priority
358      */
359     public Environment(final Coprocessor impl, final int priority,
360         final int seq, final Configuration conf) {
361       this.impl = impl;
362       this.priority = priority;
363       this.state = Coprocessor.State.INSTALLED;
364       this.seq = seq;
365       this.conf = conf;
366     }
367 
368     /** Initialize the environment */
369     public void startup() throws IOException {
370       if (state == Coprocessor.State.INSTALLED ||
371           state == Coprocessor.State.STOPPED) {
372         state = Coprocessor.State.STARTING;
373         Thread currentThread = Thread.currentThread();
374         ClassLoader hostClassLoader = currentThread.getContextClassLoader();
375         try {
376           currentThread.setContextClassLoader(this.getClassLoader());
377           impl.start(this);
378           state = Coprocessor.State.ACTIVE;
379         } finally {
380           currentThread.setContextClassLoader(hostClassLoader);
381         }
382       } else {
383         LOG.warn("Not starting coprocessor "+impl.getClass().getName()+
384             " because not inactive (state="+state.toString()+")");
385       }
386     }
387 
388     /** Clean up the environment */
389     protected void shutdown() {
390       if (state == Coprocessor.State.ACTIVE) {
391         state = Coprocessor.State.STOPPING;
392         Thread currentThread = Thread.currentThread();
393         ClassLoader hostClassLoader = currentThread.getContextClassLoader();
394         try {
395           currentThread.setContextClassLoader(this.getClassLoader());
396           impl.stop(this);
397           state = Coprocessor.State.STOPPED;
398         } catch (IOException ioe) {
399           LOG.error("Error stopping coprocessor "+impl.getClass().getName(), ioe);
400         } finally {
401           currentThread.setContextClassLoader(hostClassLoader);
402         }
403       } else {
404         LOG.warn("Not stopping coprocessor "+impl.getClass().getName()+
405             " because not active (state="+state.toString()+")");
406       }
407       // clean up any table references
408       for (HTableInterface table: openTables) {
409         try {
410           ((HTableWrapper)table).internalClose();
411         } catch (IOException e) {
412           // nothing can be done here
413           LOG.warn("Failed to close " +
414               Bytes.toStringBinary(table.getTableName()), e);
415         }
416       }
417     }
418 
419     @Override
420     public Coprocessor getInstance() {
421       return impl;
422     }
423 
424     @Override
425     public ClassLoader getClassLoader() {
426       return impl.getClass().getClassLoader();
427     }
428 
429     @Override
430     public int getPriority() {
431       return priority;
432     }
433 
434     @Override
435     public int getLoadSequence() {
436       return seq;
437     }
438 
439     /** @return the coprocessor environment version */
440     @Override
441     public int getVersion() {
442       return Coprocessor.VERSION;
443     }
444 
445     /** @return the HBase release */
446     @Override
447     public String getHBaseVersion() {
448       return VersionInfo.getVersion();
449     }
450 
451     @Override
452     public Configuration getConfiguration() {
453       return conf;
454     }
455 
456     /**
457      * Open a table from within the Coprocessor environment
458      * @param tableName the table name
459      * @return an interface for manipulating the table
460      * @exception java.io.IOException Exception
461      */
462     @Override
463     public HTableInterface getTable(TableName tableName) throws IOException {
464       return this.getTable(tableName, HTable.getDefaultExecutor(getConfiguration()));
465     }
466 
467     /**
468      * Open a table from within the Coprocessor environment
469      * @param tableName the table name
470      * @return an interface for manipulating the table
471      * @exception java.io.IOException Exception
472      */
473     @Override
474     public HTableInterface getTable(TableName tableName, ExecutorService pool) throws IOException {
475       return HTableWrapper.createWrapper(openTables, tableName, this, pool);
476     }
477   }
478 
479   protected void abortServer(final CoprocessorEnvironment environment, final Throwable e) {
480     abortServer(environment.getInstance().getClass().getName(), e);
481   }
482 
483   protected void abortServer(final String coprocessorName, final Throwable e) {
484     String message = "The coprocessor " + coprocessorName + " threw " + e.toString();
485     LOG.error(message, e);
486     if (abortable != null) {
487       abortable.abort(message, e);
488     } else {
489       LOG.warn("No available Abortable, process was not aborted");
490     }
491   }
492 
493   /**
494    * This is used by coprocessor hooks which are declared to throw IOException
495    * (or its subtypes). For such hooks, we should handle throwable objects
496    * depending on the Throwable's type. Those which are instances of
497    * IOException should be passed on to the client. This is in conformance with
498    * the HBase idiom regarding IOException: that it represents a circumstance
499    * that should be passed along to the client for its own handling. For
500    * example, a coprocessor that implements access controls would throw a
501    * subclass of IOException, such as AccessDeniedException, in its preGet()
502    * method to prevent an unauthorized client's performing a Get on a particular
503    * table.
504    * @param env Coprocessor Environment
505    * @param e Throwable object thrown by coprocessor.
506    * @exception IOException Exception
507    */
508   protected void handleCoprocessorThrowable(final CoprocessorEnvironment env, final Throwable e)
509       throws IOException {
510     if (e instanceof IOException) {
511       throw (IOException)e;
512     }
513     // If we got here, e is not an IOException. A loaded coprocessor has a
514     // fatal bug, and the server (master or regionserver) should remove the
515     // faulty coprocessor from its set of active coprocessors. Setting
516     // 'hbase.coprocessor.abortonerror' to true will cause abortServer(),
517     // which may be useful in development and testing environments where
518     // 'failing fast' for error analysis is desired.
519     if (env.getConfiguration().getBoolean(ABORT_ON_ERROR_KEY, DEFAULT_ABORT_ON_ERROR)) {
520       // server is configured to abort.
521       abortServer(env, e);
522     } else {
523       LOG.error("Removing coprocessor '" + env.toString() + "' from " +
524           "environment because it threw:  " + e,e);
525       coprocessors.remove(env);
526       try {
527         shutdown(env);
528       } catch (Exception x) {
529         LOG.error("Uncaught exception when shutting down coprocessor '"
530             + env.toString() + "'", x);
531       }
532       throw new DoNotRetryIOException("Coprocessor: '" + env.toString() +
533           "' threw: '" + e + "' and has been removed from the active " +
534           "coprocessor set.", e);
535     }
536   }
537 }