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       ((Environment)e).shutdown();
258     } else {
259       LOG.warn("Shutdown called on unknown environment: "+
260           e.getClass().getName());
261     }
262   }
263 
264   /**
265    * Find a coprocessor implementation by class name
266    * @param className the class name
267    * @return the coprocessor, or null if not found
268    */
269   public Coprocessor findCoprocessor(String className) {
270     for (E env: coprocessors) {
271       if (env.getInstance().getClass().getName().equals(className) ||
272           env.getInstance().getClass().getSimpleName().equals(className)) {
273         return env.getInstance();
274       }
275     }
276     return null;
277   }
278 
279   /**
280    * Find a coprocessor environment by class name
281    * @param className the class name
282    * @return the coprocessor, or null if not found
283    */
284   public CoprocessorEnvironment findCoprocessorEnvironment(String className) {
285     for (E env: coprocessors) {
286       if (env.getInstance().getClass().getName().equals(className) ||
287           env.getInstance().getClass().getSimpleName().equals(className)) {
288         return env;
289       }
290     }
291     return null;
292   }
293 
294   /**
295    * Retrieves the set of classloaders used to instantiate Coprocessor classes defined in external
296    * jar files.
297    * @return A set of ClassLoader instances
298    */
299   Set<ClassLoader> getExternalClassLoaders() {
300     Set<ClassLoader> externalClassLoaders = new HashSet<ClassLoader>();
301     final ClassLoader systemClassLoader = this.getClass().getClassLoader();
302     for (E env : coprocessors) {
303       ClassLoader cl = env.getInstance().getClass().getClassLoader();
304       if (cl != systemClassLoader ){
305         //do not include system classloader
306         externalClassLoaders.add(cl);
307       }
308     }
309     return externalClassLoaders;
310   }
311 
312   /**
313    * Environment priority comparator.
314    * Coprocessors are chained in sorted order.
315    */
316   static class EnvironmentPriorityComparator
317       implements Comparator<CoprocessorEnvironment> {
318     public int compare(final CoprocessorEnvironment env1,
319         final CoprocessorEnvironment env2) {
320       if (env1.getPriority() < env2.getPriority()) {
321         return -1;
322       } else if (env1.getPriority() > env2.getPriority()) {
323         return 1;
324       }
325       if (env1.getLoadSequence() < env2.getLoadSequence()) {
326         return -1;
327       } else if (env1.getLoadSequence() > env2.getLoadSequence()) {
328         return 1;
329       }
330       return 0;
331     }
332   }
333 
334   /**
335    * Encapsulation of the environment of each coprocessor
336    */
337   public static class Environment implements CoprocessorEnvironment {
338 
339     /** The coprocessor */
340     public Coprocessor impl;
341     /** Chaining priority */
342     protected int priority = Coprocessor.PRIORITY_USER;
343     /** Current coprocessor state */
344     Coprocessor.State state = Coprocessor.State.UNINSTALLED;
345     /** Accounting for tables opened by the coprocessor */
346     protected List<HTableInterface> openTables =
347       Collections.synchronizedList(new ArrayList<HTableInterface>());
348     private int seq;
349     private Configuration conf;
350 
351     /**
352      * Constructor
353      * @param impl the coprocessor instance
354      * @param priority chaining priority
355      */
356     public Environment(final Coprocessor impl, final int priority,
357         final int seq, final Configuration conf) {
358       this.impl = impl;
359       this.priority = priority;
360       this.state = Coprocessor.State.INSTALLED;
361       this.seq = seq;
362       this.conf = conf;
363     }
364 
365     /** Initialize the environment */
366     public void startup() throws IOException {
367       if (state == Coprocessor.State.INSTALLED ||
368           state == Coprocessor.State.STOPPED) {
369         state = Coprocessor.State.STARTING;
370         Thread currentThread = Thread.currentThread();
371         ClassLoader hostClassLoader = currentThread.getContextClassLoader();
372         try {
373           currentThread.setContextClassLoader(this.getClassLoader());
374           impl.start(this);
375           state = Coprocessor.State.ACTIVE;
376         } finally {
377           currentThread.setContextClassLoader(hostClassLoader);
378         }
379       } else {
380         LOG.warn("Not starting coprocessor "+impl.getClass().getName()+
381             " because not inactive (state="+state.toString()+")");
382       }
383     }
384 
385     /** Clean up the environment */
386     protected void shutdown() {
387       if (state == Coprocessor.State.ACTIVE) {
388         state = Coprocessor.State.STOPPING;
389         Thread currentThread = Thread.currentThread();
390         ClassLoader hostClassLoader = currentThread.getContextClassLoader();
391         try {
392           currentThread.setContextClassLoader(this.getClassLoader());
393           impl.stop(this);
394           state = Coprocessor.State.STOPPED;
395         } catch (IOException ioe) {
396           LOG.error("Error stopping coprocessor "+impl.getClass().getName(), ioe);
397         } finally {
398           currentThread.setContextClassLoader(hostClassLoader);
399         }
400       } else {
401         LOG.warn("Not stopping coprocessor "+impl.getClass().getName()+
402             " because not active (state="+state.toString()+")");
403       }
404       // clean up any table references
405       for (HTableInterface table: openTables) {
406         try {
407           ((HTableWrapper)table).internalClose();
408         } catch (IOException e) {
409           // nothing can be done here
410           LOG.warn("Failed to close " +
411               Bytes.toStringBinary(table.getTableName()), e);
412         }
413       }
414     }
415 
416     @Override
417     public Coprocessor getInstance() {
418       return impl;
419     }
420 
421     @Override
422     public ClassLoader getClassLoader() {
423       return impl.getClass().getClassLoader();
424     }
425 
426     @Override
427     public int getPriority() {
428       return priority;
429     }
430 
431     @Override
432     public int getLoadSequence() {
433       return seq;
434     }
435 
436     /** @return the coprocessor environment version */
437     @Override
438     public int getVersion() {
439       return Coprocessor.VERSION;
440     }
441 
442     /** @return the HBase release */
443     @Override
444     public String getHBaseVersion() {
445       return VersionInfo.getVersion();
446     }
447 
448     @Override
449     public Configuration getConfiguration() {
450       return conf;
451     }
452 
453     /**
454      * Open a table from within the Coprocessor environment
455      * @param tableName the table name
456      * @return an interface for manipulating the table
457      * @exception java.io.IOException Exception
458      */
459     @Override
460     public HTableInterface getTable(TableName tableName) throws IOException {
461       return this.getTable(tableName, HTable.getDefaultExecutor(getConfiguration()));
462     }
463 
464     /**
465      * Open a table from within the Coprocessor environment
466      * @param tableName the table name
467      * @return an interface for manipulating the table
468      * @exception java.io.IOException Exception
469      */
470     @Override
471     public HTableInterface getTable(TableName tableName, ExecutorService pool) throws IOException {
472       return HTableWrapper.createWrapper(openTables, tableName, this, pool);
473     }
474   }
475 
476   protected void abortServer(final CoprocessorEnvironment environment, final Throwable e) {
477     abortServer(environment.getInstance().getClass().getName(), e);
478   }
479 
480   protected void abortServer(final String coprocessorName, final Throwable e) {
481     String message = "The coprocessor " + coprocessorName + " threw an unexpected exception";
482     LOG.error(message, e);
483     if (abortable != null) {
484       abortable.abort(message, e);
485     } else {
486       LOG.warn("No available Abortable, process was not aborted");
487     }
488   }
489 
490   /**
491    * This is used by coprocessor hooks which are declared to throw IOException
492    * (or its subtypes). For such hooks, we should handle throwable objects
493    * depending on the Throwable's type. Those which are instances of
494    * IOException should be passed on to the client. This is in conformance with
495    * the HBase idiom regarding IOException: that it represents a circumstance
496    * that should be passed along to the client for its own handling. For
497    * example, a coprocessor that implements access controls would throw a
498    * subclass of IOException, such as AccessDeniedException, in its preGet()
499    * method to prevent an unauthorized client's performing a Get on a particular
500    * table.
501    * @param env Coprocessor Environment
502    * @param e Throwable object thrown by coprocessor.
503    * @exception IOException Exception
504    */
505   protected void handleCoprocessorThrowable(final CoprocessorEnvironment env, final Throwable e)
506       throws IOException {
507     if (e instanceof IOException) {
508       throw (IOException)e;
509     }
510     // If we got here, e is not an IOException. A loaded coprocessor has a
511     // fatal bug, and the server (master or regionserver) should remove the
512     // faulty coprocessor from its set of active coprocessors. Setting
513     // 'hbase.coprocessor.abortonerror' to true will cause abortServer(),
514     // which may be useful in development and testing environments where
515     // 'failing fast' for error analysis is desired.
516     if (env.getConfiguration().getBoolean(ABORT_ON_ERROR_KEY, DEFAULT_ABORT_ON_ERROR)) {
517       // server is configured to abort.
518       abortServer(env, e);
519     } else {
520       LOG.error("Removing coprocessor '" + env.toString() + "' from " +
521           "environment because it threw:  " + e,e);
522       coprocessors.remove(env);
523       try {
524         shutdown(env);
525       } catch (Exception x) {
526         LOG.error("Uncaught exception when shutting down coprocessor '"
527             + env.toString() + "'", x);
528       }
529       throw new DoNotRetryIOException("Coprocessor: '" + env.toString() +
530           "' threw: '" + e + "' and has been removed from the active " +
531           "coprocessor set.", e);
532     }
533   }
534 }