ibzib commented on a change in pull request #13200:
URL: https://github.com/apache/beam/pull/13200#discussion_r513097859



##########
File path: 
sdks/java/extensions/sql/zetasql/src/main/java/org/apache/beam/sdk/extensions/sql/zetasql/translation/JavaUdfLoader.java
##########
@@ -0,0 +1,217 @@
+/*
+ * 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.beam.sdk.extensions.sql.zetasql.translation;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.ProviderNotFoundException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.ServiceLoader;
+import org.apache.beam.sdk.extensions.sql.UdfProvider;
+import org.apache.beam.sdk.io.FileSystems;
+import org.apache.beam.sdk.io.fs.ResourceId;
+import org.apache.beam.sdk.transforms.Combine;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.annotations.VisibleForTesting;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList;
+import 
org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Loads {@link UdfProvider} implementations from user-provided jars.
+ *
+ * <p>All UDFs are loaded and cached for each jar to mitigate IO costs.
+ */
+public class JavaUdfLoader {
+  private static final Logger LOG = 
LoggerFactory.getLogger(JavaUdfLoader.class);
+
+  /**
+   * Maps the external jar location to the functions the jar defines. Static 
so it can persist
+   * across multiple SQL transforms.
+   */
+  private static final Map<String, UserFunctionDefinitions> cache = new 
HashMap<>();
+
+  private static ClassLoader originalClassLoader = null;
+
+  /**
+   * Load a user-defined scalar function from the specified jar.
+   *
+   * <p><strong>WARNING</strong>: The first time a jar is loaded, it is added 
to the thread's
+   * context {@link ClassLoader} so that the jar can be staged by the runner.
+   */
+  public Method loadScalarFunction(List<String> functionPath, String jarPath) {
+    String functionFullName = String.join(".", functionPath);
+    try {
+      UserFunctionDefinitions functionDefinitions = loadJar(jarPath);
+      if (!functionDefinitions.javaScalarFunctions.containsKey(functionPath)) {
+        throw new IllegalArgumentException(
+            String.format(
+                "No implementation of scalar function %s found in %s.\n"
+                    + " 1. Create a class implementing %s and annotate it with 
@AutoService(%s.class).\n"
+                    + " 2. Add function %s to the class's 
userDefinedScalarFunctions implementation.",
+                functionFullName,
+                jarPath,
+                UdfProvider.class.getSimpleName(),
+                UdfProvider.class.getSimpleName(),
+                functionFullName));
+      }
+      return functionDefinitions.javaScalarFunctions.get(functionPath);
+    } catch (IOException e) {
+      throw new RuntimeException(
+          String.format(
+              "Failed to load user-defined scalar function %s from %s", 
functionFullName, jarPath),
+          e);
+    }
+  }
+
+  /**
+   * Load a user-defined aggregate function from the specified jar.
+   *
+   * <p><strong>WARNING</strong>: The first time a jar is loaded, it is added 
to the thread's
+   * context {@link ClassLoader} so that the jar can be staged by the runner.
+   */
+  public Combine.CombineFn loadAggregateFunction(List<String> functionPath, 
String jarPath) {
+    String functionFullName = String.join(".", functionPath);
+    try {
+      UserFunctionDefinitions functionDefinitions = loadJar(jarPath);
+      if 
(!functionDefinitions.javaAggregateFunctions.containsKey(functionPath)) {
+        throw new IllegalArgumentException(
+            String.format(
+                "No implementation of aggregate function %s found in %s.\n"
+                    + " 1. Create a class implementing %s and annotate it with 
@AutoService(%s.class).\n"
+                    + " 2. Add function %s to the class's 
userDefinedAggregateFunctions implementation.",
+                functionFullName,
+                jarPath,
+                UdfProvider.class.getSimpleName(),
+                UdfProvider.class.getSimpleName(),
+                functionFullName));
+      }
+      return functionDefinitions.javaAggregateFunctions.get(functionPath);
+    } catch (IOException e) {
+      throw new RuntimeException(
+          String.format(
+              "Failed to load user-defined aggregate function %s from %s",
+              functionFullName, jarPath),
+          e);
+    }
+  }
+
+  private ClassLoader createAndSetClassLoader(String inputJarPath) throws 
IOException {
+    Preconditions.checkArgument(!inputJarPath.isEmpty(), "Jar path cannot be 
empty.");
+    ResourceId inputJar = FileSystems.matchNewResource(inputJarPath, false /* 
is directory */);
+    File tmpJar = File.createTempFile("sql-udf-", inputJar.getFilename());
+    FileSystems.copy(
+        Collections.singletonList(inputJar),
+        Collections.singletonList(
+            FileSystems.matchNewResource(tmpJar.getAbsolutePath(), false /* is 
directory */)));

Review comment:
       I logged the MD5 hash.




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Reply via email to