[
https://issues.apache.org/jira/browse/BEAM-10925?focusedWorklogId=532755&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-532755
]
ASF GitHub Bot logged work on BEAM-10925:
-----------------------------------------
Author: ASF GitHub Bot
Created on: 07/Jan/21 23:03
Start Date: 07/Jan/21 23:03
Worklog Time Spent: 10m
Work Description: amaliujia commented on a change in pull request #13629:
URL: https://github.com/apache/beam/pull/13629#discussion_r553643810
##########
File path:
sdks/java/extensions/sql/src/main/java/org/apache/beam/sdk/extensions/sql/impl/JavaUdfLoader.java
##########
@@ -0,0 +1,206 @@
+/*
+ * 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.impl;
+
+import com.google.auto.value.AutoValue;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.channels.ReadableByteChannel;
+import java.nio.channels.WritableByteChannel;
+import java.nio.file.ProviderNotFoundException;
+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.udf.ScalarFn;
+import org.apache.beam.sdk.extensions.sql.udf.UdfProvider;
+import org.apache.beam.sdk.io.FileSystems;
+import org.apache.beam.sdk.io.fs.ResourceId;
+import org.apache.beam.sdk.util.common.ReflectHelpers;
+import
org.apache.beam.vendor.calcite.v1_20_0.org.apache.commons.codec.digest.DigestUtils;
+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.apache.beam.vendor.guava.v26_0_jre.com.google.common.io.ByteStreams;
+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, FunctionDefinitions> cache = new
HashMap<>();
+
+ private static final ClassLoader originalClassLoader =
ReflectHelpers.findClassLoader();
+
+ /**
+ * 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 ScalarFn loadScalarFunction(List<String> functionPath, String
jarPath) {
+ String functionFullName = String.join(".", functionPath);
+ try {
+ FunctionDefinitions functionDefinitions = loadJar(jarPath);
+ if (!functionDefinitions.scalarFunctions().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.scalarFunctions().get(functionPath);
+ } catch (IOException e) {
+ throw new RuntimeException(
+ String.format(
+ "Failed to load user-defined scalar function %s from %s",
functionFullName, jarPath),
+ e);
+ }
+ }
+
+ /**
+ * Creates a temporary local copy of the file at {@code inputPath}, and
returns a handle to the
+ * local copy.
+ */
+ private File downloadFile(String inputPath, String mimeType) throws
IOException {
+ Preconditions.checkArgument(!inputPath.isEmpty(), "Path cannot be empty.");
+ ResourceId inputResource = FileSystems.matchNewResource(inputPath, false
/* is directory */);
+ try (ReadableByteChannel inputChannel = FileSystems.open(inputResource)) {
+ File outputFile = File.createTempFile("sql-udf-",
inputResource.getFilename());
+ ResourceId outputResource =
+ FileSystems.matchNewResource(outputFile.getAbsolutePath(), false /*
is directory */);
+ try (WritableByteChannel outputChannel =
FileSystems.create(outputResource, mimeType)) {
+ ByteStreams.copy(inputChannel, outputChannel);
+ }
+ // Compute and log checksum.
+ try (InputStream inputStream = new FileInputStream(outputFile)) {
+ LOG.info(
+ "Copied {} to {} with md5 hash {}.",
+ inputPath,
+ outputFile.getAbsolutePath(),
+ DigestUtils.md5Hex(inputStream));
+ }
+ return outputFile;
+ }
+ }
+
+ private ClassLoader createAndSetClassLoader(String inputJarPath) throws
IOException {
+ File tmpJar = downloadFile(inputJarPath, "application/java-archive");
+ // Set the thread's context class loader so that the jar can be staged by
the runner.
+ Thread.currentThread()
+ .setContextClassLoader(
Review comment:
I think the third option is the one that easy to implement and without
obvious harms.
I think the third option says to specify a known directory on the launcher
VM (so not on workers).
----------------------------------------------------------------
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:
[email protected]
Issue Time Tracking
-------------------
Worklog Id: (was: 532755)
Time Spent: 28h 50m (was: 28h 40m)
> ZetaSQL: Support Java UDF
> -------------------------
>
> Key: BEAM-10925
> URL: https://issues.apache.org/jira/browse/BEAM-10925
> Project: Beam
> Issue Type: New Feature
> Components: dsl-sql-zetasql
> Reporter: Kyle Weaver
> Assignee: Kyle Weaver
> Priority: P2
> Time Spent: 28h 50m
> Remaining Estimate: 0h
>
--
This message was sent by Atlassian Jira
(v8.3.4#803005)