You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@edgent.apache.org by dl...@apache.org on 2016/07/21 13:17:11 UTC
[10/54] [abbrv] [partial] incubator-quarks git commit: add
"org.apache." prefix to edgent package names
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/AbstractContext.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/AbstractContext.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/AbstractContext.java
new file mode 100644
index 0000000..981d5d0
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/AbstractContext.java
@@ -0,0 +1,70 @@
+/*
+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.edgent.runtime.etiao;
+
+import org.apache.edgent.execution.services.RuntimeServices;
+import org.apache.edgent.oplet.JobContext;
+import org.apache.edgent.oplet.OpletContext;
+
+/**
+ * Provides a skeletal implementation of the {@link OpletContext}
+ * interface.
+ *
+ * @param <I> Tuple type of input streams
+ * @param <O> Tuple type of output streams
+ */
+public abstract class AbstractContext<I, O> implements OpletContext<I, O> {
+
+ private final JobContext job;
+ private final RuntimeServices services;
+
+ public AbstractContext(JobContext job, RuntimeServices services) {
+ this.job = job;
+ this.services = services;
+ }
+
+ @Override
+ public <T> T getService(Class<T> serviceClass) {
+ return services.getService(serviceClass);
+ }
+
+ @Override
+ public JobContext getJobContext() {
+ return job;
+ }
+ /**
+ * Creates a unique name within the context of the current runtime.
+ * <p>
+ * The default implementation adds a suffix composed of the package
+ * name of this interface, the current job and oplet identifiers,
+ * all separated by periods ({@code '.'}). Developers should use this
+ * method to avoid name clashes when they store or register the name in
+ * an external container or registry.
+ *
+ * @param name name (possibly non-unique)
+ * @return unique name within the context of the current runtime.
+ */
+ @Override
+ public String uniquify(String name) {
+ return new StringBuilder(name).
+ append('.').append(OpletContext.class.getPackage().getName()).
+ append('.').append(getJobContext().getId()).
+ append('.').append(getId()).toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/EtiaoJob.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/EtiaoJob.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/EtiaoJob.java
new file mode 100644
index 0000000..95bf8ce
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/EtiaoJob.java
@@ -0,0 +1,229 @@
+/*
+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.edgent.runtime.etiao;
+
+import java.util.EnumSet;
+import java.util.HashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.edgent.execution.services.ControlService;
+import org.apache.edgent.execution.services.JobRegistryService;
+import org.apache.edgent.execution.services.ServiceContainer;
+import org.apache.edgent.graph.spi.execution.AbstractGraphJob;
+import org.apache.edgent.oplet.JobContext;
+import org.apache.edgent.runtime.etiao.graph.DirectGraph;
+import org.apache.edgent.runtime.etiao.mbeans.EtiaoJobBean;
+
+/**
+ * Etiao runtime implementation of the {@link org.apache.edgent.execution.Job} interface.
+ */
+public class EtiaoJob extends AbstractGraphJob implements JobContext {
+ /** Prefix used by job unique identifiers. */
+ public static final String ID_PREFIX = "JOB_";
+
+ private final DirectGraph graph;
+ private final String id;
+ private final String topologyName;
+ private final String name;
+ private final ServiceContainer containerServices;
+ private final JobRegistryService jobs;
+
+ private static final AtomicInteger jobID = new AtomicInteger(0);
+
+ /**
+ * Creates a new {@code EtiaoJob} instance which controls the lifecycle
+ * of the specified graph.
+ *
+ * @param graph graph representation of the topology
+ * @param topologyName name of the topology
+ * @param jobName name of the Job
+ * @param container service container
+ */
+ EtiaoJob(DirectGraph graph, String topologyName, String jobName, ServiceContainer container) {
+ this.graph = graph;
+ this.id = ID_PREFIX + String.valueOf(jobID.getAndIncrement());
+ this.topologyName = topologyName;
+ this.name = jobName;
+ this.containerServices = container;
+
+ ControlService cs = container.getService(ControlService.class);
+ if (cs != null) {
+ EtiaoJobBean.registerControl(cs, this);
+ }
+ this.jobs = container.getService(JobRegistryService.class);
+ if (jobs != null)
+ jobs.addJob(this);
+ }
+
+ /**
+ * {@inheritDoc}
+ * <P>
+ * If a job name is not specified, this implementation
+ * creates a job name with the following format: {@code topologyName_jobId}.
+ * </P>
+ */
+ @Override
+ public String getName() {
+ return name != null ? name : topologyName + "_" + this.id;
+ }
+
+ @Override
+ public String getId() {
+ return id;
+ }
+
+ ServiceContainer getContainerServices() {
+ return containerServices;
+ }
+
+ @Override
+ public void stateChange(Action action) {
+ switch (action) {
+ case INITIALIZE:
+ setNext(State.INITIALIZED, action);
+ executable().initialize();
+ break;
+ case START:
+ setNext(State.RUNNING, action);
+ executable().start();
+ break;
+ case PAUSE:
+ case RESUME:
+ throw new UnsupportedOperationException(action.name());
+ case CLOSE:
+ // idempotent
+ State s = setNext(State.CLOSED, action);
+ if (s != State.CLOSED)
+ executable().close();
+ else
+ completeTransition();
+ break;
+ default:
+ // TODO log Unsupported action
+ // log.severe("Unsupported action: " + action.name());
+ throw new IllegalArgumentException(action.name());
+ }
+ }
+
+ Executable executable() {
+ return graph.executable();
+ }
+
+ /* State transitions map. Each entry associates a state with a set of
+ * reachable states the system can transition to. */
+ static final HashMap<State, EnumSet<State>> stateMap;
+ static {
+ stateMap = new HashMap<State, EnumSet<State>>();
+
+ stateMap.put(State.CONSTRUCTED, EnumSet.of(State.INITIALIZED, State.CLOSED));
+ stateMap.put(State.INITIALIZED, EnumSet.of(State.RUNNING, State.CLOSED));
+ stateMap.put(State.RUNNING, EnumSet.of(State.PAUSED, State.CLOSED));
+ stateMap.put(State.PAUSED, EnumSet.of(State.RUNNING, State.CLOSED));
+ stateMap.put(State.CLOSED, EnumSet.of(State.CLOSED));
+ }
+
+ private synchronized State setNext(State desiredState, Action cause) {
+ if (!isReachable(desiredState))
+ throw new IllegalArgumentException(cause.name());
+ else {
+ setNextState(desiredState);
+ updateRegistry();
+ return getCurrentState();
+ }
+ }
+
+ private boolean isReachable(State desiredState) {
+ return !inTransition() && stateMap.get(getCurrentState()).contains(desiredState);
+ }
+
+ protected synchronized void completeTransition() {
+ super.completeTransition();
+ updateRegistry();
+ }
+
+ void onActionComplete() {
+ completeTransition();
+ }
+
+ @Override
+ public void complete() throws ExecutionException, InterruptedException {
+ if (getCurrentState() != State.CLOSED && getNextState() != State.CLOSED)
+ awaitComplete(Long.MAX_VALUE); // TODO remove timeout
+ }
+
+ @Override
+ public void complete(long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException {
+ if (unit == null)
+ throw new NullPointerException();
+ if (getCurrentState() != State.CLOSED && getNextState() != State.CLOSED &&
+ !awaitComplete(unit.toMillis(timeout))) {
+ throw new TimeoutException();
+ }
+ }
+
+ /**
+ * Complete job closing. This method can be invoked after a job close
+ * has been initiated.
+ * @param timeout the time to wait
+ * @param unit TimeUnit
+ * @throws ExecutionException if the job execution threw an ExecutionException.
+ * @throws InterruptedException if the job execution threw an InterruptedException.
+ * @throws TimeoutException if the job execution threw an TimeoutException.
+ */
+ public void completeClosing(long timeout, TimeUnit unit) throws ExecutionException, InterruptedException, TimeoutException {
+ if (unit == null)
+ throw new NullPointerException();
+ if (getCurrentState() != State.CLOSED &&
+ !awaitComplete(unit.toMillis(timeout))) {
+ throw new TimeoutException();
+ }
+ }
+
+ private boolean awaitComplete(long millis) throws ExecutionException, InterruptedException {
+ try {
+ return executable().complete(millis);
+ }
+ catch (InterruptedException e) {
+ throw e;
+ }
+ catch (Throwable t) {
+ throw Executable.executionException(t);
+ }
+ }
+
+ public DirectGraph graph() {
+ return graph;
+ }
+
+ private void updateRegistry() {
+ if (jobs != null)
+ jobs.updateJob(this);
+ }
+
+ void updateHealth(Throwable t) {
+ if (t != null) {
+ setHealth(Health.UNHEALTHY);
+ setLastError(t.getMessage());
+ }
+ updateRegistry();
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/Executable.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/Executable.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/Executable.java
new file mode 100644
index 0000000..2d3eefd
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/Executable.java
@@ -0,0 +1,362 @@
+/*
+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.edgent.runtime.etiao;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.edgent.execution.Job;
+import org.apache.edgent.execution.services.RuntimeServices;
+import org.apache.edgent.execution.services.ServiceContainer;
+import org.apache.edgent.function.BiConsumer;
+import org.apache.edgent.function.Consumer;
+import org.apache.edgent.graph.Graph;
+import org.apache.edgent.oplet.Oplet;
+import org.apache.edgent.runtime.etiao.graph.DirectGraph;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Executes and provides runtime services to the executable graph
+ * elements (oplets and functions).
+ */
+public class Executable implements RuntimeServices {
+
+ private EtiaoJob job; // instantiated when topology is submitted
+ private final ServiceContainer containerServices;
+ private final ThreadFactory controlThreads;
+ private final BiConsumer<Object, Throwable> completionHandler;
+ private final ThreadFactoryTracker userThreads;
+ private final TrackingScheduledExecutor controlScheduler;
+ private final TrackingScheduledExecutor userScheduler;
+ private Throwable lastError;
+ private static final Logger logger = LoggerFactory.getLogger(Executable.class);
+
+ /**
+ * Services specific to this job.
+ */
+ private final ServiceContainer jobServices = new ServiceContainer();
+
+ private List<Invocation<? extends Oplet<?, ?>, ?, ?>> invocations = new ArrayList<>();
+
+ /**
+ * Creates a new {@code Executable} for the specified job.
+ * @param name the name of the executable
+ * @param containerServices runtime services provided by the container
+ */
+ public Executable(String name, ServiceContainer containerServices) {
+ this(name, containerServices, null);
+ }
+
+ /**
+ * Creates a new {@code Executable} for the specified topology name, which uses the
+ * given thread factory to create new threads for oplet execution.
+ *
+ * @param name the name of the executable
+ * @param containerServices runtime services provided by the container
+ * @param threads thread factory for executing the oplets
+ */
+ public Executable(String name, ServiceContainer containerServices, ThreadFactory threads) {
+ this.containerServices = containerServices;
+ this.controlThreads = (threads != null) ? threads : Executors.defaultThreadFactory();
+ this.completionHandler = new BiConsumer<Object, Throwable>() {
+ private static final long serialVersionUID = 1L;
+
+ /**
+ * Handler invoked by userThreads, userScheduler, and controlScheduler,
+ * upon handling an uncaught exception from a user task or when they
+ * have completed all the tasks.
+ *
+ * @param t The uncaught exception; null when called because all
+ * tasks have completed.
+ */
+ @Override
+ public void accept(Object source, Throwable t) {
+ if (job == null)
+ throw new IllegalStateException("A job has not been instantiated");
+
+ if (t != null) {
+ Executable.this.setLastError(t);
+ job.updateHealth(t);
+ cleanup();
+ }
+ else if (job.getCurrentState() == Job.State.RUNNING &&
+ (source == userScheduler || source == userThreads) &&
+ !hasActiveTasks()) {
+ logger.info("No more active user tasks");
+ }
+ notifyCompleter();
+ }
+ };
+ this.userThreads = new ThreadFactoryTracker(name, controlThreads, completionHandler);
+ this.controlScheduler = TrackingScheduledExecutor.newScheduler(controlThreads, completionHandler);
+ this.userScheduler = TrackingScheduledExecutor.newScheduler(userThreads, completionHandler);
+ }
+
+ private ThreadFactory getThreads() {
+ return userThreads;
+ }
+
+ /**
+ * Returns the {@code ScheduledExecutorService} used for running
+ * executable graph elements.
+ *
+ * @return the scheduler
+ */
+ public ScheduledExecutorService getScheduler() {
+ return userScheduler;
+ }
+
+ /**
+ * Acts as a service provider for executable elements in the graph, first
+ * looking for a service specific to this job, and then one from the
+ * container.
+ */
+ @Override
+ public <T> T getService(Class<T> serviceClass) {
+ T service = jobServices.getService(serviceClass);
+ if (service != null)
+ return service;
+
+ return containerServices.getService(serviceClass);
+ }
+
+ /**
+ * Creates a new {@code Invocation} associated with the specified oplet.
+ *
+ * @param <T> Oplet type
+ * @param <I> Tuple type of input streams
+ * @param <O> Tuple type of output streams
+ * @param oplet the oplet
+ * @param inputs the invocation's inputs
+ * @param outputs the invocation's outputs
+ * @return a new invocation for the given oplet
+ */
+ public <T extends Oplet<I, O>, I, O> Invocation<T, I, O> addOpletInvocation(T oplet, int inputs, int outputs) {
+ Invocation<T, I, O> invocation = new Invocation<>(
+ Invocation.ID_PREFIX + invocations.size(), oplet, inputs, outputs);
+ invocations.add(invocation);
+ return invocation;
+ }
+
+ /**
+ * Initializes the invocations.
+ */
+ public void initialize() {
+ jobServices.addService(ThreadFactory.class, getThreads());
+ jobServices.addService(ScheduledExecutorService.class, getScheduler());
+ invokeAction(invocation -> invocation.initialize(job, this));
+ }
+
+ /**
+ * Starts all the invocations.
+ */
+ public void start() {
+ invokeAction(invocation -> invocation.start());
+ }
+
+ /**
+ * Shuts down the user scheduler and thread factory, close all
+ * invocations, then shutdown the control scheduler.
+ */
+ public void close() {
+ getScheduler().shutdownNow();
+ userThreads.shutdownNow();
+
+ invokeAction(invocation -> {
+ try {
+ invocation.close();
+ }
+ catch (Throwable t) {
+ logger.debug("Exception caught while closing invocation {}: {}", invocation.getId(), t);
+ } finally {
+ jobServices.cleanOplet(job.getId(), invocation.getId());
+ job.getContainerServices().cleanOplet(job.getId(), invocation.getId());
+ }
+ });
+
+ notifyCompleter();
+ List<Runnable> unfinished = controlScheduler.shutdownNow();
+ if (!unfinished.isEmpty()) {
+ logger.warn("Scheduler could not finish {} tasks", unfinished.size());
+ }
+ }
+
+ private void invokeAction(Consumer<Invocation<?, ?, ?>> action) {
+ ExecutorCompletionService<Boolean> completer = new ExecutorCompletionService<>(controlScheduler);
+ for (Invocation<?, ?, ?> invocation : invocations) {
+ completer.submit(() -> {
+ action.accept(invocation);
+ return true;
+ });
+ }
+
+ int remainingTasks = invocations.size();
+ while (remainingTasks > 0) {
+ try {
+ Future<Boolean> completed = completer.poll(10, TimeUnit.SECONDS);
+ if (completed == null) {
+ // TODO during close log exception and wait on the next task to complete
+ throw new RuntimeException(new TimeoutException());
+ }
+ else {
+ try {
+ completed.get();
+ }
+ catch (ExecutionException | InterruptedException | CancellationException e) {
+ logger.error("Exception caught while invoking action: {}", e);
+ }
+ }
+ } catch (InterruptedException e) {
+ logger.error("Exception caught while waiting for future to complete", e);
+ }
+ remainingTasks--;
+ }
+
+ job.onActionComplete();
+ }
+
+ /**
+ * Cleanup after failure.
+ */
+ private void cleanup() {
+ userScheduler.shutdown();
+ userThreads.shutdown();
+ }
+
+ /**
+ * Check whether there are user tasks still active.
+ * @return {@code true} if at least a user task is still active.
+ */
+ public boolean hasActiveTasks() {
+ return userScheduler.hasActiveTasks() ||
+ userThreads.hasActiveNonDaemonThreads();
+ }
+
+ public synchronized Throwable getLastError() {
+ return lastError;
+ }
+
+ private synchronized void setLastError(Throwable lastError) {
+ this.lastError = lastError;
+ }
+
+ public Job createJob(Graph graph, String topologyName, String jobName) {
+ this.job = new EtiaoJob((DirectGraph)graph, topologyName, jobName,
+ containerServices);
+ return this.job;
+ }
+
+ /**
+ * The thread that is waiting for completion of the Executable's
+ * asynchronous work, may be null.
+ */
+ private Thread completer;
+ private boolean completerNotify;
+
+ /**
+ * Waits for outstanding user threads or tasks.
+ *
+ * @throws ExecutionException if the job execution threw an exception.
+ * Wraps the latest uncaught Exception thrown by a background
+ * activity.
+ * @throws InterruptedException if the current thread was interrupted
+ * while waiting
+ * @return true if the {@code Executable} has completed, false if the if
+ * the wait timed out.
+ */
+ final boolean complete(long timeoutMillis)
+ throws InterruptedException, ExecutionException {
+
+ long totalWait = timeoutMillis;
+ if (totalWait <= 0)
+ totalWait = 1000;
+
+ synchronized (this) {
+ completer = Thread.currentThread();
+ }
+
+ final long start = System.currentTimeMillis();
+ try {
+ while ((System.currentTimeMillis() - start) < totalWait) {
+ if (Thread.interrupted()) // Clears interrupted status
+ throw new InterruptedException();
+
+ // Check for errors from background activities
+ Throwable t = getLastError();
+ if (t != null) {
+ throw executionException(t);
+ }
+
+ if (!hasActiveTasks()) {
+ break;
+ }
+
+ // Wait for notification that something interesting to us has
+ // terminated.
+ synchronized (completer) {
+ if (!completerNotify) {
+ try {
+ completer.wait(totalWait);
+ } catch (InterruptedException e) {
+ if (!completerNotify) {
+ // Interrupted, but not by a notification
+ throw e;
+ }
+ }
+ }
+ completerNotify = false;
+ }
+ }
+ } finally {
+ synchronized (this) {
+ completer = null;
+ }
+ }
+ return ((System.currentTimeMillis() - start) < totalWait);
+ }
+
+ private void notifyCompleter() {
+ Thread completer;
+ synchronized (this) {
+ completer = this.completer;
+ }
+ if (completer == null)
+ return;
+
+ synchronized (completer) {
+ completerNotify = true;
+ completer.notifyAll();
+ }
+ }
+
+ static ExecutionException executionException(Throwable t) {
+ return (t instanceof ExecutionException) ?
+ (ExecutionException) t : new ExecutionException(t);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/Invocation.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/Invocation.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/Invocation.java
new file mode 100644
index 0000000..cd9de07
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/Invocation.java
@@ -0,0 +1,205 @@
+/*
+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.edgent.runtime.etiao;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.edgent.execution.services.RuntimeServices;
+import org.apache.edgent.function.Consumer;
+import org.apache.edgent.function.Functions;
+import org.apache.edgent.oplet.JobContext;
+import org.apache.edgent.oplet.Oplet;
+import org.apache.edgent.oplet.OutputPortContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * An {@link Oplet} invocation in the context of the
+ * <a href="{@docRoot}/org/apache/edgent/runtime/etiao/package-summary.html">ETIAO</a> runtime.
+ *
+ * @param <T>
+ * Oplet type.
+ * @param <I>
+ * Data container type for input tuples.
+ * @param <O>
+ * Data container type for output tuples.
+ */
+public class Invocation<T extends Oplet<I, O>, I, O> implements AutoCloseable {
+ /** Prefix used by oplet unique identifiers. */
+ public static final String ID_PREFIX = "OP_";
+ private static final OutputPortContext DEFAULT_OUTPUT_CONTEXT =
+ new OutputPortContext() {
+ @Override
+ public String getAlias() {
+ return null;
+ }
+ };
+
+ /**
+ * Runtime unique identifier.
+ */
+ private final String id;
+ private T oplet;
+
+ private List<Consumer<O>> outputs;
+ private List<SettableForwarder<I>> inputs;
+ private List<OutputPortContext> outputContext;
+ private static final Logger logger = LoggerFactory.getLogger(Invocation.class);
+
+ protected Invocation(String id, T oplet, int inputCount, int outputCount) {
+ this.id = id;
+ this.oplet = oplet;
+ inputs = inputCount == 0 ? Collections.emptyList() : new ArrayList<>(inputCount);
+ for (int i = 0; i < inputCount; i++) {
+ inputs.add(new SettableForwarder<>());
+ }
+
+ outputs = outputCount == 0 ? Collections.emptyList() : new ArrayList<>(outputCount);
+ outputContext = outputCount == 0 ? Collections.emptyList() : new ArrayList<>(outputCount);
+ for (int i = 0; i < outputCount; i++) {
+ addOutput();
+ }
+ }
+
+ /**
+ * Returns the unique identifier associated with this {@code Invocation}.
+ *
+ * @return unique identifier
+ */
+ public String getId() {
+ return id;
+ }
+
+ /**
+ * Returns the oplet associated with this {@code Invocation}.
+ *
+ * @return the oplet associated with this invocation
+ */
+ public T getOplet() {
+ return oplet;
+ }
+
+ /**
+ * Returns the number of outputs for this invocation.
+ * @return the number of outputs
+ */
+ public int getOutputCount() {
+ return outputs.size();
+ }
+
+ /**
+ * Adds a new output. By default, the output is connected to a Consumer
+ * that discards all items passed to it.
+ *
+ * @return the index of the new output
+ */
+ public int addOutput() {
+ int index = outputs.size();
+ outputs.add(Functions.discard());
+ outputContext.add(DEFAULT_OUTPUT_CONTEXT);
+ return index;
+ }
+
+ /**
+ * Disconnects the specified port by connecting to a no-op {@code Consumer} implementation.
+ *
+ * @param port the port index
+ */
+ public void disconnect(int port) {
+ outputs.set(port, Functions.discard());
+ }
+
+ /**
+ * Disconnects the specified port and reconnects it to the specified target.
+ *
+ * @param port index of the port which is reconnected
+ * @param target target the port gets connected to
+ */
+ public void setTarget(int port, Consumer<O> target) {
+ disconnect(port);
+ outputs.set(port, target);
+ }
+
+ /**
+ * Set the specified output port's context.
+ *
+ * @param port index of the output port
+ * @param context the new {@link OutputPortContext}
+ */
+ public void setContext(int port, OutputPortContext context) {
+ if (context == null)
+ throw new NullPointerException();
+ outputContext.set(port, context);
+ }
+
+ /**
+ * Returns the list of input stream forwarders for this invocation.
+ * @return the list
+ */
+ public List<? extends Consumer<I>> getInputs() {
+ return inputs;
+ }
+
+ /**
+ * Initialize the invocation.
+ *
+ * @param job the context of the current job
+ * @param services service provider for this invocation
+ */
+ public void initialize(JobContext job, RuntimeServices services) {
+
+ InvocationContext<I, O> context = new InvocationContext<I, O>(
+ id, job, services,
+ inputs.size(),
+ outputs, outputContext);
+
+ try {
+ oplet.initialize(context);
+ } catch (Exception e) {
+ logger.error("Error while initializing oplet", e);
+ }
+ List<? extends Consumer<I>> streamers = oplet.getInputs();
+ for (int i = 0; i < inputs.size(); i++)
+ inputs.get(i).setDestination(streamers.get(i));
+ }
+
+ /**
+ * Start the oplet. Oplets must not submit any tuples not derived from
+ * input tuples until this method is called.
+ */
+ public void start() {
+ oplet.start();
+ }
+
+ @Override
+ public void close() throws Exception {
+ oplet.close();
+ }
+
+ /** For debug. Contents subject to change. */
+ @Override
+ public String toString() {
+ return "{"
+ + "id=" + getId()
+ + " oplet=" + oplet.getClass().getSimpleName()
+ + "}";
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/InvocationContext.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/InvocationContext.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/InvocationContext.java
new file mode 100644
index 0000000..d77ae42
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/InvocationContext.java
@@ -0,0 +1,88 @@
+/*
+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.edgent.runtime.etiao;
+
+import java.util.List;
+
+import org.apache.edgent.execution.services.RuntimeServices;
+import org.apache.edgent.function.Consumer;
+import org.apache.edgent.oplet.JobContext;
+import org.apache.edgent.oplet.OutputPortContext;
+
+/**
+ * Context information for the {@code Oplet}'s execution context.
+ *
+ * @param <I>
+ * Data container type for input tuples.
+ * @param <O>
+ * Data container type for output tuples.
+ */
+public class InvocationContext<I, O> extends AbstractContext<I, O> {
+
+ private final String id;
+ private final int inputCount;
+ private List<OutputPortContext> outputContext;
+
+ /**
+ * Creates an {@code InvocationContext} with the specified parameters.
+ *
+ * @param id the oplet's unique identifier
+ * @param job the current job's context
+ * @param services service provider for the current job
+ * @param inputCount number of oplet's inputs
+ * @param outputs list of oplet's outputs
+ * @param outputContext list of oplet's output port context info
+ */
+ public InvocationContext(String id, JobContext job,
+ RuntimeServices services,
+ int inputCount,
+ List<? extends Consumer<O>> outputs,
+ List<OutputPortContext> outputContext) {
+ super(job, services);
+ this.id = id;
+ this.inputCount = inputCount;
+ this.outputs = outputs;
+ this.outputContext = outputContext;
+ }
+
+ private final List<? extends Consumer<O>> outputs;
+
+ @Override
+ public String getId() {
+ return id;
+ }
+
+ @Override
+ public List<? extends Consumer<O>> getOutputs() {
+ return outputs;
+ }
+ @Override
+ public int getInputCount() {
+ return inputCount;
+ }
+ @Override
+ public int getOutputCount() {
+ return getOutputs().size();
+ }
+
+ @Override
+ public List<OutputPortContext> getOutputContext() {
+ return outputContext;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/SettableForwarder.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/SettableForwarder.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/SettableForwarder.java
new file mode 100644
index 0000000..8363561
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/SettableForwarder.java
@@ -0,0 +1,74 @@
+/*
+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.edgent.runtime.etiao;
+
+import org.apache.edgent.function.Consumer;
+import org.apache.edgent.function.Functions;
+
+/**
+ * A forwarding Streamer whose destination
+ * can be changed.
+ * External synchronization or happens-before
+ * guarantees must be provided by the object
+ * owning an instance of {@code SettableForwarder}.
+ *
+ * @param <T> Type of data on the stream.
+ */
+public final class SettableForwarder<T> implements Consumer<T> {
+ private static final long serialVersionUID = 1L;
+ private Consumer<T> destination;
+
+ /**
+ * Create with the destination set to {@link Functions#discard()}.
+ */
+ public SettableForwarder() {
+ this.destination = Functions.discard();
+ }
+
+ /**
+ * Create with the specified destination.
+ * @param destination Stream destination.
+ */
+ public SettableForwarder(Consumer<T> destination) {
+ this.destination = destination;
+ }
+
+ @Override
+ public void accept(T item) {
+ getDestination().accept(item);
+ }
+
+ /**
+ * Change the destination.
+ * No synchronization is taken.
+ * @param destination Stream destination.
+ */
+ public void setDestination(Consumer<T> destination) {
+ this.destination = destination;
+ }
+
+ /**
+ * Get the destination.
+ * No synchronization is taken.
+ * @return the destination
+ */
+ public final Consumer<T> getDestination() {
+ return destination;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/ThreadFactoryTracker.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/ThreadFactoryTracker.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/ThreadFactoryTracker.java
new file mode 100644
index 0000000..2f00317
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/ThreadFactoryTracker.java
@@ -0,0 +1,200 @@
+/*
+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.edgent.runtime.etiao;
+
+import java.util.HashSet;
+import java.util.Set;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ThreadFactory;
+
+import org.apache.edgent.function.BiConsumer;
+import org.apache.edgent.oplet.core.Source;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tracks threads created for executing user tasks.
+ * <p>
+ * All user threads are interrupted when the tracker is shutdown.
+ * Runnable implementations (see {@link Source}) must exit the task
+ * if the current thread is interrupted. A handler which notifies the
+ * {@link Executable} is invoked when a user thread abruptly terminates due
+ * to an uncaught exception.</p>
+ * <p>
+ * If no {@code ThreadFactory} is provided, then this object uses the
+ * factory returned by {@link Executors#defaultThreadFactory()}.</p>
+ */
+public class ThreadFactoryTracker implements ThreadFactory {
+
+ private final String threadName;
+ private final ThreadFactory factory;
+ private final BiConsumer<Object, Throwable> completer;
+ private final Thread.UncaughtExceptionHandler handler;
+ private volatile boolean shutdown;
+ private final ThreadSets threads = new ThreadSets();
+ private static final Logger logger = LoggerFactory.getLogger(ThreadFactoryTracker.class);
+
+ ThreadFactoryTracker(String threadName, ThreadFactory tf, BiConsumer<Object, Throwable> completer) {
+ this.threadName = threadName;
+ this.factory = (tf != null) ? tf : Executors.defaultThreadFactory();
+ this.completer = completer;
+ this.handler = new Thread.UncaughtExceptionHandler() {
+ @Override
+ public void uncaughtException(Thread thread, Throwable throwable) {
+ try {
+ if (!trackedThreadUncaughtException(thread, throwable))
+ Thread.getDefaultUncaughtExceptionHandler().uncaughtException(thread, throwable);
+ } finally {
+ threads.removeRunning(Thread.currentThread());
+ completer.accept(this, throwable);
+ }
+ }};
+ }
+
+ /**
+ * Return a thread.
+ */
+ @Override
+ public Thread newThread(Runnable r) {
+ if (shutdown)
+ return null;
+
+ Runnable wrapper = new Runnable() {
+ /**
+ * Keep track of non-daemon threads so shutdown can wait for
+ * their termination.
+ */
+ @Override
+ public void run() {
+ threads.fromNewToRunning(Thread.currentThread());
+
+ r.run();
+ /* If the task has thrown an exception, the code below is
+ * not getting executed. The uncaughtException this.handler
+ * removes the thread from the tracker list and notifies
+ * the completer.
+ */
+ threads.removeRunning(Thread.currentThread());
+ if (!hasActiveNonDaemonThreads())
+ completer.accept(ThreadFactoryTracker.this, null);
+ }
+ };
+
+ Thread t = factory.newThread(wrapper);
+ t.setName(t.getName() + "-" + threadName);
+ t.setUncaughtExceptionHandler(handler);
+ threads.addNew(t);
+ return t;
+ }
+
+ /**
+ * This initiates an orderly shutdown in which no new tasks will be
+ * accepted but previously submitted tasks continue to be executed.
+ */
+ public void shutdown() {
+ shutdown = true;
+ }
+
+ /**
+ * Interrupts all user treads and briefly waits for each thread to finish
+ * execution.
+ *
+ * User tasks must catch {@link InterruptedException} and exit the task.
+ */
+ public void shutdownNow() {
+ // Ensure no new threads will be created.
+ shutdown();
+
+ Thread[] leftoverThreads = threads.runningArray();
+ for (Thread t : leftoverThreads)
+ t.interrupt();
+ // TODO should we interrupt newThreads as well
+
+ // Briefly wait for threads to complete
+ for (Thread t : leftoverThreads) {
+ try {
+ t.join(10);
+ } catch (InterruptedException e) {
+ }
+ }
+ }
+
+ /**
+ * Check to see if there are non daemon user threads that have not yet
+ * completed. This includes non-daemon threads which have been created
+ * but are not running yet.
+ * @return {@code true} if there are active non daemon threads, false otherwise.
+ */
+ public boolean hasActiveNonDaemonThreads() {
+ return threads.hasActiveNonDaemonThreads();
+ }
+
+ /**
+ * Handle an exception thrown by a tracked thread.
+ *
+ * @return true if this exception was handled.
+ */
+ private boolean trackedThreadUncaughtException(Thread t, Throwable e) {
+ getLogger().error("Uncaught exception in thread " + t.getName(), e);
+ return true;
+ }
+
+ private Logger getLogger() {
+ return logger;
+ }
+
+ private static class ThreadSets {
+ private final Set<Thread> newThreads = new HashSet<Thread>(); // created, not running yet
+ private final Set<Thread> runningThreads = new HashSet<Thread>(); // running
+
+ synchronized void addNew(Thread t) {
+ newThreads.add(t);
+ }
+
+ synchronized void removeRunning(Thread t) {
+ runningThreads.remove(t);
+ }
+
+ synchronized void fromNewToRunning(Thread t) {
+ newThreads.remove(t);
+ runningThreads.add(t);
+ }
+
+ synchronized Thread[] runningArray() {
+ return runningThreads.toArray(new Thread[0]);
+ }
+
+ synchronized boolean hasActiveNonDaemonThreads() {
+ if (runningThreads.isEmpty() && newThreads.isEmpty())
+ return false;
+
+ for (Thread t : runningThreads) {
+ if (t.isDaemon())
+ continue;
+ return true;
+ }
+ for (Thread t : newThreads) {
+ if (t.isDaemon())
+ continue;
+ return true;
+ }
+ return false;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/TrackingScheduledExecutor.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/TrackingScheduledExecutor.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/TrackingScheduledExecutor.java
new file mode 100644
index 0000000..c4dc44d
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/TrackingScheduledExecutor.java
@@ -0,0 +1,273 @@
+/*
+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.edgent.runtime.etiao;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.Delayed;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+import java.util.concurrent.RunnableScheduledFuture;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.edgent.function.BiConsumer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Extends a {@code ScheduledThreadPoolExecutor} with the ability to track
+ * scheduled tasks and cancel them in case a task completes abruptly due to
+ * an exception.
+ *
+ * When all the tasks have completed, due to normal termination, or cancelled
+ * due to an exception, the executor invokes a completion handler.
+ */
+public final class TrackingScheduledExecutor extends ScheduledThreadPoolExecutor {
+ private final BiConsumer<Object, Throwable> completer;
+ private static final Logger logger = LoggerFactory.getLogger(TrackingScheduledExecutor.class);
+
+ /**
+ * Creates an {@code TrackingScheduledExecutor} using the supplied thread
+ * factory and a completion handler.
+ *
+ * @param threadFactory the thread factory to use
+ * @param completionHandler handler invoked when all task have completed,
+ * due to normal termination, exception, or cancellation.
+ * @return a new (@code TrackingScheduledExecutor) instance.
+ */
+ public static TrackingScheduledExecutor newScheduler(
+ ThreadFactory threadFactory, BiConsumer<Object, Throwable> completionHandler) {
+
+ TrackingScheduledExecutor stpe = new TrackingScheduledExecutor(
+ Runtime.getRuntime().availableProcessors() * 4, threadFactory, completionHandler);
+ stpe.setKeepAliveTime(1, TimeUnit.SECONDS);
+ stpe.allowCoreThreadTimeOut(true);
+ return stpe;
+ }
+
+ private TrackingScheduledExecutor(int corePoolSize, ThreadFactory tf,
+ BiConsumer<Object, Throwable> completer) {
+ super(corePoolSize, tf);
+ this.completer = completer;
+ }
+
+ /**
+ * Invoked by the super class after each task execution.
+ */
+ @Override
+ protected void afterExecute(Runnable r, Throwable t) {
+ super.afterExecute(r, t);
+ if (t == null && r instanceof Future<?>) {
+ t = unwrapFutureThrowable((Future<?>) r);
+ }
+ if (t != null) {
+ getLogger().error("Thread: " + Thread.currentThread().getName() +
+ ": task terminated with exception : ", t);
+ cleanup();
+ completer.accept(this, t);
+ }
+ }
+
+ /**
+ * asyncTasks contains all the Future for tasks that have been started
+ * and not completed. For non-periodic tasks we remove the future from
+ * asyncTasks once it is completed. Periodic tasks remain in asyncTasks
+ * until they have been cancelled.
+ */
+ private final Set<RunnableScheduledFuture<?>> asyncTasks = Collections
+ .synchronizedSet(new HashSet<RunnableScheduledFuture<?>>());
+
+ @Override
+ protected <V> RunnableScheduledFuture<V> decorateTask(Runnable runnable,
+ RunnableScheduledFuture<V> task) {
+ return trackTask(task);
+ }
+
+ @Override
+ protected <V> RunnableScheduledFuture<V> decorateTask(Callable<V> c,
+ RunnableScheduledFuture<V> task) {
+ return trackTask(task);
+ }
+
+ private void cleanup() {
+ cancelAllAsyncTasks(true);
+ }
+
+ private int cancelAllAsyncTasks(boolean mayInterruptIfRunning) {
+ int notCanceled = 0;
+ synchronized (asyncTasks) {
+ for (RunnableScheduledFuture<?> task : asyncTasks) {
+ if (!task.cancel(mayInterruptIfRunning))
+ notCanceled++;
+ }
+ // remove tasks which are done
+ hasActiveTasks();
+ }
+ return notCanceled;
+ }
+
+ /**
+ * Track an executed task so that we can determine through the complete
+ * method when all background activity is complete.
+ */
+ private <V> RunnableScheduledFuture<V> trackTask(RunnableScheduledFuture<V> task) {
+ task = new TrackedFuture<V>(task);
+ asyncTasks.add(task);
+ return task;
+ }
+
+ /**
+ * Determines whether there are tasks which have started and not completed.
+ *
+ * As a side effect, this method removes all tasks which are done but are
+ * still in the tracking list.
+ *
+ * @return {@code true} is active tasks exist.
+ */
+ public boolean hasActiveTasks() {
+ boolean doesHaveTasks = false;
+ synchronized (asyncTasks) {
+ if (asyncTasks.isEmpty())
+ return false;
+
+ Iterator<RunnableScheduledFuture<?>> i = asyncTasks.iterator();
+ while (i.hasNext()) {
+ RunnableScheduledFuture<?> task = i.next();
+ if (task.isDone())
+ i.remove();
+ else
+ doesHaveTasks = true;
+ }
+ }
+ return doesHaveTasks;
+ }
+
+ /**
+ * Get the reason of a task's abnormal completion. Callers may cancel and
+ * reschedule tasks, so a task completed by cancellation is not an error.
+ */
+ private final Throwable unwrapFutureThrowable(Future<?> ft) {
+ if (ft.isDone() && !ft.isCancelled()) {
+ try {
+ ft.get();
+ } catch (ExecutionException ee) {
+ return ee.getCause();
+ } catch (InterruptedException ie) {
+ Thread.currentThread().interrupt(); // ignore/reset
+ }
+ }
+ return null;
+ }
+
+ private Logger getLogger() {
+ return logger;
+ }
+
+ /**
+ * Track a non-periodic future so that we are aware of all background
+ * activity. Simply wrap the RunnableScheduledFuture that our executor
+ * returns ensuring that the future is removed from the list of tracked
+ * tasks once it is complete.
+ */
+ final class TrackedFuture<V> implements RunnableScheduledFuture<V> {
+
+ private final RunnableScheduledFuture<V> realTask;
+
+ TrackedFuture(RunnableScheduledFuture<V> realTask) {
+ this.realTask = realTask;
+ }
+
+ @Override
+ public void run() {
+ try {
+ realTask.run();
+ } finally {
+ if (!isPeriodic())
+ removeTrack();
+ }
+ }
+
+ /**
+ * Remove tracking of the task and notify the completer if
+ * the scheduler seems to have no work.
+ */
+ private void removeTrack() {
+ asyncTasks.remove(this);
+
+ // Notify the completer if the following is true:
+ // no asyncTasks (user tasks) pending, or the executor's task
+ // queue is empty and the number of active threads includes
+ // only the current one.
+ if (asyncTasks.isEmpty() ||
+ (getActiveCount() <= 1 && getQueue().isEmpty())) {
+ completer.accept(TrackingScheduledExecutor.this, null);
+ }
+ }
+
+ @Override
+ public boolean cancel(boolean mayInterruptIfRunning) {
+ boolean wasCancelled = realTask.cancel(mayInterruptIfRunning);
+ if (wasCancelled)
+ removeTrack();
+ return wasCancelled;
+ }
+
+ @Override
+ public boolean isCancelled() {
+ return realTask.isCancelled();
+ }
+
+ @Override
+ public boolean isDone() {
+ return realTask.isDone();
+ }
+
+ @Override
+ public V get() throws InterruptedException, ExecutionException {
+ return realTask.get();
+ }
+
+ @Override
+ public V get(long timeout, TimeUnit unit) throws InterruptedException,
+ ExecutionException, TimeoutException {
+ return realTask.get(timeout, unit);
+ }
+
+ @Override
+ public long getDelay(TimeUnit unit) {
+ return realTask.getDelay(unit);
+ }
+
+ @Override
+ public int compareTo(Delayed o) {
+ return realTask.compareTo(o);
+ }
+
+ @Override
+ public boolean isPeriodic() {
+ return realTask.isPeriodic();
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/DirectGraph.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/DirectGraph.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/DirectGraph.java
new file mode 100644
index 0000000..d5a1b5d
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/DirectGraph.java
@@ -0,0 +1,86 @@
+/*
+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.edgent.runtime.etiao.graph;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.edgent.execution.services.ServiceContainer;
+import org.apache.edgent.graph.Edge;
+import org.apache.edgent.graph.Graph;
+import org.apache.edgent.graph.Vertex;
+import org.apache.edgent.graph.spi.AbstractGraph;
+import org.apache.edgent.oplet.Oplet;
+import org.apache.edgent.runtime.etiao.Executable;
+import org.apache.edgent.runtime.etiao.Invocation;
+
+/**
+ * {@code DirectGraph} is a {@link Graph} that
+ * is executed in the current virtual machine.
+ */
+public class DirectGraph extends AbstractGraph<Executable> {
+
+ private final Executable executable;
+ private final List<ExecutableVertex<? extends Oplet<?, ?>, ?, ?>> vertices = new ArrayList<>();
+
+ /**
+ * Creates a new {@code DirectGraph} instance underlying the specified
+ * topology.
+ *
+ * @param topologyName name of the topology
+ * @param container service container
+ */
+ public DirectGraph(String topologyName, ServiceContainer container) {
+ this.executable = new Executable(topologyName, container);
+ }
+
+ /**
+ * Returns the {@code Executable} running this graph.
+ * @return the executable
+ */
+ public Executable executable() {
+ return executable;
+ }
+
+ @Override
+ public <OP extends Oplet<C, P>, C, P> ExecutableVertex<OP, C, P> insert(OP oplet, int inputs, int outputs) {
+ Invocation<OP, C, P> invocation = executable().addOpletInvocation(oplet, inputs, outputs);
+ ExecutableVertex<OP, C, P> vertex = new ExecutableVertex<>(this, invocation);
+ vertices.add(vertex);
+ return vertex;
+ }
+
+ @Override
+ public Collection<Vertex<? extends Oplet<?, ?>, ?, ?>> getVertices() {
+ return Collections.unmodifiableList(vertices);
+ }
+
+ @Override
+ public Collection<Edge> getEdges() {
+ List<Edge> edges = new ArrayList<>();
+ for (ExecutableVertex<? extends Oplet<?, ?>, ?, ?> ev : vertices) {
+ for (Edge e : ev.getEdges()) {
+ edges.add(e);
+ }
+ }
+ return Collections.unmodifiableList(edges);
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/EtiaoConnector.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/EtiaoConnector.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/EtiaoConnector.java
new file mode 100644
index 0000000..a684f00
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/EtiaoConnector.java
@@ -0,0 +1,264 @@
+/*
+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.edgent.runtime.etiao.graph;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.edgent.graph.Connector;
+import org.apache.edgent.graph.Vertex;
+import org.apache.edgent.graph.spi.DirectEdge;
+import org.apache.edgent.oplet.Oplet;
+import org.apache.edgent.oplet.core.FanOut;
+import org.apache.edgent.oplet.core.Peek;
+
+class EtiaoConnector<P> implements Connector<P> {
+
+ /** The connector's associated vertex and its output port index. */
+ private final ExecutableVertex<?, ?, P> vertex;
+ private final int oport;
+
+ /*
+ * The connector's shared state.
+ *
+ * All of the connectors for a single logical stream share the same state.
+ * i.e., the connectors for the internally created peek and fanout vertices
+ * share their associated primary ("the stream's") connector's state.
+ */
+ private SharedState<P> state;
+
+ /**
+ * Shared connector state.
+ *
+ * @param <P> The Input/Output port type.
+ */
+ private static class SharedState<P> {
+ String alias;
+ private Set<String> tags = new HashSet<>();
+
+ /** the primary ("the stream's") connector */
+ EtiaoConnector<P> primaryConnector;
+
+ /** where to add the next peek and 1st connect() op */
+ EtiaoConnector<P> activeConnector;
+
+ /** the connect() added non-peek or FanOut target */
+ Target<P> connectTarget;
+
+ /** FanOut when the connector has >1 connect() added targets */
+ ExecutableVertex<FanOut<P>, P, P> fanOutVertex;
+
+ public SharedState(EtiaoConnector<P> connector) {
+ primaryConnector = connector;
+ activeConnector = connector;
+ }
+
+ public String toString() {
+ return "{"
+ // avoid activeConnector.toString() recursion
+ + " activeConnector=<" + activeConnector.oport + "," + activeConnector.vertex + ">"
+ + " primaryConnector=<" + primaryConnector.oport + "," + primaryConnector.vertex + ">"
+ + " connectTarget=" + connectTarget
+ + " fanOutVertex=" + fanOutVertex
+ + " alias=" + alias
+ + " tags=" + tags
+ + "}";
+ }
+ }
+
+ /**
+ * Create a new connector.
+ *
+ * @param vertex the connector's associated Vertex
+ * @param oport the connector's output port index
+ */
+ public EtiaoConnector(ExecutableVertex<?, ?, P> vertex, int oport) {
+ this.vertex = vertex;
+ this.oport = oport;
+ this.state = new SharedState<P>(this); // later reset for "internal" connectors
+ }
+
+ @Override
+ public DirectGraph graph() {
+ return vertex.graph();
+ }
+
+ @Override
+ public boolean isConnected() {
+ // see Connector.isConnected() doc for semantics
+ // the primary connector can return true.
+ // internal peek connectors must return false (peekAll() depends on it)
+ // internal fanout connectors return false (used to be true and peekAll()
+ // callers had to explicitly exclude fanout ops).
+
+ return state.connectTarget != null && this == state.primaryConnector;
+ }
+
+ private boolean isFanOut() {
+ return state.fanOutVertex != null;
+ }
+
+ @Override
+ public void connect(Vertex<?, P, ?> target, int targetPort) {
+ // to be used only for connecting to non-internal (non peek/fanout) vertex
+
+ if (!isConnected()) { // 1st connect()
+ state.connectTarget = connectActiveDirect(new Target<P>((ExecutableVertex<?, P, ?>) target, targetPort));
+ return;
+ }
+
+ if (!isFanOut()) { // 2nd connect()
+ // Add a FanOut oplet, initially with a single output port
+ // connected to 1st connect()'s target
+ state.fanOutVertex = newInternalVertex(new FanOut<P>(), 1, 1);
+ EtiaoConnector<P> fanOutConnector = state.fanOutVertex.getConnectors().get(0);
+ fanOutConnector.takeTarget();
+
+ // Connect to the FanOut oplet. The FanOut becomes the connectTarget.
+ state.connectTarget = connectActiveDirect(new Target<P>(state.fanOutVertex, 0));
+ }
+
+ // 2nd-nth connect(): add target as another connector/connection from the FanOut
+ EtiaoConnector<P> fanOutConnector = state.fanOutVertex.addOutput();
+ fanOutConnector.state = state;
+ fanOutConnector.connectDirect(new Target<P>((ExecutableVertex<?, P, ?>) target, targetPort));
+
+ assert isConnected();
+ }
+
+ @Override
+ public <N extends Peek<P>> Connector<P> peek(N oplet) {
+ // see Connector.peek() method/class doc for the semantics
+
+ ExecutableVertex<N, P, P> peekVertex = newInternalVertex(oplet, 1, 1);
+ EtiaoConnector<P> peekConnector = peekVertex.getConnectors().get(0);
+
+ // The peek takes over the connection to connect() added target(s).
+ if (isConnected()) {
+ peekConnector.takeTarget();
+ }
+
+ // Connect to the new peek. It becomes the activeConnector / new addition point.
+ connectActiveDirect(new Target<P>(peekVertex, 0));
+ state.activeConnector = peekConnector;
+
+ return this;
+ }
+
+ /**
+ * Create a new vertex for internal use (with shared connector state)
+ * @param op a Peek or FanOut oplet
+ * @param nInputs number of input ports
+ * @param nOutputs number of output ports
+ * @return the new vertex
+ */
+ private <N extends Oplet<P, P>> ExecutableVertex<N, P, P>
+ newInternalVertex(N op, int nInputs, int nOutputs) {
+ ExecutableVertex<N, P, P> vertex = graph().insert(op, nInputs, nOutputs);
+ for (EtiaoConnector<P> connector : vertex.getConnectors()) {
+ connector.state = state;
+ }
+ return vertex;
+ }
+
+ /**
+ * Disconnect the connect() added target(s)
+ * @return the target
+ */
+ private Target<P> disconnectTarget() {
+ assert state.connectTarget != null;
+
+ state.activeConnector.vertex.disconnect(state.activeConnector.oport);
+ Target<P> target = state.connectTarget;
+ state.connectTarget = null;
+ assert state.connectTarget == null;
+
+ return target;
+ }
+
+ /**
+ * Take activeConnector's connection to the connect() added target(s).
+ */
+ private void takeTarget() {
+ state.connectTarget = connectDirect(disconnectTarget());
+ }
+
+ /**
+ * Connect this to the target
+ * @param target
+ * @return the target parameter
+ */
+ private Target<P> connectDirect(Target<P> target) {
+ vertex.connect(oport, target,
+ new DirectEdge(this, vertex, oport, target.vertex, target.port));
+ return target;
+ }
+
+ /**
+ * Connect the activeConnector to the target
+ * @param target
+ * @return the target parameter
+ */
+ private Target<P> connectActiveDirect(Target<P> target) {
+ ExecutableVertex<?,?,P> vertex = state.activeConnector.vertex;
+ int oport = state.activeConnector.oport;
+ vertex.connect(oport, target,
+ new DirectEdge(state.activeConnector,
+ vertex, oport, target.vertex, target.port));
+ return target;
+ }
+
+ @Override
+ public void tag(String... values) {
+ for (String v : values)
+ state.tags.add(v);
+ }
+
+ @Override
+ public Set<String> getTags() {
+ return Collections.unmodifiableSet(state.tags);
+ }
+
+ @Override
+ public void alias(String alias) {
+ if (state.alias != null)
+ throw new IllegalStateException("alias already set");
+ state.alias = alias;
+ }
+
+ @Override
+ public String getAlias() {
+ return state.alias;
+ }
+
+ /**
+ * Intended only as a debug aid and content is not guaranteed.
+ */
+ @Override
+ public String toString() {
+ return "{"
+ + getClass().getSimpleName()
+ + " oport=" + oport
+ + " vertex=" + vertex
+ + " state=" + state
+ + "}";
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/ExecutableVertex.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/ExecutableVertex.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/ExecutableVertex.java
new file mode 100644
index 0000000..669f7e9
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/ExecutableVertex.java
@@ -0,0 +1,146 @@
+/*
+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.edgent.runtime.etiao.graph;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.edgent.function.Consumer;
+import org.apache.edgent.graph.Edge;
+import org.apache.edgent.graph.spi.AbstractVertex;
+import org.apache.edgent.graph.spi.DirectEdge;
+import org.apache.edgent.oplet.Oplet;
+import org.apache.edgent.oplet.OutputPortContext;
+import org.apache.edgent.runtime.etiao.Invocation;
+
+public class ExecutableVertex<N extends Oplet<C, P>, C, P> extends AbstractVertex<N, C, P> {
+
+ private static final Edge DISCONNECTED = new DirectEdge();
+ private DirectGraph graph;
+ private final Invocation<N, C, P> invocation;
+ private final List<EtiaoConnector<P>> connectors;
+ private final List<Edge> edges;
+
+ ExecutableVertex(DirectGraph graph, Invocation<N, C, P> invocation) {
+ this.graph = graph;
+ this.invocation = invocation;
+ connectors = new ArrayList<>(invocation.getOutputCount());
+ for (int i = 0; i < invocation.getOutputCount(); i++) {
+ addConnector(i);
+ }
+ edges = new ArrayList<>(invocation.getOutputCount());
+ for (int i = 0; i < invocation.getOutputCount(); i++) {
+ edges.add(DISCONNECTED);
+ }
+ }
+
+ private EtiaoConnector<P> addConnector(int index) {
+ EtiaoConnector<P> connector = new EtiaoConnector<>(this, index);
+ connectors.add(connector);
+ return connector;
+ }
+
+ @Override
+ public DirectGraph graph() {
+ return graph;
+ }
+
+ @Override
+ public N getInstance() {
+ return invocation.getOplet();
+ }
+
+ @Override
+ public EtiaoConnector<P> addOutput() {
+ int outputPort = invocation.addOutput();
+ int edgeIndex = addEdge();
+
+ assert outputPort == edgeIndex;
+
+ return addConnector(outputPort);
+ }
+
+
+ @Override
+ public List<EtiaoConnector<P>> getConnectors() {
+ return Collections.unmodifiableList(connectors);
+ }
+
+ public String getInvocationId() {
+ return invocation.getId();
+ }
+
+ void disconnect(int sourcePort) {
+ invocation.disconnect(sourcePort);
+ edges.set(sourcePort, DISCONNECTED);
+ }
+
+ /**
+ * Connect this Vertex's source port to a target Vertex input port
+ * using the given edge.
+ *
+ * @param sourcePort
+ * @param target
+ * @param edge
+ */
+ void connect(int sourcePort, Target<P> target, Edge edge) {
+ if (edge == null)
+ throw new NullPointerException();
+ Consumer<P> input = target.vertex.invocation.getInputs().get(target.port);
+ invocation.setTarget(sourcePort, input);
+ edges.set(sourcePort, edge);
+ invocation.setContext(sourcePort, new MyOutputContext(connectors.get(sourcePort)));
+ }
+
+ private static class MyOutputContext implements OutputPortContext {
+ private final String alias;
+ MyOutputContext(EtiaoConnector<?> connector) {
+ alias = connector.getAlias();
+ }
+ @Override
+ public String getAlias() {
+ return alias;
+ }
+ }
+
+ int addEdge() {
+ int index = edges.size();
+ edges.add(DISCONNECTED);
+ return index;
+ }
+
+ List<Edge> getEdges() {
+ List<Edge> connectedEdges = new ArrayList<>();
+ for (Edge de : edges) {
+ if (de != DISCONNECTED)
+ connectedEdges.add(de);
+ }
+ return Collections.unmodifiableList(connectedEdges);
+ }
+
+ /** For debug. Contents subject to change. */
+ @Override
+ public String toString() {
+ return "{"
+ + "invocation=" + invocation
+ // + " edges=" + edges
+ + "}";
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/Target.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/Target.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/Target.java
new file mode 100644
index 0000000..9b00f8f
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/Target.java
@@ -0,0 +1,39 @@
+/*
+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.edgent.runtime.etiao.graph;
+
+class Target<T> {
+
+ public Target(ExecutableVertex<?, T, ?> vertex, int port) {
+ super();
+ this.vertex = vertex;
+ this.port = port;
+ }
+ final ExecutableVertex<?, T, ?> vertex;
+ final int port;
+
+// /** For debug. Contents subject to change. */
+// @Override
+// public String toString() {
+// return "{"
+// + "port=" + port
+// + " vertex=" + vertex
+// + "}";
+// }
+}
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/EdgeType.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/EdgeType.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/EdgeType.java
new file mode 100644
index 0000000..22373c8
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/EdgeType.java
@@ -0,0 +1,84 @@
+/*
+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.edgent.runtime.etiao.graph.model;
+
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.edgent.graph.Edge;
+
+/**
+ * Represents an edge between two {@link VertexType} nodes.
+ */
+public class EdgeType {
+ /** Source vertex identifier */
+ private final String sourceId;
+ /** Source output port index */
+ private final int sourceOutputPort;
+ /** Target vertex identifier */
+ private final String targetId;
+ /** Target input port index */
+ private final int targetInputPort;
+ /** Set of tags associated with this edge */
+ private final Set<String> tags;
+ /** Edge's alias. Null if none. */
+ private final String alias;
+
+ public EdgeType() {
+ this.sourceId = null;
+ this.sourceOutputPort = 0;
+ this.targetId = null;
+ this.targetInputPort = 0;
+ this.tags = new HashSet<>();
+ this.alias = null;
+ }
+
+ public EdgeType(Edge value, IdMapper<String> ids) {
+ this.sourceId = ids.getId(value.getSource()).toString();
+ this.sourceOutputPort = value.getSourceOutputPort();
+ this.targetId = ids.getId(value.getTarget()).toString();
+ this.targetInputPort = value.getTargetInputPort();
+ this.tags = value.getTags();
+ this.alias = value.getAlias();
+ }
+
+ public String getSourceId() {
+ return sourceId;
+ }
+
+ public int getSourceOutputPort() {
+ return sourceOutputPort;
+ }
+
+ public String getTargetId() {
+ return targetId;
+ }
+
+ public int getTargetInputPort() {
+ return targetInputPort;
+ }
+
+ public Set<String> getTags() {
+ return tags;
+ }
+
+ public String getAlias() {
+ return alias;
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/GraphType.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/GraphType.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/GraphType.java
new file mode 100644
index 0000000..377df69
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/GraphType.java
@@ -0,0 +1,149 @@
+/*
+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.edgent.runtime.etiao.graph.model;
+
+import java.util.ArrayList;
+import java.util.IdentityHashMap;
+import java.util.List;
+
+import org.apache.edgent.graph.Edge;
+import org.apache.edgent.graph.Graph;
+import org.apache.edgent.graph.Vertex;
+import org.apache.edgent.oplet.Oplet;
+
+/**
+ * A generic directed graph of vertices, connectors and edges.
+ * <p>
+ * The graph consists of {@link VertexType} objects, each having
+ * 0 or more input and/or output {@link EdgeType} objects.
+ * {@link EdgeType} objects connect an output connector to
+ * an input connector.
+ * <p>
+ * A vertex has an associated {@link Oplet}.
+ */
+public class GraphType {
+ /**
+ * List of all vertices in this graph.
+ */
+ private final List<VertexType<?,?>> vertices;
+
+ /**
+ * List of all edges in this graph.
+ */
+ private final List<EdgeType> edges;
+
+ /**
+ * Create an instance of {@link GraphType}.
+ * @param graph the associated Graph
+ */
+ public GraphType(Graph graph) {
+ this(graph, null);
+ }
+
+ /**
+ * Create an instance of {@link GraphType} using the specified
+ * {@link IdMapper} to generate unique object identifiers.
+ * @param g the associated Graph
+ * @param ids the id mapper
+ */
+ public GraphType(Graph g, IdMapper<String> ids) {
+ if (ids == null) {
+ ids = new GraphType.Mapper();
+ }
+ ArrayList<VertexType<?,?>> vertices =
+ new ArrayList<VertexType<?,?>>();
+ ArrayList<EdgeType> edges = new ArrayList<EdgeType>();
+
+ for (Vertex<? extends Oplet<?,?>, ?, ?> v : g.getVertices()) {
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ VertexType<?,?> vertex = new VertexType(v, ids);
+ vertices.add(vertex);
+ }
+
+ for (Edge e : g.getEdges()) {
+ edges.add(new EdgeType(e, ids));
+ }
+
+ this.vertices = vertices;
+ this.edges = edges;
+ }
+
+ /**
+ * Default constructor of {@link GraphType}.
+ */
+ public GraphType() {
+ this.vertices = null;
+ this.edges = null;
+ }
+
+ public List<VertexType<?,?>> getVertices() {
+ return vertices;
+ }
+
+ public List<EdgeType> getEdges() {
+ return edges;
+ }
+
+ static class Mapper implements IdMapper<String> {
+ private int lastId = 0;
+ // Map using reference-equality in place of object-equality.
+ private IdentityHashMap<Object,String> ids = new IdentityHashMap<Object,String>();
+
+ @Override
+ public String add(Object o) {
+ if (o == null)
+ throw new NullPointerException();
+
+ synchronized (ids) {
+ String id = ids.get(o);
+ if (id == null) {
+ id = String.valueOf(lastId++);
+ ids.put(o, id);
+ }
+ return id;
+ }
+ }
+
+ @Override
+ public String getId(Object o) {
+ if (o == null)
+ throw new NullPointerException();
+
+ synchronized (ids) {
+ return ids.get(o);
+ }
+ }
+
+ @Override
+ public String add(Object o, String id) {
+ if (o == null || id == null)
+ throw new NullPointerException();
+
+ synchronized (ids) {
+ if (ids.containsKey(o)) {
+ throw new IllegalStateException();
+ }
+ else {
+ ids.put(o, id);
+ }
+ return id;
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/IdMapper.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/IdMapper.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/IdMapper.java
new file mode 100644
index 0000000..1b87f22
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/IdMapper.java
@@ -0,0 +1,65 @@
+/*
+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.edgent.runtime.etiao.graph.model;
+
+/**
+ * A set of elements associated with unique identifiers.
+ *
+ * Null element references cannot be part of the set. Attempting to add or
+ * to retrieve the id of a null element throws a NullPointerException.
+ *
+ * @param <ID> the identifier type.
+ */
+interface IdMapper<ID> {
+ /**
+ * Adds the specified object to the collection and generates a unique
+ * identifier for that object. If the object has already been added
+ * to the set, then returns its identifier.
+ *
+ * @param o the object to add
+ * @return a unique identifier associated with the object.
+ */
+ ID add(Object o);
+
+ /**
+ * Adds the specified object to the collection and associates it with the
+ * specified identifier.
+ * <p>
+ * If the object has already been added to the set with the same
+ * identifier, then returns its identifier. If the object has already
+ * been added to the set with another identifier, then throw an
+ * {@code IllegalStateException}.
+ *
+ * @param o the object to add
+ * @param id the associated identifier
+ * @return the identifier associated with the object.
+ * @throws IllegalStateException if the object has already been added to
+ * the set with another identifier
+ */
+ ID add(Object o, ID id);
+
+ /**
+ * Returns the identifier associated to the specified object, or {@code null}
+ * if the object is not associated with an identifier.
+ *
+ * @param o the object to add
+ * @return the identifier associated with the object.
+ */
+ ID getId(Object o);
+}
http://git-wip-us.apache.org/repos/asf/incubator-quarks/blob/a129aa16/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/InvocationType.java
----------------------------------------------------------------------
diff --git a/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/InvocationType.java b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/InvocationType.java
new file mode 100644
index 0000000..1db674d
--- /dev/null
+++ b/runtime/etiao/src/main/java/org/apache/edgent/runtime/etiao/graph/model/InvocationType.java
@@ -0,0 +1,47 @@
+/*
+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.edgent.runtime.etiao.graph.model;
+
+import org.apache.edgent.oplet.Oplet;
+
+/**
+ * Generic type for an oplet invocation instance.
+ *
+ * @param <I>
+ * Data container type for input tuples.
+ * @param <O>
+ * Data container type for output tuples.
+ */
+public class InvocationType<I, O> {
+
+ /**
+ * Kind of the oplet to be invoked.
+ */
+ private final String kind;
+
+ // TODO add port model
+
+ public InvocationType(Oplet<I, O> value) {
+ this.kind = value.getClass().getName();
+ }
+
+ public String getClassName() {
+ return this.kind;
+ }
+}