001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.util;
019
020import edu.umd.cs.findbugs.annotations.Nullable;
021import java.util.concurrent.ConcurrentHashMap;
022import java.util.concurrent.ConcurrentMap;
023import java.util.concurrent.TimeUnit;
024import java.util.function.Function;
025import org.apache.yetus.audience.InterfaceAudience;
026import org.slf4j.Logger;
027import org.slf4j.LoggerFactory;
028
029/**
030 * Cache to hold resolved Functions of a specific signature, generated through reflection. These can
031 * be (relatively) costly to create, but then are much faster than typical Method.invoke calls when
032 * executing. The cache is built-up on demand as calls are made to new classes. The functions are
033 * cached for the lifetime of the process. If a function cannot be created (security reasons, method
034 * not found, etc), a fallback function is cached which always returns null. Callers to
035 * {@link #getAndCallByName(String, Object)} should have handling for null return values.
036 * <p>
037 * An instance is created for a specified baseClass (i.e. Filter), argClass (i.e. byte[]), and
038 * static methodName to call. These are used to resolve a Function which delegates to that static
039 * method, if it is found.
040 * @param <I> the input argument type for the resolved functions
041 * @param <R> the return type for the resolved functions
042 */
043@InterfaceAudience.Private
044public final class ReflectedFunctionCache<I, R> {
045
046  private static final Logger LOG = LoggerFactory.getLogger(ReflectedFunctionCache.class);
047
048  private final ConcurrentMap<String, Function<I, ? extends R>> lambdasByClass =
049    new ConcurrentHashMap<>();
050  private final Class<R> baseClass;
051  private final Class<I> argClass;
052  private final String methodName;
053  private final ClassLoader classLoader;
054
055  public ReflectedFunctionCache(Class<R> baseClass, Class<I> argClass, String staticMethodName) {
056    this.classLoader = getClass().getClassLoader();
057    this.baseClass = baseClass;
058    this.argClass = argClass;
059    this.methodName = staticMethodName;
060  }
061
062  /**
063   * Get and execute the Function for the given className, passing the argument to the function and
064   * returning the result.
065   * @param className the full name of the class to lookup
066   * @param argument  the argument to pass to the function, if found.
067   * @return null if a function is not found for classname, otherwise the result of the function.
068   */
069  @Nullable
070  public R getAndCallByName(String className, I argument) {
071    // todo: if we ever make java9+ our lowest supported jdk version, we can
072    // handle generating these for newly loaded classes from our DynamicClassLoader using
073    // MethodHandles.privateLookupIn(). For now this is not possible, because we can't easily
074    // create a privileged lookup in a non-default ClassLoader. So while this cache loads
075    // over time, it will never load a custom filter from "hbase.dynamic.jars.dir".
076    Function<I, ? extends R> lambda =
077      ConcurrentMapUtils.computeIfAbsent(lambdasByClass, className, () -> loadFunction(className));
078
079    return lambda.apply(argument);
080  }
081
082  private Function<I, ? extends R> loadFunction(String className) {
083    long startTime = System.nanoTime();
084    try {
085      Class<?> clazz = Class.forName(className, false, classLoader);
086      if (!baseClass.isAssignableFrom(clazz)) {
087        LOG.debug("Requested class {} is not assignable to {}, skipping creation of function",
088          className, baseClass.getName());
089        return this::notFound;
090      }
091      return ReflectionUtils.getOneArgStaticMethodAsFunction(clazz, methodName, argClass,
092        (Class<? extends R>) clazz);
093    } catch (Throwable t) {
094      LOG.debug("Failed to create function for {}", className, t);
095      return this::notFound;
096    } finally {
097      LOG.debug("Populated cache for {} in {}ms", className,
098        TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
099    }
100  }
101
102  /**
103   * In order to use computeIfAbsent, we can't store nulls in our cache. So we store a lambda which
104   * resolves to null. The contract is that getAndCallByName returns null in this case.
105   */
106  private R notFound(I argument) {
107    return null;
108  }
109
110}