001/*
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.coprocessor;
020
021import static org.apache.hadoop.hbase.client.coprocessor.AggregationHelper.getParsedGenericInstance;
022
023import com.google.protobuf.ByteString;
024import com.google.protobuf.Message;
025import com.google.protobuf.RpcCallback;
026import com.google.protobuf.RpcController;
027import com.google.protobuf.Service;
028
029import java.io.IOException;
030import java.lang.reflect.InvocationTargetException;
031import java.nio.ByteBuffer;
032import java.util.ArrayList;
033import java.util.Collections;
034import java.util.List;
035import java.util.NavigableSet;
036
037import org.apache.hadoop.hbase.Cell;
038import org.apache.hadoop.hbase.CoprocessorEnvironment;
039import org.apache.yetus.audience.InterfaceAudience;
040import org.slf4j.Logger;
041import org.slf4j.LoggerFactory;
042import org.apache.hadoop.hbase.client.Scan;
043import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
044import org.apache.hadoop.hbase.ipc.CoprocessorRpcUtils;
045import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
046import org.apache.hadoop.hbase.protobuf.generated.AggregateProtos.AggregateRequest;
047import org.apache.hadoop.hbase.protobuf.generated.AggregateProtos.AggregateResponse;
048import org.apache.hadoop.hbase.protobuf.generated.AggregateProtos.AggregateService;
049import org.apache.hadoop.hbase.regionserver.InternalScanner;
050
051/**
052 * A concrete AggregateProtocol implementation. Its system level coprocessor
053 * that computes the aggregate function at a region level.
054 * {@link ColumnInterpreter} is used to interpret column value. This class is
055 * parameterized with the following (these are the types with which the {@link ColumnInterpreter}
056 * is parameterized, and for more description on these, refer to {@link ColumnInterpreter}):
057 * @param T Cell value data type
058 * @param S Promoted data type
059 * @param P PB message that is used to transport initializer specific bytes
060 * @param Q PB message that is used to transport Cell (<T>) instance
061 * @param R PB message that is used to transport Promoted (<S>) instance
062 */
063@InterfaceAudience.Private
064public class AggregateImplementation<T, S, P extends Message, Q extends Message, R extends Message>
065extends AggregateService implements RegionCoprocessor {
066  protected static final Logger log = LoggerFactory.getLogger(AggregateImplementation.class);
067  private RegionCoprocessorEnvironment env;
068
069  /**
070   * Gives the maximum for a given combination of column qualifier and column
071   * family, in the given row range as defined in the Scan object. In its
072   * current implementation, it takes one column family and one column qualifier
073   * (if provided). In case of null column qualifier, maximum value for the
074   * entire column family will be returned.
075   */
076  @Override
077  public void getMax(RpcController controller, AggregateRequest request,
078      RpcCallback<AggregateResponse> done) {
079    InternalScanner scanner = null;
080    AggregateResponse response = null;
081    T max = null;
082    try {
083      ColumnInterpreter<T, S, P, Q, R> ci = constructColumnInterpreterFromRequest(request);
084      T temp;
085      Scan scan = ProtobufUtil.toScan(request.getScan());
086      scanner = env.getRegion().getScanner(scan);
087      List<Cell> results = new ArrayList<>();
088      byte[] colFamily = scan.getFamilies()[0];
089      NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(colFamily);
090      byte[] qualifier = null;
091      if (qualifiers != null && !qualifiers.isEmpty()) {
092        qualifier = qualifiers.pollFirst();
093      }
094      // qualifier can be null.
095      boolean hasMoreRows = false;
096      do {
097        hasMoreRows = scanner.next(results);
098        int listSize = results.size();
099        for (int i = 0; i < listSize; i++) {
100          temp = ci.getValue(colFamily, qualifier, results.get(i));
101          max = (max == null || (temp != null && ci.compare(temp, max) > 0)) ? temp : max;
102        }
103        results.clear();
104      } while (hasMoreRows);
105      if (max != null) {
106        AggregateResponse.Builder builder = AggregateResponse.newBuilder();
107        builder.addFirstPart(ci.getProtoForCellType(max).toByteString());
108        response = builder.build();
109      }
110    } catch (IOException e) {
111      CoprocessorRpcUtils.setControllerException(controller, e);
112    } finally {
113      if (scanner != null) {
114        try {
115          scanner.close();
116        } catch (IOException ignored) {}
117      }
118    }
119    log.info("Maximum from this region is "
120        + env.getRegion().getRegionInfo().getRegionNameAsString() + ": " + max);
121    done.run(response);
122  }
123
124  /**
125   * Gives the minimum for a given combination of column qualifier and column
126   * family, in the given row range as defined in the Scan object. In its
127   * current implementation, it takes one column family and one column qualifier
128   * (if provided). In case of null column qualifier, minimum value for the
129   * entire column family will be returned.
130   */
131  @Override
132  public void getMin(RpcController controller, AggregateRequest request,
133      RpcCallback<AggregateResponse> done) {
134    AggregateResponse response = null;
135    InternalScanner scanner = null;
136    T min = null;
137    try {
138      ColumnInterpreter<T, S, P, Q, R> ci = constructColumnInterpreterFromRequest(request);
139      T temp;
140      Scan scan = ProtobufUtil.toScan(request.getScan());
141      scanner = env.getRegion().getScanner(scan);
142      List<Cell> results = new ArrayList<>();
143      byte[] colFamily = scan.getFamilies()[0];
144      NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(colFamily);
145      byte[] qualifier = null;
146      if (qualifiers != null && !qualifiers.isEmpty()) {
147        qualifier = qualifiers.pollFirst();
148      }
149      boolean hasMoreRows = false;
150      do {
151        hasMoreRows = scanner.next(results);
152        int listSize = results.size();
153        for (int i = 0; i < listSize; i++) {
154          temp = ci.getValue(colFamily, qualifier, results.get(i));
155          min = (min == null || (temp != null && ci.compare(temp, min) < 0)) ? temp : min;
156        }
157        results.clear();
158      } while (hasMoreRows);
159      if (min != null) {
160        response = AggregateResponse.newBuilder().addFirstPart(
161          ci.getProtoForCellType(min).toByteString()).build();
162      }
163    } catch (IOException e) {
164      CoprocessorRpcUtils.setControllerException(controller, e);
165    } finally {
166      if (scanner != null) {
167        try {
168          scanner.close();
169        } catch (IOException ignored) {}
170      }
171    }
172    log.info("Minimum from this region is "
173        + env.getRegion().getRegionInfo().getRegionNameAsString() + ": " + min);
174    done.run(response);
175  }
176
177  /**
178   * Gives the sum for a given combination of column qualifier and column
179   * family, in the given row range as defined in the Scan object. In its
180   * current implementation, it takes one column family and one column qualifier
181   * (if provided). In case of null column qualifier, sum for the entire column
182   * family will be returned.
183   */
184  @Override
185  public void getSum(RpcController controller, AggregateRequest request,
186      RpcCallback<AggregateResponse> done) {
187    AggregateResponse response = null;
188    InternalScanner scanner = null;
189    long sum = 0l;
190    try {
191      ColumnInterpreter<T, S, P, Q, R> ci = constructColumnInterpreterFromRequest(request);
192      S sumVal = null;
193      T temp;
194      Scan scan = ProtobufUtil.toScan(request.getScan());
195      scanner = env.getRegion().getScanner(scan);
196      byte[] colFamily = scan.getFamilies()[0];
197      NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(colFamily);
198      byte[] qualifier = null;
199      if (qualifiers != null && !qualifiers.isEmpty()) {
200        qualifier = qualifiers.pollFirst();
201      }
202      List<Cell> results = new ArrayList<>();
203      boolean hasMoreRows = false;
204      do {
205        hasMoreRows = scanner.next(results);
206        int listSize = results.size();
207        for (int i = 0; i < listSize; i++) {
208          temp = ci.getValue(colFamily, qualifier, results.get(i));
209          if (temp != null)
210            sumVal = ci.add(sumVal, ci.castToReturnType(temp));
211        }
212        results.clear();
213      } while (hasMoreRows);
214      if (sumVal != null) {
215        response = AggregateResponse.newBuilder().addFirstPart(
216          ci.getProtoForPromotedType(sumVal).toByteString()).build();
217      }
218    } catch (IOException e) {
219      CoprocessorRpcUtils.setControllerException(controller, e);
220    } finally {
221      if (scanner != null) {
222        try {
223          scanner.close();
224        } catch (IOException ignored) {}
225      }
226    }
227    log.debug("Sum from this region is "
228        + env.getRegion().getRegionInfo().getRegionNameAsString() + ": " + sum);
229    done.run(response);
230  }
231
232  /**
233   * Gives the row count for the given column family and column qualifier, in
234   * the given row range as defined in the Scan object.
235   */
236  @Override
237  public void getRowNum(RpcController controller, AggregateRequest request,
238      RpcCallback<AggregateResponse> done) {
239    AggregateResponse response = null;
240    long counter = 0l;
241    List<Cell> results = new ArrayList<>();
242    InternalScanner scanner = null;
243    try {
244      Scan scan = ProtobufUtil.toScan(request.getScan());
245      byte[][] colFamilies = scan.getFamilies();
246      byte[] colFamily = colFamilies != null ? colFamilies[0] : null;
247      NavigableSet<byte[]> qualifiers = colFamilies != null ?
248          scan.getFamilyMap().get(colFamily) : null;
249      byte[] qualifier = null;
250      if (qualifiers != null && !qualifiers.isEmpty()) {
251        qualifier = qualifiers.pollFirst();
252      }
253      if (scan.getFilter() == null && qualifier == null)
254        scan.setFilter(new FirstKeyOnlyFilter());
255      scanner = env.getRegion().getScanner(scan);
256      boolean hasMoreRows = false;
257      do {
258        hasMoreRows = scanner.next(results);
259        if (results.size() > 0) {
260          counter++;
261        }
262        results.clear();
263      } while (hasMoreRows);
264      ByteBuffer bb = ByteBuffer.allocate(8).putLong(counter);
265      bb.rewind();
266      response = AggregateResponse.newBuilder().addFirstPart(
267          ByteString.copyFrom(bb)).build();
268    } catch (IOException e) {
269      CoprocessorRpcUtils.setControllerException(controller, e);
270    } finally {
271      if (scanner != null) {
272        try {
273          scanner.close();
274        } catch (IOException ignored) {}
275      }
276    }
277    log.info("Row counter from this region is "
278        + env.getRegion().getRegionInfo().getRegionNameAsString() + ": " + counter);
279    done.run(response);
280  }
281
282  /**
283   * Gives a Pair with first object as Sum and second object as row count,
284   * computed for a given combination of column qualifier and column family in
285   * the given row range as defined in the Scan object. In its current
286   * implementation, it takes one column family and one column qualifier (if
287   * provided). In case of null column qualifier, an aggregate sum over all the
288   * entire column family will be returned.
289   * <p>
290   * The average is computed in
291   * AggregationClient#avg(byte[], ColumnInterpreter, Scan) by
292   * processing results from all regions, so its "ok" to pass sum and a Long
293   * type.
294   */
295  @Override
296  public void getAvg(RpcController controller, AggregateRequest request,
297      RpcCallback<AggregateResponse> done) {
298    AggregateResponse response = null;
299    InternalScanner scanner = null;
300    try {
301      ColumnInterpreter<T, S, P, Q, R> ci = constructColumnInterpreterFromRequest(request);
302      S sumVal = null;
303      Long rowCountVal = 0l;
304      Scan scan = ProtobufUtil.toScan(request.getScan());
305      scanner = env.getRegion().getScanner(scan);
306      byte[] colFamily = scan.getFamilies()[0];
307      NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(colFamily);
308      byte[] qualifier = null;
309      if (qualifiers != null && !qualifiers.isEmpty()) {
310        qualifier = qualifiers.pollFirst();
311      }
312      List<Cell> results = new ArrayList<>();
313      boolean hasMoreRows = false;
314
315      do {
316        results.clear();
317        hasMoreRows = scanner.next(results);
318        int listSize = results.size();
319        for (int i = 0; i < listSize; i++) {
320          sumVal = ci.add(sumVal, ci.castToReturnType(ci.getValue(colFamily,
321              qualifier, results.get(i))));
322        }
323        rowCountVal++;
324      } while (hasMoreRows);
325      if (sumVal != null) {
326        ByteString first = ci.getProtoForPromotedType(sumVal).toByteString();
327        AggregateResponse.Builder pair = AggregateResponse.newBuilder();
328        pair.addFirstPart(first);
329        ByteBuffer bb = ByteBuffer.allocate(8).putLong(rowCountVal);
330        bb.rewind();
331        pair.setSecondPart(ByteString.copyFrom(bb));
332        response = pair.build();
333      }
334    } catch (IOException e) {
335      CoprocessorRpcUtils.setControllerException(controller, e);
336    } finally {
337      if (scanner != null) {
338        try {
339          scanner.close();
340        } catch (IOException ignored) {}
341      }
342    }
343    done.run(response);
344  }
345
346  /**
347   * Gives a Pair with first object a List containing Sum and sum of squares,
348   * and the second object as row count. It is computed for a given combination of
349   * column qualifier and column family in the given row range as defined in the
350   * Scan object. In its current implementation, it takes one column family and
351   * one column qualifier (if provided). The idea is get the value of variance first:
352   * the average of the squares less the square of the average a standard
353   * deviation is square root of variance.
354   */
355  @Override
356  public void getStd(RpcController controller, AggregateRequest request,
357      RpcCallback<AggregateResponse> done) {
358    InternalScanner scanner = null;
359    AggregateResponse response = null;
360    try {
361      ColumnInterpreter<T, S, P, Q, R> ci = constructColumnInterpreterFromRequest(request);
362      S sumVal = null, sumSqVal = null, tempVal = null;
363      long rowCountVal = 0l;
364      Scan scan = ProtobufUtil.toScan(request.getScan());
365      scanner = env.getRegion().getScanner(scan);
366      byte[] colFamily = scan.getFamilies()[0];
367      NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(colFamily);
368      byte[] qualifier = null;
369      if (qualifiers != null && !qualifiers.isEmpty()) {
370        qualifier = qualifiers.pollFirst();
371      }
372      List<Cell> results = new ArrayList<>();
373
374      boolean hasMoreRows = false;
375
376      do {
377        tempVal = null;
378        hasMoreRows = scanner.next(results);
379        int listSize = results.size();
380        for (int i = 0; i < listSize; i++) {
381          tempVal = ci.add(tempVal, ci.castToReturnType(ci.getValue(colFamily,
382              qualifier, results.get(i))));
383        }
384        results.clear();
385        sumVal = ci.add(sumVal, tempVal);
386        sumSqVal = ci.add(sumSqVal, ci.multiply(tempVal, tempVal));
387        rowCountVal++;
388      } while (hasMoreRows);
389      if (sumVal != null) {
390        ByteString first_sumVal = ci.getProtoForPromotedType(sumVal).toByteString();
391        ByteString first_sumSqVal = ci.getProtoForPromotedType(sumSqVal).toByteString();
392        AggregateResponse.Builder pair = AggregateResponse.newBuilder();
393        pair.addFirstPart(first_sumVal);
394        pair.addFirstPart(first_sumSqVal);
395        ByteBuffer bb = ByteBuffer.allocate(8).putLong(rowCountVal);
396        bb.rewind();
397        pair.setSecondPart(ByteString.copyFrom(bb));
398        response = pair.build();
399      }
400    } catch (IOException e) {
401      CoprocessorRpcUtils.setControllerException(controller, e);
402    } finally {
403      if (scanner != null) {
404        try {
405          scanner.close();
406        } catch (IOException ignored) {}
407      }
408    }
409    done.run(response);
410  }
411
412  /**
413   * Gives a List containing sum of values and sum of weights.
414   * It is computed for the combination of column
415   * family and column qualifier(s) in the given row range as defined in the
416   * Scan object. In its current implementation, it takes one column family and
417   * two column qualifiers. The first qualifier is for values column and
418   * the second qualifier (optional) is for weight column.
419   */
420  @Override
421  public void getMedian(RpcController controller, AggregateRequest request,
422      RpcCallback<AggregateResponse> done) {
423    AggregateResponse response = null;
424    InternalScanner scanner = null;
425    try {
426      ColumnInterpreter<T, S, P, Q, R> ci = constructColumnInterpreterFromRequest(request);
427      S sumVal = null, sumWeights = null, tempVal = null, tempWeight = null;
428      Scan scan = ProtobufUtil.toScan(request.getScan());
429      scanner = env.getRegion().getScanner(scan);
430      byte[] colFamily = scan.getFamilies()[0];
431      NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(colFamily);
432      byte[] valQualifier = null, weightQualifier = null;
433      if (qualifiers != null && !qualifiers.isEmpty()) {
434        valQualifier = qualifiers.pollFirst();
435        // if weighted median is requested, get qualifier for the weight column
436        weightQualifier = qualifiers.pollLast();
437      }
438      List<Cell> results = new ArrayList<>();
439
440      boolean hasMoreRows = false;
441
442      do {
443        tempVal = null;
444        tempWeight = null;
445        hasMoreRows = scanner.next(results);
446        int listSize = results.size();
447        for (int i = 0; i < listSize; i++) {
448          Cell kv = results.get(i);
449          tempVal = ci.add(tempVal, ci.castToReturnType(ci.getValue(colFamily,
450              valQualifier, kv)));
451          if (weightQualifier != null) {
452            tempWeight = ci.add(tempWeight,
453                ci.castToReturnType(ci.getValue(colFamily, weightQualifier, kv)));
454          }
455        }
456        results.clear();
457        sumVal = ci.add(sumVal, tempVal);
458        sumWeights = ci.add(sumWeights, tempWeight);
459      } while (hasMoreRows);
460      ByteString first_sumVal = ci.getProtoForPromotedType(sumVal).toByteString();
461      S s = sumWeights == null ? ci.castToReturnType(ci.getMinValue()) : sumWeights;
462      ByteString first_sumWeights = ci.getProtoForPromotedType(s).toByteString();
463      AggregateResponse.Builder pair = AggregateResponse.newBuilder();
464      pair.addFirstPart(first_sumVal);
465      pair.addFirstPart(first_sumWeights);
466      response = pair.build();
467    } catch (IOException e) {
468      CoprocessorRpcUtils.setControllerException(controller, e);
469    } finally {
470      if (scanner != null) {
471        try {
472          scanner.close();
473        } catch (IOException ignored) {}
474      }
475    }
476    done.run(response);
477  }
478
479  @SuppressWarnings("unchecked")
480  // Used server-side too by Aggregation Coprocesor Endpoint. Undo this interdependence. TODO.
481  ColumnInterpreter<T,S,P,Q,R> constructColumnInterpreterFromRequest(
482      AggregateRequest request) throws IOException {
483    String className = request.getInterpreterClassName();
484    try {
485      ColumnInterpreter<T,S,P,Q,R> ci;
486      Class<?> cls = Class.forName(className);
487      ci = (ColumnInterpreter<T, S, P, Q, R>) cls.getDeclaredConstructor().newInstance();
488
489      if (request.hasInterpreterSpecificBytes()) {
490        ByteString b = request.getInterpreterSpecificBytes();
491        P initMsg = getParsedGenericInstance(ci.getClass(), 2, b);
492        ci.initialize(initMsg);
493      }
494      return ci;
495    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
496        NoSuchMethodException | InvocationTargetException e) {
497      throw new IOException(e);
498    }
499  }
500
501  @Override
502  public Iterable<Service> getServices() {
503    return Collections.singleton(this);
504  }
505
506  /**
507   * Stores a reference to the coprocessor environment provided by the
508   * {@link org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost} from the region where this
509   * coprocessor is loaded.  Since this is a coprocessor endpoint, it always expects to be loaded
510   * on a table region, so always expects this to be an instance of
511   * {@link RegionCoprocessorEnvironment}.
512   * @param env the environment provided by the coprocessor host
513   * @throws IOException if the provided environment is not an instance of
514   * {@code RegionCoprocessorEnvironment}
515   */
516  @Override
517  public void start(CoprocessorEnvironment env) throws IOException {
518    if (env instanceof RegionCoprocessorEnvironment) {
519      this.env = (RegionCoprocessorEnvironment)env;
520    } else {
521      throw new CoprocessorException("Must be loaded on a table region!");
522    }
523  }
524
525  @Override
526  public void stop(CoprocessorEnvironment env) throws IOException {
527    // nothing to do
528  }
529
530}