You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@livy.apache.org by js...@apache.org on 2017/07/05 03:06:52 UTC
[23/33] incubator-livy git commit: LIVY-375. Change Livy code package
name to org.apache.livy
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/driver/JobContextImpl.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/driver/JobContextImpl.java b/rsc/src/main/java/com/cloudera/livy/rsc/driver/JobContextImpl.java
deleted file mode 100644
index de2f6a4..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/driver/JobContextImpl.java
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.driver;
-
-import java.io.File;
-import java.lang.reflect.Method;
-
-import org.apache.spark.SparkContext;
-import org.apache.spark.api.java.JavaFutureAction;
-import org.apache.spark.api.java.JavaSparkContext;
-import org.apache.spark.sql.SQLContext;
-import org.apache.spark.sql.hive.HiveContext;
-import org.apache.spark.streaming.Duration;
-import org.apache.spark.streaming.api.java.JavaStreamingContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.cloudera.livy.JobContext;
-import com.cloudera.livy.rsc.Utils;
-
-class JobContextImpl implements JobContext {
-
- private static final Logger LOG = LoggerFactory.getLogger(JobContextImpl.class);
-
- private final JavaSparkContext sc;
- private final File localTmpDir;
- private volatile SQLContext sqlctx;
- private volatile HiveContext hivectx;
- private volatile JavaStreamingContext streamingctx;
- private final RSCDriver driver;
- private volatile Object sparksession;
-
- public JobContextImpl(JavaSparkContext sc, File localTmpDir, RSCDriver driver) {
- this.sc = sc;
- this.localTmpDir = localTmpDir;
- this.driver = driver;
- }
-
- @Override
- public JavaSparkContext sc() {
- return sc;
- }
-
- @Override
- public Object sparkSession() throws Exception {
- if (sparksession == null) {
- synchronized (this) {
- if (sparksession == null) {
- try {
- Class<?> clz = Class.forName("org.apache.spark.sql.SparkSession$");
- Object spark = clz.getField("MODULE$").get(null);
- Method m = clz.getMethod("builder");
- Object builder = m.invoke(spark);
- builder.getClass().getMethod("sparkContext", SparkContext.class)
- .invoke(builder, sc.sc());
- sparksession = builder.getClass().getMethod("getOrCreate").invoke(builder);
- } catch (Exception e) {
- LOG.warn("SparkSession is not supported", e);
- throw e;
- }
- }
- }
- }
-
- return sparksession;
- }
-
- @Override
- public SQLContext sqlctx() {
- if (sqlctx == null) {
- synchronized (this) {
- if (sqlctx == null) {
- sqlctx = new SQLContext(sc);
- }
- }
- }
- return sqlctx;
- }
-
- @Override
- public HiveContext hivectx() {
- if (hivectx == null) {
- synchronized (this) {
- if (hivectx == null) {
- hivectx = new HiveContext(sc.sc());
- }
- }
- }
- return hivectx;
- }
-
- @Override
- public synchronized JavaStreamingContext streamingctx(){
- Utils.checkState(streamingctx != null, "method createStreamingContext must be called first.");
- return streamingctx;
- }
-
- @Override
- public synchronized void createStreamingContext(long batchDuration) {
- Utils.checkState(streamingctx == null, "Streaming context is not null.");
- streamingctx = new JavaStreamingContext(sc, new Duration(batchDuration));
- }
-
- @Override
- public synchronized void stopStreamingCtx() {
- Utils.checkState(streamingctx != null, "Streaming Context is null");
- streamingctx.stop();
- streamingctx = null;
- }
-
- @Override
- public File getLocalTmpDir() {
- return localTmpDir;
- }
-
- public synchronized void stop() {
- if (streamingctx != null) {
- stopStreamingCtx();
- }
- if (sc != null) {
- sc.stop();
- }
- }
-
- public void addFile(String path) {
- driver.addFile(path);
- }
-
- public void addJarOrPyFile(String path) throws Exception {
- driver.addJarOrPyFile(path);
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/driver/JobWrapper.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/driver/JobWrapper.java b/rsc/src/main/java/com/cloudera/livy/rsc/driver/JobWrapper.java
deleted file mode 100644
index bb24e6b..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/driver/JobWrapper.java
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.driver;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Future;
-import java.util.concurrent.atomic.AtomicInteger;
-
-import org.apache.spark.api.java.JavaFutureAction;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.cloudera.livy.Job;
-
-public class JobWrapper<T> implements Callable<Void> {
-
- private static final Logger LOG = LoggerFactory.getLogger(JobWrapper.class);
-
- public final String jobId;
-
- private final RSCDriver driver;
- private final Job<T> job;
- private final AtomicInteger completed;
-
- private Future<?> future;
-
- public JobWrapper(RSCDriver driver, String jobId, Job<T> job) {
- this.driver = driver;
- this.jobId = jobId;
- this.job = job;
- this.completed = new AtomicInteger();
- }
-
- @Override
- public Void call() throws Exception {
- try {
- jobStarted();
- T result = job.call(driver.jobContext());
- finished(result, null);
- } catch (Throwable t) {
- // Catch throwables in a best-effort to report job status back to the client. It's
- // re-thrown so that the executor can destroy the affected thread (or the JVM can
- // die or whatever would happen if the throwable bubbled up).
- LOG.info("Failed to run job " + jobId, t);
- finished(null, t);
- throw new ExecutionException(t);
- } finally {
- driver.activeJobs.remove(jobId);
- }
- return null;
- }
-
- void submit(ExecutorService executor) {
- this.future = executor.submit(this);
- }
-
- void jobDone() {
- synchronized (completed) {
- completed.incrementAndGet();
- completed.notifyAll();
- }
- }
-
- boolean cancel() {
- return future != null ? future.cancel(true) : true;
- }
-
- protected void finished(T result, Throwable error) {
- if (error == null) {
- driver.jobFinished(jobId, result, null);
- } else {
- driver.jobFinished(jobId, null, error);
- }
- }
-
- protected void jobStarted() {
- driver.jobStarted(jobId);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/driver/MutableClassLoader.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/driver/MutableClassLoader.java b/rsc/src/main/java/com/cloudera/livy/rsc/driver/MutableClassLoader.java
deleted file mode 100644
index 772879f..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/driver/MutableClassLoader.java
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.driver;
-
-import java.net.URL;
-import java.net.URLClassLoader;
-
-class MutableClassLoader extends URLClassLoader {
-
- MutableClassLoader(ClassLoader parent) {
- super(new URL[] { }, parent);
- }
-
- @Override
- public void addURL(URL url) {
- super.addURL(url);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/driver/RSCDriver.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/driver/RSCDriver.java b/rsc/src/main/java/com/cloudera/livy/rsc/driver/RSCDriver.java
deleted file mode 100644
index ce567b4..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/driver/RSCDriver.java
+++ /dev/null
@@ -1,510 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.driver;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URI;
-import java.nio.file.Files;
-import java.nio.file.attribute.PosixFilePermission;
-import java.nio.file.attribute.PosixFilePermissions;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.NoSuchElementException;
-import java.util.Set;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedDeque;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicReference;
-
-import io.netty.channel.ChannelHandler.Sharable;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.util.concurrent.ScheduledFuture;
-import org.apache.commons.io.FileUtils;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.spark.SparkConf;
-import org.apache.spark.SparkContext;
-import org.apache.spark.api.java.JavaSparkContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.cloudera.livy.client.common.Serializer;
-import com.cloudera.livy.rsc.BaseProtocol;
-import com.cloudera.livy.rsc.BypassJobStatus;
-import com.cloudera.livy.rsc.FutureListener;
-import com.cloudera.livy.rsc.RSCConf;
-import com.cloudera.livy.rsc.Utils;
-import com.cloudera.livy.rsc.rpc.Rpc;
-import com.cloudera.livy.rsc.rpc.RpcDispatcher;
-import com.cloudera.livy.rsc.rpc.RpcServer;
-
-import static com.cloudera.livy.rsc.RSCConf.Entry.*;
-
-/**
- * Driver code for the Spark client library.
- */
-@Sharable
-public class RSCDriver extends BaseProtocol {
-
- private static final Logger LOG = LoggerFactory.getLogger(RSCDriver.class);
-
- private final Serializer serializer;
- private final Object jcLock;
- private final Object shutdownLock;
- private final ExecutorService executor;
- private final File localTmpDir;
- // Used to queue up requests while the SparkContext is being created.
- private final List<JobWrapper<?>> jobQueue;
- // Keeps track of connected clients.
- protected final Collection<Rpc> clients;
-
- final Map<String, JobWrapper<?>> activeJobs;
- private final Collection<BypassJobWrapper> bypassJobs;
-
- private RpcServer server;
- private volatile JobContextImpl jc;
- private volatile boolean running;
-
- protected final SparkConf conf;
- protected final RSCConf livyConf;
-
- private final AtomicReference<ScheduledFuture<?>> idleTimeout;
-
- public RSCDriver(SparkConf conf, RSCConf livyConf) throws Exception {
- Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwx------");
- this.localTmpDir = Files.createTempDirectory("rsc-tmp",
- PosixFilePermissions.asFileAttribute(perms)).toFile();
- this.executor = Executors.newCachedThreadPool();
- this.jobQueue = new LinkedList<>();
- this.clients = new ConcurrentLinkedDeque<>();
- this.serializer = new Serializer();
-
- this.conf = conf;
- this.livyConf = livyConf;
- this.jcLock = new Object();
- this.shutdownLock = new Object();
-
- this.activeJobs = new ConcurrentHashMap<>();
- this.bypassJobs = new ConcurrentLinkedDeque<>();
- this.idleTimeout = new AtomicReference<>();
- }
-
- private synchronized void shutdown() {
- if (!running) {
- return;
- }
-
- running = false;
-
- // Cancel any pending jobs.
- for (JobWrapper<?> job : activeJobs.values()) {
- job.cancel();
- }
-
- try {
- shutdownContext();
- } catch (Exception e) {
- LOG.warn("Error during shutdown.", e);
- }
- try {
- shutdownServer();
- } catch (Exception e) {
- LOG.warn("Error during shutdown.", e);
- }
-
- synchronized (shutdownLock) {
- shutdownLock.notifyAll();
- }
- synchronized (jcLock) {
- jcLock.notifyAll();
- }
- }
-
- private void initializeServer() throws Exception {
- String clientId = livyConf.get(CLIENT_ID);
- Utils.checkArgument(clientId != null, "No client ID provided.");
- String secret = livyConf.get(CLIENT_SECRET);
- Utils.checkArgument(secret != null, "No secret provided.");
-
- String launcherAddress = livyConf.get(LAUNCHER_ADDRESS);
- Utils.checkArgument(launcherAddress != null, "Missing launcher address.");
- int launcherPort = livyConf.getInt(LAUNCHER_PORT);
- Utils.checkArgument(launcherPort > 0, "Missing launcher port.");
-
- LOG.info("Connecting to: {}:{}", launcherAddress, launcherPort);
-
- // We need to unset this configuration since it doesn't really apply for the driver side.
- // If the driver runs on a multi-homed machine, this can lead to issues where the Livy
- // server cannot connect to the auto-detected address, but since the driver can run anywhere
- // on the cluster, it would be tricky to solve that problem in a generic way.
- livyConf.set(RPC_SERVER_ADDRESS, null);
-
- if (livyConf.getBoolean(TEST_STUCK_START_DRIVER)) {
- // Test flag is turned on so we will just infinite loop here. It should cause
- // timeout and we should still see yarn application being cleaned up.
- LOG.info("Infinite looping as test flag TEST_STUCK_START_SESSION is turned on.");
- while(true) {
- try {
- TimeUnit.MINUTES.sleep(10);
- } catch (InterruptedException e) {
- LOG.warn("Interrupted during test sleep.", e);
- }
- }
- }
-
- // Bring up the RpcServer an register the secret provided by the Livy server as a client.
- LOG.info("Starting RPC server...");
- this.server = new RpcServer(livyConf);
- server.registerClient(clientId, secret, new RpcServer.ClientCallback() {
- @Override
- public RpcDispatcher onNewClient(Rpc client) {
- registerClient(client);
- return RSCDriver.this;
- }
-
- @Override
- public void onSaslComplete(Rpc client) {
- onClientAuthenticated(client);
- }
- });
-
- // The RPC library takes care of timing out this.
- Rpc callbackRpc = Rpc.createClient(livyConf, server.getEventLoopGroup(),
- launcherAddress, launcherPort, clientId, secret, this).get();
- try {
- callbackRpc.call(new RemoteDriverAddress(server.getAddress(), server.getPort())).get(
- livyConf.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);
- } catch (TimeoutException te) {
- LOG.warn("Timed out sending address to Livy server, shutting down.");
- throw te;
- } finally {
- callbackRpc.close();
- }
-
- // At this point we install the idle timeout handler, in case the Livy server fails to connect
- // back.
- setupIdleTimeout();
- }
-
- private void registerClient(final Rpc client) {
- clients.add(client);
- stopIdleTimeout();
-
- Utils.addListener(client.getChannel().closeFuture(), new FutureListener<Void>() {
- @Override
- public void onSuccess(Void unused) {
- clients.remove(client);
- setupIdleTimeout();
- }
- });
- LOG.debug("Registered new connection from {}.", client.getChannel());
- }
-
- private void setupIdleTimeout() {
- if (clients.size() > 0) {
- return;
- }
-
- Runnable timeoutTask = new Runnable() {
- @Override
- public void run() {
- LOG.warn("Shutting down RSC due to idle timeout ({}).", livyConf.get(SERVER_IDLE_TIMEOUT));
- shutdown();
- }
- };
- ScheduledFuture<?> timeout = server.getEventLoopGroup().schedule(timeoutTask,
- livyConf.getTimeAsMs(SERVER_IDLE_TIMEOUT), TimeUnit.MILLISECONDS);
-
- // If there's already an idle task registered, then cancel the new one.
- if (!this.idleTimeout.compareAndSet(null, timeout)) {
- LOG.debug("Timeout task already registered.");
- timeout.cancel(false);
- }
-
- // If a new client connected while the idle task was being set up, then stop the task.
- if (clients.size() > 0) {
- stopIdleTimeout();
- }
- }
-
- private void stopIdleTimeout() {
- ScheduledFuture<?> idleTimeout = this.idleTimeout.getAndSet(null);
- if (idleTimeout != null) {
- LOG.debug("Cancelling idle timeout since new client connected.");
- idleTimeout.cancel(false);
- }
- }
-
- protected void broadcast(Object msg) {
- for (Rpc client : clients) {
- try {
- client.call(msg);
- } catch (Exception e) {
- LOG.warn("Failed to send message to client " + client, e);
- }
- }
- }
-
- /**
- * Initializes the SparkContext used by this driver. This implementation creates a
- * context with the provided configuration. Subclasses can override this behavior,
- * and returning a null context is allowed. In that case, the context exposed by
- * JobContext will be null.
- */
- protected JavaSparkContext initializeContext() throws Exception {
- long t1 = System.nanoTime();
- LOG.info("Starting Spark context...");
- JavaSparkContext sc = new JavaSparkContext(conf);
- LOG.info("Spark context finished initialization in {}ms",
- TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - t1));
- return sc;
- }
-
- protected void onClientAuthenticated(final Rpc client) {
-
- }
-
- /**
- * Called to shut down the driver; any initialization done by initializeContext() should
- * be undone here. This is guaranteed to be called only once.
- */
- protected void shutdownContext() {
- if (jc != null) {
- jc.stop();
- }
- executor.shutdownNow();
- try {
- FileUtils.deleteDirectory(localTmpDir);
- } catch (IOException e) {
- LOG.warn("Failed to delete local tmp dir: " + localTmpDir, e);
- }
- }
-
- private void shutdownServer() {
- if (server != null) {
- server.close();
- }
- for (Rpc client: clients) {
- client.close();
- }
- }
-
- void run() throws Exception {
- this.running = true;
-
- // Set up a class loader that can be modified, so that we can add jars uploaded
- // by the client to the driver's class path.
- ClassLoader driverClassLoader = new MutableClassLoader(
- Thread.currentThread().getContextClassLoader());
- Thread.currentThread().setContextClassLoader(driverClassLoader);
-
- try {
- initializeServer();
-
- JavaSparkContext sc = initializeContext();
- synchronized (jcLock) {
- jc = new JobContextImpl(sc, localTmpDir, this);
- jcLock.notifyAll();
- }
-
- synchronized (jcLock) {
- for (JobWrapper<?> job : jobQueue) {
- submit(job);
- }
- jobQueue.clear();
- }
-
- synchronized (shutdownLock) {
- try {
- while (running) {
- shutdownLock.wait();
- }
- } catch (InterruptedException ie) {
- // Nothing to do.
- }
- }
- } finally {
- shutdown();
- }
- }
-
- public void submit(JobWrapper<?> job) {
- if (jc != null) {
- job.submit(executor);
- return;
- }
- synchronized (jcLock) {
- if (jc != null) {
- job.submit(executor);
- } else {
- LOG.info("SparkContext not yet up, queueing job request.");
- jobQueue.add(job);
- }
- }
- }
-
- JobContextImpl jobContext() {
- return jc;
- }
-
- Serializer serializer() {
- return serializer;
- }
-
- <T> void jobFinished(String jobId, T result, Throwable error) {
- LOG.debug("Send job({}) result to Client.", jobId);
- broadcast(new JobResult<T>(jobId, result, error));
- }
-
- void jobStarted(String jobId) {
- broadcast(new JobStarted(jobId));
- }
-
- public void handle(ChannelHandlerContext ctx, CancelJob msg) {
- JobWrapper<?> job = activeJobs.get(msg.id);
- if (job == null || !job.cancel()) {
- LOG.info("Requested to cancel an already finished job.");
- }
- }
-
- public void handle(ChannelHandlerContext ctx, EndSession msg) {
- if (livyConf.getBoolean(TEST_STUCK_END_SESSION)) {
- LOG.warn("Ignoring EndSession request because TEST_STUCK_END_SESSION is set.");
- } else {
- LOG.debug("Shutting down due to EndSession request.");
- shutdown();
- }
- }
-
- public void handle(ChannelHandlerContext ctx, JobRequest<?> msg) {
- LOG.info("Received job request {}", msg.id);
- JobWrapper<?> wrapper = new JobWrapper<>(this, msg.id, msg.job);
- activeJobs.put(msg.id, wrapper);
- submit(wrapper);
- }
-
- public void handle(ChannelHandlerContext ctx, BypassJobRequest msg) throws Exception {
- LOG.info("Received bypass job request {}", msg.id);
- BypassJobWrapper wrapper = createWrapper(msg);
- bypassJobs.add(wrapper);
- activeJobs.put(msg.id, wrapper);
- if (msg.synchronous) {
- waitForJobContext();
- try {
- wrapper.call();
- } catch (Throwable t) {
- // Wrapper already logged and saved the exception, just avoid it bubbling up
- // to the RPC layer.
- }
- } else {
- submit(wrapper);
- }
- }
-
- protected BypassJobWrapper createWrapper(BypassJobRequest msg) throws Exception {
- return new BypassJobWrapper(this, msg.id, new BypassJob(this.serializer(), msg.serializedJob));
- }
-
- @SuppressWarnings("unchecked")
- public Object handle(ChannelHandlerContext ctx, SyncJobRequest msg) throws Exception {
- waitForJobContext();
- return msg.job.call(jc);
- }
-
- public BypassJobStatus handle(ChannelHandlerContext ctx, GetBypassJobStatus msg) {
- for (Iterator<BypassJobWrapper> it = bypassJobs.iterator(); it.hasNext();) {
- BypassJobWrapper job = it.next();
- if (job.jobId.equals(msg.id)) {
- BypassJobStatus status = job.getStatus();
- switch (status.state) {
- case CANCELLED:
- case FAILED:
- case SUCCEEDED:
- it.remove();
- break;
-
- default:
- // No-op.
- }
- return status;
- }
- }
-
- throw new NoSuchElementException(msg.id);
- }
-
- private void waitForJobContext() throws InterruptedException {
- synchronized (jcLock) {
- while (jc == null) {
- jcLock.wait();
- if (!running) {
- throw new IllegalStateException("Remote context is shutting down.");
- }
- }
- }
- }
-
- protected void addFile(String path) {
- jc.sc().addFile(path);
- }
-
- protected void addJarOrPyFile(String path) throws Exception {
- File localCopyDir = new File(jc.getLocalTmpDir(), "__livy__");
- File localCopy = copyFileToLocal(localCopyDir, path, jc.sc().sc());
- addLocalFileToClassLoader(localCopy);
- jc.sc().addJar(path);
- }
-
- public void addLocalFileToClassLoader(File localCopy) throws MalformedURLException {
- MutableClassLoader cl = (MutableClassLoader) Thread.currentThread().getContextClassLoader();
- cl.addURL(localCopy.toURI().toURL());
- }
-
- public File copyFileToLocal(
- File localCopyDir,
- String filePath,
- SparkContext sc) throws Exception {
- synchronized (jc) {
- if (!localCopyDir.isDirectory() && !localCopyDir.mkdir()) {
- throw new IOException("Failed to create directory to add pyFile");
- }
- }
- URI uri = new URI(filePath);
- String name = uri.getFragment() != null ? uri.getFragment() : uri.getPath();
- name = new File(name).getName();
- File localCopy = new File(localCopyDir, name);
-
- if (localCopy.exists()) {
- throw new IOException(String.format("A file with name %s has " +
- "already been uploaded.", name));
- }
- Configuration conf = sc.hadoopConfiguration();
- FileSystem fs = FileSystem.get(uri, conf);
- fs.copyToLocalFile(new Path(uri), new Path(localCopy.toURI()));
- return localCopy;
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/driver/RSCDriverBootstrapper.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/driver/RSCDriverBootstrapper.java b/rsc/src/main/java/com/cloudera/livy/rsc/driver/RSCDriverBootstrapper.java
deleted file mode 100644
index 4c326c2..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/driver/RSCDriverBootstrapper.java
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.driver;
-
-import java.io.FileInputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.util.Properties;
-import static java.nio.charset.StandardCharsets.UTF_8;
-
-import org.apache.spark.SparkConf;
-
-import com.cloudera.livy.rsc.RSCConf;
-import static com.cloudera.livy.rsc.RSCConf.Entry.*;
-
-/**
- * The entry point for the RSC. Parses command line arguments and instantiates the correct
- * driver based on the configuration.
- *
- * The driver is expected to have a public constructor that takes a two parameters:
- * a SparkConf and a RSCConf.
- */
-public final class RSCDriverBootstrapper {
-
- public static void main(String[] args) throws Exception {
- Properties props;
-
- switch (args.length) {
- case 0:
- props = System.getProperties();
- break;
-
- case 1:
- props = new Properties();
- Reader r = new InputStreamReader(new FileInputStream(args[0]), UTF_8);
- try {
- props.load(r);
- } finally {
- r.close();
- }
- break;
-
- default:
- throw new IllegalArgumentException("Too many arguments.");
- }
-
- SparkConf conf = new SparkConf(false);
- RSCConf livyConf = new RSCConf(null);
-
- for (String key : props.stringPropertyNames()) {
- String value = props.getProperty(key);
- if (key.startsWith(RSCConf.LIVY_SPARK_PREFIX)) {
- livyConf.set(key.substring(RSCConf.LIVY_SPARK_PREFIX.length()), value);
- props.remove(key);
- } else if (key.startsWith(RSCConf.SPARK_CONF_PREFIX)) {
- conf.set(key, value);
- }
- }
-
- String driverClass = livyConf.get(DRIVER_CLASS);
- if (driverClass == null) {
- driverClass = RSCDriver.class.getName();
- }
-
- RSCDriver driver = (RSCDriver) Thread.currentThread()
- .getContextClassLoader()
- .loadClass(driverClass)
- .getConstructor(SparkConf.class, RSCConf.class)
- .newInstance(conf, livyConf);
-
- driver.run();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/driver/Statement.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/driver/Statement.java b/rsc/src/main/java/com/cloudera/livy/rsc/driver/Statement.java
deleted file mode 100644
index 67aaa1f..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/driver/Statement.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.driver;
-
-import java.util.concurrent.atomic.AtomicReference;
-
-import com.fasterxml.jackson.annotation.JsonRawValue;
-
-public class Statement {
- public final Integer id;
- public final String code;
- public final AtomicReference<StatementState> state;
- @JsonRawValue
- public volatile String output;
- public double progress;
-
- public Statement(Integer id, String code, StatementState state, String output) {
- this.id = id;
- this.code = code;
- this.state = new AtomicReference<>(state);
- this.output = output;
- this.progress = 0.0;
- }
-
- public Statement() {
- this(null, null, null, null);
- }
-
- public boolean compareAndTransit(final StatementState from, final StatementState to) {
- if (state.compareAndSet(from, to)) {
- StatementState.validate(from, to);
- return true;
- }
- return false;
- }
-
- public void updateProgress(double p) {
- if (this.state.get().isOneOf(StatementState.Cancelled, StatementState.Available)) {
- this.progress = 1.0;
- } else {
- this.progress = p;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/driver/StatementState.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/driver/StatementState.java b/rsc/src/main/java/com/cloudera/livy/rsc/driver/StatementState.java
deleted file mode 100644
index 61a86d0..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/driver/StatementState.java
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.driver;
-
-import java.util.*;
-
-import com.fasterxml.jackson.annotation.JsonValue;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public enum StatementState {
- Waiting("waiting"),
- Running("running"),
- Available("available"),
- Cancelling("cancelling"),
- Cancelled("cancelled");
-
- private static final Logger LOG = LoggerFactory.getLogger(StatementState.class);
-
- private final String state;
-
- StatementState(final String text) {
- this.state = text;
- }
-
- @JsonValue
- @Override
- public String toString() {
- return state;
- }
-
- public boolean isOneOf(StatementState... states) {
- for (StatementState s : states) {
- if (s == this) {
- return true;
- }
- }
- return false;
- }
-
- private static final Map<StatementState, List<StatementState>> PREDECESSORS;
-
- static void put(StatementState key,
- Map<StatementState, List<StatementState>> map,
- StatementState... values) {
- map.put(key, Collections.unmodifiableList(Arrays.asList(values)));
- }
-
- static {
- final Map<StatementState, List<StatementState>> predecessors =
- new EnumMap<>(StatementState.class);
- put(Waiting, predecessors);
- put(Running, predecessors, Waiting);
- put(Available, predecessors, Running);
- put(Cancelling, predecessors, Running);
- put(Cancelled, predecessors, Waiting, Cancelling);
-
- PREDECESSORS = Collections.unmodifiableMap(predecessors);
- }
-
- static boolean isValid(StatementState from, StatementState to) {
- return PREDECESSORS.get(to).contains(from);
- }
-
- static void validate(StatementState from, StatementState to) {
- LOG.debug("{} -> {}", from, to);
- if (!isValid(from, to)) {
- throw new IllegalStateException("Illegal Transition: " + from + " -> " + to);
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/rpc/KryoMessageCodec.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/KryoMessageCodec.java b/rsc/src/main/java/com/cloudera/livy/rsc/rpc/KryoMessageCodec.java
deleted file mode 100644
index b784160..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/KryoMessageCodec.java
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.rpc;
-
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.nio.ByteBuffer;
-import java.util.Arrays;
-import java.util.List;
-
-import com.esotericsoftware.kryo.Kryo;
-import com.esotericsoftware.kryo.io.ByteBufferInputStream;
-import com.esotericsoftware.kryo.io.Input;
-import com.esotericsoftware.kryo.io.Output;
-import com.esotericsoftware.shaded.org.objenesis.strategy.StdInstantiatorStrategy;
-import io.netty.buffer.ByteBuf;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.handler.codec.ByteToMessageCodec;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.cloudera.livy.client.common.Serializer;
-import com.cloudera.livy.rsc.Utils;
-
-/**
- * Codec that serializes / deserializes objects using Kryo. Objects are encoded with a 4-byte
- * header with the length of the serialized data.
- */
-class KryoMessageCodec extends ByteToMessageCodec<Object> {
-
- private static final Logger LOG = LoggerFactory.getLogger(KryoMessageCodec.class);
-
- private final int maxMessageSize;
- private final Serializer serializer;
- private volatile EncryptionHandler encryptionHandler;
-
- public KryoMessageCodec(int maxMessageSize, Class<?>... messages) {
- this.maxMessageSize = maxMessageSize;
- this.serializer = new Serializer(messages);
- this.encryptionHandler = null;
- }
-
- @Override
- protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out)
- throws Exception {
- if (in.readableBytes() < 4) {
- return;
- }
-
- in.markReaderIndex();
- int msgSize = in.readInt();
- checkSize(msgSize);
-
- if (in.readableBytes() < msgSize) {
- // Incomplete message in buffer.
- in.resetReaderIndex();
- return;
- }
-
- try {
- ByteBuffer nioBuffer = maybeDecrypt(in.nioBuffer(in.readerIndex(), msgSize));
- Object msg = serializer.deserialize(nioBuffer);
- LOG.debug("Decoded message of type {} ({} bytes)",
- msg != null ? msg.getClass().getName() : msg, msgSize);
- out.add(msg);
- } finally {
- in.skipBytes(msgSize);
- }
- }
-
- @Override
- protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf buf)
- throws Exception {
- ByteBuffer msgData = maybeEncrypt(serializer.serialize(msg));
- LOG.debug("Encoded message of type {} ({} bytes)", msg.getClass().getName(),
- msgData.remaining());
- checkSize(msgData.remaining());
-
- buf.ensureWritable(msgData.remaining() + 4);
- buf.writeInt(msgData.remaining());
- buf.writeBytes(msgData);
- }
-
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- if (encryptionHandler != null) {
- encryptionHandler.dispose();
- }
- super.channelInactive(ctx);
- }
-
- private void checkSize(int msgSize) {
- Utils.checkArgument(msgSize > 0, "Message size (%s bytes) must be positive.", msgSize);
- Utils.checkArgument(maxMessageSize <= 0 || msgSize <= maxMessageSize,
- "Message (%s bytes) exceeds maximum allowed size (%s bytes).", msgSize, maxMessageSize);
- }
-
- private ByteBuffer maybeEncrypt(ByteBuffer data) throws Exception {
- return doWrapOrUnWrap(data, true);
- }
-
- private ByteBuffer maybeDecrypt(ByteBuffer data) throws Exception {
- return doWrapOrUnWrap(data, false);
- }
-
- private ByteBuffer doWrapOrUnWrap(ByteBuffer data, boolean wrap) throws IOException {
- if (encryptionHandler == null) {
- return data;
- }
-
- byte[] byteData;
- int len = data.limit() - data.position();
- int offset;
- if (data.hasArray()) {
- byteData = data.array();
- offset = data.position() + data.arrayOffset();
- data.position(data.limit());
- } else {
- byteData = new byte[len];
- offset = 0;
- data.get(byteData);
- }
-
- byte[] result;
- if (wrap) {
- result = encryptionHandler.wrap(byteData, offset, len);
- } else {
- result = encryptionHandler.unwrap(byteData, offset, len);
- }
- return ByteBuffer.wrap(result);
- }
-
- void setEncryptionHandler(EncryptionHandler handler) {
- this.encryptionHandler = handler;
- }
-
- interface EncryptionHandler {
-
- byte[] wrap(byte[] data, int offset, int len) throws IOException;
-
- byte[] unwrap(byte[] data, int offset, int len) throws IOException;
-
- void dispose() throws IOException;
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/rpc/README.md
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/README.md b/rsc/src/main/java/com/cloudera/livy/rsc/rpc/README.md
deleted file mode 100644
index ca9e98c..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/README.md
+++ /dev/null
@@ -1,32 +0,0 @@
-Spark Client RPC
-================
-
-Basic flow of events:
-
-- Client side creates an RPC server
-- Client side spawns RemoteDriver, which manages the SparkContext, and provides a secret
-- Client side sets up a timer to wait for RemoteDriver to connect back
-- RemoteDriver connects back to client, SASL handshake ensues
-- Connection is established and now there's a session between the client and the driver.
-
-Features of the RPC layer:
-
-- All messages serialized via Kryo
-- All messages are replied to. It's either an empty "ack" or an actual response - that depends
- on the message.
-- RPC send API is asynchronous - callers get a future that can be used to wait for the message.
-- Currently, no connection retry. If connection goes down, both sides tear down the session.
-
-Notes:
-
-- Because serialization is using Kryo, types need explicit empty constructors or things will
- fail to deserialize. This can be seen in the way exceptions are propagated - the throwing
- side sends just a string stack trace to the remote, because certain fields on exceptions
- don't have empty constructors.
-- The above is especially important because at the moment there's no way to register custom
- serializers in the RPC library.
-
-Future work:
-
-- Random initial RPC id + id wrapping.
-- SSL / security in general.
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/rpc/Rpc.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/Rpc.java b/rsc/src/main/java/com/cloudera/livy/rsc/rpc/Rpc.java
deleted file mode 100644
index f095eff..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/Rpc.java
+++ /dev/null
@@ -1,460 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.rpc;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReference;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.sasl.RealmCallback;
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslClient;
-import javax.security.sasl.SaslException;
-
-import io.netty.bootstrap.Bootstrap;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelFuture;
-import io.netty.channel.ChannelFutureListener;
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.ChannelInboundHandlerAdapter;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.embedded.EmbeddedChannel;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioSocketChannel;
-import io.netty.handler.logging.LogLevel;
-import io.netty.handler.logging.LoggingHandler;
-import io.netty.util.concurrent.EventExecutorGroup;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.GenericFutureListener;
-import io.netty.util.concurrent.ImmediateEventExecutor;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.concurrent.ScheduledFuture;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.cloudera.livy.rsc.RSCConf;
-import com.cloudera.livy.rsc.Utils;
-import static com.cloudera.livy.rsc.RSCConf.Entry.*;
-
-/**
- * Encapsulates the RPC functionality. Provides higher-level methods to talk to the remote
- * endpoint.
- */
-public class Rpc implements Closeable {
-
- private static final Logger LOG = LoggerFactory.getLogger(Rpc.class);
-
- static final String SASL_REALM = "rsc";
- static final String SASL_USER = "rsc";
- static final String SASL_PROTOCOL = "rsc";
- static final String SASL_AUTH_CONF = "auth-conf";
-
- /**
- * Creates an RPC client for a server running on the given remote host and port.
- *
- * @param config RPC configuration data.
- * @param eloop Event loop for managing the connection.
- * @param host Host name or IP address to connect to.
- * @param port Port where server is listening.
- * @param clientId The client ID that identifies the connection.
- * @param secret Secret for authenticating the client with the server.
- * @param dispatcher Dispatcher used to handle RPC calls.
- * @return A future that can be used to monitor the creation of the RPC object.
- */
- public static Promise<Rpc> createClient(
- final RSCConf config,
- final EventLoopGroup eloop,
- String host,
- int port,
- final String clientId,
- final String secret,
- final RpcDispatcher dispatcher) throws Exception {
- int connectTimeoutMs = (int) config.getTimeAsMs(RPC_CLIENT_CONNECT_TIMEOUT);
-
- final ChannelFuture cf = new Bootstrap()
- .group(eloop)
- .handler(new ChannelInboundHandlerAdapter() { })
- .channel(NioSocketChannel.class)
- .option(ChannelOption.SO_KEEPALIVE, true)
- .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, connectTimeoutMs)
- .connect(host, port);
-
- final Promise<Rpc> promise = eloop.next().newPromise();
- final AtomicReference<Rpc> rpc = new AtomicReference<Rpc>();
-
- // Set up a timeout to undo everything.
- final Runnable timeoutTask = new Runnable() {
- @Override
- public void run() {
- promise.setFailure(new TimeoutException("Timed out waiting for RPC server connection."));
- }
- };
- final ScheduledFuture<?> timeoutFuture = eloop.schedule(timeoutTask,
- config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT), TimeUnit.MILLISECONDS);
-
- // The channel listener instantiates the Rpc instance when the connection is established,
- // and initiates the SASL handshake.
- cf.addListener(new ChannelFutureListener() {
- @Override
- public void operationComplete(ChannelFuture cf) throws Exception {
- if (cf.isSuccess()) {
- SaslClientHandler saslHandler = new SaslClientHandler(config, clientId, promise,
- timeoutFuture, secret, dispatcher);
- Rpc rpc = createRpc(config, saslHandler, (SocketChannel) cf.channel(), eloop);
- saslHandler.rpc = rpc;
- saslHandler.sendHello(cf.channel());
- } else {
- promise.setFailure(cf.cause());
- }
- }
- });
-
- // Handle cancellation of the promise.
- promise.addListener(new GenericFutureListener<Promise<Rpc>>() {
- @Override
- public void operationComplete(Promise<Rpc> p) {
- if (p.isCancelled()) {
- cf.cancel(true);
- }
- }
- });
-
- return promise;
- }
-
- static Rpc createServer(SaslHandler saslHandler, RSCConf config, SocketChannel channel,
- EventExecutorGroup egroup) throws IOException {
- return createRpc(config, saslHandler, channel, egroup);
- }
-
- private static Rpc createRpc(RSCConf config,
- SaslHandler saslHandler,
- SocketChannel client,
- EventExecutorGroup egroup)
- throws IOException {
- LogLevel logLevel = LogLevel.TRACE;
- String logLevelStr = config.get(RPC_CHANNEL_LOG_LEVEL);
- if (logLevelStr != null) {
- try {
- logLevel = LogLevel.valueOf(logLevelStr);
- } catch (Exception e) {
- LOG.warn("Invalid log level {}, reverting to default.", logLevelStr);
- }
- }
-
- boolean logEnabled = false;
- switch (logLevel) {
- case DEBUG:
- logEnabled = LOG.isDebugEnabled();
- break;
- case ERROR:
- logEnabled = LOG.isErrorEnabled();
- break;
- case INFO:
- logEnabled = LOG.isInfoEnabled();
- break;
- case TRACE:
- logEnabled = LOG.isTraceEnabled();
- break;
- case WARN:
- logEnabled = LOG.isWarnEnabled();
- break;
- }
-
- if (logEnabled) {
- client.pipeline().addLast("logger", new LoggingHandler(Rpc.class, logLevel));
- }
-
- KryoMessageCodec kryo = new KryoMessageCodec(config.getInt(RPC_MAX_MESSAGE_SIZE),
- MessageHeader.class, NullMessage.class, SaslMessage.class);
- saslHandler.setKryoMessageCodec(kryo);
- client.pipeline()
- .addLast("codec", kryo)
- .addLast("sasl", saslHandler);
- return new Rpc(config, client, egroup);
- }
-
- static Rpc createEmbedded(RpcDispatcher dispatcher) {
- EmbeddedChannel c = new EmbeddedChannel(
- new LoggingHandler(Rpc.class),
- new KryoMessageCodec(0, MessageHeader.class, NullMessage.class),
- dispatcher);
- Rpc rpc = new Rpc(new RSCConf(null), c, ImmediateEventExecutor.INSTANCE);
- rpc.dispatcher = dispatcher;
- return rpc;
- }
-
- private final RSCConf config;
- private final AtomicBoolean rpcClosed;
- private final AtomicLong rpcId;
- private final Channel channel;
- private final EventExecutorGroup egroup;
- private volatile RpcDispatcher dispatcher;
-
- private Rpc(RSCConf config, Channel channel, EventExecutorGroup egroup) {
- Utils.checkArgument(channel != null);
- Utils.checkArgument(egroup != null);
- this.config = config;
- this.channel = channel;
- this.dispatcher = null;
- this.egroup = egroup;
- this.rpcClosed = new AtomicBoolean();
- this.rpcId = new AtomicLong();
-
- // Note: this does not work for embedded channels.
- channel.pipeline().addLast("monitor", new ChannelInboundHandlerAdapter() {
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- close();
- super.channelInactive(ctx);
- }
- });
- }
-
- /**
- * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the
- * operation.
- */
- public Future<Void> call(Object msg) {
- return call(msg, Void.class);
- }
-
- /**
- * Send an RPC call to the remote endpoint and returns a future that can be used to monitor the
- * operation.
- *
- * @param msg RPC call to send.
- * @param retType Type of expected reply.
- * @return A future used to monitor the operation.
- */
- public <T> Future<T> call(final Object msg, Class<T> retType) {
- Utils.checkArgument(msg != null);
- Utils.checkState(channel.isOpen(), "RPC channel is closed.");
- try {
- final long id = rpcId.getAndIncrement();
- final Promise<T> promise = egroup.next().newPromise();
- final ChannelFutureListener listener = new ChannelFutureListener() {
- @Override
- public void operationComplete(ChannelFuture cf) {
- if (!cf.isSuccess() && !promise.isDone()) {
- LOG.warn("Failed to send RPC, closing connection.", cf.cause());
- promise.setFailure(cf.cause());
- dispatcher.discardRpc(id);
- close();
- }
- }
- };
-
- dispatcher.registerRpc(id, promise, msg.getClass().getName());
- channel.eventLoop().submit(new Runnable() {
- @Override
- public void run() {
- channel.write(new MessageHeader(id, Rpc.MessageType.CALL)).addListener(listener);
- channel.writeAndFlush(msg).addListener(listener);
- }
- });
-
- return promise;
- } catch (Exception e) {
- throw Utils.propagate(e);
- }
- }
-
- public Channel getChannel() {
- return channel;
- }
-
- void setDispatcher(RpcDispatcher dispatcher) {
- Utils.checkNotNull(dispatcher);
- Utils.checkState(this.dispatcher == null, "Dispatcher already set.");
- this.dispatcher = dispatcher;
- channel.pipeline().addLast("dispatcher", dispatcher);
- }
-
- @Override
- public void close() {
- if (!rpcClosed.compareAndSet(false, true)) {
- return;
- }
- try {
- channel.close().sync();
- } catch (InterruptedException ie) {
- Thread.interrupted();
- }
- }
-
- static enum MessageType {
- CALL,
- REPLY,
- ERROR;
- }
-
- static class MessageHeader {
- final long id;
- final MessageType type;
-
- MessageHeader() {
- this(-1, null);
- }
-
- MessageHeader(long id, MessageType type) {
- this.id = id;
- this.type = type;
- }
-
- }
-
- static class NullMessage {
-
- }
-
- static class SaslMessage {
- final String clientId;
- final byte[] payload;
-
- SaslMessage() {
- this(null, null);
- }
-
- SaslMessage(byte[] payload) {
- this(null, payload);
- }
-
- SaslMessage(String clientId, byte[] payload) {
- this.clientId = clientId;
- this.payload = payload;
- }
-
- }
-
- private static class SaslClientHandler extends SaslHandler implements CallbackHandler {
-
- private final SaslClient client;
- private final String clientId;
- private final String secret;
- private final RpcDispatcher dispatcher;
- private Promise<Rpc> promise;
- private ScheduledFuture<?> timeout;
-
- // Can't be set in constructor due to circular dependency.
- private Rpc rpc;
-
- SaslClientHandler(
- RSCConf config,
- String clientId,
- Promise<Rpc> promise,
- ScheduledFuture<?> timeout,
- String secret,
- RpcDispatcher dispatcher)
- throws IOException {
- super(config);
- this.clientId = clientId;
- this.promise = promise;
- this.timeout = timeout;
- this.secret = secret;
- this.dispatcher = dispatcher;
- this.client = Sasl.createSaslClient(new String[] { config.get(SASL_MECHANISMS) },
- null, SASL_PROTOCOL, SASL_REALM, config.getSaslOptions(), this);
- }
-
- @Override
- protected boolean isComplete() {
- return client.isComplete();
- }
-
- @Override
- protected String getNegotiatedProperty(String name) {
- return (String) client.getNegotiatedProperty(name);
- }
-
- @Override
- protected SaslMessage update(SaslMessage challenge) throws IOException {
- byte[] response = client.evaluateChallenge(challenge.payload);
- return response != null ? new SaslMessage(response) : null;
- }
-
- @Override
- public byte[] wrap(byte[] data, int offset, int len) throws IOException {
- return client.wrap(data, offset, len);
- }
-
- @Override
- public byte[] unwrap(byte[] data, int offset, int len) throws IOException {
- return client.unwrap(data, offset, len);
- }
-
- @Override
- public void dispose() throws IOException {
- if (!client.isComplete()) {
- onError(new SaslException("Client closed before SASL negotiation finished."));
- }
- client.dispose();
- }
-
- @Override
- protected void onComplete() throws Exception {
- timeout.cancel(true);
- rpc.setDispatcher(dispatcher);
- promise.setSuccess(rpc);
- timeout = null;
- promise = null;
- }
-
- @Override
- protected void onError(Throwable error) {
- timeout.cancel(true);
- if (!promise.isDone()) {
- promise.setFailure(error);
- }
- }
-
- @Override
- public void handle(Callback[] callbacks) {
- for (Callback cb : callbacks) {
- if (cb instanceof NameCallback) {
- ((NameCallback)cb).setName(clientId);
- } else if (cb instanceof PasswordCallback) {
- ((PasswordCallback)cb).setPassword(secret.toCharArray());
- } else if (cb instanceof RealmCallback) {
- RealmCallback rb = (RealmCallback) cb;
- rb.setText(rb.getDefaultText());
- }
- }
- }
-
- void sendHello(Channel c) throws Exception {
- byte[] hello = client.hasInitialResponse() ?
- client.evaluateChallenge(new byte[0]) : new byte[0];
- c.writeAndFlush(new SaslMessage(clientId, hello)).sync();
- }
-
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcDispatcher.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcDispatcher.java b/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcDispatcher.java
deleted file mode 100644
index 38f6867..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcDispatcher.java
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.rpc;
-
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentLinkedQueue;
-
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import io.netty.util.concurrent.Promise;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.cloudera.livy.rsc.Utils;
-
-/**
- * An implementation of ChannelInboundHandler that dispatches incoming messages to an instance
- * method based on the method signature.
- * <p/>
- * A handler's signature must be of the form:
- * <p/>
- * <blockquote><tt>protected void handle(ChannelHandlerContext, MessageType)</tt></blockquote>
- * <p/>
- * Where "MessageType" must match exactly the type of the message to handle. Polymorphism is not
- * supported. Handlers can return a value, which becomes the RPC reply; if a null is returned, then
- * a reply is still sent, with an empty payload.
- */
-public abstract class RpcDispatcher extends SimpleChannelInboundHandler<Object> {
-
- private static final Logger LOG = LoggerFactory.getLogger(RpcDispatcher.class);
-
- private final Map<Class<?>, Method> handlers = new ConcurrentHashMap<>();
- private final Collection<OutstandingRpc> rpcs = new ConcurrentLinkedQueue<OutstandingRpc>();
-
- private volatile Rpc.MessageHeader lastHeader;
-
- /** Override this to add a name to the dispatcher, for debugging purposes. */
- protected String name() {
- return getClass().getSimpleName();
- }
-
- @Override
- protected final void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
- if (lastHeader == null) {
- if (!(msg instanceof Rpc.MessageHeader)) {
- LOG.warn("[{}] Expected RPC header, got {} instead.", name(),
- msg != null ? msg.getClass().getName() : null);
- throw new IllegalArgumentException();
- }
- lastHeader = (Rpc.MessageHeader) msg;
- } else {
- LOG.debug("[{}] Received RPC message: type={} id={} payload={}", name(),
- lastHeader.type, lastHeader.id, msg != null ? msg.getClass().getName() : null);
- try {
- switch (lastHeader.type) {
- case CALL:
- handleCall(ctx, msg);
- break;
- case REPLY:
- handleReply(ctx, msg, findRpc(lastHeader.id));
- break;
- case ERROR:
- handleError(ctx, msg, findRpc(lastHeader.id));
- break;
- default:
- throw new IllegalArgumentException("Unknown RPC message type: " + lastHeader.type);
- }
- } finally {
- lastHeader = null;
- }
- }
- }
-
- private OutstandingRpc findRpc(long id) {
- for (Iterator<OutstandingRpc> it = rpcs.iterator(); it.hasNext();) {
- OutstandingRpc rpc = it.next();
- if (rpc.id == id) {
- it.remove();
- return rpc;
- }
- }
- throw new IllegalArgumentException(String.format(
- "Received RPC reply for unknown RPC (%d).", id));
- }
-
- private void handleCall(ChannelHandlerContext ctx, Object msg) throws Exception {
- Method handler = handlers.get(msg.getClass());
- if (handler == null) {
- // Try both getDeclaredMethod() and getMethod() so that we try both private methods
- // of the class, and public methods of parent classes.
- try {
- handler = getClass().getDeclaredMethod("handle", ChannelHandlerContext.class,
- msg.getClass());
- } catch (NoSuchMethodException e) {
- try {
- handler = getClass().getMethod("handle", ChannelHandlerContext.class,
- msg.getClass());
- } catch (NoSuchMethodException e2) {
- LOG.warn(String.format("[%s] Failed to find handler for msg '%s'.", name(),
- msg.getClass().getName()));
- writeMessage(ctx, Rpc.MessageType.ERROR, Utils.stackTraceAsString(e.getCause()));
- return;
- }
- }
- handler.setAccessible(true);
- handlers.put(msg.getClass(), handler);
- }
-
- try {
- Object payload = handler.invoke(this, ctx, msg);
- if (payload == null) {
- payload = new Rpc.NullMessage();
- }
- writeMessage(ctx, Rpc.MessageType.REPLY, payload);
- } catch (InvocationTargetException ite) {
- LOG.debug(String.format("[%s] Error in RPC handler.", name()), ite.getCause());
- writeMessage(ctx, Rpc.MessageType.ERROR, Utils.stackTraceAsString(ite.getCause()));
- }
- }
-
- private void writeMessage(ChannelHandlerContext ctx, Rpc.MessageType replyType, Object payload) {
- ctx.channel().write(new Rpc.MessageHeader(lastHeader.id, replyType));
- ctx.channel().writeAndFlush(payload);
- }
-
- private void handleReply(ChannelHandlerContext ctx, Object msg, OutstandingRpc rpc)
- throws Exception {
- rpc.future.setSuccess(msg instanceof Rpc.NullMessage ? null : msg);
- }
-
- private void handleError(ChannelHandlerContext ctx, Object msg, OutstandingRpc rpc)
- throws Exception {
- if (msg instanceof String) {
- LOG.warn("Received error message:{}.", msg);
- rpc.future.setFailure(new RpcException((String) msg));
- } else {
- String error = String.format("Received error with unexpected payload (%s).",
- msg != null ? msg.getClass().getName() : null);
- LOG.warn(String.format("[%s] %s", name(), error));
- rpc.future.setFailure(new IllegalArgumentException(error));
- ctx.close();
- }
- }
-
- @Override
- public final void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- if (LOG.isDebugEnabled()) {
- LOG.debug(String.format("[%s] Caught exception in channel pipeline.", name()), cause);
- } else {
- LOG.info("[{}] Closing channel due to exception in pipeline ({}).", name(),
- cause.getMessage());
- }
-
- if (lastHeader != null) {
- // There's an RPC waiting for a reply. Exception was most probably caught while processing
- // the RPC, so send an error.
- ctx.channel().write(new Rpc.MessageHeader(lastHeader.id, Rpc.MessageType.ERROR));
- ctx.channel().writeAndFlush(Utils.stackTraceAsString(cause));
- lastHeader = null;
- }
-
- ctx.close();
- }
-
- @Override
- public final void channelInactive(ChannelHandlerContext ctx) throws Exception {
- if (rpcs.size() > 0) {
- LOG.warn("[{}] Closing RPC channel with {} outstanding RPCs.", name(), rpcs.size());
- for (OutstandingRpc rpc : rpcs) {
- rpc.future.cancel(true);
- }
- } else {
- LOG.debug("Channel {} became inactive.", ctx.channel());
- }
- super.channelInactive(ctx);
- }
-
- void registerRpc(long id, Promise<?> promise, String type) {
- LOG.debug("[{}] Registered outstanding rpc {} ({}).", name(), id, type);
- rpcs.add(new OutstandingRpc(id, promise));
- }
-
- void discardRpc(long id) {
- LOG.debug("[{}] Discarding failed RPC {}.", name(), id);
- findRpc(id);
- }
-
- private static class OutstandingRpc {
- final long id;
- final Promise<Object> future;
-
- @SuppressWarnings("unchecked")
- OutstandingRpc(long id, Promise<?> future) {
- this.id = id;
- this.future = (Promise<Object>) future;
- }
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcException.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcException.java b/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcException.java
deleted file mode 100644
index d382df9..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcException.java
+++ /dev/null
@@ -1,26 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.rpc;
-
-public class RpcException extends RuntimeException {
-
- RpcException(String remoteStackTrace) {
- super(remoteStackTrace);
- }
-
-}
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcServer.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcServer.java b/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcServer.java
deleted file mode 100644
index 44db976..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/RpcServer.java
+++ /dev/null
@@ -1,368 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.rpc;
-
-import java.io.Closeable;
-import java.io.IOException;
-import java.net.BindException;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.SocketException;
-import java.security.SecureRandom;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.TimeUnit;
-import javax.security.auth.callback.Callback;
-import javax.security.auth.callback.CallbackHandler;
-import javax.security.auth.callback.NameCallback;
-import javax.security.auth.callback.PasswordCallback;
-import javax.security.sasl.AuthorizeCallback;
-import javax.security.sasl.RealmCallback;
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslException;
-import javax.security.sasl.SaslServer;
-
-import io.netty.bootstrap.ServerBootstrap;
-import io.netty.channel.Channel;
-import io.netty.channel.ChannelInitializer;
-import io.netty.channel.ChannelOption;
-import io.netty.channel.EventLoopGroup;
-import io.netty.channel.nio.NioEventLoopGroup;
-import io.netty.channel.socket.SocketChannel;
-import io.netty.channel.socket.nio.NioServerSocketChannel;
-import io.netty.util.concurrent.ScheduledFuture;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.cloudera.livy.rsc.RSCConf;
-import com.cloudera.livy.rsc.Utils;
-import static com.cloudera.livy.rsc.RSCConf.Entry.*;
-
-/**
- * An RPC server. The server matches remote clients based on a secret that is generated on
- * the server - the secret needs to be given to the client through some other mechanism for
- * this to work.
- */
-public class RpcServer implements Closeable {
-
- private static final Logger LOG = LoggerFactory.getLogger(RpcServer.class);
- private static final SecureRandom RND = new SecureRandom();
-
- private final String address;
- private Channel channel;
- private final EventLoopGroup group;
- private final int port;
- private final ConcurrentMap<String, ClientInfo> pendingClients;
- private final RSCConf config;
- private final String portRange;
- private static enum PortRangeSchema{START_PORT, END_PORT, MAX};
- private final String PORT_DELIMITER = "~";
- /**
- * Creating RPC Server
- * @param lconf
- * @throws IOException
- * @throws InterruptedException
- */
- public RpcServer(RSCConf lconf) throws IOException, InterruptedException {
- this.config = lconf;
- this.portRange = config.get(LAUNCHER_PORT_RANGE);
- this.group = new NioEventLoopGroup(
- this.config.getInt(RPC_MAX_THREADS),
- Utils.newDaemonThreadFactory("RPC-Handler-%d"));
- int [] portData = getPortNumberAndRange();
- int startingPortNumber = portData[PortRangeSchema.START_PORT.ordinal()];
- int endPort = portData[PortRangeSchema.END_PORT.ordinal()];
- boolean isContected = false;
- for(int tries = startingPortNumber ; tries<=endPort ; tries++){
- try {
- this.channel = getChannel(tries);
- isContected = true;
- break;
- } catch(SocketException e){
- LOG.debug("RPC not able to connect port " + tries + " " + e.getMessage());
- }
- }
- if(!isContected) {
- throw new IOException("Unable to connect to provided ports " + this.portRange);
- }
- this.port = ((InetSocketAddress) channel.localAddress()).getPort();
- this.pendingClients = new ConcurrentHashMap<>();
- LOG.info("Connected to the port " + this.port);
- String address = config.get(RPC_SERVER_ADDRESS);
- if (address == null) {
- address = config.findLocalAddress();
- }
- this.address = address;
- }
-
- /**
- * Get Port Numbers
- */
- private int[] getPortNumberAndRange() throws ArrayIndexOutOfBoundsException,
- NumberFormatException {
- String[] split = this.portRange.split(PORT_DELIMITER);
- int [] portRange = new int [PortRangeSchema.MAX.ordinal()];
- try {
- portRange[PortRangeSchema.START_PORT.ordinal()] =
- Integer.parseInt(split[PortRangeSchema.START_PORT.ordinal()]);
- portRange[PortRangeSchema.END_PORT.ordinal()] =
- Integer.parseInt(split[PortRangeSchema.END_PORT.ordinal()]);
- } catch(ArrayIndexOutOfBoundsException e) {
- LOG.error("Port Range format is not correct " + this.portRange);
- throw e;
- } catch(NumberFormatException e) {
- LOG.error("Port are not in numeric format " + this.portRange);
- throw e;
- }
- return portRange;
- }
- /**
- * @throws InterruptedException
- **/
- private Channel getChannel(int portNumber) throws BindException, InterruptedException {
- Channel channel = new ServerBootstrap()
- .group(group)
- .channel(NioServerSocketChannel.class)
- .childHandler(new ChannelInitializer<SocketChannel>() {
- @Override
- public void initChannel(SocketChannel ch) throws Exception {
- SaslServerHandler saslHandler = new SaslServerHandler(config);
- final Rpc newRpc = Rpc.createServer(saslHandler, config, ch, group);
- saslHandler.rpc = newRpc;
-
- Runnable cancelTask = new Runnable() {
- @Override
- public void run() {
- LOG.warn("Timed out waiting for hello from client.");
- newRpc.close();
- }
- };
- saslHandler.cancelTask = group.schedule(cancelTask,
- config.getTimeAsMs(RPC_CLIENT_HANDSHAKE_TIMEOUT),
- TimeUnit.MILLISECONDS);
- }
- })
- .option(ChannelOption.SO_BACKLOG, 1)
- .option(ChannelOption.SO_REUSEADDR, true)
- .childOption(ChannelOption.SO_KEEPALIVE, true)
- .bind(portNumber)
- .sync()
- .channel();
- return channel;
- }
- /**
- * Tells the RPC server to expect connections from clients.
- *
- * @param clientId An identifier for the client. Must be unique.
- * @param secret The secret the client will send to the server to identify itself.
- * @param callback The callback for when a new client successfully connects with the given
- * credentials.
- */
- public void registerClient(String clientId, String secret, ClientCallback callback) {
- final ClientInfo client = new ClientInfo(clientId, secret, callback);
- if (pendingClients.putIfAbsent(clientId, client) != null) {
- throw new IllegalStateException(
- String.format("Client '%s' already registered.", clientId));
- }
- }
-
- /**
- * Stop waiting for connections for a given client ID.
- *
- * @param clientId The client ID to forget.
- */
- public void unregisterClient(String clientId) {
- pendingClients.remove(clientId);
- }
-
- /**
- * Creates a secret for identifying a client connection.
- */
- public String createSecret() {
- byte[] secret = new byte[config.getInt(RPC_SECRET_RANDOM_BITS) / 8];
- RND.nextBytes(secret);
-
- StringBuilder sb = new StringBuilder();
- for (byte b : secret) {
- if (b < 10) {
- sb.append("0");
- }
- sb.append(Integer.toHexString(b));
- }
- return sb.toString();
- }
-
- public String getAddress() {
- return address;
- }
-
- public int getPort() {
- return port;
- }
-
- public EventLoopGroup getEventLoopGroup() {
- return group;
- }
-
- @Override
- public void close() {
- try {
- channel.close();
- pendingClients.clear();
- } finally {
- group.shutdownGracefully();
- }
- }
-
- /**
- * A callback that can be registered to be notified when new clients are created and
- * successfully authenticate against the server.
- */
- public interface ClientCallback {
-
- /**
- * Called when a new client successfully connects.
- *
- * @param client The RPC instance for the new client.
- * @return The RpcDispatcher to be used for the client.
- */
- RpcDispatcher onNewClient(Rpc client);
-
-
- /**
- * Called when a new client successfully completed SASL authentication.
- *
- * @param client The RPC instance for the new client.
- */
- void onSaslComplete(Rpc client);
- }
-
- private class SaslServerHandler extends SaslHandler implements CallbackHandler {
-
- private final SaslServer server;
- private Rpc rpc;
- private ScheduledFuture<?> cancelTask;
- private String clientId;
- private ClientInfo client;
-
- SaslServerHandler(RSCConf config) throws IOException {
- super(config);
- this.server = Sasl.createSaslServer(config.get(SASL_MECHANISMS), Rpc.SASL_PROTOCOL,
- Rpc.SASL_REALM, config.getSaslOptions(), this);
- }
-
- @Override
- protected boolean isComplete() {
- return server.isComplete();
- }
-
- @Override
- protected String getNegotiatedProperty(String name) {
- return (String) server.getNegotiatedProperty(name);
- }
-
- @Override
- protected Rpc.SaslMessage update(Rpc.SaslMessage challenge) throws IOException {
- if (clientId == null) {
- Utils.checkArgument(challenge.clientId != null,
- "Missing client ID in SASL handshake.");
- clientId = challenge.clientId;
- client = pendingClients.get(clientId);
- Utils.checkArgument(client != null,
- "Unexpected client ID '%s' in SASL handshake.", clientId);
- }
-
- return new Rpc.SaslMessage(server.evaluateResponse(challenge.payload));
- }
-
- @Override
- public byte[] wrap(byte[] data, int offset, int len) throws IOException {
- return server.wrap(data, offset, len);
- }
-
- @Override
- public byte[] unwrap(byte[] data, int offset, int len) throws IOException {
- return server.unwrap(data, offset, len);
- }
-
- @Override
- public void dispose() throws IOException {
- if (!server.isComplete()) {
- onError(new SaslException("Server closed before SASL negotiation finished."));
- }
- server.dispose();
- }
-
- @Override
- protected void onComplete() throws Exception {
- cancelTask.cancel(true);
-
- RpcDispatcher dispatcher = null;
- try {
- dispatcher = client.callback.onNewClient(rpc);
- } catch (Exception e) {
- LOG.warn("Client callback threw an exception.", e);
- }
-
- if (dispatcher != null) {
- rpc.setDispatcher(dispatcher);
- }
-
- client.callback.onSaslComplete(rpc);
- }
-
- @Override
- protected void onError(Throwable error) {
- cancelTask.cancel(true);
- }
-
- @Override
- public void handle(Callback[] callbacks) {
- Utils.checkState(client != null, "Handshake not initialized yet.");
- for (Callback cb : callbacks) {
- if (cb instanceof NameCallback) {
- ((NameCallback)cb).setName(clientId);
- } else if (cb instanceof PasswordCallback) {
- ((PasswordCallback)cb).setPassword(client.secret.toCharArray());
- } else if (cb instanceof AuthorizeCallback) {
- ((AuthorizeCallback) cb).setAuthorized(true);
- } else if (cb instanceof RealmCallback) {
- RealmCallback rb = (RealmCallback) cb;
- rb.setText(rb.getDefaultText());
- }
- }
- }
-
- }
-
- private static class ClientInfo {
-
- final String id;
- final String secret;
- final ClientCallback callback;
-
- private ClientInfo(String id, String secret, ClientCallback callback) {
- this.id = id;
- this.secret = secret;
- this.callback = callback;
- }
-
- }
-
-}
-
http://git-wip-us.apache.org/repos/asf/incubator-livy/blob/412ccc8f/rsc/src/main/java/com/cloudera/livy/rsc/rpc/SaslHandler.java
----------------------------------------------------------------------
diff --git a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/SaslHandler.java b/rsc/src/main/java/com/cloudera/livy/rsc/rpc/SaslHandler.java
deleted file mode 100644
index 094fa1c..0000000
--- a/rsc/src/main/java/com/cloudera/livy/rsc/rpc/SaslHandler.java
+++ /dev/null
@@ -1,116 +0,0 @@
-/*
- * 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 com.cloudera.livy.rsc.rpc;
-
-import java.io.IOException;
-import javax.security.sasl.Sasl;
-import javax.security.sasl.SaslException;
-
-import io.netty.channel.ChannelHandlerContext;
-import io.netty.channel.SimpleChannelInboundHandler;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.cloudera.livy.rsc.RSCConf;
-
-/**
- * Abstract SASL handler. Abstracts the auth protocol handling and encryption, if it's enabled.
- * Needs subclasses to provide access to the actual underlying SASL implementation (client or
- * server).
- */
-abstract class SaslHandler extends SimpleChannelInboundHandler<Rpc.SaslMessage>
- implements KryoMessageCodec.EncryptionHandler {
-
- // LOG is not static to make debugging easier (being able to identify which sub-class
- // generated the log message).
- private final Logger LOG;
- private final boolean requiresEncryption;
- private KryoMessageCodec kryo;
- private boolean hasAuthResponse = false;
-
- protected SaslHandler(RSCConf config) {
- this.requiresEncryption = Rpc.SASL_AUTH_CONF.equals(config.get(RSCConf.Entry.SASL_QOP));
- this.LOG = LoggerFactory.getLogger(getClass());
- }
-
- // Use a separate method to make it easier to create a SaslHandler without having to
- // plumb the KryoMessageCodec instance through the constructors.
- void setKryoMessageCodec(KryoMessageCodec kryo) {
- this.kryo = kryo;
- }
-
- @Override
- protected final void channelRead0(ChannelHandlerContext ctx, Rpc.SaslMessage msg)
- throws Exception {
- LOG.debug("Handling SASL challenge message...");
- Rpc.SaslMessage response = update(msg);
- if (response != null) {
- LOG.debug("Sending SASL challenge response...");
- hasAuthResponse = true;
- ctx.channel().writeAndFlush(response).sync();
- }
-
- if (!isComplete()) {
- return;
- }
-
- // If negotiation is complete, remove this handler from the pipeline, and register it with
- // the Kryo instance to handle encryption if needed.
- ctx.channel().pipeline().remove(this);
- String qop = getNegotiatedProperty(Sasl.QOP);
- LOG.debug("SASL negotiation finished with QOP {}.", qop);
- if (Rpc.SASL_AUTH_CONF.equals(qop)) {
- LOG.info("SASL confidentiality enabled.");
- kryo.setEncryptionHandler(this);
- } else {
- if (requiresEncryption) {
- throw new SaslException("Encryption required, but SASL negotiation did not set it up.");
- }
- dispose();
- }
-
- onComplete();
- }
-
- @Override
- public void channelInactive(ChannelHandlerContext ctx) throws Exception {
- dispose();
- super.channelInactive(ctx);
- }
-
- @Override
- public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
- if (!isComplete()) {
- LOG.info("Exception in SASL negotiation.", cause);
- onError(cause);
- ctx.close();
- }
- ctx.fireExceptionCaught(cause);
- }
-
- protected abstract boolean isComplete();
-
- protected abstract String getNegotiatedProperty(String name);
-
- protected abstract Rpc.SaslMessage update(Rpc.SaslMessage challenge) throws IOException;
-
- protected abstract void onComplete() throws Exception;
-
- protected abstract void onError(Throwable t);
-
-}