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.regionserver;
21  
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.Collection;
25  import java.util.HashMap;
26  import java.util.List;
27  import java.util.Map;
28  import java.util.NavigableSet;
29  import java.util.UUID;
30  import java.util.concurrent.ConcurrentHashMap;
31  import java.util.concurrent.ConcurrentMap;
32  import java.util.regex.Matcher;
33  
34  import com.google.common.collect.ImmutableList;
35  import com.google.common.collect.Lists;
36  import com.google.protobuf.Message;
37  import com.google.protobuf.Service;
38  
39  import org.apache.commons.collections.map.AbstractReferenceMap;
40  import org.apache.commons.collections.map.ReferenceMap;
41  import org.apache.commons.logging.Log;
42  import org.apache.commons.logging.LogFactory;
43  import org.apache.commons.math.stat.descriptive.DescriptiveStatistics;
44  import org.apache.hadoop.hbase.classification.InterfaceAudience;
45  import org.apache.hadoop.hbase.classification.InterfaceStability;
46  import org.apache.hadoop.conf.Configuration;
47  import org.apache.hadoop.fs.FileSystem;
48  import org.apache.hadoop.fs.Path;
49  import org.apache.hadoop.hbase.Cell;
50  import org.apache.hadoop.hbase.Coprocessor;
51  import org.apache.hadoop.hbase.CoprocessorEnvironment;
52  import org.apache.hadoop.hbase.HBaseConfiguration;
53  import org.apache.hadoop.hbase.HBaseInterfaceAudience;
54  import org.apache.hadoop.hbase.HConstants;
55  import org.apache.hadoop.hbase.HRegionInfo;
56  import org.apache.hadoop.hbase.HTableDescriptor;
57  import org.apache.hadoop.hbase.client.Append;
58  import org.apache.hadoop.hbase.client.Delete;
59  import org.apache.hadoop.hbase.client.Durability;
60  import org.apache.hadoop.hbase.client.Get;
61  import org.apache.hadoop.hbase.client.Increment;
62  import org.apache.hadoop.hbase.client.Mutation;
63  import org.apache.hadoop.hbase.client.Put;
64  import org.apache.hadoop.hbase.client.Result;
65  import org.apache.hadoop.hbase.client.Scan;
66  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
67  import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
68  import org.apache.hadoop.hbase.coprocessor.EndpointObserver;
69  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
70  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
71  import org.apache.hadoop.hbase.coprocessor.RegionObserver;
72  import org.apache.hadoop.hbase.coprocessor.RegionObserver.MutationType;
73  import org.apache.hadoop.hbase.filter.ByteArrayComparable;
74  import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
75  import org.apache.hadoop.hbase.io.FSDataInputStreamWrapper;
76  import org.apache.hadoop.hbase.io.Reference;
77  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
78  import org.apache.hadoop.hbase.regionserver.Region.Operation;
79  import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;
80  import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
81  import org.apache.hadoop.hbase.wal.WALKey;
82  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
83  import org.apache.hadoop.hbase.util.BoundedConcurrentLinkedQueue;
84  import org.apache.hadoop.hbase.util.Bytes;
85  import org.apache.hadoop.hbase.util.CoprocessorClassLoader;
86  import org.apache.hadoop.hbase.util.Pair;
87  
88  /**
89   * Implements the coprocessor environment and runtime support for coprocessors
90   * loaded within a {@link Region}.
91   */
92  @InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.COPROC)
93  @InterfaceStability.Evolving
94  public class RegionCoprocessorHost
95      extends CoprocessorHost<RegionCoprocessorHost.RegionEnvironment> {
96  
97    private static final Log LOG = LogFactory.getLog(RegionCoprocessorHost.class);
98    // The shared data map
99    private static ReferenceMap sharedDataMap =
100       new ReferenceMap(AbstractReferenceMap.HARD, AbstractReferenceMap.WEAK);
101 
102   /**
103    * 
104    * Encapsulation of the environment of each coprocessor
105    */
106   static class RegionEnvironment extends CoprocessorHost.Environment
107       implements RegionCoprocessorEnvironment {
108 
109     private Region region;
110     private RegionServerServices rsServices;
111     ConcurrentMap<String, Object> sharedData;
112     private static final int LATENCY_BUFFER_SIZE = 100;
113     private final BoundedConcurrentLinkedQueue<Long> coprocessorTimeNanos =
114         new BoundedConcurrentLinkedQueue<Long>(LATENCY_BUFFER_SIZE);
115     private final boolean useLegacyPre;
116     private final boolean useLegacyPost;
117 
118     /**
119      * Constructor
120      * @param impl the coprocessor instance
121      * @param priority chaining priority
122      */
123     public RegionEnvironment(final Coprocessor impl, final int priority,
124         final int seq, final Configuration conf, final Region region,
125         final RegionServerServices services, final ConcurrentMap<String, Object> sharedData) {
126       super(impl, priority, seq, conf);
127       this.region = region;
128       this.rsServices = services;
129       this.sharedData = sharedData;
130       // Pick which version of the WAL related events we'll call.
131       // This way we avoid calling the new version on older RegionObservers so
132       // we can maintain binary compatibility.
133       // See notes in javadoc for RegionObserver
134       useLegacyPre = useLegacyMethod(impl.getClass(), "preWALRestore", ObserverContext.class,
135           HRegionInfo.class, WALKey.class, WALEdit.class);
136       useLegacyPost = useLegacyMethod(impl.getClass(), "postWALRestore", ObserverContext.class,
137           HRegionInfo.class, WALKey.class, WALEdit.class);
138     }
139 
140     /** @return the region */
141     @Override
142     public Region getRegion() {
143       return region;
144     }
145 
146     /** @return reference to the region server services */
147     @Override
148     public RegionServerServices getRegionServerServices() {
149       return rsServices;
150     }
151 
152     public void shutdown() {
153       super.shutdown();
154     }
155 
156     @Override
157     public ConcurrentMap<String, Object> getSharedData() {
158       return sharedData;
159     }
160 
161     public void offerExecutionLatency(long latencyNanos) {
162       coprocessorTimeNanos.offer(latencyNanos);
163     }
164 
165     public Collection<Long> getExecutionLatenciesNanos() {
166       final List<Long> latencies = Lists.newArrayListWithCapacity(coprocessorTimeNanos.size());
167       coprocessorTimeNanos.drainTo(latencies);
168       return latencies;
169     }
170 
171     @Override
172     public HRegionInfo getRegionInfo() {
173       return region.getRegionInfo();
174     }
175 
176   }
177 
178   static class TableCoprocessorAttribute {
179     private Path path;
180     private String className;
181     private int priority;
182     private Configuration conf;
183 
184     public TableCoprocessorAttribute(Path path, String className, int priority,
185         Configuration conf) {
186       this.path = path;
187       this.className = className;
188       this.priority = priority;
189       this.conf = conf;
190     }
191 
192     public Path getPath() {
193       return path;
194     }
195 
196     public String getClassName() {
197       return className;
198     }
199 
200     public int getPriority() {
201       return priority;
202     }
203 
204     public Configuration getConf() {
205       return conf;
206     }
207   }
208 
209   /** The region server services */
210   RegionServerServices rsServices;
211   /** The region */
212   Region region;
213 
214   /**
215    * Constructor
216    * @param region the region
217    * @param rsServices interface to available region server functionality
218    * @param conf the configuration
219    */
220   public RegionCoprocessorHost(final Region region,
221       final RegionServerServices rsServices, final Configuration conf) {
222     super(rsServices);
223     this.conf = conf;
224     this.rsServices = rsServices;
225     this.region = region;
226     this.pathPrefix = Integer.toString(this.region.getRegionInfo().hashCode());
227 
228     // load system default cp's from configuration.
229     loadSystemCoprocessors(conf, REGION_COPROCESSOR_CONF_KEY);
230 
231     // load system default cp's for user tables from configuration.
232     if (!region.getRegionInfo().getTable().isSystemTable()) {
233       loadSystemCoprocessors(conf, USER_REGION_COPROCESSOR_CONF_KEY);
234     }
235 
236     // load Coprocessor From HDFS
237     loadTableCoprocessors(conf);
238   }
239 
240   static List<TableCoprocessorAttribute> getTableCoprocessorAttrsFromSchema(Configuration conf,
241       HTableDescriptor htd) {
242     List<TableCoprocessorAttribute> result = Lists.newArrayList();
243     for (Map.Entry<Bytes, Bytes> e: htd.getValues().entrySet()) {
244       String key = Bytes.toString(e.getKey().get()).trim();
245       if (HConstants.CP_HTD_ATTR_KEY_PATTERN.matcher(key).matches()) {
246         String spec = Bytes.toString(e.getValue().get()).trim();
247         // found one
248         try {
249           Matcher matcher = HConstants.CP_HTD_ATTR_VALUE_PATTERN.matcher(spec);
250           if (matcher.matches()) {
251             // jar file path can be empty if the cp class can be loaded
252             // from class loader.
253             Path path = matcher.group(1).trim().isEmpty() ?
254                 null : new Path(matcher.group(1).trim());
255             String className = matcher.group(2).trim();
256             if (className.isEmpty()) {
257               LOG.error("Malformed table coprocessor specification: key=" +
258                 key + ", spec: " + spec);
259               continue;
260             }
261             String priorityStr = matcher.group(3).trim();
262             int priority = priorityStr.isEmpty() ?
263                 Coprocessor.PRIORITY_USER : Integer.parseInt(priorityStr);
264             String cfgSpec = null;
265             try {
266               cfgSpec = matcher.group(4);
267             } catch (IndexOutOfBoundsException ex) {
268               // ignore
269             }
270             Configuration ourConf;
271             if (cfgSpec != null) {
272               cfgSpec = cfgSpec.substring(cfgSpec.indexOf('|') + 1);
273               // do an explicit deep copy of the passed configuration
274               ourConf = new Configuration(false);
275               HBaseConfiguration.merge(ourConf, conf);
276               Matcher m = HConstants.CP_HTD_ATTR_VALUE_PARAM_PATTERN.matcher(cfgSpec);
277               while (m.find()) {
278                 ourConf.set(m.group(1), m.group(2));
279               }
280             } else {
281               ourConf = conf;
282             }
283             result.add(new TableCoprocessorAttribute(path, className, priority, ourConf));
284           } else {
285             LOG.error("Malformed table coprocessor specification: key=" + key +
286               ", spec: " + spec);
287           }
288         } catch (Exception ioe) {
289           LOG.error("Malformed table coprocessor specification: key=" + key +
290             ", spec: " + spec);
291         }
292       }
293     }
294     return result;
295   }
296 
297   /**
298    * Sanity check the table coprocessor attributes of the supplied schema. Will
299    * throw an exception if there is a problem.
300    * @param conf
301    * @param htd
302    * @throws IOException
303    */
304   public static void testTableCoprocessorAttrs(final Configuration conf,
305       final HTableDescriptor htd) throws IOException {
306     String pathPrefix = UUID.randomUUID().toString();
307     for (TableCoprocessorAttribute attr: getTableCoprocessorAttrsFromSchema(conf, htd)) {
308       if (attr.getPriority() < 0) {
309         throw new IOException("Priority for coprocessor " + attr.getClassName() +
310           " cannot be less than 0");
311       }
312       ClassLoader old = Thread.currentThread().getContextClassLoader();
313       try {
314         ClassLoader cl;
315         if (attr.getPath() != null) {
316           cl = CoprocessorClassLoader.getClassLoader(attr.getPath(),
317             CoprocessorHost.class.getClassLoader(), pathPrefix, conf);
318         } else {
319           cl = CoprocessorHost.class.getClassLoader();
320         }
321         Thread.currentThread().setContextClassLoader(cl);
322         cl.loadClass(attr.getClassName());
323       } catch (ClassNotFoundException e) {
324         throw new IOException("Class " + attr.getClassName() + " cannot be loaded", e);
325       } finally {
326         Thread.currentThread().setContextClassLoader(old);
327       }
328     }
329   }
330 
331   void loadTableCoprocessors(final Configuration conf) {
332     boolean coprocessorsEnabled = conf.getBoolean(COPROCESSORS_ENABLED_CONF_KEY,
333       DEFAULT_COPROCESSORS_ENABLED);
334     boolean tableCoprocessorsEnabled = conf.getBoolean(USER_COPROCESSORS_ENABLED_CONF_KEY,
335       DEFAULT_USER_COPROCESSORS_ENABLED);
336     if (!(coprocessorsEnabled && tableCoprocessorsEnabled)) {
337       return;
338     }
339 
340     // scan the table attributes for coprocessor load specifications
341     // initialize the coprocessors
342     List<RegionEnvironment> configured = new ArrayList<RegionEnvironment>();
343     for (TableCoprocessorAttribute attr: getTableCoprocessorAttrsFromSchema(conf, 
344         region.getTableDesc())) {
345       // Load encompasses classloading and coprocessor initialization
346       try {
347         RegionEnvironment env = load(attr.getPath(), attr.getClassName(), attr.getPriority(),
348           attr.getConf());
349         configured.add(env);
350         LOG.info("Loaded coprocessor " + attr.getClassName() + " from HTD of " +
351             region.getTableDesc().getTableName().getNameAsString() + " successfully.");
352       } catch (Throwable t) {
353         // Coprocessor failed to load, do we abort on error?
354         if (conf.getBoolean(ABORT_ON_ERROR_KEY, DEFAULT_ABORT_ON_ERROR)) {
355           abortServer(attr.getClassName(), t);
356         } else {
357           LOG.error("Failed to load coprocessor " + attr.getClassName(), t);
358         }
359       }
360     }
361     // add together to coprocessor set for COW efficiency
362     coprocessors.addAll(configured);
363   }
364 
365   @Override
366   public RegionEnvironment createEnvironment(Class<?> implClass,
367       Coprocessor instance, int priority, int seq, Configuration conf) {
368     // Check if it's an Endpoint.
369     // Due to current dynamic protocol design, Endpoint
370     // uses a different way to be registered and executed.
371     // It uses a visitor pattern to invoke registered Endpoint
372     // method.
373     for (Class<?> c : implClass.getInterfaces()) {
374       if (CoprocessorService.class.isAssignableFrom(c)) {
375         region.registerService( ((CoprocessorService)instance).getService() );
376       }
377     }
378     ConcurrentMap<String, Object> classData;
379     // make sure only one thread can add maps
380     synchronized (sharedDataMap) {
381       // as long as at least one RegionEnvironment holds on to its classData it will
382       // remain in this map
383       classData = (ConcurrentMap<String, Object>)sharedDataMap.get(implClass.getName());
384       if (classData == null) {
385         classData = new ConcurrentHashMap<String, Object>();
386         sharedDataMap.put(implClass.getName(), classData);
387       }
388     }
389     return new RegionEnvironment(instance, priority, seq, conf, region,
390         rsServices, classData);
391   }
392 
393   /**
394    * HBASE-4014 : This is used by coprocessor hooks which are not declared to throw exceptions.
395    *
396    * For example, {@link
397    * org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost#preOpen()} and
398    * {@link org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost#postOpen()} are such hooks.
399    *
400    * See also
401    * {@link org.apache.hadoop.hbase.master.MasterCoprocessorHost#handleCoprocessorThrowable(
402    *    CoprocessorEnvironment, Throwable)}
403    * @param env The coprocessor that threw the exception.
404    * @param e The exception that was thrown.
405    */
406   private void handleCoprocessorThrowableNoRethrow(
407       final CoprocessorEnvironment env, final Throwable e) {
408     try {
409       handleCoprocessorThrowable(env,e);
410     } catch (IOException ioe) {
411       // We cannot throw exceptions from the caller hook, so ignore.
412       LOG.warn(
413         "handleCoprocessorThrowable() threw an IOException while attempting to handle Throwable " +
414         e + ". Ignoring.",e);
415     }
416   }
417 
418   /**
419    * Invoked before a region open.
420    *
421    * @throws IOException Signals that an I/O exception has occurred.
422    */
423   public void preOpen() throws IOException {
424     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
425       @Override
426       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
427           throws IOException {
428         oserver.preOpen(ctx);
429       }
430     });
431   }
432 
433   /**
434    * Invoked after a region open
435    */
436   public void postOpen() {
437     try {
438       execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
439         @Override
440         public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
441             throws IOException {
442           oserver.postOpen(ctx);
443         }
444       });
445     } catch (IOException e) {
446       LOG.warn(e);
447     }
448   }
449 
450   /**
451    * Invoked after log replay on region
452    */
453   public void postLogReplay() {
454     try {
455       execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
456         @Override
457         public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
458             throws IOException {
459           oserver.postLogReplay(ctx);
460         }
461       });
462     } catch (IOException e) {
463       LOG.warn(e);
464     }
465   }
466 
467   /**
468    * Invoked before a region is closed
469    * @param abortRequested true if the server is aborting
470    */
471   public void preClose(final boolean abortRequested) throws IOException {
472     execOperation(false, new RegionOperation() {
473       @Override
474       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
475           throws IOException {
476         oserver.preClose(ctx, abortRequested);
477       }
478     });
479   }
480 
481   /**
482    * Invoked after a region is closed
483    * @param abortRequested true if the server is aborting
484    */
485   public void postClose(final boolean abortRequested) {
486     try {
487       execOperation(false, new RegionOperation() {
488         @Override
489         public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
490             throws IOException {
491           oserver.postClose(ctx, abortRequested);
492         }
493         public void postEnvCall(RegionEnvironment env) {
494           shutdown(env);
495         }
496       });
497     } catch (IOException e) {
498       LOG.warn(e);
499     }
500   }
501 
502   /**
503    * See
504    * {@link RegionObserver#preCompactScannerOpen(ObserverContext, Store, List, ScanType, long, InternalScanner, CompactionRequest)}
505    */
506   public InternalScanner preCompactScannerOpen(final Store store,
507       final List<StoreFileScanner> scanners, final ScanType scanType, final long earliestPutTs,
508       final CompactionRequest request) throws IOException {
509     return execOperationWithResult(null,
510         coprocessors.isEmpty() ? null : new RegionOperationWithResult<InternalScanner>() {
511       @Override
512       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
513           throws IOException {
514         setResult(oserver.preCompactScannerOpen(ctx, store, scanners, scanType,
515           earliestPutTs, getResult(), request));
516       }
517     });
518   }
519 
520   /**
521    * Called prior to selecting the {@link StoreFile}s for compaction from the list of currently
522    * available candidates.
523    * @param store The store where compaction is being requested
524    * @param candidates The currently available store files
525    * @param request custom compaction request
526    * @return If {@code true}, skip the normal selection process and use the current list
527    * @throws IOException
528    */
529   public boolean preCompactSelection(final Store store, final List<StoreFile> candidates,
530       final CompactionRequest request) throws IOException {
531     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
532       @Override
533       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
534           throws IOException {
535         oserver.preCompactSelection(ctx, store, candidates, request);
536       }
537     });
538   }
539 
540   /**
541    * Called after the {@link StoreFile}s to be compacted have been selected from the available
542    * candidates.
543    * @param store The store where compaction is being requested
544    * @param selected The store files selected to compact
545    * @param request custom compaction
546    */
547   public void postCompactSelection(final Store store, final ImmutableList<StoreFile> selected,
548       final CompactionRequest request) {
549     try {
550       execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
551         @Override
552         public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
553             throws IOException {
554           oserver.postCompactSelection(ctx, store, selected, request);
555         }
556       });
557     } catch (IOException e) {
558       LOG.warn(e);
559     }
560   }
561 
562   /**
563    * Called prior to rewriting the store files selected for compaction
564    * @param store the store being compacted
565    * @param scanner the scanner used to read store data during compaction
566    * @param scanType type of Scan
567    * @param request the compaction that will be executed
568    * @throws IOException
569    */
570   public InternalScanner preCompact(final Store store, final InternalScanner scanner,
571       final ScanType scanType, final CompactionRequest request) throws IOException {
572     return execOperationWithResult(false, scanner,
573         coprocessors.isEmpty() ? null : new RegionOperationWithResult<InternalScanner>() {
574       @Override
575       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
576           throws IOException {
577         setResult(oserver.preCompact(ctx, store, getResult(), scanType, request));
578       }
579     });
580   }
581 
582   /**
583    * Called after the store compaction has completed.
584    * @param store the store being compacted
585    * @param resultFile the new store file written during compaction
586    * @param request the compaction that is being executed
587    * @throws IOException
588    */
589   public void postCompact(final Store store, final StoreFile resultFile,
590       final CompactionRequest request) throws IOException {
591     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
592       @Override
593       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
594           throws IOException {
595         oserver.postCompact(ctx, store, resultFile, request);
596       }
597     });
598   }
599 
600   /**
601    * Invoked before a memstore flush
602    * @throws IOException
603    */
604   public InternalScanner preFlush(final Store store, final InternalScanner scanner)
605       throws IOException {
606     return execOperationWithResult(false, scanner,
607         coprocessors.isEmpty() ? null : new RegionOperationWithResult<InternalScanner>() {
608       @Override
609       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
610           throws IOException {
611         setResult(oserver.preFlush(ctx, store, getResult()));
612       }
613     });
614   }
615 
616   /**
617    * Invoked before a memstore flush
618    * @throws IOException
619    */
620   public void preFlush() throws IOException {
621     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
622       @Override
623       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
624           throws IOException {
625         oserver.preFlush(ctx);
626       }
627     });
628   }
629 
630   /**
631    * See
632    * {@link RegionObserver#preFlushScannerOpen(ObserverContext,
633    *    Store, KeyValueScanner, InternalScanner)}
634    */
635   public InternalScanner preFlushScannerOpen(final Store store,
636       final KeyValueScanner memstoreScanner) throws IOException {
637     return execOperationWithResult(null,
638         coprocessors.isEmpty() ? null : new RegionOperationWithResult<InternalScanner>() {
639       @Override
640       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
641           throws IOException {
642         setResult(oserver.preFlushScannerOpen(ctx, store, memstoreScanner, getResult()));
643       }
644     });
645   }
646 
647   /**
648    * Invoked after a memstore flush
649    * @throws IOException
650    */
651   public void postFlush() throws IOException {
652     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
653       @Override
654       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
655           throws IOException {
656         oserver.postFlush(ctx);
657       }
658     });
659   }
660 
661   /**
662    * Invoked after a memstore flush
663    * @throws IOException
664    */
665   public void postFlush(final Store store, final StoreFile storeFile) throws IOException {
666     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
667       @Override
668       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
669           throws IOException {
670         oserver.postFlush(ctx, store, storeFile);
671       }
672     });
673   }
674 
675   /**
676    * Invoked just before a split
677    * @throws IOException
678    */
679   // TODO: Deprecate this
680   public void preSplit() throws IOException {
681     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
682       @Override
683       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
684           throws IOException {
685         oserver.preSplit(ctx);
686       }
687     });
688   }
689 
690   /**
691    * Invoked just before a split
692    * @throws IOException
693    */
694   public void preSplit(final byte[] splitRow) throws IOException {
695     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
696       @Override
697       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
698           throws IOException {
699         oserver.preSplit(ctx, splitRow);
700       }
701     });
702   }
703 
704   /**
705    * Invoked just after a split
706    * @param l the new left-hand daughter region
707    * @param r the new right-hand daughter region
708    * @throws IOException
709    */
710   public void postSplit(final Region l, final Region r) throws IOException {
711     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
712       @Override
713       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
714           throws IOException {
715         oserver.postSplit(ctx, l, r);
716       }
717     });
718   }
719 
720   public boolean preSplitBeforePONR(final byte[] splitKey,
721       final List<Mutation> metaEntries) throws IOException {
722     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
723       @Override
724       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
725           throws IOException {
726         oserver.preSplitBeforePONR(ctx, splitKey, metaEntries);
727       }
728     });
729   }
730 
731   public void preSplitAfterPONR() throws IOException {
732     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
733       @Override
734       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
735           throws IOException {
736         oserver.preSplitAfterPONR(ctx);
737       }
738     });
739   }
740 
741   /**
742    * Invoked just before the rollback of a failed split is started
743    * @throws IOException
744    */
745   public void preRollBackSplit() throws IOException {
746     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
747       @Override
748       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
749           throws IOException {
750         oserver.preRollBackSplit(ctx);
751       }
752     });
753   }
754 
755   /**
756    * Invoked just after the rollback of a failed split is done
757    * @throws IOException
758    */
759   public void postRollBackSplit() throws IOException {
760     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
761       @Override
762       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
763           throws IOException {
764         oserver.postRollBackSplit(ctx);
765       }
766     });
767   }
768 
769   /**
770    * Invoked after a split is completed irrespective of a failure or success.
771    * @throws IOException
772    */
773   public void postCompleteSplit() throws IOException {
774     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
775       @Override
776       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
777           throws IOException {
778         oserver.postCompleteSplit(ctx);
779       }
780     });
781   }
782 
783   // RegionObserver support
784 
785   /**
786    * @param get the Get request
787    * @return true if default processing should be bypassed
788    * @exception IOException Exception
789    */
790   public boolean preGet(final Get get, final List<Cell> results)
791       throws IOException {
792     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
793       @Override
794       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
795           throws IOException {
796         oserver.preGetOp(ctx, get, results);
797       }
798     });
799   }
800 
801   /**
802    * @param get the Get request
803    * @param results the result sett
804    * @exception IOException Exception
805    */
806   public void postGet(final Get get, final List<Cell> results)
807       throws IOException {
808     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
809       @Override
810       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
811           throws IOException {
812         oserver.postGetOp(ctx, get, results);
813       }
814     });
815   }
816 
817   /**
818    * @param get the Get request
819    * @return true or false to return to client if bypassing normal operation,
820    * or null otherwise
821    * @exception IOException Exception
822    */
823   public Boolean preExists(final Get get) throws IOException {
824     return execOperationWithResult(true, false,
825         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
826       @Override
827       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
828           throws IOException {
829         setResult(oserver.preExists(ctx, get, getResult()));
830       }
831     });
832   }
833 
834   /**
835    * @param get the Get request
836    * @param exists the result returned by the region server
837    * @return the result to return to the client
838    * @exception IOException Exception
839    */
840   public boolean postExists(final Get get, boolean exists)
841       throws IOException {
842     return execOperationWithResult(exists,
843         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
844       @Override
845       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
846           throws IOException {
847         setResult(oserver.postExists(ctx, get, getResult()));
848       }
849     });
850   }
851 
852   /**
853    * @param put The Put object
854    * @param edit The WALEdit object.
855    * @param durability The durability used
856    * @return true if default processing should be bypassed
857    * @exception IOException Exception
858    */
859   public boolean prePut(final Put put, final WALEdit edit, final Durability durability)
860       throws IOException {
861     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
862       @Override
863       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
864           throws IOException {
865         oserver.prePut(ctx, put, edit, durability);
866       }
867     });
868   }
869 
870   /**
871    * @param mutation - the current mutation
872    * @param kv - the current cell
873    * @param byteNow - current timestamp in bytes
874    * @param get - the get that could be used
875    * Note that the get only does not specify the family and qualifier that should be used
876    * @return true if default processing should be bypassed
877    * @exception IOException
878    *              Exception
879    */
880   public boolean prePrepareTimeStampForDeleteVersion(final Mutation mutation,
881       final Cell kv, final byte[] byteNow, final Get get) throws IOException {
882     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
883       @Override
884       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
885           throws IOException {
886         oserver.prePrepareTimeStampForDeleteVersion(ctx, mutation, kv, byteNow, get);
887       }
888     });
889   }
890 
891   /**
892    * @param put The Put object
893    * @param edit The WALEdit object.
894    * @param durability The durability used
895    * @exception IOException Exception
896    */
897   public void postPut(final Put put, final WALEdit edit, final Durability durability)
898       throws IOException {
899     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
900       @Override
901       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
902           throws IOException {
903         oserver.postPut(ctx, put, edit, durability);
904       }
905     });
906   }
907 
908   /**
909    * @param delete The Delete object
910    * @param edit The WALEdit object.
911    * @param durability The durability used
912    * @return true if default processing should be bypassed
913    * @exception IOException Exception
914    */
915   public boolean preDelete(final Delete delete, final WALEdit edit, final Durability durability)
916       throws IOException {
917     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
918       @Override
919       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
920           throws IOException {
921         oserver.preDelete(ctx, delete, edit, durability);
922       }
923     });
924   }
925 
926   /**
927    * @param delete The Delete object
928    * @param edit The WALEdit object.
929    * @param durability The durability used
930    * @exception IOException Exception
931    */
932   public void postDelete(final Delete delete, final WALEdit edit, final Durability durability)
933       throws IOException {
934     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
935       @Override
936       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
937           throws IOException {
938         oserver.postDelete(ctx, delete, edit, durability);
939       }
940     });
941   }
942 
943   /**
944    * @param miniBatchOp
945    * @return true if default processing should be bypassed
946    * @throws IOException
947    */
948   public boolean preBatchMutate(
949       final MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
950     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
951       @Override
952       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
953           throws IOException {
954         oserver.preBatchMutate(ctx, miniBatchOp);
955       }
956     });
957   }
958 
959   /**
960    * @param miniBatchOp
961    * @throws IOException
962    */
963   public void postBatchMutate(
964       final MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
965     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
966       @Override
967       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
968           throws IOException {
969         oserver.postBatchMutate(ctx, miniBatchOp);
970       }
971     });
972   }
973 
974   public void postBatchMutateIndispensably(
975       final MiniBatchOperationInProgress<Mutation> miniBatchOp, final boolean success)
976       throws IOException {
977     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
978       @Override
979       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
980           throws IOException {
981         oserver.postBatchMutateIndispensably(ctx, miniBatchOp, success);
982       }
983     });
984   }
985 
986   /**
987    * @param row row to check
988    * @param family column family
989    * @param qualifier column qualifier
990    * @param compareOp the comparison operation
991    * @param comparator the comparator
992    * @param put data to put if check succeeds
993    * @return true or false to return to client if default processing should
994    * be bypassed, or null otherwise
995    * @throws IOException e
996    */
997   public Boolean preCheckAndPut(final byte [] row, final byte [] family,
998       final byte [] qualifier, final CompareOp compareOp,
999       final ByteArrayComparable comparator, final Put put)
1000       throws IOException {
1001     return execOperationWithResult(true, false,
1002         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1003       @Override
1004       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1005           throws IOException {
1006         setResult(oserver.preCheckAndPut(ctx, row, family, qualifier,
1007           compareOp, comparator, put, getResult()));
1008       }
1009     });
1010   }
1011 
1012   /**
1013    * @param row row to check
1014    * @param family column family
1015    * @param qualifier column qualifier
1016    * @param compareOp the comparison operation
1017    * @param comparator the comparator
1018    * @param put data to put if check succeeds
1019    * @return true or false to return to client if default processing should
1020    * be bypassed, or null otherwise
1021    * @throws IOException e
1022    */
1023   public Boolean preCheckAndPutAfterRowLock(final byte[] row, final byte[] family,
1024       final byte[] qualifier, final CompareOp compareOp, final ByteArrayComparable comparator,
1025       final Put put) throws IOException {
1026     return execOperationWithResult(true, false,
1027         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1028       @Override
1029       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1030           throws IOException {
1031         setResult(oserver.preCheckAndPutAfterRowLock(ctx, row, family, qualifier,
1032           compareOp, comparator, put, getResult()));
1033       }
1034     });
1035   }
1036 
1037   /**
1038    * @param row row to check
1039    * @param family column family
1040    * @param qualifier column qualifier
1041    * @param compareOp the comparison operation
1042    * @param comparator the comparator
1043    * @param put data to put if check succeeds
1044    * @throws IOException e
1045    */
1046   public boolean postCheckAndPut(final byte [] row, final byte [] family,
1047       final byte [] qualifier, final CompareOp compareOp,
1048       final ByteArrayComparable comparator, final Put put,
1049       boolean result) throws IOException {
1050     return execOperationWithResult(result,
1051         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1052       @Override
1053       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1054           throws IOException {
1055         setResult(oserver.postCheckAndPut(ctx, row, family, qualifier,
1056           compareOp, comparator, put, getResult()));
1057       }
1058     });
1059   }
1060 
1061   /**
1062    * @param row row to check
1063    * @param family column family
1064    * @param qualifier column qualifier
1065    * @param compareOp the comparison operation
1066    * @param comparator the comparator
1067    * @param delete delete to commit if check succeeds
1068    * @return true or false to return to client if default processing should
1069    * be bypassed, or null otherwise
1070    * @throws IOException e
1071    */
1072   public Boolean preCheckAndDelete(final byte [] row, final byte [] family,
1073       final byte [] qualifier, final CompareOp compareOp,
1074       final ByteArrayComparable comparator, final Delete delete)
1075       throws IOException {
1076     return execOperationWithResult(true, false,
1077         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1078       @Override
1079       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1080           throws IOException {
1081         setResult(oserver.preCheckAndDelete(ctx, row, family,
1082             qualifier, compareOp, comparator, delete, getResult()));
1083       }
1084     });
1085   }
1086 
1087   /**
1088    * @param row row to check
1089    * @param family column family
1090    * @param qualifier column qualifier
1091    * @param compareOp the comparison operation
1092    * @param comparator the comparator
1093    * @param delete delete to commit if check succeeds
1094    * @return true or false to return to client if default processing should
1095    * be bypassed, or null otherwise
1096    * @throws IOException e
1097    */
1098   public Boolean preCheckAndDeleteAfterRowLock(final byte[] row, final byte[] family,
1099       final byte[] qualifier, final CompareOp compareOp, final ByteArrayComparable comparator,
1100       final Delete delete) throws IOException {
1101     return execOperationWithResult(true, false,
1102         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1103       @Override
1104       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1105           throws IOException {
1106         setResult(oserver.preCheckAndDeleteAfterRowLock(ctx, row,
1107               family, qualifier, compareOp, comparator, delete, getResult()));
1108       }
1109     });
1110   }
1111 
1112   /**
1113    * @param row row to check
1114    * @param family column family
1115    * @param qualifier column qualifier
1116    * @param compareOp the comparison operation
1117    * @param comparator the comparator
1118    * @param delete delete to commit if check succeeds
1119    * @throws IOException e
1120    */
1121   public boolean postCheckAndDelete(final byte [] row, final byte [] family,
1122       final byte [] qualifier, final CompareOp compareOp,
1123       final ByteArrayComparable comparator, final Delete delete,
1124       boolean result) throws IOException {
1125     return execOperationWithResult(result,
1126         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1127       @Override
1128       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1129           throws IOException {
1130         setResult(oserver.postCheckAndDelete(ctx, row, family,
1131             qualifier, compareOp, comparator, delete, getResult()));
1132       }
1133     });
1134   }
1135 
1136   /**
1137    * @param append append object
1138    * @return result to return to client if default operation should be
1139    * bypassed, null otherwise
1140    * @throws IOException if an error occurred on the coprocessor
1141    */
1142   public Result preAppend(final Append append) throws IOException {
1143     return execOperationWithResult(true, null,
1144         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Result>() {
1145       @Override
1146       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1147           throws IOException {
1148         setResult(oserver.preAppend(ctx, append));
1149       }
1150     });
1151   }
1152 
1153   /**
1154    * @param append append object
1155    * @return result to return to client if default operation should be
1156    * bypassed, null otherwise
1157    * @throws IOException if an error occurred on the coprocessor
1158    */
1159   public Result preAppendAfterRowLock(final Append append) throws IOException {
1160     return execOperationWithResult(true, null,
1161         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Result>() {
1162       @Override
1163       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1164           throws IOException {
1165         setResult(oserver.preAppendAfterRowLock(ctx, append));
1166       }
1167     });
1168   }
1169 
1170   /**
1171    * @param increment increment object
1172    * @return result to return to client if default operation should be
1173    * bypassed, null otherwise
1174    * @throws IOException if an error occurred on the coprocessor
1175    */
1176   public Result preIncrement(final Increment increment) throws IOException {
1177     return execOperationWithResult(true, null,
1178         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Result>() {
1179       @Override
1180       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1181           throws IOException {
1182         setResult(oserver.preIncrement(ctx, increment));
1183       }
1184     });
1185   }
1186 
1187   /**
1188    * @param increment increment object
1189    * @return result to return to client if default operation should be
1190    * bypassed, null otherwise
1191    * @throws IOException if an error occurred on the coprocessor
1192    */
1193   public Result preIncrementAfterRowLock(final Increment increment) throws IOException {
1194     return execOperationWithResult(true, null,
1195         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Result>() {
1196       @Override
1197       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1198           throws IOException {
1199         setResult(oserver.preIncrementAfterRowLock(ctx, increment));
1200       }
1201     });
1202   }
1203 
1204   /**
1205    * @param append Append object
1206    * @param result the result returned by the append
1207    * @throws IOException if an error occurred on the coprocessor
1208    */
1209   public void postAppend(final Append append, final Result result) throws IOException {
1210     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
1211       @Override
1212       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1213           throws IOException {
1214         oserver.postAppend(ctx, append, result);
1215       }
1216     });
1217   }
1218 
1219   /**
1220    * @param increment increment object
1221    * @param result the result returned by postIncrement
1222    * @throws IOException if an error occurred on the coprocessor
1223    */
1224   public Result postIncrement(final Increment increment, Result result) throws IOException {
1225     return execOperationWithResult(result,
1226         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Result>() {
1227       @Override
1228       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1229           throws IOException {
1230         setResult(oserver.postIncrement(ctx, increment, getResult()));
1231       }
1232     });
1233   }
1234 
1235   /**
1236    * @param scan the Scan specification
1237    * @return scanner id to return to client if default operation should be
1238    * bypassed, false otherwise
1239    * @exception IOException Exception
1240    */
1241   public RegionScanner preScannerOpen(final Scan scan) throws IOException {
1242     return execOperationWithResult(true, null,
1243         coprocessors.isEmpty() ? null : new RegionOperationWithResult<RegionScanner>() {
1244       @Override
1245       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1246           throws IOException {
1247         setResult(oserver.preScannerOpen(ctx, scan, getResult()));
1248       }
1249     });
1250   }
1251 
1252   /**
1253    * See
1254    * {@link RegionObserver#preStoreScannerOpen(ObserverContext,
1255    *    Store, Scan, NavigableSet, KeyValueScanner)}
1256    */
1257   public KeyValueScanner preStoreScannerOpen(final Store store, final Scan scan,
1258       final NavigableSet<byte[]> targetCols) throws IOException {
1259     return execOperationWithResult(null,
1260         coprocessors.isEmpty() ? null : new RegionOperationWithResult<KeyValueScanner>() {
1261       @Override
1262       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1263           throws IOException {
1264         setResult(oserver.preStoreScannerOpen(ctx, store, scan, targetCols, getResult()));
1265       }
1266     });
1267   }
1268 
1269   /**
1270    * @param scan the Scan specification
1271    * @param s the scanner
1272    * @return the scanner instance to use
1273    * @exception IOException Exception
1274    */
1275   public RegionScanner postScannerOpen(final Scan scan, RegionScanner s) throws IOException {
1276     return execOperationWithResult(s,
1277         coprocessors.isEmpty() ? null : new RegionOperationWithResult<RegionScanner>() {
1278       @Override
1279       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1280           throws IOException {
1281         setResult(oserver.postScannerOpen(ctx, scan, getResult()));
1282       }
1283     });
1284   }
1285 
1286   /**
1287    * @param s the scanner
1288    * @param results the result set returned by the region server
1289    * @param limit the maximum number of results to return
1290    * @return 'has next' indication to client if bypassing default behavior, or
1291    * null otherwise
1292    * @exception IOException Exception
1293    */
1294   public Boolean preScannerNext(final InternalScanner s,
1295       final List<Result> results, final int limit) throws IOException {
1296     return execOperationWithResult(true, false,
1297         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1298       @Override
1299       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1300           throws IOException {
1301         setResult(oserver.preScannerNext(ctx, s, results, limit, getResult()));
1302       }
1303     });
1304   }
1305 
1306   /**
1307    * @param s the scanner
1308    * @param results the result set returned by the region server
1309    * @param limit the maximum number of results to return
1310    * @param hasMore
1311    * @return 'has more' indication to give to client
1312    * @exception IOException Exception
1313    */
1314   public boolean postScannerNext(final InternalScanner s,
1315       final List<Result> results, final int limit, boolean hasMore)
1316       throws IOException {
1317     return execOperationWithResult(hasMore,
1318         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1319       @Override
1320       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1321           throws IOException {
1322         setResult(oserver.postScannerNext(ctx, s, results, limit, getResult()));
1323       }
1324     });
1325   }
1326 
1327   /**
1328    * This will be called by the scan flow when the current scanned row is being filtered out by the
1329    * filter.
1330    * @param s the scanner
1331    * @param curRowCell The cell in the current row which got filtered out
1332    * @return whether more rows are available for the scanner or not
1333    * @throws IOException
1334    */
1335   public boolean postScannerFilterRow(final InternalScanner s, final Cell curRowCell)
1336       throws IOException {
1337     return execOperationWithResult(true,
1338         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1339       @Override
1340       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1341           throws IOException {
1342         setResult(oserver.postScannerFilterRow(ctx, s, curRowCell, getResult()));
1343       }
1344     });
1345   }
1346 
1347   /**
1348    * @param s the scanner
1349    * @return true if default behavior should be bypassed, false otherwise
1350    * @exception IOException Exception
1351    */
1352   public boolean preScannerClose(final InternalScanner s) throws IOException {
1353     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
1354       @Override
1355       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1356           throws IOException {
1357         oserver.preScannerClose(ctx, s);
1358       }
1359     });
1360   }
1361 
1362   /**
1363    * @exception IOException Exception
1364    */
1365   public void postScannerClose(final InternalScanner s) throws IOException {
1366     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
1367       @Override
1368       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1369           throws IOException {
1370         oserver.postScannerClose(ctx, s);
1371       }
1372     });
1373   }
1374 
1375   /**
1376    * @param info
1377    * @param logKey
1378    * @param logEdit
1379    * @return true if default behavior should be bypassed, false otherwise
1380    * @throws IOException
1381    */
1382   public boolean preWALRestore(final HRegionInfo info, final WALKey logKey,
1383       final WALEdit logEdit) throws IOException {
1384     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
1385       @Override
1386       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1387           throws IOException {
1388         // Once we don't need to support the legacy call, replace RegionOperation with a version
1389         // that's ObserverContext<RegionEnvironment> and avoid this cast.
1390         final RegionEnvironment env = (RegionEnvironment)ctx.getEnvironment();
1391         if (env.useLegacyPre) {
1392           if (logKey instanceof HLogKey) {
1393             oserver.preWALRestore(ctx, info, (HLogKey)logKey, logEdit);
1394           } else {
1395             legacyWarning(oserver.getClass(), "There are wal keys present that are not HLogKey.");
1396           }
1397         } else {
1398           oserver.preWALRestore(ctx, info, logKey, logEdit);
1399         }
1400       }
1401     });
1402   }
1403 
1404   /**
1405    * @return true if default behavior should be bypassed, false otherwise
1406    * @deprecated use {@link #preWALRestore(HRegionInfo, WALKey, WALEdit)}
1407    */
1408   @Deprecated
1409   public boolean preWALRestore(final HRegionInfo info, final HLogKey logKey,
1410       final WALEdit logEdit) throws IOException {
1411     return preWALRestore(info, (WALKey)logKey, logEdit);
1412   }
1413 
1414   /**
1415    * @param info
1416    * @param logKey
1417    * @param logEdit
1418    * @throws IOException
1419    */
1420   public void postWALRestore(final HRegionInfo info, final WALKey logKey, final WALEdit logEdit)
1421       throws IOException {
1422     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
1423       @Override
1424       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1425           throws IOException {
1426         // Once we don't need to support the legacy call, replace RegionOperation with a version
1427         // that's ObserverContext<RegionEnvironment> and avoid this cast.
1428         final RegionEnvironment env = (RegionEnvironment)ctx.getEnvironment();
1429         if (env.useLegacyPost) {
1430           if (logKey instanceof HLogKey) {
1431             oserver.postWALRestore(ctx, info, (HLogKey)logKey, logEdit);
1432           } else {
1433             legacyWarning(oserver.getClass(), "There are wal keys present that are not HLogKey.");
1434           }
1435         } else {
1436           oserver.postWALRestore(ctx, info, logKey, logEdit);
1437         }
1438       }
1439     });
1440   }
1441 
1442   /**
1443    * @deprecated use {@link #postWALRestore(HRegionInfo, WALKey, WALEdit)}
1444    */
1445   @Deprecated
1446   public void postWALRestore(final HRegionInfo info, final HLogKey logKey, final WALEdit logEdit)
1447       throws IOException {
1448     postWALRestore(info, (WALKey)logKey, logEdit);
1449   }
1450 
1451   /**
1452    * @param familyPaths pairs of { CF, file path } submitted for bulk load
1453    * @return true if the default operation should be bypassed
1454    * @throws IOException
1455    */
1456   public boolean preBulkLoadHFile(final List<Pair<byte[], String>> familyPaths) throws IOException {
1457     return execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
1458       @Override
1459       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1460           throws IOException {
1461         oserver.preBulkLoadHFile(ctx, familyPaths);
1462       }
1463     });
1464   }
1465 
1466   /**
1467    * @param familyPaths pairs of { CF, file path } submitted for bulk load
1468    * @param hasLoaded whether load was successful or not
1469    * @return the possibly modified value of hasLoaded
1470    * @throws IOException
1471    */
1472   public boolean postBulkLoadHFile(final List<Pair<byte[], String>> familyPaths,
1473       boolean hasLoaded) throws IOException {
1474     return execOperationWithResult(hasLoaded,
1475         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Boolean>() {
1476       @Override
1477       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1478           throws IOException {
1479         setResult(oserver.postBulkLoadHFile(ctx, familyPaths, getResult()));
1480       }
1481     });
1482   }
1483 
1484   public void postStartRegionOperation(final Operation op) throws IOException {
1485     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
1486       @Override
1487       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1488           throws IOException {
1489         oserver.postStartRegionOperation(ctx, op);
1490       }
1491     });
1492   }
1493 
1494   public void postCloseRegionOperation(final Operation op) throws IOException {
1495     execOperation(coprocessors.isEmpty() ? null : new RegionOperation() {
1496       @Override
1497       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1498           throws IOException {
1499         oserver.postCloseRegionOperation(ctx, op);
1500       }
1501     });
1502   }
1503 
1504   /**
1505    * @param fs fileystem to read from
1506    * @param p path to the file
1507    * @param in {@link FSDataInputStreamWrapper}
1508    * @param size Full size of the file
1509    * @param cacheConf
1510    * @param r original reference file. This will be not null only when reading a split file.
1511    * @return a Reader instance to use instead of the base reader if overriding
1512    * default behavior, null otherwise
1513    * @throws IOException
1514    */
1515   public StoreFile.Reader preStoreFileReaderOpen(final FileSystem fs, final Path p,
1516       final FSDataInputStreamWrapper in, final long size, final CacheConfig cacheConf,
1517       final Reference r) throws IOException {
1518     return execOperationWithResult(null,
1519         coprocessors.isEmpty() ? null : new RegionOperationWithResult<StoreFile.Reader>() {
1520       @Override
1521       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1522           throws IOException {
1523         setResult(oserver.preStoreFileReaderOpen(ctx, fs, p, in, size, cacheConf, r, getResult()));
1524       }
1525     });
1526   }
1527 
1528   /**
1529    * @param fs fileystem to read from
1530    * @param p path to the file
1531    * @param in {@link FSDataInputStreamWrapper}
1532    * @param size Full size of the file
1533    * @param cacheConf
1534    * @param r original reference file. This will be not null only when reading a split file.
1535    * @param reader the base reader instance
1536    * @return The reader to use
1537    * @throws IOException
1538    */
1539   public StoreFile.Reader postStoreFileReaderOpen(final FileSystem fs, final Path p,
1540       final FSDataInputStreamWrapper in, final long size, final CacheConfig cacheConf,
1541       final Reference r, final StoreFile.Reader reader) throws IOException {
1542     return execOperationWithResult(reader,
1543         coprocessors.isEmpty() ? null : new RegionOperationWithResult<StoreFile.Reader>() {
1544       @Override
1545       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1546           throws IOException {
1547         setResult(oserver.postStoreFileReaderOpen(ctx, fs, p, in, size, cacheConf, r, getResult()));
1548       }
1549     });
1550   }
1551 
1552   public Cell postMutationBeforeWAL(final MutationType opType, final Mutation mutation,
1553       final Cell oldCell, Cell newCell) throws IOException {
1554     return execOperationWithResult(newCell,
1555         coprocessors.isEmpty() ? null : new RegionOperationWithResult<Cell>() {
1556       @Override
1557       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1558           throws IOException {
1559         setResult(oserver.postMutationBeforeWAL(ctx, opType, mutation, oldCell, getResult()));
1560       }
1561     });
1562   }
1563 
1564   public Message preEndpointInvocation(final Service service, final String methodName,
1565       Message request) throws IOException {
1566     return execOperationWithResult(request,
1567         coprocessors.isEmpty() ? null : new EndpointOperationWithResult<Message>() {
1568       @Override
1569       public void call(EndpointObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1570           throws IOException {
1571         setResult(oserver.preEndpointInvocation(ctx, service, methodName, getResult()));
1572       }
1573     });
1574   }
1575 
1576   public void postEndpointInvocation(final Service service, final String methodName,
1577       final Message request, final Message.Builder responseBuilder) throws IOException {
1578     execOperation(coprocessors.isEmpty() ? null : new EndpointOperation() {
1579       @Override
1580       public void call(EndpointObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1581           throws IOException {
1582         oserver.postEndpointInvocation(ctx, service, methodName, request, responseBuilder);
1583       }
1584     });
1585   }
1586 
1587   public DeleteTracker postInstantiateDeleteTracker(DeleteTracker tracker) throws IOException {
1588     return execOperationWithResult(tracker,
1589         coprocessors.isEmpty() ? null : new RegionOperationWithResult<DeleteTracker>() {
1590       @Override
1591       public void call(RegionObserver oserver, ObserverContext<RegionCoprocessorEnvironment> ctx)
1592           throws IOException {
1593         setResult(oserver.postInstantiateDeleteTracker(ctx, getResult()));
1594       }
1595     });
1596   }
1597 
1598   public Map<String, DescriptiveStatistics> getCoprocessorExecutionStatistics() {
1599     Map<String, DescriptiveStatistics> results = new HashMap<String, DescriptiveStatistics>();
1600     for (RegionEnvironment env : coprocessors) {
1601       DescriptiveStatistics ds = new DescriptiveStatistics();
1602       if (env.getInstance() instanceof RegionObserver) {
1603         for (Long time : env.getExecutionLatenciesNanos()) {
1604           ds.addValue(time);
1605         }
1606         // Ensures that web ui circumvents the display of NaN values when there are zero samples.
1607         if (ds.getN() == 0) {
1608           ds.addValue(0);
1609         }
1610         results.put(env.getInstance().getClass().getSimpleName(), ds);
1611       }
1612     }
1613     return results;
1614   }
1615 
1616   private static abstract class CoprocessorOperation
1617       extends ObserverContext<RegionCoprocessorEnvironment> {
1618     public abstract void call(Coprocessor observer,
1619         ObserverContext<RegionCoprocessorEnvironment> ctx) throws IOException;
1620     public abstract boolean hasCall(Coprocessor observer);
1621     public void postEnvCall(RegionEnvironment env) { }
1622   }
1623 
1624   private static abstract class RegionOperation extends CoprocessorOperation {
1625     public abstract void call(RegionObserver observer,
1626         ObserverContext<RegionCoprocessorEnvironment> ctx) throws IOException;
1627 
1628     public boolean hasCall(Coprocessor observer) {
1629       return observer instanceof RegionObserver;
1630     }
1631 
1632     public void call(Coprocessor observer, ObserverContext<RegionCoprocessorEnvironment> ctx)
1633         throws IOException {
1634       call((RegionObserver)observer, ctx);
1635     }
1636   }
1637 
1638   private static abstract class RegionOperationWithResult<T> extends RegionOperation {
1639     private T result = null;
1640     public void setResult(final T result) { this.result = result; }
1641     public T getResult() { return this.result; }
1642   }
1643 
1644   private static abstract class EndpointOperation extends CoprocessorOperation {
1645     public abstract void call(EndpointObserver observer,
1646         ObserverContext<RegionCoprocessorEnvironment> ctx) throws IOException;
1647 
1648     public boolean hasCall(Coprocessor observer) {
1649       return observer instanceof EndpointObserver;
1650     }
1651 
1652     public void call(Coprocessor observer, ObserverContext<RegionCoprocessorEnvironment> ctx)
1653         throws IOException {
1654       call((EndpointObserver)observer, ctx);
1655     }
1656   }
1657 
1658   private static abstract class EndpointOperationWithResult<T> extends EndpointOperation {
1659     private T result = null;
1660     public void setResult(final T result) { this.result = result; }
1661     public T getResult() { return this.result; }
1662   }
1663 
1664   private boolean execOperation(final CoprocessorOperation ctx)
1665       throws IOException {
1666     return execOperation(true, ctx);
1667   }
1668 
1669   private <T> T execOperationWithResult(final T defaultValue,
1670       final RegionOperationWithResult<T> ctx) throws IOException {
1671     if (ctx == null) return defaultValue;
1672     ctx.setResult(defaultValue);
1673     execOperation(true, ctx);
1674     return ctx.getResult();
1675   }
1676 
1677   private <T> T execOperationWithResult(final boolean ifBypass, final T defaultValue,
1678       final RegionOperationWithResult<T> ctx) throws IOException {
1679     boolean bypass = false;
1680     T result = defaultValue;
1681     if (ctx != null) {
1682       ctx.setResult(defaultValue);
1683       bypass = execOperation(true, ctx);
1684       result = ctx.getResult();
1685     }
1686     return bypass == ifBypass ? result : null;
1687   }
1688 
1689   private <T> T execOperationWithResult(final T defaultValue,
1690       final EndpointOperationWithResult<T> ctx) throws IOException {
1691     if (ctx == null) return defaultValue;
1692     ctx.setResult(defaultValue);
1693     execOperation(true, ctx);
1694     return ctx.getResult();
1695   }
1696 
1697   private boolean execOperation(final boolean earlyExit, final CoprocessorOperation ctx)
1698       throws IOException {
1699     boolean bypass = false;
1700     for (RegionEnvironment env: coprocessors) {
1701       Coprocessor observer = env.getInstance();
1702       if (ctx.hasCall(observer)) {
1703         long startTime = System.nanoTime();
1704         ctx.prepare(env);
1705         Thread currentThread = Thread.currentThread();
1706         ClassLoader cl = currentThread.getContextClassLoader();
1707         try {
1708           currentThread.setContextClassLoader(env.getClassLoader());
1709           ctx.call(observer, ctx);
1710         } catch (Throwable e) {
1711           handleCoprocessorThrowable(env, e);
1712         } finally {
1713           currentThread.setContextClassLoader(cl);
1714         }
1715         env.offerExecutionLatency(System.nanoTime() - startTime);
1716         bypass |= ctx.shouldBypass();
1717         if (earlyExit && ctx.shouldComplete()) {
1718           break;
1719         }
1720       }
1721 
1722       ctx.postEnvCall(env);
1723     }
1724     return bypass;
1725   }
1726 }