You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hive.apache.org by na...@apache.org on 2015/02/13 06:55:17 UTC

svn commit: r1659461 [3/3] - in /hive/trunk: common/src/java/org/apache/hadoop/hive/common/ common/src/java/org/apache/hadoop/hive/conf/ contrib/src/test/results/clientnegative/ metastore/src/test/org/apache/hadoop/hive/metastore/ ql/src/java/org/apach...

Added: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Registry.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Registry.java?rev=1659461&view=auto
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Registry.java (added)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Registry.java Fri Feb 13 05:55:16 2015
@@ -0,0 +1,522 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.exec;
+
+import com.google.common.base.Splitter;
+import com.google.common.collect.Sets;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.hive.ql.exec.FunctionInfo.FunctionResource;
+import org.apache.hadoop.hive.ql.ErrorMsg;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.parse.SemanticException;
+import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
+import org.apache.hadoop.hive.ql.session.SessionState;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFBridge;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFEvaluator;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFParameterInfo;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFResolver;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDAFResolver2;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBridge;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDFMacro;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDTF;
+import org.apache.hadoop.hive.ql.udf.generic.SimpleGenericUDAFParameterInfo;
+import org.apache.hadoop.hive.ql.udf.ptf.TableFunctionResolver;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
+import org.apache.hadoop.util.ReflectionUtils;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.regex.Pattern;
+import java.util.regex.PatternSyntaxException;
+
+// Extracted from FunctionRegistry
+public class Registry {
+
+  private static final Log LOG = LogFactory.getLog(FunctionRegistry.class);
+
+  // prefix for window functions, to discern LEAD/LAG UDFs from window functions with the same name
+  private static final String WINDOW_FUNC_PREFIX = "@_";
+
+  /**
+   * The mapping from expression function names to expression classes.
+   */
+  private final Map<String, FunctionInfo> mFunctions = new LinkedHashMap<String, FunctionInfo>();
+  private final Set<Class<?>> builtIns = Collections.synchronizedSet(new HashSet<Class<?>>());
+
+  private final boolean isNative;
+
+  Registry(boolean isNative) {
+    this.isNative = isNative;
+  }
+
+  public Registry() {
+    this(false);
+  }
+
+  /**
+   * Registers the appropriate kind of temporary function based on a class's
+   * type.
+   *
+   * @param functionName name under which to register function
+   * @param udfClass     class implementing UD[A|T]F
+   * @return true if udfClass's type was recognized (so registration
+   *         succeeded); false otherwise
+   */
+  @SuppressWarnings("unchecked")
+  public FunctionInfo registerFunction(
+      String functionName, Class<?> udfClass, FunctionResource... resources) {
+
+    FunctionUtils.UDFClassType udfClassType = FunctionUtils.getUDFClassType(udfClass);
+    switch (udfClassType) {
+      case UDF:
+        return registerUDF(
+            functionName, (Class<? extends UDF>) udfClass, false, resources);
+      case GENERIC_UDF:
+        return registerGenericUDF(
+            functionName, (Class<? extends GenericUDF>) udfClass, resources);
+      case GENERIC_UDTF:
+        return registerGenericUDTF(
+            functionName, (Class<? extends GenericUDTF>) udfClass, resources);
+      case UDAF:
+        return registerUDAF(
+            functionName, (Class<? extends UDAF>) udfClass, resources);
+      case GENERIC_UDAF_RESOLVER:
+        return registerGenericUDAF(
+            functionName, (GenericUDAFResolver)
+            ReflectionUtils.newInstance(udfClass, null), resources);
+      case TABLE_FUNCTION_RESOLVER:
+        // native or not would be decided by annotation. need to evaluate that first
+        return registerTableFunction(functionName,
+            (Class<? extends TableFunctionResolver>) udfClass, resources);
+    }
+    return null;
+
+  }
+
+  public FunctionInfo registerUDF(String functionName,
+      Class<? extends UDF> UDFClass, boolean isOperator, FunctionResource... resources) {
+    return registerUDF(functionName, UDFClass, isOperator, functionName.toLowerCase(), resources);
+  }
+
+  public FunctionInfo registerUDF(String functionName,
+      Class<? extends UDF> UDFClass, boolean isOperator, String displayName,
+      FunctionResource... resources) {
+    validateClass(UDFClass, UDF.class);
+    FunctionInfo fI = new FunctionInfo(isNative, displayName,
+        new GenericUDFBridge(displayName, isOperator, UDFClass.getName()), resources);
+    addFunction(functionName, fI);
+    return fI;
+  }
+
+  public FunctionInfo registerGenericUDF(String functionName,
+      Class<? extends GenericUDF> genericUDFClass, FunctionResource... resources) {
+    validateClass(genericUDFClass, GenericUDF.class);
+    FunctionInfo fI = new FunctionInfo(isNative, functionName,
+        ReflectionUtils.newInstance(genericUDFClass, null), resources);
+    addFunction(functionName, fI);
+    return fI;
+  }
+
+  public FunctionInfo registerGenericUDTF(String functionName,
+      Class<? extends GenericUDTF> genericUDTFClass, FunctionResource... resources) {
+    validateClass(genericUDTFClass, GenericUDTF.class);
+    FunctionInfo fI = new FunctionInfo(isNative, functionName,
+        ReflectionUtils.newInstance(genericUDTFClass, null), resources);
+    addFunction(functionName, fI);
+    return fI;
+  }
+
+  public FunctionInfo registerGenericUDAF(String functionName,
+      GenericUDAFResolver genericUDAFResolver, FunctionResource... resources) {
+    FunctionInfo function =
+        new WindowFunctionInfo(isNative, functionName, genericUDAFResolver, resources);
+    addFunction(functionName, function);
+    addFunction(WINDOW_FUNC_PREFIX + functionName, function);
+    return function;
+  }
+
+  public FunctionInfo registerUDAF(String functionName,
+      Class<? extends UDAF> udafClass, FunctionResource... resources) {
+    validateClass(udafClass, UDAF.class);
+    FunctionInfo function = new WindowFunctionInfo(isNative, functionName,
+        new GenericUDAFBridge(ReflectionUtils.newInstance(udafClass, null)), resources);
+    addFunction(functionName, function);
+    addFunction(WINDOW_FUNC_PREFIX + functionName, function);
+    return function;
+  }
+
+  public FunctionInfo registerTableFunction(String functionName,
+      Class<? extends TableFunctionResolver> tFnCls, FunctionResource... resources) {
+    validateClass(tFnCls, TableFunctionResolver.class);
+    FunctionInfo function = new FunctionInfo(isNative, functionName, tFnCls, resources);
+    addFunction(functionName, function);
+    return function;
+  }
+
+  public FunctionInfo registerMacro(String macroName, ExprNodeDesc body,
+      List<String> colNames, List<TypeInfo> colTypes) {
+    return registerMacro(macroName, body, colNames, colTypes, null);
+  }
+
+  public FunctionInfo registerMacro(String macroName, ExprNodeDesc body,
+      List<String> colNames, List<TypeInfo> colTypes, FunctionResource... resources) {
+    GenericUDFMacro macro = new GenericUDFMacro(macroName, body, colNames, colTypes);
+    FunctionInfo fI = new FunctionInfo(isNative, macroName, macro, resources);
+    addFunction(macroName, fI);
+    return fI;
+  }
+
+  public FunctionInfo registerPermanentFunction(String functionName,
+      String className, boolean registerToSession, FunctionResource... resources) {
+    FunctionInfo function = new FunctionInfo(functionName, className, resources);
+    // register to session first for backward compatibility
+    if (registerToSession) {
+      String qualifiedName = FunctionUtils.qualifyFunctionName(
+          functionName, SessionState.get().getCurrentDatabase().toLowerCase());
+      if (registerToSessionRegistry(qualifiedName, function) != null) {
+        addFunction(functionName, function);
+        return function;
+      }
+    }
+    addFunction(functionName, function);
+    return null;
+  }
+
+  /**
+   * Typically a WindowFunction is the same as a UDAF. The only exceptions are Lead & Lag UDAFs. These
+   * are not registered as regular UDAFs because
+   * - we plan to support Lead & Lag as UDFs (usable only within argument expressions
+   *   of UDAFs when windowing is involved). Since mFunctions holds both UDFs and UDAFs we cannot
+   *   add both FunctionInfos to mFunctions.
+   *
+   * @param name
+   * @param wFn
+   */
+  void registerWindowFunction(String name, GenericUDAFResolver wFn) {
+    addFunction(WINDOW_FUNC_PREFIX + name, new WindowFunctionInfo(isNative, name, wFn, null));
+  }
+
+  private void validateClass(Class input, Class expected) {
+    if (!expected.isAssignableFrom(input)) {
+      throw new RuntimeException("Registering UDF Class " + input
+          + " which does not extend " + expected);
+    }
+  }
+
+  /**
+   * Looks up the function name in the registry. If enabled, will attempt to search the metastore
+   * for the function.
+   * @param functionName
+   * @return
+   */
+  public synchronized FunctionInfo getFunctionInfo(String functionName) throws SemanticException {
+    functionName = functionName.toLowerCase();
+    if (FunctionUtils.isQualifiedFunctionName(functionName)) {
+      return getQualifiedFunctionInfo(functionName);
+    }
+    // First try without qualifiers - would resolve builtin/temp functions.
+    // Otherwise try qualifying with current db name.
+    FunctionInfo functionInfo = mFunctions.get(functionName);
+    if (functionInfo != null && functionInfo.isBlockedFunction()) {
+      throw new SemanticException ("UDF " + functionName + " is not allowed");
+    }
+    if (functionInfo == null) {
+      String qualifiedName = FunctionUtils.qualifyFunctionName(
+          functionName, SessionState.get().getCurrentDatabase().toLowerCase());
+      functionInfo = getQualifiedFunctionInfo(qualifiedName);
+    }
+    return functionInfo;
+  }
+
+  public WindowFunctionInfo getWindowFunctionInfo(String functionName) throws SemanticException {
+    FunctionInfo info = getFunctionInfo(WINDOW_FUNC_PREFIX + functionName);
+    if (info instanceof WindowFunctionInfo) {
+      return (WindowFunctionInfo) info;
+    }
+    return null;
+  }
+
+  /**
+   * @param udfClass Function class.
+   * @return True iff the fnExpr represents a hive built-in function.
+   */
+  public boolean isBuiltInFunc(Class<?> udfClass) {
+    return udfClass != null && builtIns.contains(udfClass);
+  }
+
+  public synchronized Set<String> getCurrentFunctionNames() {
+    return getFunctionNames((Pattern)null);
+  }
+
+  public synchronized Set<String> getFunctionNames(String funcPatternStr) {
+    try {
+      return getFunctionNames(Pattern.compile(funcPatternStr));
+    } catch (PatternSyntaxException e) {
+      return Collections.emptySet();
+    }
+  }
+
+  /**
+   * Returns a set of registered function names. This is used for the CLI
+   * command "SHOW FUNCTIONS 'regular expression';" Returns an empty set when
+   * the regular expression is not valid.
+   *
+   * @param funcPattern regular expression of the interested function names
+   * @return set of strings contains function names
+   */
+  public synchronized Set<String> getFunctionNames(Pattern funcPattern) {
+    Set<String> funcNames = new TreeSet<String>();
+    for (String funcName : mFunctions.keySet()) {
+      if (funcName.contains(WINDOW_FUNC_PREFIX)) {
+        continue;
+      }
+      if (funcPattern == null || funcPattern.matcher(funcName).matches()) {
+        funcNames.add(funcName);
+      }
+    }
+    return funcNames;
+  }
+
+  /**
+   * Adds to the set of synonyms of the supplied function.
+   * @param funcName
+   * @param funcInfo
+   * @param synonyms
+   */
+  public synchronized void getFunctionSynonyms(
+      String funcName, FunctionInfo funcInfo, Set<String> synonyms) throws SemanticException {
+    Class<?> funcClass = funcInfo.getFunctionClass();
+    for (Map.Entry<String, FunctionInfo> entry : mFunctions.entrySet()) {
+      String name = entry.getKey();
+      if (name.contains(WINDOW_FUNC_PREFIX) || name.equals(funcName)) {
+        continue;
+      }
+      FunctionInfo function = entry.getValue();
+      if (function.getFunctionClass() == funcClass) {
+        synonyms.add(name);
+      }
+    }
+  }
+
+  /**
+   * Get the GenericUDAF evaluator for the name and argumentClasses.
+   *
+   * @param name         the name of the UDAF
+   * @param argumentOIs
+   * @param isDistinct
+   * @param isAllColumns
+   * @return The UDAF evaluator
+   */
+  @SuppressWarnings("deprecation")
+  public GenericUDAFEvaluator getGenericUDAFEvaluator(String name,
+      List<ObjectInspector> argumentOIs, boolean isDistinct,
+      boolean isAllColumns) throws SemanticException {
+
+    GenericUDAFResolver udafResolver = getGenericUDAFResolver(name);
+    if (udafResolver == null) {
+      return null;
+    }
+
+    GenericUDAFEvaluator udafEvaluator;
+    ObjectInspector args[] = new ObjectInspector[argumentOIs.size()];
+    // Can't use toArray here because Java is dumb when it comes to
+    // generics + arrays.
+    for (int ii = 0; ii < argumentOIs.size(); ++ii) {
+      args[ii] = argumentOIs.get(ii);
+    }
+
+    GenericUDAFParameterInfo paramInfo =
+        new SimpleGenericUDAFParameterInfo(
+            args, isDistinct, isAllColumns);
+    if (udafResolver instanceof GenericUDAFResolver2) {
+      udafEvaluator =
+          ((GenericUDAFResolver2) udafResolver).getEvaluator(paramInfo);
+    } else {
+      udafEvaluator = udafResolver.getEvaluator(paramInfo.getParameters());
+    }
+    return udafEvaluator;
+  }
+
+  public GenericUDAFEvaluator getGenericWindowingEvaluator(String functionName,
+      List<ObjectInspector> argumentOIs, boolean isDistinct, boolean isAllColumns)
+      throws SemanticException {
+    functionName = functionName.toLowerCase();
+    WindowFunctionInfo info = getWindowFunctionInfo(functionName);
+    if (info == null) {
+      return null;
+    }
+    if (!functionName.equals(FunctionRegistry.LEAD_FUNC_NAME) &&
+        !functionName.equals(FunctionRegistry.LAG_FUNC_NAME)) {
+      return getGenericUDAFEvaluator(functionName, argumentOIs, isDistinct, isAllColumns);
+    }
+
+    // this must be lead/lag UDAF
+    ObjectInspector args[] = new ObjectInspector[argumentOIs.size()];
+    GenericUDAFResolver udafResolver = info.getGenericUDAFResolver();
+    GenericUDAFParameterInfo paramInfo = new SimpleGenericUDAFParameterInfo(
+        argumentOIs.toArray(args), isDistinct, isAllColumns);
+    return ((GenericUDAFResolver2) udafResolver).getEvaluator(paramInfo);
+  }
+
+  private synchronized void addFunction(String functionName, FunctionInfo function) {
+    if (isNative ^ function.isNative()) {
+      throw new RuntimeException("Function " + functionName + " is not for this registry");
+    }
+    functionName = functionName.toLowerCase();
+    FunctionInfo prev = mFunctions.get(functionName);
+    if (prev != null) {
+      if (isBuiltInFunc(prev.getFunctionClass())) {
+        throw new RuntimeException("Function " + functionName + " is hive builtin function, " +
+            "which cannot be overriden.");
+      }
+      prev.discarded();
+    }
+    mFunctions.put(functionName, function);
+    if (function.isBuiltIn()) {
+      builtIns.add(function.getFunctionClass());
+    }
+  }
+
+  public synchronized void unregisterFunction(String functionName) throws HiveException {
+    functionName = functionName.toLowerCase();
+    FunctionInfo fi = mFunctions.get(functionName);
+    if (fi != null) {
+      if (fi.isBuiltIn()) {
+        throw new HiveException(ErrorMsg.DROP_NATIVE_FUNCTION.getMsg(functionName));
+      }
+      mFunctions.remove(functionName);
+      fi.discarded();
+    }
+  }
+
+  public GenericUDAFResolver getGenericUDAFResolver(String functionName) throws SemanticException {
+    FunctionInfo info = getFunctionInfo(functionName);
+    if (info != null) {
+      return info.getGenericUDAFResolver();
+    }
+    return null;
+  }
+
+  private FunctionInfo getQualifiedFunctionInfo(String qualifiedName) throws SemanticException {
+    FunctionInfo info = mFunctions.get(qualifiedName);
+    if (info != null && info.isBlockedFunction()) {
+      throw new SemanticException ("UDF " + qualifiedName + " is not allowed");
+    }
+    if (!isNative && info != null && info.isDiscarded()) {
+      // the persistent function is discarded. try reload
+      mFunctions.remove(qualifiedName);
+      return null;
+    }
+    // HIVE-6672: In HiveServer2 the JARs for this UDF may have been loaded by a different thread,
+    // and the current thread may not be able to resolve the UDF. Test for this condition
+    // and if necessary load the JARs in this thread.
+    if (isNative && info != null && info.isPersistent()) {
+      return registerToSessionRegistry(qualifiedName, info);
+    }
+    return info;
+  }
+
+  // should be called after session registry is checked
+  private FunctionInfo registerToSessionRegistry(String qualifiedName, FunctionInfo function) {
+    FunctionInfo ret = null;
+
+    ClassLoader prev = Utilities.getSessionSpecifiedClassLoader();
+    try {
+      // Found UDF in metastore - now add it to the function registry
+      // At this point we should add any relevant jars that would be needed for the UDf.
+      FunctionResource[] resources = function.getResources();
+      try {
+        FunctionTask.addFunctionResources(resources);
+      } catch (Exception e) {
+        LOG.error("Unable to load resources for " + qualifiedName + ":" + e, e);
+        return null;
+      }
+
+      ClassLoader loader = Utilities.getSessionSpecifiedClassLoader();
+      Class<?> udfClass = Class.forName(function.getClassName(), true, loader);
+
+      ret = FunctionRegistry.registerTemporaryUDF(qualifiedName, udfClass, resources);
+      if (ret == null) {
+        LOG.error(function.getClassName() + " is not a valid UDF class and was not registered.");
+      }
+    } catch (ClassNotFoundException e) {
+      // Lookup of UDf class failed
+      LOG.error("Unable to load UDF class: " + e);
+      Utilities.restoreSessionSpecifiedClassLoader(prev);
+    }
+    function.shareStateWith(ret);
+    return ret;
+  }
+
+  private void checkFunctionClass(FunctionInfo cfi) throws ClassNotFoundException {
+    // This call will fail for non-generic UDFs using GenericUDFBridge
+    Class<?> udfClass = cfi.getFunctionClass();
+    // Even if we have a reference to the class (which will be the case for GenericUDFs),
+    // the classloader may not be able to resolve the class, which would mean reflection-based
+    // methods would fail such as for plan deserialization. Make sure this works too.
+    Class.forName(udfClass.getName(), true, Utilities.getSessionSpecifiedClassLoader());
+  }
+
+  public synchronized void clear() {
+    if (isNative) {
+      throw new IllegalStateException("System function registry cannot be cleared");
+    }
+    mFunctions.clear();
+    builtIns.clear();
+  }
+
+  /**
+   * Setup blocked flag for all builtin UDFs as per udf whitelist and blacklist
+   * @param whiteListStr
+   * @param blackListStr
+   */
+  public void setupPermissionsForUDFs(String whiteListStr, String blackListStr) {
+    Set<String> whiteList = Sets.newHashSet(
+        Splitter.on(",").trimResults().omitEmptyStrings().split(whiteListStr.toLowerCase()));
+    Set<String> blackList = Sets.newHashSet(
+        Splitter.on(",").trimResults().omitEmptyStrings().split(blackListStr.toLowerCase()));
+    blackList.removeAll(FunctionRegistry.HIVE_OPERATORS);
+
+    for (Map.Entry<String, FunctionInfo> funcEntry : mFunctions.entrySet()) {
+      funcEntry.getValue().setBlockedFunction(
+          isUdfBlocked(funcEntry.getKey(), whiteList, blackList));
+    }
+  }
+
+  /**
+   * Check if the function belongs to whitelist or blacklist
+   * @param functionName
+   * @param whiteList
+   * @param blackList
+   * @return true if the given udf is to be blocked
+   */
+  boolean isUdfBlocked(String functionName, Set<String> whiteList, Set<String> blackList) {
+    functionName = functionName.toLowerCase();
+    return blackList.contains(functionName) ||
+        (!whiteList.isEmpty() && !whiteList.contains(functionName));
+  }
+}

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/Utilities.java Fri Feb 13 05:55:16 2015
@@ -2100,8 +2100,8 @@ public final class Utilities {
     }
     ClassLoader sessionCL = state.getConf().getClassLoader();
     if (sessionCL != null) {
-      if (LOG.isDebugEnabled()) {
-        LOG.debug("Use session specified class loader");
+      if (LOG.isTraceEnabled()) {
+        LOG.trace("Use session specified class loader");  //it's normal case
       }
       return sessionCL;
     }
@@ -2111,6 +2111,17 @@ public final class Utilities {
     return JavaUtils.getClassLoader();
   }
 
+  public static void restoreSessionSpecifiedClassLoader(ClassLoader prev) {
+    SessionState state = SessionState.get();
+    if (state != null && state.getConf() != null) {
+      ClassLoader current = state.getConf().getClassLoader();
+      if (current != prev && JavaUtils.closeClassLoadersTo(current, prev)) {
+        Thread.currentThread().setContextClassLoader(prev);
+        state.getConf().setClassLoader(prev);
+      }
+    }
+  }
+
   /**
    * Create a URL from a string representing a path to a local file.
    * The path string can be just a path, or can start with file:/, file:///

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/WindowFunctionInfo.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/WindowFunctionInfo.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/WindowFunctionInfo.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/WindowFunctionInfo.java Fri Feb 13 05:55:16 2015
@@ -22,23 +22,20 @@ import org.apache.hadoop.hive.ql.udf.gen
 import org.apache.hive.common.util.AnnotationUtils;
 
 @SuppressWarnings("deprecation")
-public class WindowFunctionInfo implements CommonFunctionInfo {
-  boolean supportsWindow = true;
-  boolean pivotResult = false;
-  boolean impliesOrder = false;
-  FunctionInfo fInfo;
-
-  WindowFunctionInfo(FunctionInfo fInfo) {
-    assert fInfo.isGenericUDAF();
-    this.fInfo = fInfo;
-    Class<? extends GenericUDAFResolver> wfnCls = fInfo.getGenericUDAFResolver().getClass();
+public class WindowFunctionInfo extends FunctionInfo {
+
+  private final boolean supportsWindow;
+  private final boolean pivotResult;
+  private final boolean impliesOrder;
+
+  public WindowFunctionInfo(boolean isNative, String functionName,
+      GenericUDAFResolver resolver, FunctionResource[] resources) {
+    super(isNative, functionName, resolver, resources);
     WindowFunctionDescription def =
-          AnnotationUtils.getAnnotation(wfnCls, WindowFunctionDescription.class);
-    if ( def != null) {
-      supportsWindow = def.supportsWindow();
-      pivotResult = def.pivotResult();
-      impliesOrder = def.impliesOrder();
-    }
+        AnnotationUtils.getAnnotation(resolver.getClass(), WindowFunctionDescription.class);
+    supportsWindow = def == null ? true : def.supportsWindow();
+    pivotResult = def == null ? false : def.pivotResult();
+    impliesOrder = def == null ? false : def.impliesOrder();
   }
 
   public boolean isSupportsWindow() {
@@ -52,12 +49,4 @@ public class WindowFunctionInfo implemen
   public boolean isImpliesOrder() {
     return impliesOrder;
   }
-  public FunctionInfo getfInfo() {
-    return fInfo;
-  }
-
-  @Override
-  public Class<?> getFunctionClass() {
-    return getfInfo().getFunctionClass();
-  }
 }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/mr/ExecDriver.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/mr/ExecDriver.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/mr/ExecDriver.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/exec/mr/ExecDriver.java Fri Feb 13 05:55:16 2015
@@ -395,6 +395,7 @@ public class ExecDriver extends Task<Map
       if (pwd != null) {
         HiveConf.setVar(job, HiveConf.ConfVars.METASTOREPWD, "HIVE");
       }
+      LOG.error(job.get("mapreduce.framework.name"));
       JobClient jc = new JobClient(job);
       // make this client wait if job tracker is not behaving well.
       Throttle.checkJobTracker(job, LOG);

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/index/IndexPredicateAnalyzer.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/index/IndexPredicateAnalyzer.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/index/IndexPredicateAnalyzer.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/index/IndexPredicateAnalyzer.java Fri Feb 13 05:55:16 2015
@@ -204,7 +204,7 @@ public class IndexPredicateAnalyzer {
   private ExprNodeDesc analyzeExpr(
     ExprNodeGenericFuncDesc expr,
     List<IndexSearchCondition> searchConditions,
-    Object... nodeOutputs) {
+    Object... nodeOutputs) throws SemanticException {
 
     if (FunctionRegistry.isOpAnd(expr)) {
       assert(nodeOutputs.length == 2);

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java Fri Feb 13 05:55:16 2015
@@ -29,7 +29,6 @@ import static org.apache.hadoop.hive.ser
 
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.net.URI;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.HashMap;
@@ -49,8 +48,6 @@ import org.apache.hadoop.conf.Configurat
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.fs.PathFilter;
-import org.apache.hadoop.fs.permission.FsPermission;
 import org.apache.hadoop.hive.common.FileUtils;
 import org.apache.hadoop.hive.common.HiveStatsUtils;
 import org.apache.hadoop.hive.common.ObjectPair;
@@ -73,7 +70,6 @@ import org.apache.hadoop.hive.metastore.
 import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
 import org.apache.hadoop.hive.metastore.api.CompactionType;
 import org.apache.hadoop.hive.metastore.api.Database;
-import org.apache.hadoop.hive.metastore.api.EventRequestType;
 import org.apache.hadoop.hive.metastore.api.FieldSchema;
 import org.apache.hadoop.hive.metastore.api.FireEventRequest;
 import org.apache.hadoop.hive.metastore.api.FireEventRequestData;
@@ -102,6 +98,8 @@ import org.apache.hadoop.hive.metastore.
 import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
 import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
 import org.apache.hadoop.hive.ql.ErrorMsg;
+import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
+import org.apache.hadoop.hive.ql.exec.FunctionTask;
 import org.apache.hadoop.hive.ql.exec.Utilities;
 import org.apache.hadoop.hive.ql.index.HiveIndexHandler;
 import org.apache.hadoop.hive.ql.io.AcidUtils;
@@ -156,6 +154,31 @@ public class Hive {
     }
   };
 
+  // register all permanent functions. need improvement
+  static {
+    try {
+      reloadFunctions();
+    } catch (Exception e) {
+      LOG.warn("Failed to access metastore. This class should not accessed in runtime.",e);
+    }
+  }
+
+  public static void reloadFunctions() throws HiveException {
+    Hive db = Hive.get();
+    for (String dbName : db.getAllDatabases()) {
+      for (String functionName : db.getFunctions(dbName, "*")) {
+        Function function = db.getFunction(dbName, functionName);
+        try {
+          FunctionRegistry.registerPermanentFunction(functionName, function.getClassName(), false,
+              FunctionTask.toFunctionResource(function.getResourceUris()));
+        } catch (Exception e) {
+          LOG.warn("Failed to register persistent function " +
+              functionName + ":" + function.getClassName() + ". Ignore and continue.");
+        }
+      }
+    }
+  }
+
   public static Hive get(Configuration c, Class<?> clazz) throws HiveException {
     return get(c instanceof HiveConf ? (HiveConf)c : new HiveConf(c, clazz));
   }
@@ -1590,10 +1613,18 @@ private void constructOneLBLocationMap(F
       throws HiveException {
     List<Path> newFiles = new ArrayList<Path>();
     Table tbl = getTable(tableName);
+    HiveConf sessionConf = SessionState.getSessionConf();
     if (replace) {
-      tbl.replaceFiles(loadPath, isSrcLocal);
+      Path tableDest = tbl.getPath();
+      replaceFiles(tableDest, loadPath, tableDest, tableDest, sessionConf, isSrcLocal);
     } else {
-      tbl.copyFiles(loadPath, isSrcLocal, isAcid, newFiles);
+      FileSystem fs;
+      try {
+        fs = tbl.getDataLocation().getFileSystem(sessionConf);
+        copyFiles(sessionConf, loadPath, tbl.getPath(), fs, isSrcLocal, isAcid, newFiles);
+      } catch (IOException e) {
+        throw new HiveException("addFiles: filesystem error in check phase", e);
+      }
       tbl.getParameters().put(StatsSetupConst.STATS_GENERATED_VIA_STATS_TASK, "true");
     }
 

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Partition.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Partition.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Partition.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Partition.java Fri Feb 13 05:55:16 2015
@@ -43,6 +43,7 @@ import org.apache.hadoop.hive.metastore.
 import org.apache.hadoop.hive.ql.exec.Utilities;
 import org.apache.hadoop.hive.ql.io.HiveFileFormatUtils;
 import org.apache.hadoop.hive.ql.io.HiveOutputFormat;
+import org.apache.hadoop.hive.ql.session.SessionState;
 import org.apache.hadoop.hive.serde2.Deserializer;
 import org.apache.hadoop.mapred.InputFormat;
 import org.apache.hadoop.mapred.OutputFormat;
@@ -246,10 +247,8 @@ public class Partition implements Serial
   final public Deserializer getDeserializer() {
     if (deserializer == null) {
       try {
-        deserializer = MetaStoreUtils.getDeserializer(Hive.get().getConf(),
+        deserializer = MetaStoreUtils.getDeserializer(SessionState.getSessionConf(),
             tPartition, table.getTTable());
-      } catch (HiveException e) {
-        throw new RuntimeException(e);
       } catch (MetaException e) {
         throw new RuntimeException(e);
       }
@@ -367,7 +366,7 @@ public class Partition implements Serial
     try {
       // Previously, this got the filesystem of the Table, which could be
       // different from the filesystem of the partition.
-      FileSystem fs = getDataLocation().getFileSystem(Hive.get().getConf());
+      FileSystem fs = getDataLocation().getFileSystem(SessionState.getSessionConf());
       String pathPattern = getDataLocation().toString();
       if (getBucketCount() > 0) {
         pathPattern = pathPattern + "/*";
@@ -495,11 +494,11 @@ public class Partition implements Serial
   public List<FieldSchema> getCols() {
 
     try {
-      if (Table.hasMetastoreBasedSchema(Hive.get().getConf(), tPartition.getSd())) {
+      if (Table.hasMetastoreBasedSchema(SessionState.getSessionConf(), tPartition.getSd())) {
         return tPartition.getSd().getCols();
       }
-      return Hive.getFieldsFromDeserializer(table.getTableName(), getDeserializer());
-    } catch (HiveException e) {
+      return MetaStoreUtils.getFieldsFromDeserializer(table.getTableName(), getDeserializer());
+    } catch (Exception e) {
       LOG.error("Unable to get cols from serde: " +
           tPartition.getSd().getSerdeInfo().getSerializationLib(), e);
     }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Table.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Table.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Table.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/metadata/Table.java Fri Feb 13 05:55:16 2015
@@ -18,7 +18,6 @@
 
 package org.apache.hadoop.hive.ql.metadata;
 
-import java.io.IOException;
 import java.io.Serializable;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -41,7 +40,6 @@ import org.apache.hadoop.hive.metastore.
 import org.apache.hadoop.hive.metastore.ProtectMode;
 import org.apache.hadoop.hive.metastore.TableType;
 import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.Index;
 import org.apache.hadoop.hive.metastore.api.MetaException;
 import org.apache.hadoop.hive.metastore.api.Order;
 import org.apache.hadoop.hive.metastore.api.SerDeInfo;
@@ -259,7 +257,7 @@ public class Table implements Serializab
   }
 
   final public Class<? extends Deserializer> getDeserializerClass() throws Exception {
-    return MetaStoreUtils.getDeserializerClass(Hive.get().getConf(), tTable);
+    return MetaStoreUtils.getDeserializerClass(SessionState.getSessionConf(), tTable);
   }
 
   final public Deserializer getDeserializer(boolean skipConfError) {
@@ -271,11 +269,9 @@ public class Table implements Serializab
 
   final public Deserializer getDeserializerFromMetaStore(boolean skipConfError) {
     try {
-      return MetaStoreUtils.getDeserializer(Hive.get().getConf(), tTable, skipConfError);
+      return MetaStoreUtils.getDeserializer(SessionState.getSessionConf(), tTable, skipConfError);
     } catch (MetaException e) {
       throw new RuntimeException(e);
-    } catch (HiveException e) {
-      throw new RuntimeException(e);
     }
   }
 
@@ -285,7 +281,7 @@ public class Table implements Serializab
     }
     try {
       storageHandler = HiveUtils.getStorageHandler(
-        Hive.get().getConf(),
+          SessionState.getSessionConf(),
         getProperty(
           org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.META_TABLE_STORAGE));
     } catch (Exception e) {
@@ -589,12 +585,12 @@ public class Table implements Serializab
 
     String serializationLib = getSerializationLib();
     try {
-      if (hasMetastoreBasedSchema(Hive.get().getConf(), serializationLib)) {
+      if (hasMetastoreBasedSchema(SessionState.getSessionConf(), serializationLib)) {
         return tTable.getSd().getCols();
       } else {
-        return Hive.getFieldsFromDeserializer(getTableName(), getDeserializer());
+        return MetaStoreUtils.getFieldsFromDeserializer(getTableName(), getDeserializer());
       }
-    } catch (HiveException e) {
+    } catch (Exception e) {
       LOG.error("Unable to get field from serde: " + serializationLib, e);
     }
     return new ArrayList<FieldSchema>();
@@ -625,45 +621,6 @@ public class Table implements Serializab
     return tTable.getSd().getNumBuckets();
   }
 
-  /**
-   * Replaces the directory corresponding to the table by srcf. Works by
-   * deleting the table directory and renaming the source directory.
-   *
-   * @param srcf
-   *          Source directory
-   * @param isSrcLocal
-   *          If the source directory is LOCAL
-   */
-  protected void replaceFiles(Path srcf, boolean isSrcLocal)
-      throws HiveException {
-    Path tableDest = getPath();
-    Hive.replaceFiles(tableDest, srcf, tableDest, tableDest, Hive.get().getConf(),
-        isSrcLocal);
-  }
-
-  /**
-   * Inserts files specified into the partition. Works by moving files
-   *
-   * @param srcf
-   *          Files to be moved. Leaf directories or globbed file paths
-   * @param isSrcLocal
-   *          If the source directory is LOCAL
-   * @param isAcid
-   *          True if this is an ACID based insert, update, or delete
-   * @param newFiles optional list of paths.  If non-null, then all files copyied to the table
-   *                 will be added to this list.
-   */
-  protected void copyFiles(Path srcf, boolean isSrcLocal, boolean isAcid, List<Path> newFiles)
-      throws HiveException {
-    FileSystem fs;
-    try {
-      fs = getDataLocation().getFileSystem(Hive.get().getConf());
-      Hive.copyFiles(Hive.get().getConf(), srcf, getPath(), fs, isSrcLocal, isAcid, newFiles);
-    } catch (IOException e) {
-      throw new HiveException("addFiles: filesystem error in check phase", e);
-    }
-  }
-
   public void setInputFormatClass(String name) throws HiveException {
     if (name == null) {
       inputFormatClass = null;
@@ -934,22 +891,12 @@ public class Table implements Serializab
     return dbName + "@" + tabName;
   }
 
-  /**
-   * @return List containing Indexes names if there are indexes on this table
-   * @throws HiveException
-   **/
-  public List<Index> getAllIndexes(short max) throws HiveException {
-    Hive hive = Hive.get();
-    return hive.getIndexes(getTTable().getDbName(), getTTable().getTableName(), max);
-  }
-
   @SuppressWarnings("nls")
   public FileStatus[] getSortedPaths() {
     try {
       // Previously, this got the filesystem of the Table, which could be
       // different from the filesystem of the partition.
-      FileSystem fs = FileSystem.get(getPath().toUri(), Hive.get()
-          .getConf());
+      FileSystem fs = FileSystem.get(getPath().toUri(), SessionState.getSessionConf());
       String pathPattern = getPath().toString();
       if (getNumBuckets() > 0) {
         pathPattern = pathPattern + "/*";

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/IndexUtils.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/IndexUtils.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/IndexUtils.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/IndexUtils.java Fri Feb 13 05:55:16 2015
@@ -190,7 +190,7 @@ public final class IndexUtils {
 
     List<Index> indexesOnTable;
     try {
-      indexesOnTable = baseTableMetaData.getAllIndexes((short) -1); // get all indexes
+      indexesOnTable = getAllIndexes(baseTableMetaData, (short) -1); // get all indexes
     } catch (HiveException e) {
       throw new SemanticException("Error accessing metastore", e);
     }
@@ -204,6 +204,14 @@ public final class IndexUtils {
     return matchingIndexes;
   }
 
+  /**
+   * @return List containing Indexes names if there are indexes on this table
+   * @throws HiveException
+   **/
+  public static List<Index> getAllIndexes(Table table, short max) throws HiveException {
+    Hive hive = Hive.get();
+    return hive.getIndexes(table.getTTable().getDbName(), table.getTTable().getTableName(), max);
+  }
 
   public static Task<?> createRootTask(HiveConf builderConf, Set<ReadEntity> inputs,
       Set<WriteEntity> outputs, StringBuilder command,

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/SqlFunctionConverter.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/SqlFunctionConverter.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/SqlFunctionConverter.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/translator/SqlFunctionConverter.java Fri Feb 13 05:55:16 2015
@@ -64,7 +64,7 @@ import com.google.common.collect.Immutab
 import com.google.common.collect.Maps;
 
 public class SqlFunctionConverter {
-  private static final Log                 LOG = LogFactory.getLog(SqlFunctionConverter.class);
+  private static final Log LOG = LogFactory.getLog(SqlFunctionConverter.class);
 
   static final Map<String, SqlOperator>    hiveToCalcite;
   static final Map<SqlOperator, HiveToken> calciteToHiveToken;
@@ -79,7 +79,7 @@ public class SqlFunctionConverter {
 
   public static SqlOperator getCalciteOperator(String funcTextName, GenericUDF hiveUDF,
       ImmutableList<RelDataType> calciteArgTypes, RelDataType retType)
-      throws CalciteSemanticException {
+      throws SemanticException {
     // handle overloaded methods first
     if (hiveUDF instanceof GenericUDFOPNegative) {
       return SqlStdOperatorTable.UNARY_MINUS;
@@ -182,7 +182,8 @@ public class SqlFunctionConverter {
     } catch (UDFArgumentException e) {
       throw new RuntimeException(e);
     }
-    return new FunctionInfo(fi.isNative(), fi.getDisplayName(), (GenericUDF) udf);
+    return new FunctionInfo(
+        fi.isNative(), fi.getDisplayName(), (GenericUDF) udf, fi.getResources());
   }
 
   // TODO: 1) handle Agg Func Name translation 2) is it correct to add func

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/ppr/PartitionPruner.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/ppr/PartitionPruner.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/ppr/PartitionPruner.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/optimizer/ppr/PartitionPruner.java Fri Feb 13 05:55:16 2015
@@ -348,7 +348,7 @@ public class PartitionPruner implements
     if (!(expr instanceof ExprNodeGenericFuncDesc)) {
       return false;
     }
-    if (!FunctionRegistry.isNativeFuncExpr((ExprNodeGenericFuncDesc)expr)) {
+    if (!FunctionRegistry.isBuiltInFuncExpr((ExprNodeGenericFuncDesc) expr)) {
       return true;
     }
     for (ExprNodeDesc child : expr.getChildren()) {

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/FunctionSemanticAnalyzer.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/FunctionSemanticAnalyzer.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/FunctionSemanticAnalyzer.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/FunctionSemanticAnalyzer.java Fri Feb 13 05:55:16 2015
@@ -28,6 +28,7 @@ import org.apache.hadoop.hive.metastore.
 import org.apache.hadoop.hive.metastore.api.ResourceType;
 import org.apache.hadoop.hive.metastore.api.ResourceUri;
 import org.apache.hadoop.hive.ql.ErrorMsg;
+import org.apache.hadoop.hive.ql.exec.FunctionInfo;
 import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
 import org.apache.hadoop.hive.ql.exec.FunctionUtils;
 import org.apache.hadoop.hive.ql.exec.TaskFactory;
@@ -35,6 +36,7 @@ import org.apache.hadoop.hive.ql.hooks.E
 import org.apache.hadoop.hive.ql.hooks.WriteEntity;
 import org.apache.hadoop.hive.ql.metadata.HiveException;
 import org.apache.hadoop.hive.ql.plan.CreateFunctionDesc;
+import org.apache.hadoop.hive.ql.plan.ReloadFunctionDesc;
 import org.apache.hadoop.hive.ql.plan.DropFunctionDesc;
 import org.apache.hadoop.hive.ql.plan.FunctionWork;
 import org.apache.hadoop.hive.ql.plan.PlanUtils;
@@ -53,11 +55,12 @@ public class FunctionSemanticAnalyzer ex
 
   @Override
   public void analyzeInternal(ASTNode ast) throws SemanticException {
-    if (ast.getToken().getType() == HiveParser.TOK_CREATEFUNCTION) {
+    if (ast.getType() == HiveParser.TOK_CREATEFUNCTION) {
       analyzeCreateFunction(ast);
-    }
-    if (ast.getToken().getType() == HiveParser.TOK_DROPFUNCTION) {
-        analyzeDropFunction(ast);
+    } else if (ast.getType() == HiveParser.TOK_DROPFUNCTION) {
+      analyzeDropFunction(ast);
+    } else if (ast.getType() == HiveParser.TOK_RELOADFUNCTION) {
+      rootTasks.add(TaskFactory.get(new FunctionWork(new ReloadFunctionDesc()), conf));
     }
 
     LOG.info("analyze done");
@@ -93,13 +96,16 @@ public class FunctionSemanticAnalyzer ex
     boolean throwException =
       !ifExists && !HiveConf.getBoolVar(conf, ConfVars.DROPIGNORESNONEXISTENT);
 
-    if (FunctionRegistry.getFunctionInfo(functionName) == null) {
+    FunctionInfo info = FunctionRegistry.getFunctionInfo(functionName);
+    if (info == null) {
       if (throwException) {
         throw new SemanticException(ErrorMsg.INVALID_FUNCTION.getMsg(functionName));
       } else {
         // Fail silently
         return;
       }
+    } else if (info.isBuiltIn()) {
+      throw new SemanticException(ErrorMsg.DROP_NATIVE_FUNCTION.getMsg(functionName));
     }
 
     boolean isTemporaryFunction = (ast.getFirstChildWithType(HiveParser.TOK_TEMPORARY) != null);

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/HiveLexer.g
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/HiveLexer.g?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/HiveLexer.g (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/HiveLexer.g Fri Feb 13 05:55:16 2015
@@ -297,6 +297,7 @@ KW_REWRITE : 'REWRITE';
 KW_AUTHORIZATION: 'AUTHORIZATION';
 KW_CONF: 'CONF';
 KW_VALUES: 'VALUES';
+KW_RELOAD: 'RELOAD';
 
 // Operators
 // NOTE: if you add a new function/operator, add it to sysFuncNames so that describe function _FUNC_ will work.

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/HiveParser.g
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/HiveParser.g?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/HiveParser.g (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/HiveParser.g Fri Feb 13 05:55:16 2015
@@ -216,6 +216,7 @@ TOK_STRINGLITERALSEQUENCE;
 TOK_CHARSETLITERAL;
 TOK_CREATEFUNCTION;
 TOK_DROPFUNCTION;
+TOK_RELOADFUNCTION;
 TOK_CREATEMACRO;
 TOK_DROPMACRO;
 TOK_TEMPORARY;
@@ -702,6 +703,7 @@ ddlStatement
     | createIndexStatement
     | dropIndexStatement
     | dropFunctionStatement
+    | reloadFunctionStatement
     | dropMacroStatement
     | analyzeStatement
     | lockStatement
@@ -1625,6 +1627,11 @@ dropFunctionStatement
     ->                  ^(TOK_DROPFUNCTION functionIdentifier ifExists?)
     ;
 
+reloadFunctionStatement
+@init { pushMsg("reload function statement", state); }
+@after { popMsg(state); }
+    : KW_RELOAD KW_FUNCTION -> ^(TOK_RELOADFUNCTION);
+
 createMacroStatement
 @init { pushMsg("create macro statement", state); }
 @after { popMsg(state); }

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/IdentifiersParser.g
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/IdentifiersParser.g?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/IdentifiersParser.g (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/IdentifiersParser.g Fri Feb 13 05:55:16 2015
@@ -572,5 +572,5 @@ principalIdentifier
 
 nonReserved
     :
-    KW_TRUE | KW_FALSE | KW_LIKE | KW_EXISTS | KW_ASC | KW_DESC | KW_ORDER | KW_GROUP | KW_BY | KW_AS | KW_INSERT | KW_OVERWRITE | KW_OUTER | KW_LEFT | KW_RIGHT | KW_FULL | KW_PARTITION | KW_PARTITIONS | KW_TABLE | KW_TABLES | KW_COLUMNS | KW_INDEX | KW_INDEXES | KW_REBUILD | KW_FUNCTIONS | KW_SHOW | KW_MSCK | KW_REPAIR | KW_DIRECTORY | KW_LOCAL | KW_USING | KW_CLUSTER | KW_DISTRIBUTE | KW_SORT | KW_LOAD | KW_EXPORT | KW_IMPORT | KW_DATA | KW_INPATH | KW_IS | KW_NULL | KW_CREATE | KW_EXTERNAL | KW_ALTER | KW_CHANGE | KW_FIRST | KW_AFTER | KW_DESCRIBE | KW_DROP | KW_RENAME | KW_IGNORE | KW_PROTECTION | KW_TO | KW_COMMENT | KW_BOOLEAN | KW_TINYINT | KW_SMALLINT | KW_INT | KW_BIGINT | KW_FLOAT | KW_DOUBLE | KW_DATE | KW_DATETIME | KW_TIMESTAMP | KW_DECIMAL | KW_STRING | KW_ARRAY | KW_STRUCT | KW_UNIONTYPE | KW_PARTITIONED | KW_CLUSTERED | KW_SORTED | KW_INTO | KW_BUCKETS | KW_ROW | KW_ROWS | KW_FORMAT | KW_DELIMITED | KW_FIELDS | KW_TERMINATED | KW_ESCAPED | KW_COLLECTION | KW_ITEMS | 
 KW_KEYS | KW_KEY_TYPE | KW_LINES | KW_STORED | KW_FILEFORMAT | KW_INPUTFORMAT | KW_OUTPUTFORMAT | KW_INPUTDRIVER | KW_OUTPUTDRIVER | KW_OFFLINE | KW_ENABLE | KW_DISABLE | KW_READONLY | KW_NO_DROP | KW_LOCATION | KW_BUCKET | KW_OUT | KW_OF | KW_PERCENT | KW_ADD | KW_REPLACE | KW_RLIKE | KW_REGEXP | KW_TEMPORARY | KW_EXPLAIN | KW_FORMATTED | KW_PRETTY | KW_DEPENDENCY | KW_LOGICAL | KW_SERDE | KW_WITH | KW_DEFERRED | KW_SERDEPROPERTIES | KW_DBPROPERTIES | KW_LIMIT | KW_SET | KW_UNSET | KW_TBLPROPERTIES | KW_IDXPROPERTIES | KW_VALUE_TYPE | KW_ELEM_TYPE | KW_MAPJOIN | KW_STREAMTABLE | KW_HOLD_DDLTIME | KW_CLUSTERSTATUS | KW_UTC | KW_UTCTIMESTAMP | KW_LONG | KW_DELETE | KW_PLUS | KW_MINUS | KW_FETCH | KW_INTERSECT | KW_VIEW | KW_IN | KW_DATABASES | KW_MATERIALIZED | KW_SCHEMA | KW_SCHEMAS | KW_GRANT | KW_REVOKE | KW_SSL | KW_UNDO | KW_LOCK | KW_LOCKS | KW_UNLOCK | KW_SHARED | KW_EXCLUSIVE | KW_PROCEDURE | KW_UNSIGNED | KW_WHILE | KW_READ | KW_READS | KW_PURGE | KW_RANGE | KW_ANALYZE | KW_
 BEFORE | KW_BETWEEN | KW_BOTH | KW_BINARY | KW_CONTINUE | KW_CURSOR | KW_TRIGGER | KW_RECORDREADER | KW_RECORDWRITER | KW_SEMI | KW_LATERAL | KW_TOUCH | KW_ARCHIVE | KW_UNARCHIVE | KW_COMPUTE | KW_STATISTICS | KW_USE | KW_OPTION | KW_CONCATENATE | KW_SHOW_DATABASE | KW_UPDATE | KW_RESTRICT | KW_CASCADE | KW_SKEWED | KW_ROLLUP | KW_CUBE | KW_DIRECTORIES | KW_FOR | KW_GROUPING | KW_SETS | KW_TRUNCATE | KW_NOSCAN | KW_USER | KW_ROLE | KW_ROLES | KW_INNER | KW_DEFINED | KW_ADMIN | KW_JAR | KW_FILE | KW_OWNER | KW_PRINCIPALS | KW_ALL | KW_DEFAULT | KW_NONE | KW_COMPACT | KW_COMPACTIONS | KW_TRANSACTIONS | KW_REWRITE | KW_AUTHORIZATION | KW_VALUES | KW_URI | KW_SERVER
+    KW_TRUE | KW_FALSE | KW_LIKE | KW_EXISTS | KW_ASC | KW_DESC | KW_ORDER | KW_GROUP | KW_BY | KW_AS | KW_INSERT | KW_OVERWRITE | KW_OUTER | KW_LEFT | KW_RIGHT | KW_FULL | KW_PARTITION | KW_PARTITIONS | KW_TABLE | KW_TABLES | KW_COLUMNS | KW_INDEX | KW_INDEXES | KW_REBUILD | KW_FUNCTIONS | KW_SHOW | KW_MSCK | KW_REPAIR | KW_DIRECTORY | KW_LOCAL | KW_USING | KW_CLUSTER | KW_DISTRIBUTE | KW_SORT | KW_LOAD | KW_EXPORT | KW_IMPORT | KW_DATA | KW_INPATH | KW_IS | KW_NULL | KW_CREATE | KW_EXTERNAL | KW_ALTER | KW_CHANGE | KW_FIRST | KW_AFTER | KW_DESCRIBE | KW_DROP | KW_RENAME | KW_IGNORE | KW_PROTECTION | KW_TO | KW_COMMENT | KW_BOOLEAN | KW_TINYINT | KW_SMALLINT | KW_INT | KW_BIGINT | KW_FLOAT | KW_DOUBLE | KW_DATE | KW_DATETIME | KW_TIMESTAMP | KW_DECIMAL | KW_STRING | KW_ARRAY | KW_STRUCT | KW_UNIONTYPE | KW_PARTITIONED | KW_CLUSTERED | KW_SORTED | KW_INTO | KW_BUCKETS | KW_ROW | KW_ROWS | KW_FORMAT | KW_DELIMITED | KW_FIELDS | KW_TERMINATED | KW_ESCAPED | KW_COLLECTION | KW_ITEMS | 
 KW_KEYS | KW_KEY_TYPE | KW_LINES | KW_STORED | KW_FILEFORMAT | KW_INPUTFORMAT | KW_OUTPUTFORMAT | KW_INPUTDRIVER | KW_OUTPUTDRIVER | KW_OFFLINE | KW_ENABLE | KW_DISABLE | KW_READONLY | KW_NO_DROP | KW_LOCATION | KW_BUCKET | KW_OUT | KW_OF | KW_PERCENT | KW_ADD | KW_REPLACE | KW_RLIKE | KW_REGEXP | KW_TEMPORARY | KW_EXPLAIN | KW_FORMATTED | KW_PRETTY | KW_DEPENDENCY | KW_LOGICAL | KW_SERDE | KW_WITH | KW_DEFERRED | KW_SERDEPROPERTIES | KW_DBPROPERTIES | KW_LIMIT | KW_SET | KW_UNSET | KW_TBLPROPERTIES | KW_IDXPROPERTIES | KW_VALUE_TYPE | KW_ELEM_TYPE | KW_MAPJOIN | KW_STREAMTABLE | KW_HOLD_DDLTIME | KW_CLUSTERSTATUS | KW_UTC | KW_UTCTIMESTAMP | KW_LONG | KW_DELETE | KW_PLUS | KW_MINUS | KW_FETCH | KW_INTERSECT | KW_VIEW | KW_IN | KW_DATABASES | KW_MATERIALIZED | KW_SCHEMA | KW_SCHEMAS | KW_GRANT | KW_REVOKE | KW_SSL | KW_UNDO | KW_LOCK | KW_LOCKS | KW_UNLOCK | KW_SHARED | KW_EXCLUSIVE | KW_PROCEDURE | KW_UNSIGNED | KW_WHILE | KW_READ | KW_READS | KW_PURGE | KW_RANGE | KW_ANALYZE | KW_
 BEFORE | KW_BETWEEN | KW_BOTH | KW_BINARY | KW_CONTINUE | KW_CURSOR | KW_TRIGGER | KW_RECORDREADER | KW_RECORDWRITER | KW_SEMI | KW_LATERAL | KW_TOUCH | KW_ARCHIVE | KW_UNARCHIVE | KW_COMPUTE | KW_STATISTICS | KW_USE | KW_OPTION | KW_CONCATENATE | KW_SHOW_DATABASE | KW_UPDATE | KW_RESTRICT | KW_CASCADE | KW_SKEWED | KW_ROLLUP | KW_CUBE | KW_DIRECTORIES | KW_FOR | KW_GROUPING | KW_SETS | KW_TRUNCATE | KW_NOSCAN | KW_USER | KW_ROLE | KW_ROLES | KW_INNER | KW_DEFINED | KW_ADMIN | KW_JAR | KW_FILE | KW_OWNER | KW_PRINCIPALS | KW_ALL | KW_DEFAULT | KW_NONE | KW_COMPACT | KW_COMPACTIONS | KW_TRANSACTIONS | KW_REWRITE | KW_AUTHORIZATION | KW_VALUES | KW_URI | KW_SERVER | KW_RELOAD
     ;

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/IndexUpdater.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/IndexUpdater.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/IndexUpdater.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/IndexUpdater.java Fri Feb 13 05:55:16 2015
@@ -30,6 +30,7 @@ import org.apache.hadoop.hive.ql.metadat
 import org.apache.hadoop.hive.ql.metadata.HiveException;
 import org.apache.hadoop.hive.ql.metadata.Partition;
 import org.apache.hadoop.hive.ql.metadata.Table;
+import org.apache.hadoop.hive.ql.optimizer.IndexUtils;
 import org.apache.hadoop.hive.ql.plan.LoadTableDesc;
 import org.apache.hadoop.hive.ql.plan.TableDesc;
 
@@ -69,7 +70,7 @@ public class IndexUpdater {
     for (LoadTableDesc ltd : loadTableWork) {
       TableDesc td = ltd.getTable();
       Table srcTable = hive.getTable(td.getTableName());
-      List<Index> tblIndexes = srcTable.getAllIndexes((short)-1);
+      List<Index> tblIndexes = IndexUtils.getAllIndexes(srcTable, (short)-1);
       Map<String, String> partSpec = ltd.getPartitionSpec();
       if (partSpec == null || partSpec.size() == 0) {
         //unpartitioned table, update whole index

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzerFactory.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzerFactory.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzerFactory.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/SemanticAnalyzerFactory.java Fri Feb 13 05:55:16 2015
@@ -260,6 +260,7 @@ public final class SemanticAnalyzerFacto
 
       case HiveParser.TOK_CREATEFUNCTION:
       case HiveParser.TOK_DROPFUNCTION:
+      case HiveParser.TOK_RELOADFUNCTION:
         return new FunctionSemanticAnalyzer(conf);
 
       case HiveParser.TOK_ANALYZE:

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/WindowingSpec.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/WindowingSpec.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/WindowingSpec.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/parse/WindowingSpec.java Fri Feb 13 05:55:16 2015
@@ -216,7 +216,8 @@ public class WindowingSpec {
    * - A Window Specification with no Order and no Window Frame is interpreted as:
          ROW BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
    */
-  private void effectiveWindowFrame(WindowFunctionSpec wFn, WindowSpec wdwSpec) {
+  private void effectiveWindowFrame(WindowFunctionSpec wFn, WindowSpec wdwSpec)
+      throws SemanticException {
 
     WindowFunctionInfo wFnInfo = FunctionRegistry.getWindowFunctionInfo(wFn.getName());
     boolean supportsWindowing = wFnInfo == null ? true : wFnInfo.isSupportsWindow();

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/FunctionWork.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/FunctionWork.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/FunctionWork.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/FunctionWork.java Fri Feb 13 05:55:16 2015
@@ -28,6 +28,7 @@ public class FunctionWork implements Ser
   private static final long serialVersionUID = 1L;
   private CreateFunctionDesc createFunctionDesc;
   private DropFunctionDesc dropFunctionDesc;
+  private ReloadFunctionDesc reloadFunctionDesc;
   private CreateMacroDesc createMacroDesc;
   private DropMacroDesc dropMacroDesc;
 
@@ -45,6 +46,10 @@ public class FunctionWork implements Ser
     this.dropFunctionDesc = dropFunctionDesc;
   }
 
+  public FunctionWork(ReloadFunctionDesc reloadFunctionDesc) {
+    this.reloadFunctionDesc = reloadFunctionDesc;
+  }
+
   public FunctionWork(CreateMacroDesc createMacroDesc) {
     this.createMacroDesc = createMacroDesc;
   }
@@ -69,6 +74,14 @@ public class FunctionWork implements Ser
     this.dropFunctionDesc = dropFunctionDesc;
   }
 
+  public ReloadFunctionDesc getReloadFunctionDesc() {
+    return reloadFunctionDesc;
+  }
+
+  public void setReloadFunctionDesc(ReloadFunctionDesc reloadFunctionDesc) {
+    this.reloadFunctionDesc = reloadFunctionDesc;
+  }
+
   public CreateMacroDesc getCreateMacroDesc() {
     return createMacroDesc;
   }

Added: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/ReloadFunctionDesc.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/ReloadFunctionDesc.java?rev=1659461&view=auto
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/ReloadFunctionDesc.java (added)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/plan/ReloadFunctionDesc.java Fri Feb 13 05:55:16 2015
@@ -0,0 +1,26 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.plan;
+
+import java.io.Serializable;
+
+@Explain(displayName = "Reload Function")
+public class ReloadFunctionDesc implements Serializable {
+  private static final long serialVersionUID = 1L;
+}

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/session/SessionState.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/session/SessionState.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/session/SessionState.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/session/SessionState.java Fri Feb 13 05:55:16 2015
@@ -26,7 +26,16 @@ import java.io.PrintStream;
 import java.net.URI;
 import java.net.URLClassLoader;
 import java.sql.Timestamp;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
 
 import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang.StringUtils;
@@ -42,6 +51,7 @@ import org.apache.hadoop.hive.conf.HiveC
 import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
 import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
 import org.apache.hadoop.hive.ql.MapRedStats;
+import org.apache.hadoop.hive.ql.exec.Registry;
 import org.apache.hadoop.hive.ql.exec.Utilities;
 import org.apache.hadoop.hive.ql.exec.spark.session.SparkSession;
 import org.apache.hadoop.hive.ql.exec.spark.session.SparkSessionManagerImpl;
@@ -252,6 +262,8 @@ public class SessionState {
    */
   private final Set<String> preReloadableAuxJars = new HashSet<String>();
 
+  private final Registry registry = new Registry();
+
   /**
    * CURRENT_TIMESTAMP value for query
    */
@@ -407,11 +419,33 @@ public class SessionState {
     return hdfsEncryptionShim;
   }
 
+  // SessionState is not available in runtime and Hive.get().getConf() is not safe to call 
+  private static class SessionStates {
+    private SessionState state;
+    private HiveConf conf;
+    private void attach(SessionState state) {
+      this.state = state;
+      attach(state.getConf());
+    }
+    private void attach(HiveConf conf) {
+      this.conf = conf;
+      ClassLoader classLoader = conf.getClassLoader();
+      if (classLoader != null) {
+        Thread.currentThread().setContextClassLoader(classLoader);
+      }
+    }
+  }
+  
   /**
    * Singleton Session object per thread.
    *
    **/
-  private static ThreadLocal<SessionState> tss = new ThreadLocal<SessionState>();
+  private static ThreadLocal<SessionStates> tss = new ThreadLocal<SessionStates>() {
+    @Override
+    protected SessionStates initialValue() {
+      return new SessionStates();
+    }
+  };
 
   /**
    * start a new session and set it to current session.
@@ -425,8 +459,7 @@ public class SessionState {
    * Sets the given session state in the thread local var for sessions.
    */
   public static void setCurrentSessionState(SessionState startSs) {
-    tss.set(startSs);
-    Thread.currentThread().setContextClassLoader(startSs.getConf().getClassLoader());
+    tss.get().attach(startSs);
   }
 
   public static void detachSession() {
@@ -752,11 +785,32 @@ public class SessionState {
    * get the current session.
    */
   public static SessionState get() {
-    return tss.get();
+    return tss.get().state;
+  }
+
+  public static HiveConf getSessionConf() {
+    SessionStates state = tss.get();
+    if (state.conf == null) {
+      state.attach(new HiveConf());
+    }
+    return state.conf;
+  }
+
+  public static Registry getRegistry() {
+    SessionState session = get();
+    return session != null ? session.registry : null;
+  }
+
+  public static Registry getRegistryForWrite() {
+    Registry registry = getRegistry();
+    if (registry == null) {
+      throw new RuntimeException("Function registery for session is not initialized");
+    }
+    return registry;
   }
 
   /**
-   * get hiveHitsory object which does structured logging.
+   * get hiveHistory object which does structured logging.
    *
    * @return The hive history object
    */
@@ -1051,13 +1105,13 @@ public class SessionState {
     return added.get(0);
   }
 
-  public List<String> add_resources(ResourceType t, List<String> values)
+  public List<String> add_resources(ResourceType t, Collection<String> values)
       throws RuntimeException {
     // By default don't convert to unix
     return add_resources(t, values, false);
   }
 
-  public List<String> add_resources(ResourceType t, List<String> values, boolean convertToUnix)
+  public List<String> add_resources(ResourceType t, Collection<String> values, boolean convertToUnix)
       throws RuntimeException {
     Set<String> resourceMap = getResourceMap(t);
 
@@ -1271,6 +1325,7 @@ public class SessionState {
   }
 
   public void close() throws IOException {
+    registry.clear();;
     if (txnMgr != null) txnMgr.closeTxnManager();
     JavaUtils.closeClassLoadersTo(conf.getClassLoader(), parentLoader);
     File resourceDir =

Modified: hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/udf/ptf/WindowingTableFunction.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/udf/ptf/WindowingTableFunction.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/udf/ptf/WindowingTableFunction.java (original)
+++ hive/trunk/ql/src/java/org/apache/hadoop/hive/ql/udf/ptf/WindowingTableFunction.java Fri Feb 13 05:55:16 2015
@@ -69,8 +69,7 @@ public class WindowingTableFunction exte
   public void execute(PTFPartitionIterator<Object> pItr, PTFPartition outP) throws HiveException {
     ArrayList<List<?>> oColumns = new ArrayList<List<?>>();
     PTFPartition iPart = pItr.getPartition();
-    StructObjectInspector inputOI;
-    inputOI = (StructObjectInspector) iPart.getOutputOI();
+    StructObjectInspector inputOI = iPart.getOutputOI();
 
     WindowTableFunctionDef wTFnDef = (WindowTableFunctionDef) getTableDef();
     Order order = wTFnDef.getOrder().getExpressions().get(0).getOrder();
@@ -145,7 +144,8 @@ public class WindowingTableFunction exte
     return true;
   }
 
-  private boolean streamingPossible(Configuration cfg, WindowFunctionDef wFnDef) {
+  private boolean streamingPossible(Configuration cfg, WindowFunctionDef wFnDef)
+      throws HiveException {
     WindowFrameDef wdwFrame = wFnDef.getWindowFrame();
     WindowFunctionInfo wFnInfo = FunctionRegistry.getWindowFunctionInfo(wFnDef
         .getName());
@@ -202,7 +202,7 @@ public class WindowingTableFunction exte
    * So no Unbounded Preceding or Following.
    */
   @SuppressWarnings("resource")
-  private int[] setCanAcceptInputAsStream(Configuration cfg) {
+  private int[] setCanAcceptInputAsStream(Configuration cfg) throws HiveException {
 
     canAcceptInputAsStream = false;
 
@@ -514,7 +514,6 @@ public class WindowingTableFunction exte
       i++;
     }
 
-    i=0;
     for(i=0; i < iPart.getOutputOI().getAllStructFieldRefs().size(); i++) {
       output.add(null);
     }

Modified: hive/trunk/ql/src/test/org/apache/hadoop/hive/ql/parse/TestMacroSemanticAnalyzer.java
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/test/org/apache/hadoop/hive/ql/parse/TestMacroSemanticAnalyzer.java?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/test/org/apache/hadoop/hive/ql/parse/TestMacroSemanticAnalyzer.java (original)
+++ hive/trunk/ql/src/test/org/apache/hadoop/hive/ql/parse/TestMacroSemanticAnalyzer.java Fri Feb 13 05:55:16 2015
@@ -66,12 +66,12 @@ public class TestMacroSemanticAnalyzer {
   @Test
   public void testDropMacroExistsDoNotIgnoreErrors() throws Exception {
     conf.setBoolVar(ConfVars.DROPIGNORESNONEXISTENT, false);
-    FunctionRegistry.registerGenericUDF(false, "SOME_MACRO", GenericUDFMacro.class);
+    FunctionRegistry.registerTemporaryUDF("SOME_MACRO", GenericUDFMacro.class);
     analyze(parse("DROP TEMPORARY MACRO SOME_MACRO"));
   }
   @Test
   public void testDropMacro() throws Exception {
-    FunctionRegistry.registerGenericUDF(false, "SOME_MACRO", GenericUDFMacro.class);
+    FunctionRegistry.registerTemporaryUDF("SOME_MACRO", GenericUDFMacro.class);
     analyze(parse("DROP TEMPORARY MACRO SOME_MACRO"));
   }
   @Test(expected = SemanticException.class)

Modified: hive/trunk/ql/src/test/queries/clientnegative/drop_native_udf.q
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/test/queries/clientnegative/drop_native_udf.q?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/test/queries/clientnegative/drop_native_udf.q (original)
+++ hive/trunk/ql/src/test/queries/clientnegative/drop_native_udf.q Fri Feb 13 05:55:16 2015
@@ -1 +1 @@
-DROP TEMPORARY FUNCTION max;
+DROP FUNCTION max;

Modified: hive/trunk/ql/src/test/results/clientnegative/create_function_nonexistent_class.q.out
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/test/results/clientnegative/create_function_nonexistent_class.q.out?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/test/results/clientnegative/create_function_nonexistent_class.q.out (original)
+++ hive/trunk/ql/src/test/results/clientnegative/create_function_nonexistent_class.q.out Fri Feb 13 05:55:16 2015
@@ -2,5 +2,5 @@ PREHOOK: query: create function default.
 PREHOOK: type: CREATEFUNCTION
 PREHOOK: Output: database:default
 PREHOOK: Output: default.badfunc
-FAILED: Class my.nonexistent.class not found
+Failed to register default.badfunc using class my.nonexistent.class
 FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.FunctionTask

Modified: hive/trunk/ql/src/test/results/clientnegative/create_function_nonudf_class.q.out
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/test/results/clientnegative/create_function_nonudf_class.q.out?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/test/results/clientnegative/create_function_nonudf_class.q.out (original)
+++ hive/trunk/ql/src/test/results/clientnegative/create_function_nonudf_class.q.out Fri Feb 13 05:55:16 2015
@@ -2,5 +2,5 @@ PREHOOK: query: create function default.
 PREHOOK: type: CREATEFUNCTION
 PREHOOK: Output: database:default
 PREHOOK: Output: default.badfunc
-FAILED: Class java.lang.String does not implement UDF, GenericUDF, or UDAF
+Failed to register default.badfunc using class java.lang.String
 FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.FunctionTask

Modified: hive/trunk/ql/src/test/results/clientnegative/drop_native_udf.q.out
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/test/results/clientnegative/drop_native_udf.q.out?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/test/results/clientnegative/drop_native_udf.q.out (original)
+++ hive/trunk/ql/src/test/results/clientnegative/drop_native_udf.q.out Fri Feb 13 05:55:16 2015
@@ -1,4 +1 @@
-PREHOOK: query: DROP TEMPORARY FUNCTION max
-PREHOOK: type: DROPFUNCTION
-PREHOOK: Output: max
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.FunctionTask
+FAILED: SemanticException [Error 10301]: Cannot drop native function max

Modified: hive/trunk/ql/src/test/results/clientnegative/udf_nonexistent_resource.q.out
URL: http://svn.apache.org/viewvc/hive/trunk/ql/src/test/results/clientnegative/udf_nonexistent_resource.q.out?rev=1659461&r1=1659460&r2=1659461&view=diff
==============================================================================
--- hive/trunk/ql/src/test/results/clientnegative/udf_nonexistent_resource.q.out (original)
+++ hive/trunk/ql/src/test/results/clientnegative/udf_nonexistent_resource.q.out Fri Feb 13 05:55:16 2015
@@ -4,4 +4,5 @@ PREHOOK: Output: database:default
 PREHOOK: Output: default.lookup
 #### A masked pattern was here ####
 nonexistent_file.txt does not exist
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.FunctionTask. nonexistent_file.txt does not exist
+Failed to register default.lookup using class org.apache.hadoop.hive.ql.udf.UDFFileLookup
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.FunctionTask