You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@twill.apache.org by ch...@apache.org on 2016/10/04 16:25:28 UTC

[01/16] twill git commit: (TWILL-188) Added methods to Location for manipulation of permission

Repository: twill
Updated Branches:
  refs/heads/site d4a3b6c69 -> f285ac443


(TWILL-188) Added methods to Location for manipulation of permission

- Three methods are added
  void createNew(String permission)
  String getPermissions()
  void setPermissions(String permission)


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/02a374f6
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/02a374f6
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/02a374f6

Branch: refs/heads/site
Commit: 02a374f6b55653abde6300807841d4da0332631a
Parents: 290cf1d
Author: Terence Yim <ch...@apache.org>
Authored: Wed Aug 24 15:52:56 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Thu Aug 25 09:15:21 2016 -0700

----------------------------------------------------------------------
 .../apache/twill/filesystem/LocalLocation.java  | 98 ++++++++++++++++++--
 .../org/apache/twill/filesystem/Location.java   | 41 +++++++-
 .../twill/filesystem/FileContextLocation.java   | 55 ++++++++++-
 .../apache/twill/filesystem/HDFSLocation.java   | 71 ++++++++++++--
 .../twill/filesystem/LocationTestBase.java      | 73 +++++++++++++++
 5 files changed, 316 insertions(+), 22 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/02a374f6/twill-common/src/main/java/org/apache/twill/filesystem/LocalLocation.java
----------------------------------------------------------------------
diff --git a/twill-common/src/main/java/org/apache/twill/filesystem/LocalLocation.java b/twill-common/src/main/java/org/apache/twill/filesystem/LocalLocation.java
index 037f4f9..b0ffa33 100644
--- a/twill-common/src/main/java/org/apache/twill/filesystem/LocalLocation.java
+++ b/twill-common/src/main/java/org/apache/twill/filesystem/LocalLocation.java
@@ -25,14 +25,22 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.URI;
+import java.nio.channels.Channels;
+import java.nio.channels.WritableByteChannel;
+import java.nio.file.FileAlreadyExistsException;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.PosixFilePermission;
+import java.nio.file.attribute.PosixFilePermissions;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Deque;
+import java.util.EnumSet;
 import java.util.LinkedList;
 import java.util.List;
+import java.util.Set;
 import java.util.UUID;
 
 /**
@@ -79,19 +87,21 @@ final class LocalLocation implements Location {
    */
   @Override
   public OutputStream getOutputStream() throws IOException {
-    File parent = file.getParentFile();
-    if (!parent.exists()) {
-      parent.mkdirs();
-    }
+    ensureDirectory(file.getParentFile());
     return new FileOutputStream(file);
   }
 
-  /**
-   * Local location doesn't supports permission. It's the same as calling {@link #getOutputStream()}.
-   */
   @Override
   public OutputStream getOutputStream(String permission) throws IOException {
-    return getOutputStream();
+    ensureDirectory(file.getParentFile());
+    Set<PosixFilePermission> permissions = parsePermissions(permission);
+    Path path = file.toPath();
+    WritableByteChannel channel = Files.newByteChannel(path,
+                                                       EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE),
+                                                       PosixFilePermissions.asFileAttribute(permissions));
+    // Set the permission explicitly again to skip the umask
+    Files.setPosixFilePermissions(path, permissions);
+    return Channels.newOutputStream(channel);
   }
 
   /**
@@ -107,6 +117,29 @@ final class LocalLocation implements Location {
     return file.createNewFile();
   }
 
+  @Override
+  public boolean createNew(String permission) throws IOException {
+    Set<PosixFilePermission> permissions = parsePermissions(permission);
+    try {
+      Path path = Files.createFile(file.toPath(), PosixFilePermissions.asFileAttribute(permissions));
+      // Set the permission explicitly again to skip the umask
+      Files.setPosixFilePermissions(path, permissions);
+      return true;
+    } catch (FileAlreadyExistsException e) {
+      return false;
+    }
+  }
+
+  @Override
+  public String getPermissions() throws IOException {
+    return PosixFilePermissions.toString(Files.getPosixFilePermissions(file.toPath()));
+  }
+
+  @Override
+  public void setPermissions(String permission) throws IOException {
+    Files.setPosixFilePermissions(file.toPath(), parsePermissions(permission));
+  }
+
   /**
    * Appends the child to the current {@link Location} on local filesystem.
    * <p>
@@ -255,4 +288,53 @@ final class LocalLocation implements Location {
   public String toString() {
     return file.toString();
   }
+
+  /**
+   * Ensures the given {@link File} is a directory. If it doesn't exist, it will be created.
+   */
+  private void ensureDirectory(File dir) throws IOException {
+    // Check, create, check to resolve race conditions if there are concurrent creation of the directory.
+    if (!dir.isDirectory() && !dir.mkdirs() && !dir.isDirectory()) {
+      throw new IOException("Failed to create directory " + dir);
+    }
+  }
+
+  /**
+   * Parses the given permission to a set of {@link PosixFilePermission}.
+   *
+   * @param permission the permission as passed to the {@link #createNew(String)} or {@link #getOutputStream(String)}
+   *                   methods.
+   * @return a new set of {@link PosixFilePermission}.
+   */
+  private Set<PosixFilePermission> parsePermissions(String permission) {
+    Set<PosixFilePermission> permissions;
+    if (permission.length() == 3) {
+      permissions = parseNumericPermissions(permission);
+    } else if (permission.length() == 9) {
+      permissions = PosixFilePermissions.fromString(permission);
+    } else {
+      throw new IllegalArgumentException("Invalid permission " + permission +
+                                           ". Permission should either be a three digit or nine character string.");
+    }
+
+    return permissions;
+  }
+
+  /**
+   * Parses a three digit UNIX numeric permission representation to a set of {@link PosixFilePermission}.
+   */
+  private Set<PosixFilePermission> parseNumericPermissions(String permission) {
+    String posixPermission = "";
+    for (int i = 0; i < 3; i++) {
+      int digit = permission.charAt(i) - '0';
+      if (digit < 0 || digit > 7) {
+        throw new IllegalArgumentException("Invalid permission " + permission +
+                                             ". Only digits between 0-7 are allowed.");
+      }
+      posixPermission += ((digit & 4) != 0) ? "r" : "-";
+      posixPermission += ((digit & 2) != 0) ? "w" : "-";
+      posixPermission += ((digit & 1) != 0) ? "x" : "-";
+    }
+    return PosixFilePermissions.fromString(posixPermission);
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/02a374f6/twill-common/src/main/java/org/apache/twill/filesystem/Location.java
----------------------------------------------------------------------
diff --git a/twill-common/src/main/java/org/apache/twill/filesystem/Location.java b/twill-common/src/main/java/org/apache/twill/filesystem/Location.java
index 2560e55..229050d 100644
--- a/twill-common/src/main/java/org/apache/twill/filesystem/Location.java
+++ b/twill-common/src/main/java/org/apache/twill/filesystem/Location.java
@@ -21,6 +21,7 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.URI;
+import java.nio.file.attribute.PosixFilePermissions;
 import java.util.List;
 import javax.annotation.Nullable;
 
@@ -53,11 +54,42 @@ public interface Location {
    * Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name
    * does not yet exist.
    * @return {@code true} if the file is successfully create, {@code false} otherwise.
-   * @throws IOException
+   * @throws IOException if error encountered during creation of the file
    */
   boolean createNew() throws IOException;
 
   /**
+   * Atomically creates a new, empty file named by this abstract pathname if and only if a file with this name
+   * does not yet exist. The newly created file will have permission set based on the given permission settings.
+   *
+   * @param permission A permission string. It has to be either a three digit or a nine character string.
+   *                   For the three digit string, it is similar to the UNIX permission numeric representation.
+   *                   The first digit is the permission for owner, second digit is the permission for group and
+   *                   the third digit is the permission for all.
+   *                   For the nine character string, it uses the format as specified by the
+   *                   {@link PosixFilePermissions#fromString(String)} method.
+   * @return {@code true} if the file is successfully create, {@code false} otherwise.
+   * @throws IOException if error encountered during creation of the file
+   */
+  boolean createNew(String permission) throws IOException;
+
+  /**
+   * Returns the permissions of this {@link Location}. The permission string is a nine character string as the format
+   * specified by the {@link PosixFilePermissions#fromString(String)} method.
+   *
+   * @throws IOException if failed to get the permissions of the location
+   */
+  String getPermissions() throws IOException;
+
+  /**
+   * Sets the permissions on this location.
+   *
+   * @param permission A permission string. See {@link #createNew(String)} for the format.
+   * @throws IOException if failed to set the permission
+   */
+  void setPermissions(String permission) throws IOException;
+
+  /**
    * @return An {@link java.io.InputStream} for this location.
    * @throws IOException
    */
@@ -73,7 +105,12 @@ public interface Location {
    * Creates an {@link OutputStream} for this location with the given permission. The actual permission supported
    * depends on implementation.
    *
-   * @param permission A POSIX permission string.
+   * @param permission A permission string. It has to be either a three digit or a nine character string.
+   *                   For the three digit string, it is similar to the UNIX permission numeric representation.
+   *                   The first digit is the permission for owner, second digit is the permission for group and
+   *                   the third digit is the permission for all.
+   *                   For the nine character string, it uses the format as specified by the
+   *                   {@link PosixFilePermissions#fromString(String)} method.
    * @return An {@link OutputStream} for writing to this location.
    * @throws IOException If failed to create the {@link OutputStream}.
    */

http://git-wip-us.apache.org/repos/asf/twill/blob/02a374f6/twill-yarn/src/main/java/org/apache/twill/filesystem/FileContextLocation.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/filesystem/FileContextLocation.java b/twill-yarn/src/main/java/org/apache/twill/filesystem/FileContextLocation.java
index 85698d0..e87ddf1 100644
--- a/twill-yarn/src/main/java/org/apache/twill/filesystem/FileContextLocation.java
+++ b/twill-yarn/src/main/java/org/apache/twill/filesystem/FileContextLocation.java
@@ -78,6 +78,32 @@ final class FileContextLocation implements Location {
   }
 
   @Override
+  public boolean createNew(String permission) throws IOException {
+    try {
+      FsPermission fsPermission = parsePermissions(permission);
+      fc.create(path, EnumSet.of(CreateFlag.CREATE),
+                Options.CreateOpts.createParent(),
+                Options.CreateOpts.perms(fsPermission)).close();
+      // Set the permission explicitly again to skip the umask
+      fc.setPermission(path, fsPermission);
+      return true;
+    } catch (FileAlreadyExistsException e) {
+      return false;
+    }
+  }
+
+  @Override
+  public String getPermissions() throws IOException {
+    FsPermission permission = fc.getFileStatus(path).getPermission();
+    return permission.getUserAction().SYMBOL + permission.getGroupAction().SYMBOL + permission.getOtherAction().SYMBOL;
+  }
+
+  @Override
+  public void setPermissions(String permission) throws IOException {
+    fc.setPermission(path, parsePermissions(permission));
+  }
+
+  @Override
   public InputStream getInputStream() throws IOException {
     return fc.open(path);
   }
@@ -89,9 +115,13 @@ final class FileContextLocation implements Location {
 
   @Override
   public OutputStream getOutputStream(String permission) throws IOException {
-    return fc.create(path, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE),
-                     Options.CreateOpts.perms(new FsPermission(permission)),
-                     Options.CreateOpts.createParent());
+    FsPermission fsPermission = parsePermissions(permission);
+    OutputStream os = fc.create(path, EnumSet.of(CreateFlag.CREATE, CreateFlag.OVERWRITE),
+                                Options.CreateOpts.perms(fsPermission),
+                                Options.CreateOpts.createParent());
+    // Set the permission explicitly again to skip the umask
+    fc.setPermission(path, fsPermission);
+    return os;
   }
 
   @Override
@@ -221,4 +251,23 @@ final class FileContextLocation implements Location {
   public String toString() {
     return toURI().toString();
   }
+
+  /**
+   * Parses the given permission to {@link FsPermission}.
+   *
+   * @param permission the permission as passed to the {@link #createNew(String)} or {@link #getOutputStream(String)}
+   *                   methods.
+   * @return a new {@link FsPermission}.
+   */
+  private FsPermission parsePermissions(String permission) {
+    if (permission.length() == 3) {
+      return new FsPermission(permission);
+    } else if (permission.length() == 9) {
+      // The FsPermission expect a 10 characters string, which it will ignore the first character
+      return FsPermission.valueOf("-" + permission);
+    } else {
+      throw new IllegalArgumentException("Invalid permission " + permission +
+                                           ". Permission should either be a three digit or nine character string.");
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/02a374f6/twill-yarn/src/main/java/org/apache/twill/filesystem/HDFSLocation.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/filesystem/HDFSLocation.java b/twill-yarn/src/main/java/org/apache/twill/filesystem/HDFSLocation.java
index aa29384..aa34e5b 100644
--- a/twill-yarn/src/main/java/org/apache/twill/filesystem/HDFSLocation.java
+++ b/twill-yarn/src/main/java/org/apache/twill/filesystem/HDFSLocation.java
@@ -19,7 +19,8 @@ package org.apache.twill.filesystem;
 
 import com.google.common.base.Objects;
 import com.google.common.collect.ImmutableList;
-import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CreateFlag;
+import org.apache.hadoop.fs.FileAlreadyExistsException;
 import org.apache.hadoop.fs.FileStatus;
 import org.apache.hadoop.fs.FileSystem;
 import org.apache.hadoop.fs.Options;
@@ -31,6 +32,7 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.URI;
+import java.util.EnumSet;
 import java.util.List;
 import java.util.UUID;
 
@@ -85,14 +87,17 @@ final class HDFSLocation implements Location {
 
   @Override
   public OutputStream getOutputStream(String permission) throws IOException {
-    Configuration conf = fs.getConf();
-    return fs.create(path,
-                     new FsPermission(permission),
-                     true,
-                     conf.getInt("io.file.buffer.size", 4096),
-                     fs.getDefaultReplication(path),
-                     fs.getDefaultBlockSize(path),
-                     null);
+    FsPermission fsPermission = parsePermissions(permission);
+    OutputStream os = fs.create(path,
+                                fsPermission,
+                                true,
+                                fs.getConf().getInt("io.file.buffer.size", 4096),
+                                fs.getDefaultReplication(path),
+                                fs.getDefaultBlockSize(path),
+                                null);
+    // Set the permission explicitly again to skip the umask
+    fs.setPermission(path, fsPermission);
+    return os;
   }
 
   /**
@@ -133,6 +138,34 @@ final class HDFSLocation implements Location {
     return fs.createNewFile(path);
   }
 
+  @Override
+  public boolean createNew(String permission) throws IOException {
+    try {
+      FsPermission fsPermission = parsePermissions(permission);
+      fs.create(path, fsPermission, EnumSet.of(CreateFlag.CREATE),
+                fs.getConf().getInt("io.file.buffer.size", 4096),
+                fs.getDefaultReplication(path),
+                fs.getDefaultBlockSize(path),
+                null).close();
+      // Set the permission explicitly again to skip the umask
+      fs.setPermission(path, fsPermission);
+      return true;
+    } catch (FileAlreadyExistsException e) {
+      return false;
+    }
+  }
+
+  @Override
+  public String getPermissions() throws IOException {
+    FsPermission permission = fs.getFileStatus(path).getPermission();
+    return permission.getUserAction().SYMBOL + permission.getGroupAction().SYMBOL + permission.getOtherAction().SYMBOL;
+  }
+
+  @Override
+  public void setPermissions(String permission) throws IOException {
+    fs.setPermission(path, parsePermissions(permission));
+  }
+
   /**
    * @return A {@link URI} for this location on HDFS.
    */
@@ -243,4 +276,24 @@ final class HDFSLocation implements Location {
   public String toString() {
     return path.toString();
   }
+
+  /**
+   * Parses the given permission to {@link FsPermission}. Since the {@link HDFSLocationFactory} and this class are
+   * deprecated, this method is copied from {@link FileContextLocation} instead of creating an extra library to share.
+   *
+   * @param permission the permission as passed to the {@link #createNew(String)} or {@link #getOutputStream(String)}
+   *                   methods.
+   * @return a new {@link FsPermission}.
+   */
+  private FsPermission parsePermissions(String permission) {
+    if (permission.length() == 3) {
+      return new FsPermission(permission);
+    } else if (permission.length() == 9) {
+      // The FsPermission expect a 10 characters string, which it will ignore the first character
+      return FsPermission.valueOf("-" + permission);
+    } else {
+      throw new IllegalArgumentException("Invalid permission " + permission +
+                                           ". Permission should either be a three digit or nine character string.");
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/02a374f6/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java b/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java
index af485dc..15c28f4 100644
--- a/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java
+++ b/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java
@@ -187,5 +187,78 @@ public abstract class LocationTestBase {
     }
   }
 
+  @Test
+  public void testPermissions() throws IOException {
+    LocationFactory factory = locationFactoryCache.getUnchecked("permission1");
+
+    // Test permissions setting on createNew calls
+    Location location = factory.create("test400-1");
+    Assert.assertTrue(location.createNew("400"));
+    Assert.assertEquals("r--------", location.getPermissions());
+    location = factory.create("test400-2");
+    Assert.assertTrue(location.createNew("r--------"));
+    Assert.assertEquals("r--------", location.getPermissions());
+    Assert.assertFalse(location.createNew("600"));
+
+    location = factory.create("test660-1");
+    Assert.assertTrue(location.createNew("660"));
+    Assert.assertEquals("rw-rw----", location.getPermissions());
+    location = factory.create("test660-2");
+    Assert.assertTrue(location.createNew("rw-rw----"));
+    Assert.assertEquals("rw-rw----", location.getPermissions());
+    Assert.assertFalse(location.createNew("600"));
+
+    location = factory.create("test755-1");
+    Assert.assertTrue(location.createNew("755"));
+    Assert.assertEquals("rwxr-xr-x", location.getPermissions());
+    location = factory.create("test755-2");
+    Assert.assertTrue(location.createNew("rwxr-xr-x"));
+    Assert.assertEquals("rwxr-xr-x", location.getPermissions());
+    Assert.assertFalse(location.createNew("600"));
+
+    // Test permissions setting on getOutputStream calls
+    factory = locationFactoryCache.getUnchecked("permission2");
+
+    location = factory.create("test400-1");
+    location.getOutputStream("400").close();
+    Assert.assertEquals("r--------", location.getPermissions());
+    location = factory.create("test400-2");
+    location.getOutputStream("r--------").close();
+    Assert.assertEquals("r--------", location.getPermissions());
+
+    location = factory.create("test660-1");
+    location.getOutputStream("660").close();
+    Assert.assertEquals("rw-rw----", location.getPermissions());
+    location = factory.create("test660-2");
+    location.getOutputStream("rw-rw----").close();
+    Assert.assertEquals("rw-rw----", location.getPermissions());
+
+    location = factory.create("test755-1");
+    location.getOutputStream("755").close();
+    Assert.assertEquals("rwxr-xr-x", location.getPermissions());
+    location = factory.create("test755-2");
+    location.getOutputStream("rwxr-xr-x").close();
+    Assert.assertEquals("rwxr-xr-x", location.getPermissions());
+
+    // Test permissions setting on setPermission method
+    factory = locationFactoryCache.getUnchecked("permission3");
+
+    // Setting permission on non-existed file should have IOException thrown
+    location = factory.create("somefile");
+    try {
+      location.setPermissions("400");
+      Assert.fail("IOException expected on setting permission on non-existing Location.");
+    } catch (IOException e) {
+      // expected
+    }
+
+    // Create file with read only permission
+    Assert.assertTrue(location.createNew("444"));
+    Assert.assertEquals("r--r--r--", location.getPermissions());
+    // Change the permission to write only
+    location.setPermissions("222");
+    Assert.assertEquals("-w--w--w-", location.getPermissions());
+  }
+
   protected abstract LocationFactory createLocationFactory(String pathBase) throws Exception;
 }


[11/16] twill git commit: (TWILL-177) Make ZKDiscoveryService AutoCloseable

Posted by ch...@apache.org.
(TWILL-177) Make ZKDiscoveryService AutoCloseable

- Release ZK watches when closed
- Fixed a race condition in ZKDiscoveryServiceTest
- Fix the easy to fail InitializeFailTestRun
  - Match with an error message emitted from AM instead of from the container.
    - It\u2019s possible that the one from the container don\u2019t have chance to
      send out before it gets killed.

This closes #8 on Github.

Signed-off-by: Terence Yim <ch...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/ced2044f
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/ced2044f
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/ced2044f

Branch: refs/heads/site
Commit: ced2044f185db59192e38411cb9e28f597a5ea04
Parents: fd9d726
Author: Terence Yim <ch...@apache.org>
Authored: Thu Aug 25 18:41:15 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Tue Sep 13 14:18:49 2016 -0700

----------------------------------------------------------------------
 .../twill/internal/AbstractTwillController.java |  17 +-
 .../twill/internal/AbstractTwillService.java    |   8 +-
 .../discovery/DefaultServiceDiscovered.java     |   9 +-
 .../twill/discovery/ZKDiscoveryService.java     | 165 +++++++--
 .../discovery/DiscoveryServiceTestBase.java     | 349 +++++++++++--------
 .../twill/discovery/ZKDiscoveryServiceTest.java | 114 +++---
 .../internal/container/TwillContainerMain.java  |  30 +-
 .../org/apache/twill/yarn/BaseYarnTest.java     |  15 +
 .../apache/twill/yarn/EchoServerTestRun.java    |   4 +-
 .../twill/yarn/InitializeFailTestRun.java       |  12 +-
 .../org/apache/twill/yarn/YarnTestSuite.java    |   1 -
 .../internal/zookeeper/LeaderElection.java      |   7 +-
 12 files changed, 484 insertions(+), 247 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillController.java
----------------------------------------------------------------------
diff --git a/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillController.java b/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillController.java
index 41a044b..e60f6a3 100644
--- a/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillController.java
+++ b/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillController.java
@@ -28,7 +28,6 @@ import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
-
 import org.apache.twill.api.Command;
 import org.apache.twill.api.ResourceReport;
 import org.apache.twill.api.RunId;
@@ -38,7 +37,6 @@ import org.apache.twill.api.logging.LogEntry;
 import org.apache.twill.api.logging.LogHandler;
 import org.apache.twill.api.logging.LogThrowable;
 import org.apache.twill.common.Cancellable;
-import org.apache.twill.discovery.DiscoveryServiceClient;
 import org.apache.twill.discovery.ServiceDiscovered;
 import org.apache.twill.discovery.ZKDiscoveryService;
 import org.apache.twill.internal.json.LogEntryDecoder;
@@ -73,14 +71,13 @@ public abstract class AbstractTwillController extends AbstractZKServiceControlle
 
   private final Queue<LogHandler> logHandlers;
   private final KafkaClientService kafkaClient;
-  private final DiscoveryServiceClient discoveryServiceClient;
-  private volatile Cancellable logCancellable;
+  private ZKDiscoveryService discoveryServiceClient;
+  private Cancellable logCancellable;
 
   public AbstractTwillController(RunId runId, ZKClient zkClient, Iterable<LogHandler> logHandlers) {
     super(runId, zkClient);
     this.logHandlers = new ConcurrentLinkedQueue<>();
     this.kafkaClient = new ZKKafkaClientService(ZKClients.namespace(zkClient, "/" + runId.getId() + "/kafka"));
-    this.discoveryServiceClient = new ZKDiscoveryService(zkClient);
     Iterables.addAll(this.logHandlers, logHandlers);
   }
 
@@ -95,10 +92,13 @@ public abstract class AbstractTwillController extends AbstractZKServiceControlle
   }
 
   @Override
-  protected void doShutDown() {
+  protected synchronized void doShutDown() {
     if (logCancellable != null) {
       logCancellable.cancel();
     }
+    if (discoveryServiceClient != null) {
+      discoveryServiceClient.close();
+    }
     // Safe to call stop no matter when state the KafkaClientService is in.
     kafkaClient.stopAndWait();
   }
@@ -115,7 +115,10 @@ public abstract class AbstractTwillController extends AbstractZKServiceControlle
   }
 
   @Override
-  public final ServiceDiscovered discoverService(String serviceName) {
+  public final synchronized ServiceDiscovered discoverService(String serviceName) {
+    if (discoveryServiceClient == null) {
+      discoveryServiceClient = new ZKDiscoveryService(zkClient);
+    }
     return discoveryServiceClient.discover(serviceName);
   }
 

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillService.java
----------------------------------------------------------------------
diff --git a/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillService.java b/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillService.java
index 8688d0b..1717117 100644
--- a/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillService.java
+++ b/twill-core/src/main/java/org/apache/twill/internal/AbstractTwillService.java
@@ -27,6 +27,7 @@ import com.google.common.util.concurrent.Service;
 import com.google.gson.Gson;
 import com.google.gson.JsonObject;
 import org.apache.twill.api.RunId;
+import org.apache.twill.common.Cancellable;
 import org.apache.twill.common.Threads;
 import org.apache.twill.internal.state.Message;
 import org.apache.twill.internal.state.MessageCallback;
@@ -88,6 +89,7 @@ public abstract class AbstractTwillService extends AbstractExecutionThreadServic
   protected final ZKClient zkClient;
   protected final RunId runId;
   private ExecutorService messageCallbackExecutor;
+  private Cancellable watcherCancellable;
 
   protected AbstractTwillService(final ZKClient zkClient, RunId runId) {
     this.zkClient = zkClient;
@@ -145,7 +147,7 @@ public abstract class AbstractTwillService extends AbstractExecutionThreadServic
                                                      new ThreadPoolExecutor.DiscardPolicy());
 
     // Watch for session expiration, recreate the live node if reconnected after expiration.
-    zkClient.addConnectionWatcher(new Watcher() {
+    watcherCancellable = zkClient.addConnectionWatcher(new Watcher() {
       private boolean expired = false;
 
       @Override
@@ -181,6 +183,10 @@ public abstract class AbstractTwillService extends AbstractExecutionThreadServic
 
   @Override
   protected final void shutDown() throws Exception {
+    if (watcherCancellable != null) {
+      watcherCancellable.cancel();
+    }
+
     messageCallbackExecutor.shutdownNow();
     try {
       doStop();

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java b/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java
index dbb0f7c..ca55390 100644
--- a/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java
+++ b/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java
@@ -20,6 +20,8 @@ package org.apache.twill.discovery;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Lists;
 import org.apache.twill.common.Cancellable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import java.util.Iterator;
 import java.util.List;
@@ -36,6 +38,8 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
  */
 final class DefaultServiceDiscovered implements ServiceDiscovered {
 
+  private static final Logger LOG = LoggerFactory.getLogger(DefaultServiceDiscovered.class);
+
   private final String name;
   private final AtomicReference<Set<Discoverable>> discoverables;
   private final List<ListenerCaller> listenerCallers;
@@ -49,7 +53,10 @@ final class DefaultServiceDiscovered implements ServiceDiscovered {
   }
 
   void setDiscoverables(Set<Discoverable> discoverables) {
-    this.discoverables.set(ImmutableSet.copyOf(discoverables));
+    Set<Discoverable> newDiscoverables = ImmutableSet.copyOf(discoverables);
+    LOG.debug("Discoverables changed: {}={}", name, newDiscoverables);
+
+    this.discoverables.set(newDiscoverables);
 
     // Collect all listeners with a read lock to the listener list.
     List<ListenerCaller> callers = Lists.newArrayList();

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java b/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java
index 4f2d0f7..6a3f64d 100644
--- a/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java
+++ b/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java
@@ -20,6 +20,8 @@ package org.apache.twill.discovery;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.CacheLoader;
 import com.google.common.cache.LoadingCache;
+import com.google.common.cache.RemovalListener;
+import com.google.common.cache.RemovalNotification;
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Lists;
@@ -47,14 +49,18 @@ import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import java.net.InetSocketAddress;
+import java.util.ArrayList;
+import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.Executor;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReentrantLock;
+import javax.annotation.Nullable;
 
 /**
  * Zookeeper implementation of {@link DiscoveryService} and {@link DiscoveryServiceClient}.
@@ -93,19 +99,21 @@ import java.util.concurrent.locks.ReentrantLock;
  *   </pre>
  * </blockquote>
  */
-public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceClient {
+public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceClient, AutoCloseable {
   private static final Logger LOG = LoggerFactory.getLogger(ZKDiscoveryService.class);
 
   private static final long RETRY_MILLIS = 1000;
 
+  private final AtomicBoolean closed;
   // In memory map for recreating ephemeral nodes after session expires.
   // It map from discoverable to the corresponding Cancellable
   private final Multimap<Discoverable, DiscoveryCancellable> discoverables;
   private final Lock lock;
 
-  private final LoadingCache<String, ServiceDiscovered> services;
+  private final LoadingCache<String, ServiceDiscoveredCacheEntry> services;
   private final ZKClient zkClient;
   private final ScheduledExecutorService retryExecutor;
+  private final Cancellable watcherCancellable;
 
   /**
    * Constructs ZKDiscoveryService using the provided zookeeper client for storing service registry.
@@ -122,13 +130,24 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
    *                  If namespace is {@code null}, no namespace will be used.
    */
   public ZKDiscoveryService(ZKClient zkClient, String namespace) {
+    this.closed = new AtomicBoolean();
     this.discoverables = HashMultimap.create();
     this.lock = new ReentrantLock();
     this.retryExecutor = Executors.newSingleThreadScheduledExecutor(
       Threads.createDaemonThreadFactory("zk-discovery-retry"));
     this.zkClient = namespace == null ? zkClient : ZKClients.namespace(zkClient, namespace);
-    this.services = CacheBuilder.newBuilder().build(createServiceLoader());
-    this.zkClient.addConnectionWatcher(createConnectionWatcher());
+    this.services = CacheBuilder.newBuilder()
+      .removalListener(new RemovalListener<String, ServiceDiscoveredCacheEntry>() {
+        @Override
+        public void onRemoval(RemovalNotification<String, ServiceDiscoveredCacheEntry> notification) {
+          ServiceDiscoveredCacheEntry entry = notification.getValue();
+          if (entry != null) {
+            entry.cancel();
+          }
+        }
+      })
+      .build(createServiceLoader());
+    this.watcherCancellable = this.zkClient.addConnectionWatcher(createConnectionWatcher());
   }
 
   /**
@@ -146,6 +165,10 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
    */
   @Override
   public Cancellable register(final Discoverable discoverable) {
+    if (closed.get()) {
+      throw new IllegalStateException("Cannot register discoverable through a closed ZKDiscoveryService");
+    }
+
     final SettableFuture<String> future = SettableFuture.create();
     final DiscoveryCancellable cancellable = new DiscoveryCancellable(discoverable);
 
@@ -157,7 +180,11 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
         cancellable.setPath(result);
         lock.lock();
         try {
-          discoverables.put(discoverable, cancellable);
+          if (!closed.get()) {
+            discoverables.put(discoverable, cancellable);
+          } else {
+            cancellable.asyncCancel();
+          }
         } finally {
           lock.unlock();
         }
@@ -182,9 +209,47 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
 
   @Override
   public ServiceDiscovered discover(String service) {
+    if (closed.get()) {
+      throw new IllegalStateException("Cannot discover through a closed ZKDiscoveryService");
+    }
     return services.getUnchecked(service);
   }
 
+  @Override
+  public void close() {
+    if (!closed.compareAndSet(false, true)) {
+      return;
+    }
+
+    // Stop the registration retry executor
+    retryExecutor.shutdownNow();
+
+    // Cancel the connection watcher
+    watcherCancellable.cancel();
+
+    // Cancel all registered services
+    List<ListenableFuture<?>> futures = new ArrayList<>();
+    lock.lock();
+    try {
+      for (Map.Entry<Discoverable, DiscoveryCancellable> entry : discoverables.entries()) {
+        LOG.debug("Un-registering service {} - {}", entry.getKey().getName(), entry.getKey().getSocketAddress());
+        futures.add(entry.getValue().asyncCancel());
+      }
+    } finally {
+      lock.unlock();
+    }
+    try {
+      Futures.successfulAsList(futures).get();
+      LOG.debug("All services unregistered");
+    } catch (Exception e) {
+      // This is not expected to happen
+      LOG.warn("Unexpected exception when waiting for all services to get unregistered", e);
+    }
+
+    // Cancel all services being watched
+    services.invalidateAll();
+  }
+
   /**
    * Handle registration failure.
    *
@@ -197,11 +262,14 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
                                      final SettableFuture<String> completion,
                                      final FutureCallback<String> creationCallback,
                                      final Throwable failureCause) {
+    if (closed.get()) {
+      return;
+    }
 
     final String path = getNodePath(discoverable);
     Futures.addCallback(zkClient.exists(path), new FutureCallback<Stat>() {
       @Override
-      public void onSuccess(Stat result) {
+      public void onSuccess(@Nullable Stat result) {
         if (result == null) {
           // If the node is gone, simply retry.
           LOG.info("Node {} is gone. Retry registration for {}.", path, discoverable);
@@ -244,16 +312,21 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
   }
 
   private void retryRegister(final Discoverable discoverable, final FutureCallback<String> creationCallback) {
+    if (closed.get()) {
+      return;
+    }
+
     retryExecutor.schedule(new Runnable() {
 
       @Override
       public void run() {
-        Futures.addCallback(doRegister(discoverable), creationCallback, Threads.SAME_THREAD_EXECUTOR);
+        if (!closed.get()) {
+          Futures.addCallback(doRegister(discoverable), creationCallback, Threads.SAME_THREAD_EXECUTOR);
+        }
       }
     }, RETRY_MILLIS, TimeUnit.MILLISECONDS);
   }
 
-
   /**
    * Generate unique node path for a given {@link Discoverable}.
    * @param discoverable An instance of {@link Discoverable}.
@@ -288,6 +361,11 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
           lock.lock();
           try {
             for (final Map.Entry<Discoverable, DiscoveryCancellable> entry : discoverables.entries()) {
+              if (closed.get()) {
+                entry.getValue().asyncCancel();
+                continue;
+              }
+
               LOG.info("Re-registering service: {}", entry.getKey());
 
               // Must be non-blocking in here.
@@ -318,22 +396,22 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
   /**
    * Creates a CacheLoader for creating live Iterable for watching instances changes for a given service.
    */
-  private CacheLoader<String, ServiceDiscovered> createServiceLoader() {
-    return new CacheLoader<String, ServiceDiscovered>() {
+  private CacheLoader<String, ServiceDiscoveredCacheEntry> createServiceLoader() {
+    return new CacheLoader<String, ServiceDiscoveredCacheEntry>() {
       @Override
-      public ServiceDiscovered load(String service) throws Exception {
+      public ServiceDiscoveredCacheEntry load(String service) throws Exception {
         final DefaultServiceDiscovered serviceDiscovered = new DefaultServiceDiscovered(service);
-        final String serviceBase = "/" + service;
+        final String pathBase = "/" + service;
 
         // Watch for children changes in /service
-        ZKOperations.watchChildren(zkClient, serviceBase, new ZKOperations.ChildrenCallback() {
+        Cancellable cancellable = ZKOperations.watchChildren(zkClient, pathBase, new ZKOperations.ChildrenCallback() {
           @Override
           public void updated(NodeChildren nodeChildren) {
             // Fetch data of all children nodes in parallel.
             List<String> children = nodeChildren.getChildren();
             List<OperationFuture<NodeData>> dataFutures = Lists.newArrayListWithCapacity(children.size());
             for (String child : children) {
-              dataFutures.add(zkClient.getData(serviceBase + "/" + child));
+              dataFutures.add(zkClient.getData(pathBase + "/" + child));
             }
 
             // Update the service map when all fetching are done.
@@ -356,7 +434,7 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
             }, Threads.SAME_THREAD_EXECUTOR);
           }
         });
-        return serviceDiscovered;
+        return new ServiceDiscoveredCacheEntry(serviceDiscovered, cancellable);
       }
     };
   }
@@ -394,18 +472,23 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
 
     @Override
     public void cancel() {
+      Futures.getUnchecked(asyncCancel());
+      LOG.debug("Service unregistered: {} {}", discoverable, path);
+    }
+
+    ListenableFuture<?> asyncCancel() {
       if (!cancelled.compareAndSet(false, true)) {
-        return;
+        return Futures.immediateFuture(null);
       }
 
       // Take a snapshot of the volatile path.
       String path = this.path;
 
-      // If it is null, meaning cancel() is called before the ephemeral node is created, hence
+      // If it is null, meaning cancel is called before the ephemeral node is created, hence
       // setPath() will be called in future (through zk callback when creation is completed)
       // so that deletion will be done in setPath().
       if (path == null) {
-        return;
+        return Futures.immediateFuture(null);
       }
 
       // Remove this Cancellable from the map so that upon session expiration won't try to register.
@@ -418,9 +501,49 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
 
       // Delete the path. It's ok if the path not exists
       // (e.g. what session expired and before node has been re-created)
-      Futures.getUnchecked(ZKOperations.ignoreError(zkClient.delete(path),
-                                                    KeeperException.NoNodeException.class, path));
-      LOG.debug("Service unregistered: {} {}", discoverable, path);
+      try {
+        return ZKOperations.ignoreError(zkClient.delete(path), KeeperException.NoNodeException.class, path);
+      } catch (Exception e) {
+        return Futures.immediateFailedFuture(e);
+      }
+    }
+  }
+
+  /**
+   * Class to be used as the service discovered cache entry.
+   */
+  private static final class ServiceDiscoveredCacheEntry implements Cancellable, ServiceDiscovered {
+    private final ServiceDiscovered serviceDiscovered;
+    private final Cancellable cancellable;
+
+    private ServiceDiscoveredCacheEntry(ServiceDiscovered serviceDiscovered, Cancellable cancellable) {
+      this.serviceDiscovered = serviceDiscovered;
+      this.cancellable = cancellable;
+    }
+
+    @Override
+    public void cancel() {
+      cancellable.cancel();
+    }
+
+    @Override
+    public String getName() {
+      return serviceDiscovered.getName();
+    }
+
+    @Override
+    public Cancellable watchChanges(ChangeListener listener, Executor executor) {
+      return serviceDiscovered.watchChanges(listener, executor);
+    }
+
+    @Override
+    public boolean contains(Discoverable discoverable) {
+      return serviceDiscovered.contains(discoverable);
+    }
+
+    @Override
+    public Iterator<Discoverable> iterator() {
+      return serviceDiscovered.iterator();
     }
   }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java b/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java
index 8fe5a37..f2d2a83 100644
--- a/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java
+++ b/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java
@@ -25,8 +25,11 @@ import org.apache.twill.common.Cancellable;
 import org.apache.twill.common.Threads;
 import org.junit.Assert;
 import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
@@ -41,225 +44,260 @@ import java.util.concurrent.TimeUnit;
  */
 public abstract class DiscoveryServiceTestBase {
 
+  private static final Logger LOG = LoggerFactory.getLogger(DiscoveryServiceTestBase.class);
+
   protected abstract Map.Entry<DiscoveryService, DiscoveryServiceClient> create();
 
   @Test
   public void simpleDiscoverable() throws Exception {
-    final String payload = "data";
+    final byte[] payload = "data".getBytes(StandardCharsets.UTF_8);
     Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
-    DiscoveryService discoveryService = entry.getKey();
-    DiscoveryServiceClient discoveryServiceClient = entry.getValue();
+    try {
+      DiscoveryService discoveryService = entry.getKey();
+      DiscoveryServiceClient discoveryServiceClient = entry.getValue();
 
-    // Register one service running on one host:port
-    Cancellable cancellable = register(discoveryService, "foo", "localhost", 8090, payload.getBytes());
+      // Register one service running on one host:port
+      Cancellable cancellable = register(discoveryService, "foo", "localhost", 8090, payload);
 
-    // Discover that registered host:port.
-    ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover("foo");
-    Assert.assertTrue(waitTillExpected(1, serviceDiscovered));
+      // Discover that registered host:port.
+      ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover("foo");
+      Assert.assertTrue(waitTillExpected(1, serviceDiscovered));
 
-    Discoverable discoverable = new Discoverable("foo", new InetSocketAddress("localhost", 8090), payload.getBytes());
+      Discoverable discoverable = new Discoverable("foo", new InetSocketAddress("localhost", 8090), payload);
 
-    // Check it exists.
-    Assert.assertTrue(serviceDiscovered.contains(discoverable));
+      // Check it exists.
+      Assert.assertTrue(serviceDiscovered.contains(discoverable));
 
-    // Remove the service
-    cancellable.cancel();
+      // Remove the service
+      cancellable.cancel();
 
-    // There should be no service.
-    Assert.assertTrue(waitTillExpected(0, serviceDiscovered));
+      // There should be no service.
+      Assert.assertTrue(waitTillExpected(0, serviceDiscovered));
 
-    Assert.assertFalse(serviceDiscovered.contains(discoverable));
+      Assert.assertFalse(serviceDiscovered.contains(discoverable));
+    } finally {
+      closeServices(entry);
+    }
   }
 
   @Test
   public void testChangeListener() throws InterruptedException {
     Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
-    DiscoveryService discoveryService = entry.getKey();
-    DiscoveryServiceClient discoveryServiceClient = entry.getValue();
-
-    // Start discovery
-    String serviceName = "listener_test";
-    ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover(serviceName);
+    try {
+      DiscoveryService discoveryService = entry.getKey();
+      DiscoveryServiceClient discoveryServiceClient = entry.getValue();
+
+      // Start discovery
+      final String serviceName = "listener_test";
+      ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover(serviceName);
+
+      // Watch for changes.
+      final BlockingQueue<List<Discoverable>> events = new ArrayBlockingQueue<List<Discoverable>>(10);
+      serviceDiscovered.watchChanges(new ServiceDiscovered.ChangeListener() {
+        @Override
+        public void onChange(ServiceDiscovered serviceDiscovered) {
+          List<Discoverable> discoverables = ImmutableList.copyOf(serviceDiscovered);
+          LOG.info("ServiceDiscovered callback: {}={}", serviceName, discoverables);
+          events.add(discoverables);
+        }
+      }, Threads.SAME_THREAD_EXECUTOR);
 
-    // Watch for changes.
-    final BlockingQueue<List<Discoverable>> events = new ArrayBlockingQueue<List<Discoverable>>(10);
-    serviceDiscovered.watchChanges(new ServiceDiscovered.ChangeListener() {
-      @Override
-      public void onChange(ServiceDiscovered serviceDiscovered) {
-        events.add(ImmutableList.copyOf(serviceDiscovered));
-      }
-    }, Threads.SAME_THREAD_EXECUTOR);
+      // An empty list will be received first, as no endpoint has been registered.
+      List<Discoverable> discoverables = events.poll(20, TimeUnit.SECONDS);
+      Assert.assertNotNull(discoverables);
+      Assert.assertTrue(discoverables.isEmpty());
 
-    // An empty list will be received first, as no endpoint has been registered.
-    List<Discoverable> discoverables = events.poll(20, TimeUnit.SECONDS);
-    Assert.assertNotNull(discoverables);
-    Assert.assertTrue(discoverables.isEmpty());
+      // Register a service
+      Cancellable cancellable = register(discoveryService, serviceName, "localhost", 10000);
 
-    // Register a service
-    Cancellable cancellable = register(discoveryService, serviceName, "localhost", 10000);
+      discoverables = events.poll(20, TimeUnit.SECONDS);
+      Assert.assertNotNull(discoverables);
 
-    discoverables = events.poll(20, TimeUnit.SECONDS);
-    Assert.assertNotNull(discoverables);
-    Assert.assertEquals(1, discoverables.size());
+      // It's possible that the list retrieved is empty in ZK case due to the creation of the parent node
+      // when creating the service discovery ZK node
+      if (discoverables.isEmpty()) {
+        // If that's the case, poll it again and it should be non-empty
+        discoverables = events.poll(20, TimeUnit.SECONDS);
+      }
+      Assert.assertEquals(1, discoverables.size());
 
-    // Register another service endpoint
-    Cancellable cancellable2 = register(discoveryService, serviceName, "localhost", 10001);
+      // Register another service endpoint
+      Cancellable cancellable2 = register(discoveryService, serviceName, "localhost", 10001);
 
-    discoverables = events.poll(20, TimeUnit.SECONDS);
-    Assert.assertNotNull(discoverables);
-    Assert.assertEquals(2, discoverables.size());
+      discoverables = events.poll(20, TimeUnit.SECONDS);
+      Assert.assertNotNull(discoverables);
+      Assert.assertEquals(2, discoverables.size());
 
-    // Cancel both of them
-    cancellable.cancel();
-    cancellable2.cancel();
+      // Cancel both of them
+      cancellable.cancel();
+      cancellable2.cancel();
 
-    // There could be more than one event triggered, but the last event should be an empty list.
-    discoverables = events.poll(20, TimeUnit.SECONDS);
-    Assert.assertNotNull(discoverables);
-    if (!discoverables.isEmpty()) {
+      // There could be more than one event triggered, but the last event should be an empty list.
       discoverables = events.poll(20, TimeUnit.SECONDS);
-    }
+      Assert.assertNotNull(discoverables);
+      if (!discoverables.isEmpty()) {
+        discoverables = events.poll(20, TimeUnit.SECONDS);
+      }
 
-    Assert.assertTrue(discoverables.isEmpty());
+      Assert.assertTrue(discoverables.isEmpty());
+    } finally {
+      closeServices(entry);
+    }
   }
 
   @Test
   public void testCancelChangeListener() throws InterruptedException {
     Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
-    DiscoveryService discoveryService = entry.getKey();
-    DiscoveryServiceClient discoveryServiceClient = entry.getValue();
-
-    String serviceName = "cancel_listener";
-    ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover(serviceName);
-
-    // An executor that delay execute a Runnable. It's for testing race because listener cancel and discovery changes.
-    Executor delayExecutor = new Executor() {
-      @Override
-      public void execute(final Runnable command) {
-        Thread t = new Thread() {
-          @Override
-          public void run() {
-            try {
-              TimeUnit.SECONDS.sleep(2);
-              command.run();
-            } catch (InterruptedException e) {
-              throw Throwables.propagate(e);
+    try {
+      DiscoveryService discoveryService = entry.getKey();
+      DiscoveryServiceClient discoveryServiceClient = entry.getValue();
+
+      String serviceName = "cancel_listener";
+      ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover(serviceName);
+
+      // An executor that delay execute a Runnable. It's for testing race because listener cancel and discovery changes.
+      Executor delayExecutor = new Executor() {
+        @Override
+        public void execute(final Runnable command) {
+          Thread t = new Thread() {
+            @Override
+            public void run() {
+              try {
+                TimeUnit.SECONDS.sleep(2);
+                command.run();
+              } catch (InterruptedException e) {
+                throw Throwables.propagate(e);
+              }
             }
-          }
-        };
-        t.start();
-      }
-    };
+          };
+          t.start();
+        }
+      };
 
-    final BlockingQueue<List<Discoverable>> events = new ArrayBlockingQueue<List<Discoverable>>(10);
-    Cancellable cancelWatch = serviceDiscovered.watchChanges(new ServiceDiscovered.ChangeListener() {
-      @Override
-      public void onChange(ServiceDiscovered serviceDiscovered) {
-        events.add(ImmutableList.copyOf(serviceDiscovered));
-      }
-    }, delayExecutor);
+      final BlockingQueue<List<Discoverable>> events = new ArrayBlockingQueue<List<Discoverable>>(10);
+      Cancellable cancelWatch = serviceDiscovered.watchChanges(new ServiceDiscovered.ChangeListener() {
+        @Override
+        public void onChange(ServiceDiscovered serviceDiscovered) {
+          events.add(ImmutableList.copyOf(serviceDiscovered));
+        }
+      }, delayExecutor);
 
-    // Wait for the init event call
-    Assert.assertNotNull(events.poll(3, TimeUnit.SECONDS));
+      // Wait for the init event call
+      Assert.assertNotNull(events.poll(3, TimeUnit.SECONDS));
 
-    // Register a new service endpoint, wait a short while and then cancel the listener
-    register(discoveryService, serviceName, "localhost", 1);
-    TimeUnit.SECONDS.sleep(1);
-    cancelWatch.cancel();
+      // Register a new service endpoint, wait a short while and then cancel the listener
+      register(discoveryService, serviceName, "localhost", 1);
+      TimeUnit.SECONDS.sleep(1);
+      cancelWatch.cancel();
 
-    // The change listener shouldn't get any event, since the invocation is delayed by the executor.
-    Assert.assertNull(events.poll(3, TimeUnit.SECONDS));
+      // The change listener shouldn't get any event, since the invocation is delayed by the executor.
+      Assert.assertNull(events.poll(3, TimeUnit.SECONDS));
+    } finally {
+      closeServices(entry);
+    }
   }
 
   @Test
   public void manySameDiscoverable() throws Exception {
     Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
-    DiscoveryService discoveryService = entry.getKey();
-    DiscoveryServiceClient discoveryServiceClient = entry.getValue();
+    try {
+      DiscoveryService discoveryService = entry.getKey();
+      DiscoveryServiceClient discoveryServiceClient = entry.getValue();
 
-    List<Cancellable> cancellables = Lists.newArrayList();
+      List<Cancellable> cancellables = Lists.newArrayList();
 
-    cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 1));
-    cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 2));
-    cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 3));
-    cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 4));
-    cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 5));
+      cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 1));
+      cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 2));
+      cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 3));
+      cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 4));
+      cancellables.add(register(discoveryService, "manyDiscoverable", "localhost", 5));
 
-    ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover("manyDiscoverable");
-    Assert.assertTrue(waitTillExpected(5, serviceDiscovered));
+      ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover("manyDiscoverable");
+      Assert.assertTrue(waitTillExpected(5, serviceDiscovered));
 
-    for (int i = 0; i < 5; i++) {
-      cancellables.get(i).cancel();
-      Assert.assertTrue(waitTillExpected(4 - i, serviceDiscovered));
+      for (int i = 0; i < 5; i++) {
+        cancellables.get(i).cancel();
+        Assert.assertTrue(waitTillExpected(4 - i, serviceDiscovered));
+      }
+    } finally {
+      closeServices(entry);
     }
   }
 
   @Test
   public void multiServiceDiscoverable() throws Exception {
     Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
-    DiscoveryService discoveryService = entry.getKey();
-    DiscoveryServiceClient discoveryServiceClient = entry.getValue();
+    try {
+      DiscoveryService discoveryService = entry.getKey();
+      DiscoveryServiceClient discoveryServiceClient = entry.getValue();
 
-    List<Cancellable> cancellables = Lists.newArrayList();
+      List<Cancellable> cancellables = Lists.newArrayList();
 
-    cancellables.add(register(discoveryService, "service1", "localhost", 1));
-    cancellables.add(register(discoveryService, "service1", "localhost", 2));
-    cancellables.add(register(discoveryService, "service1", "localhost", 3));
-    cancellables.add(register(discoveryService, "service1", "localhost", 4));
-    cancellables.add(register(discoveryService, "service1", "localhost", 5));
+      cancellables.add(register(discoveryService, "service1", "localhost", 1));
+      cancellables.add(register(discoveryService, "service1", "localhost", 2));
+      cancellables.add(register(discoveryService, "service1", "localhost", 3));
+      cancellables.add(register(discoveryService, "service1", "localhost", 4));
+      cancellables.add(register(discoveryService, "service1", "localhost", 5));
 
-    cancellables.add(register(discoveryService, "service2", "localhost", 1));
-    cancellables.add(register(discoveryService, "service2", "localhost", 2));
-    cancellables.add(register(discoveryService, "service2", "localhost", 3));
+      cancellables.add(register(discoveryService, "service2", "localhost", 1));
+      cancellables.add(register(discoveryService, "service2", "localhost", 2));
+      cancellables.add(register(discoveryService, "service2", "localhost", 3));
 
-    cancellables.add(register(discoveryService, "service3", "localhost", 1));
-    cancellables.add(register(discoveryService, "service3", "localhost", 2));
+      cancellables.add(register(discoveryService, "service3", "localhost", 1));
+      cancellables.add(register(discoveryService, "service3", "localhost", 2));
 
-    ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover("service1");
-    Assert.assertTrue(waitTillExpected(5, serviceDiscovered));
+      ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover("service1");
+      Assert.assertTrue(waitTillExpected(5, serviceDiscovered));
 
-    serviceDiscovered = discoveryServiceClient.discover("service2");
-    Assert.assertTrue(waitTillExpected(3, serviceDiscovered));
+      serviceDiscovered = discoveryServiceClient.discover("service2");
+      Assert.assertTrue(waitTillExpected(3, serviceDiscovered));
 
-    serviceDiscovered = discoveryServiceClient.discover("service3");
-    Assert.assertTrue(waitTillExpected(2, serviceDiscovered));
+      serviceDiscovered = discoveryServiceClient.discover("service3");
+      Assert.assertTrue(waitTillExpected(2, serviceDiscovered));
 
-    cancellables.add(register(discoveryService, "service3", "localhost", 3));
-    Assert.assertTrue(waitTillExpected(3, serviceDiscovered)); // Shows live iterator.
+      cancellables.add(register(discoveryService, "service3", "localhost", 3));
+      Assert.assertTrue(waitTillExpected(3, serviceDiscovered)); // Shows live iterator.
 
-    for (Cancellable cancellable : cancellables) {
-      cancellable.cancel();
-    }
+      for (Cancellable cancellable : cancellables) {
+        cancellable.cancel();
+      }
 
-    Assert.assertTrue(waitTillExpected(0, discoveryServiceClient.discover("service1")));
-    Assert.assertTrue(waitTillExpected(0, discoveryServiceClient.discover("service2")));
-    Assert.assertTrue(waitTillExpected(0, discoveryServiceClient.discover("service3")));
+      Assert.assertTrue(waitTillExpected(0, discoveryServiceClient.discover("service1")));
+      Assert.assertTrue(waitTillExpected(0, discoveryServiceClient.discover("service2")));
+      Assert.assertTrue(waitTillExpected(0, discoveryServiceClient.discover("service3")));
+    } finally {
+      closeServices(entry);
+    }
   }
 
   @Test
   public void testIterator() throws InterruptedException {
     // This test is to verify TWILL-75
     Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
-    final DiscoveryService service = entry.getKey();
-    DiscoveryServiceClient client = entry.getValue();
+    try {
+      final DiscoveryService service = entry.getKey();
+      DiscoveryServiceClient client = entry.getValue();
 
-    final String serviceName = "iterator";
-    ServiceDiscovered discovered = client.discover(serviceName);
+      final String serviceName = "iterator";
+      ServiceDiscovered discovered = client.discover(serviceName);
 
-    // Create a thread for performing registration.
-    Thread t = new Thread() {
-      @Override
-      public void run() {
-        service.register(new Discoverable(serviceName, new InetSocketAddress(12345), new byte[]{}));
-      }
-    };
+      // Create a thread for performing registration.
+      Thread t = new Thread() {
+        @Override
+        public void run() {
+          service.register(new Discoverable(serviceName, new InetSocketAddress(12345), new byte[]{}));
+        }
+      };
 
-    Iterator<Discoverable> iterator = discovered.iterator();
-    t.start();
-    t.join();
+      Iterator<Discoverable> iterator = discovered.iterator();
+      t.start();
+      t.join();
 
-    // This would throw exception if there is race condition.
-    Assert.assertFalse(iterator.hasNext());
+      // This would throw exception if there is race condition.
+      Assert.assertFalse(iterator.hasNext());
+    } finally {
+      closeServices(entry);
+    }
   }
 
   protected Cancellable register(DiscoveryService service, final String name, final String host, final int port) {
@@ -288,4 +326,21 @@ public abstract class DiscoveryServiceTestBase {
       throw Throwables.propagate(e);
     }
   }
+
+  protected final void closeServices(Map.Entry<DiscoveryService, DiscoveryServiceClient> entry) {
+    if (entry.getKey() instanceof AutoCloseable) {
+      try {
+        ((AutoCloseable) entry.getKey()).close();
+      } catch (Exception e) {
+        LOG.warn("Failed to close DiscoveryService {}", entry.getKey(), e);
+      }
+    }
+    if (entry.getValue() instanceof AutoCloseable) {
+      try {
+        ((AutoCloseable) entry.getValue()).close();
+      } catch (Exception e) {
+        LOG.warn("Failed to close DiscoveryServiceClient {}", entry.getValue(), e);
+      }
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-discovery-core/src/test/java/org/apache/twill/discovery/ZKDiscoveryServiceTest.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/test/java/org/apache/twill/discovery/ZKDiscoveryServiceTest.java b/twill-discovery-core/src/test/java/org/apache/twill/discovery/ZKDiscoveryServiceTest.java
index 7d6e369..dcf3935 100644
--- a/twill-discovery-core/src/test/java/org/apache/twill/discovery/ZKDiscoveryServiceTest.java
+++ b/twill-discovery-core/src/test/java/org/apache/twill/discovery/ZKDiscoveryServiceTest.java
@@ -66,80 +66,86 @@ public class ZKDiscoveryServiceTest extends DiscoveryServiceTestBase {
   @Test (timeout = 30000)
   public void testDoubleRegister() throws Exception {
     Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
-    DiscoveryService discoveryService = entry.getKey();
-    DiscoveryServiceClient discoveryServiceClient = entry.getValue();
-
-    // Register on the same host port, it shouldn't fail.
-    Cancellable cancellable = register(discoveryService, "test_double_reg", "localhost", 54321);
-    Cancellable cancellable2 = register(discoveryService, "test_double_reg", "localhost", 54321);
-
-    ServiceDiscovered discoverables = discoveryServiceClient.discover("test_double_reg");
-
-    Assert.assertTrue(waitTillExpected(1, discoverables));
+    try {
+      DiscoveryService discoveryService = entry.getKey();
+      DiscoveryServiceClient discoveryServiceClient = entry.getValue();
 
-    cancellable.cancel();
-    cancellable2.cancel();
+      // Register on the same host port, it shouldn't fail.
+      Cancellable cancellable = register(discoveryService, "test_double_reg", "localhost", 54321);
+      Cancellable cancellable2 = register(discoveryService, "test_double_reg", "localhost", 54321);
 
-    // Register again with two different clients, but killing session of the first one.
-    final ZKClientService zkClient2 = ZKClientServices.delegate(
-      ZKClients.retryOnFailure(
-        ZKClients.reWatchOnExpire(
-          ZKClientService.Builder.of(zkServer.getConnectionStr()).build()),
-        RetryStrategies.fixDelay(1, TimeUnit.SECONDS)));
-    zkClient2.startAndWait();
+      ServiceDiscovered discoverables = discoveryServiceClient.discover("test_double_reg");
 
-    try {
-      DiscoveryService discoveryService2 = new ZKDiscoveryService(zkClient2);
-      cancellable2 = register(discoveryService2, "test_multi_client", "localhost", 54321);
-
-      // Schedule a thread to shutdown zkClient2.
-      new Thread() {
-        @Override
-        public void run() {
-          try {
-            TimeUnit.SECONDS.sleep(2);
-            zkClient2.stopAndWait();
-          } catch (InterruptedException e) {
-            LOG.error(e.getMessage(), e);
-          }
-        }
-      }.start();
+      Assert.assertTrue(waitTillExpected(1, discoverables));
 
-      // This call would block until zkClient2 is shutdown.
-      cancellable = register(discoveryService, "test_multi_client", "localhost", 54321);
       cancellable.cancel();
-
+      cancellable2.cancel();
+
+      // Register again with two different clients, but killing session of the first one.
+      final ZKClientService zkClient2 = ZKClientServices.delegate(
+        ZKClients.retryOnFailure(
+          ZKClients.reWatchOnExpire(
+            ZKClientService.Builder.of(zkServer.getConnectionStr()).build()),
+          RetryStrategies.fixDelay(1, TimeUnit.SECONDS)));
+      zkClient2.startAndWait();
+
+      try (ZKDiscoveryService discoveryService2 = new ZKDiscoveryService(zkClient2)) {
+        cancellable2 = register(discoveryService2, "test_multi_client", "localhost", 54321);
+
+        // Schedule a thread to shutdown zkClient2.
+        new Thread() {
+          @Override
+          public void run() {
+            try {
+              TimeUnit.SECONDS.sleep(2);
+              zkClient2.stopAndWait();
+            } catch (InterruptedException e) {
+              LOG.error(e.getMessage(), e);
+            }
+          }
+        }.start();
+
+        // This call would block until zkClient2 is shutdown.
+        cancellable = register(discoveryService, "test_multi_client", "localhost", 54321);
+        cancellable.cancel();
+      } finally {
+        zkClient2.stopAndWait();
+      }
     } finally {
-      zkClient2.stopAndWait();
+      closeServices(entry);
     }
   }
 
   @Test
   public void testSessionExpires() throws Exception {
     Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
-    DiscoveryService discoveryService = entry.getKey();
-    DiscoveryServiceClient discoveryServiceClient = entry.getValue();
+    try {
+      DiscoveryService discoveryService = entry.getKey();
+      DiscoveryServiceClient discoveryServiceClient = entry.getValue();
 
-    Cancellable cancellable = register(discoveryService, "test_expires", "localhost", 54321);
+      Cancellable cancellable = register(discoveryService, "test_expires", "localhost", 54321);
 
-    ServiceDiscovered discoverables = discoveryServiceClient.discover("test_expires");
+      ServiceDiscovered discoverables = discoveryServiceClient.discover("test_expires");
 
-    // Discover that registered host:port.
-    Assert.assertTrue(waitTillExpected(1, discoverables));
+      // Discover that registered host:port.
+      Assert.assertTrue(waitTillExpected(1, discoverables));
 
-    KillZKSession.kill(zkClient.getZooKeeperSupplier().get(), zkServer.getConnectionStr(), 10000);
+      KillZKSession.kill(zkClient.getZooKeeperSupplier().get(), zkServer.getConnectionStr(), 10000);
 
-    // Register one more endpoint to make sure state has been reflected after reconnection
-    Cancellable cancellable2 = register(discoveryService, "test_expires", "localhost", 54322);
+      // Register one more endpoint to make sure state has been reflected after reconnection
+      Cancellable cancellable2 = register(discoveryService, "test_expires", "localhost", 54322);
 
-    // Reconnection would trigger re-registration.
-    Assert.assertTrue(waitTillExpected(2, discoverables));
+      // Reconnection would trigger re-registration.
+      Assert.assertTrue(waitTillExpected(2, discoverables));
 
-    cancellable.cancel();
-    cancellable2.cancel();
+      cancellable.cancel();
+      cancellable2.cancel();
 
-    // Verify that both are now gone.
-    Assert.assertTrue(waitTillExpected(0, discoverables));
+      // Verify that both are now gone.
+      Assert.assertTrue(waitTillExpected(0, discoverables));
+    } finally {
+      closeServices(entry);
+    }
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-yarn/src/main/java/org/apache/twill/internal/container/TwillContainerMain.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/internal/container/TwillContainerMain.java b/twill-yarn/src/main/java/org/apache/twill/internal/container/TwillContainerMain.java
index 3ea786a..efccd89 100644
--- a/twill-yarn/src/main/java/org/apache/twill/internal/container/TwillContainerMain.java
+++ b/twill-yarn/src/main/java/org/apache/twill/internal/container/TwillContainerMain.java
@@ -20,6 +20,7 @@ package org.apache.twill.internal.container;
 import com.google.common.base.Charsets;
 import com.google.common.base.Strings;
 import com.google.common.io.Files;
+import com.google.common.util.concurrent.AbstractIdleService;
 import com.google.common.util.concurrent.AbstractService;
 import com.google.common.util.concurrent.Service;
 import org.apache.hadoop.conf.Configuration;
@@ -102,9 +103,11 @@ public final class TwillContainerMain extends ServiceMain {
                                                 createAppLocation(conf));
     new TwillContainerMain().doMain(
       service,
-      new LogFlushService(),
       zkClientService,
-      new TwillZKPathService(containerZKClient, runId));
+      new LogFlushService(),
+      new TwillZKPathService(containerZKClient, runId),
+      new CloseableServiceWrapper(discoveryService)
+    );
   }
 
   @Override
@@ -196,4 +199,27 @@ public final class TwillContainerMain extends ServiceMain {
       notifyStopped();
     }
   }
+
+  /**
+   * A wrapper to adapt a {@link AutoCloseable} to a {@link ServiceMain}. The service has no-op during start up
+   * and will call the {@link AutoCloseable#close()} on shutdown.
+   */
+  private static final class CloseableServiceWrapper extends AbstractIdleService {
+
+    private final AutoCloseable closeable;
+
+    private CloseableServiceWrapper(AutoCloseable closeable) {
+      this.closeable = closeable;
+    }
+
+    @Override
+    protected void startUp() throws Exception {
+      // no-op
+    }
+
+    @Override
+    protected void shutDown() throws Exception {
+      closeable.close();
+    }
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java b/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java
index 2cac2f3..4f95391 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java
@@ -24,8 +24,11 @@ import org.apache.hadoop.yarn.api.records.NodeReport;
 import org.apache.twill.api.TwillController;
 import org.apache.twill.api.TwillRunner;
 import org.junit.After;
+import org.junit.Before;
 import org.junit.ClassRule;
+import org.junit.Rule;
 import org.junit.rules.TemporaryFolder;
+import org.junit.rules.TestName;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -66,6 +69,18 @@ public abstract class BaseYarnTest {
     }
   };
 
+  @Rule
+  public final TestName testName = new TestName();
+
+  @Before
+  public void beforeTest() {
+    LOG.info("Before test {}", testName.getMethodName());
+  }
+
+  @After
+  public void afterTest() {
+    LOG.info("After test {}", testName.getMethodName());
+  }
 
   @After
   public final void cleanupTest() {

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java b/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java
index 211b7ba..278a436 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java
@@ -197,7 +197,7 @@ public final class EchoServerTestRun extends BaseYarnTest {
       }
 
       // There should be two instances up and running.
-      echoServices = controller.discoverService("echo");
+      echoServices = controllers.get(1).discoverService("echo");
       Assert.assertTrue(waitForSize(echoServices, 2, 120));
 
       // Stop one instance of the app
@@ -207,7 +207,7 @@ public final class EchoServerTestRun extends BaseYarnTest {
       Assert.assertNotNull(zkClient.exists("/EchoServer").get());
 
       // We should still be able to do discovery, which depends on the ZK node.
-      echoServices = controller.discoverService("echo");
+      echoServices = controllers.get(1).discoverService("echo");
       Assert.assertTrue(waitForSize(echoServices, 1, 120));
 
       // Stop second instance of the app

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-yarn/src/test/java/org/apache/twill/yarn/InitializeFailTestRun.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/InitializeFailTestRun.java b/twill-yarn/src/test/java/org/apache/twill/yarn/InitializeFailTestRun.java
index 64f5a69..c446879 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/InitializeFailTestRun.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/InitializeFailTestRun.java
@@ -23,7 +23,6 @@ import org.apache.twill.api.TwillController;
 import org.apache.twill.api.TwillRunner;
 import org.apache.twill.api.logging.LogEntry;
 import org.apache.twill.api.logging.LogHandler;
-import org.apache.twill.api.logging.LogThrowable;
 import org.apache.twill.api.logging.PrinterLogHandler;
 import org.junit.Assert;
 import org.junit.Test;
@@ -48,15 +47,8 @@ public class InitializeFailTestRun extends BaseYarnTest {
     LogHandler logVerifyHandler = new LogHandler() {
       @Override
       public void onLog(LogEntry logEntry) {
-        LogThrowable logThrowable = logEntry.getThrowable();
-        if (logThrowable != null) {
-          while (logThrowable.getCause() != null) {
-            logThrowable = logThrowable.getCause();
-          }
-          if (IllegalStateException.class.getName().equals(logThrowable.getClassName())
-            && logThrowable.getMessage().contains("Fail to init")) {
-            logLatch.countDown();
-          }
+        if (logEntry.getMessage().endsWith("exited abnormally with state COMPLETE, exit code 10.")) {
+          logLatch.countDown();
         }
       }
     };

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java b/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java
index f1e1ac9..6dd281d 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java
@@ -44,5 +44,4 @@ import org.junit.runners.Suite;
   RestartRunnableTestRun.class
 })
 public final class YarnTestSuite extends BaseYarnTest {
-
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/ced2044f/twill-zookeeper/src/main/java/org/apache/twill/internal/zookeeper/LeaderElection.java
----------------------------------------------------------------------
diff --git a/twill-zookeeper/src/main/java/org/apache/twill/internal/zookeeper/LeaderElection.java b/twill-zookeeper/src/main/java/org/apache/twill/internal/zookeeper/LeaderElection.java
index 8433b18..d8bb49d 100644
--- a/twill-zookeeper/src/main/java/org/apache/twill/internal/zookeeper/LeaderElection.java
+++ b/twill-zookeeper/src/main/java/org/apache/twill/internal/zookeeper/LeaderElection.java
@@ -25,6 +25,7 @@ import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
 import com.google.common.util.concurrent.SettableFuture;
 import org.apache.twill.api.ElectionHandler;
+import org.apache.twill.common.Cancellable;
 import org.apache.twill.common.Threads;
 import org.apache.twill.zookeeper.NodeChildren;
 import org.apache.twill.zookeeper.NodeData;
@@ -70,6 +71,7 @@ public final class LeaderElection extends AbstractService {
   private ExecutorService executor;
   private String zkNodePath;
   private State state;
+  private Cancellable watcherCancellable;
 
   public LeaderElection(ZKClient zkClient, String prefix, ElectionHandler handler) {
     this.guid = UUID.randomUUID().toString();
@@ -89,7 +91,7 @@ public final class LeaderElection extends AbstractService {
       @Override
       public void run() {
         register();
-        LeaderElection.this.zkClient.addConnectionWatcher(wrapWatcher(new ConnectionWatcher()));
+        watcherCancellable = zkClient.addConnectionWatcher(wrapWatcher(new ConnectionWatcher()));
       }
     });
     notifyStarted();
@@ -121,6 +123,9 @@ public final class LeaderElection extends AbstractService {
     executor.execute(new Runnable() {
       @Override
       public void run() {
+        if (watcherCancellable != null) {
+          watcherCancellable.cancel();
+        }
         if (state != State.CANCELLED) {
           // becomeFollower has to be called before deleting node to make sure no two active leader.
           if (state == State.LEADER) {


[16/16] twill git commit: Merge branch 'master' into site

Posted by ch...@apache.org.
Merge branch 'master' into site


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/f285ac44
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/f285ac44
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/f285ac44

Branch: refs/heads/site
Commit: f285ac4439bdb5d50add9f69b5cc22bc974d5dff
Parents: d4a3b6c 983a14a
Author: Terence Yim <ch...@apache.org>
Authored: Tue Oct 4 09:25:18 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Tue Oct 4 09:25:18 2016 -0700

----------------------------------------------------------------------
 .travis.yml                                     |   1 +
 pom.xml                                         |   2 +-
 twill-api/pom.xml                               |   2 +-
 .../org/apache/twill/api/ServiceAnnouncer.java  |  10 +-
 .../internal/DefaultTwillRunResources.java      |  12 +
 twill-common/pom.xml                            |   2 +-
 .../apache/twill/filesystem/LocalLocation.java  |  98 ++++-
 .../org/apache/twill/filesystem/Location.java   |  41 +-
 twill-core/pom.xml                              |   2 +-
 .../twill/internal/AbstractTwillController.java |  17 +-
 .../twill/internal/AbstractTwillService.java    |   8 +-
 .../twill/internal/BasicTwillContext.java       |  17 +-
 .../java/org/apache/twill/internal/Configs.java |   5 +
 .../twill/internal/DefaultResourceReport.java   |  10 +
 .../twill/internal/ProcessController.java       |   2 +-
 .../twill/internal/TwillContainerLauncher.java  |  65 +++-
 .../internal/kafka/EmbeddedKafkaServer.java     |  42 +-
 twill-discovery-api/pom.xml                     |   2 +-
 .../apache/twill/discovery/Discoverable.java    |  57 ++-
 twill-discovery-core/pom.xml                    |   2 +-
 .../discovery/DefaultServiceDiscovered.java     |  21 +-
 .../twill/discovery/DiscoverableAdapter.java    |  20 +-
 .../twill/discovery/DiscoverableWrapper.java    |  69 ----
 .../discovery/InMemoryDiscoveryService.java     |   7 +-
 .../twill/discovery/ZKDiscoveryService.java     | 174 +++++++--
 .../discovery/DiscoveryServiceTestBase.java     | 383 ++++++++++---------
 .../twill/discovery/ZKDiscoveryServiceTest.java | 114 +++---
 twill-examples/echo/pom.xml                     |   2 +-
 twill-examples/pom.xml                          |   2 +-
 twill-examples/yarn/pom.xml                     |   2 +-
 twill-ext/pom.xml                               |   2 +-
 twill-java8-test/pom.xml                        |   2 +-
 twill-yarn/pom.xml                              |   2 +-
 .../internal/yarn/Hadoop20YarnAppClient.java    |  44 ++-
 .../internal/yarn/Hadoop21YarnAppClient.java    |  42 +-
 .../twill/filesystem/FileContextLocation.java   |  55 ++-
 .../apache/twill/filesystem/HDFSLocation.java   |  71 +++-
 .../appmaster/ApplicationMasterMain.java        |   6 -
 .../appmaster/ApplicationMasterService.java     |  77 ++--
 .../appmaster/RunnableProcessLauncher.java      |   5 +
 .../internal/appmaster/RunningContainers.java   | 167 +++++---
 .../internal/container/TwillContainerMain.java  |  30 +-
 .../twill/internal/yarn/YarnAppClient.java      |   3 +-
 .../apache/twill/internal/yarn/YarnUtils.java   |   2 +-
 .../apache/twill/yarn/YarnTwillController.java  |   2 +-
 .../twill/yarn/YarnTwillRunnerService.java      |   6 +-
 .../twill/filesystem/LocationTestBase.java      |  73 ++++
 .../org/apache/twill/yarn/BaseYarnTest.java     |  20 +
 .../apache/twill/yarn/EchoServerTestRun.java    |  12 +-
 .../twill/yarn/InitializeFailTestRun.java       |  12 +-
 .../org/apache/twill/yarn/LogLevelTestRun.java  |   2 +-
 .../twill/yarn/PlacementPolicyTestRun.java      |  14 +-
 .../twill/yarn/ResourceReportTestRun.java       |   2 +-
 .../twill/yarn/RestartRunnableTestRun.java      | 348 +++++++++++++++++
 .../java/org/apache/twill/yarn/TwillTester.java |  23 +-
 .../org/apache/twill/yarn/YarnTestSuite.java    |   4 +-
 twill-zookeeper/pom.xml                         |   2 +-
 .../internal/zookeeper/LeaderElection.java      |   7 +-
 58 files changed, 1637 insertions(+), 589 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/f285ac44/pom.xml
----------------------------------------------------------------------


[08/16] twill git commit: Empty commit to close #7

Posted by ch...@apache.org.
Empty commit to close #7

This closes #7 on Github


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/2d617d27
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/2d617d27
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/2d617d27

Branch: refs/heads/site
Commit: 2d617d27ad3819ecd8fef94d18ff97a0d57158a0
Parents: 11e29a8
Author: Terence Yim <ch...@apache.org>
Authored: Mon Aug 29 22:40:37 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Mon Aug 29 22:40:37 2016 -0700

----------------------------------------------------------------------

----------------------------------------------------------------------



[04/16] twill git commit: TWILL-190 Wait for Twill runnables to stop when restarting them, also kill non-responding Twill runnables after a timeout

Posted by ch...@apache.org.
TWILL-190 Wait for Twill runnables to stop when restarting them, also kill non-responding Twill runnables after a timeout

This closes #4 on Github.

Signed-off-by: Terence Yim <ch...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/069e0289
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/069e0289
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/069e0289

Branch: refs/heads/site
Commit: 069e0289d45d9ab46561ff80142dc65426050c2d
Parents: 9d346ae
Author: poorna <po...@cask.co>
Authored: Wed Aug 17 01:12:36 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Fri Aug 26 10:11:42 2016 -0700

----------------------------------------------------------------------
 .../internal/DefaultTwillRunResources.java      |  12 +
 .../twill/internal/DefaultResourceReport.java   |  10 +
 .../twill/internal/TwillContainerLauncher.java  |  65 +++-
 .../appmaster/ApplicationMasterService.java     |  77 ++--
 .../internal/appmaster/RunningContainers.java   | 167 +++++----
 .../org/apache/twill/yarn/BaseYarnTest.java     |   5 +
 .../apache/twill/yarn/EchoServerTestRun.java    |   8 +-
 .../twill/yarn/PlacementPolicyTestRun.java      |  14 +-
 .../twill/yarn/ResourceReportTestRun.java       |   2 +-
 .../twill/yarn/RestartRunnableTestRun.java      | 348 +++++++++++++++++++
 .../java/org/apache/twill/yarn/TwillTester.java |  21 ++
 .../org/apache/twill/yarn/YarnTestSuite.java    |   3 +-
 12 files changed, 629 insertions(+), 103 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-api/src/main/java/org/apache/twill/internal/DefaultTwillRunResources.java
----------------------------------------------------------------------
diff --git a/twill-api/src/main/java/org/apache/twill/internal/DefaultTwillRunResources.java b/twill-api/src/main/java/org/apache/twill/internal/DefaultTwillRunResources.java
index 6671e63..93ef90e 100644
--- a/twill-api/src/main/java/org/apache/twill/internal/DefaultTwillRunResources.java
+++ b/twill-api/src/main/java/org/apache/twill/internal/DefaultTwillRunResources.java
@@ -120,4 +120,16 @@ public class DefaultTwillRunResources implements TwillRunResources {
     return hash;
   }
 
+  @Override
+  public String toString() {
+    return "DefaultTwillRunResources{" +
+      "containerId='" + containerId + '\'' +
+      ", instanceId=" + instanceId +
+      ", virtualCores=" + virtualCores +
+      ", memoryMB=" + memoryMB +
+      ", host='" + host + '\'' +
+      ", debugPort=" + debugPort +
+      ", logLevel=" + logLevel +
+      '}';
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-core/src/main/java/org/apache/twill/internal/DefaultResourceReport.java
----------------------------------------------------------------------
diff --git a/twill-core/src/main/java/org/apache/twill/internal/DefaultResourceReport.java b/twill-core/src/main/java/org/apache/twill/internal/DefaultResourceReport.java
index 08c6900..08c93f8 100644
--- a/twill-core/src/main/java/org/apache/twill/internal/DefaultResourceReport.java
+++ b/twill-core/src/main/java/org/apache/twill/internal/DefaultResourceReport.java
@@ -148,4 +148,14 @@ public final class DefaultResourceReport implements ResourceReport {
   public List<String> getServices() {
     return services.get();
   }
+
+  @Override
+  public String toString() {
+    return "DefaultResourceReport{" +
+      "usedResources=" + usedResources +
+      ", appMasterResources=" + appMasterResources +
+      ", applicationId='" + applicationId + '\'' +
+      ", services=" + services +
+      '}';
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-core/src/main/java/org/apache/twill/internal/TwillContainerLauncher.java
----------------------------------------------------------------------
diff --git a/twill-core/src/main/java/org/apache/twill/internal/TwillContainerLauncher.java b/twill-core/src/main/java/org/apache/twill/internal/TwillContainerLauncher.java
index d01db4b..3eefb8c 100644
--- a/twill-core/src/main/java/org/apache/twill/internal/TwillContainerLauncher.java
+++ b/twill-core/src/main/java/org/apache/twill/internal/TwillContainerLauncher.java
@@ -18,9 +18,11 @@
 package org.apache.twill.internal;
 
 import com.google.common.base.Charsets;
+import com.google.common.base.Stopwatch;
 import com.google.common.collect.ImmutableList;
 import com.google.common.util.concurrent.Futures;
 import com.google.common.util.concurrent.ListenableFuture;
+import com.google.common.util.concurrent.Uninterruptibles;
 import com.google.gson.Gson;
 import com.google.gson.JsonElement;
 import org.apache.twill.api.RunId;
@@ -39,6 +41,8 @@ import org.slf4j.LoggerFactory;
 
 import java.io.IOException;
 import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 /**
  * This class helps launching a container.
@@ -148,7 +152,8 @@ public final class TwillContainerLauncher {
       .addCommand(firstCommand, command.toArray(new String[command.size()]))
       .launch();
 
-    TwillContainerControllerImpl controller = new TwillContainerControllerImpl(zkClient, runId, processController);
+    TwillContainerControllerImpl controller =
+      new TwillContainerControllerImpl(zkClient, runId, runtimeSpec.getName(), instanceId, processController);
     controller.start();
     return controller;
   }
@@ -156,13 +161,20 @@ public final class TwillContainerLauncher {
   private static final class TwillContainerControllerImpl extends AbstractZKServiceController
                                                           implements TwillContainerController {
 
+    private final String runnable;
+    private final int instanceId;
     private final ProcessController<Void> processController;
+    // This latch can be used to wait for container shutdown
+    private final CountDownLatch shutdownLatch;
     private volatile ContainerLiveNodeData liveData;
 
-    protected TwillContainerControllerImpl(ZKClient zkClient, RunId runId,
+    protected TwillContainerControllerImpl(ZKClient zkClient, RunId runId, String runnable, int instanceId,
                                            ProcessController<Void> processController) {
       super(runId, zkClient);
+      this.runnable = runnable;
+      this.instanceId = instanceId;
       this.processController = processController;
+      this.shutdownLatch = new CountDownLatch(1);
     }
 
     @Override
@@ -172,7 +184,21 @@ public final class TwillContainerLauncher {
 
     @Override
     protected void doShutDown() {
-      // No-op
+      // Wait for sometime for the container to stop
+      // TODO: Use configurable value for stop time (TWILL-192)
+      int maxWaitSecs = Constants.APPLICATION_MAX_STOP_SECONDS - 30;
+      maxWaitSecs = maxWaitSecs < 15 ? 15 : maxWaitSecs;
+      try {
+        if (Uninterruptibles.awaitUninterruptibly(shutdownLatch, maxWaitSecs, TimeUnit.SECONDS)) {
+          return;
+        }
+      } catch (Exception e) {
+        LOG.error("Got exception while trying to stop runnable {}, instance {}", runnable, instanceId, e);
+      }
+      // Container has not shutdown even after maxWaitSecs after sending stop message,
+      // we'll need to kill the container
+      LOG.warn("Killing runnable {}, instance {} after waiting {} secs", runnable, instanceId, maxWaitSecs);
+      killAndWait(maxWaitSecs);
     }
 
     @Override
@@ -207,8 +233,12 @@ public final class TwillContainerLauncher {
     }
 
     @Override
-    public synchronized void completed(int exitStatus) {
-      forceShutDown();
+    public void completed(int exitStatus) {
+      // count down the shutdownLatch to inform any waiting threads that this container is complete
+      shutdownLatch.countDown();
+      synchronized (this) {
+        forceShutDown();
+      }
     }
 
     @Override
@@ -220,5 +250,30 @@ public final class TwillContainerLauncher {
     public void kill() {
       processController.cancel();
     }
+
+    private void killAndWait(int maxWaitSecs) {
+      Stopwatch watch = new Stopwatch();
+      watch.start();
+      while (watch.elapsedTime(TimeUnit.SECONDS) < maxWaitSecs) {
+        // Kill the application
+        try {
+          kill();
+        } catch (Exception e) {
+          LOG.error("Exception while killing runnable {}, instance {}", runnable, instanceId, e);
+        }
+
+        // Wait on the shutdownLatch,
+        // if the runnable has stopped then the latch will be count down by completed() method
+        if (Uninterruptibles.awaitUninterruptibly(shutdownLatch, 10, TimeUnit.SECONDS)) {
+          // Runnable has stopped now
+          return;
+        }
+      }
+
+      // Timeout reached, runnable has not stopped
+      LOG.error("Failed to kill runnable {}, instance {} after {} seconds", runnable, instanceId,
+                watch.elapsedTime(TimeUnit.SECONDS));
+      // TODO: should we throw exception here?
+    }
   }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterService.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterService.java b/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterService.java
index c376de4..f46adb2 100644
--- a/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterService.java
+++ b/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterService.java
@@ -25,6 +25,7 @@ import com.google.common.base.Supplier;
 import com.google.common.base.Throwables;
 import com.google.common.collect.DiscreteDomains;
 import com.google.common.collect.HashMultiset;
+import com.google.common.collect.ImmutableSet;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
@@ -87,6 +88,7 @@ import java.io.FileReader;
 import java.io.IOException;
 import java.io.Reader;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.LinkedHashMap;
@@ -259,7 +261,7 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
 
     // For checking if all containers are stopped.
     final Set<String> ids = Sets.newHashSet(runningContainers.getContainerIds());
-    YarnAMClient.AllocateHandler handler = new YarnAMClient.AllocateHandler() {
+    final YarnAMClient.AllocateHandler handler = new YarnAMClient.AllocateHandler() {
       @Override
       public void acquired(List<? extends ProcessLauncher<YarnContainerInfo>> launchers) {
         // no-op
@@ -268,20 +270,35 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
       @Override
       public void completed(List<YarnContainerStatus> completed) {
         for (YarnContainerStatus status : completed) {
+          handleCompleted(completed);
           ids.remove(status.getContainerId());
         }
       }
     };
 
-    runningContainers.stopAll();
-
-    // Poll for 5 seconds to wait for containers to stop.
-    int count = 0;
-    while (!ids.isEmpty() && count++ < 5) {
-      amClient.allocate(0.0f, handler);
-      TimeUnit.SECONDS.sleep(1);
-    }
+    // Handle heartbeats during shutdown because runningContainers.stopAll() waits until
+    // handleCompleted() is called for every stopped runnable
+    ExecutorService stopPoller = Executors.newSingleThreadExecutor(Threads.createDaemonThreadFactory("stopPoller"));
+    stopPoller.execute(new Runnable() {
+      @Override
+      public void run() {
+        while (!ids.isEmpty()) {
+          try {
+            amClient.allocate(0.0f, handler);
+            if (!ids.isEmpty()) {
+              TimeUnit.SECONDS.sleep(1);
+            }
+          } catch (Exception e) {
+            LOG.error("Got exception while getting heartbeat", e);
+          }
+        }
+      }
+    });
 
+    // runningContainers.stopAll() will wait for all the running runnables to stop or kill them after a timeout
+    runningContainers.stopAll();
+    // Since all the runnables are now stopped, it is okay to stop the poller.
+    stopPoller.shutdownNow();
     cleanupDir();
   }
 
@@ -375,6 +392,7 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
       }
 
       // If nothing is in provisioning, and no pending request, move to next one
+      int count = runnableContainerRequests.size();
       while (provisioning.isEmpty() && currentRequest == null && !runnableContainerRequests.isEmpty()) {
         RunnableContainerRequest runnableContainerRequest = runnableContainerRequests.peek();
         if (!runnableContainerRequest.isReadyToBeProvisioned()) {
@@ -382,6 +400,11 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
           runnableContainerRequest = runnableContainerRequests.poll();
           runnableContainerRequests.add(runnableContainerRequest);
 
+          // We checked all the requests that were pending when we started this loop
+          // Any remaining requests are not ready to be provisioned
+          if (--count <= 0) {
+            break;
+          }
           continue;
         }
         currentRequest = runnableContainerRequest.takeRequest();
@@ -498,7 +521,7 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
         completedContainerCount.get(runnableName) : 0;
       if (expectedCount.getCount() > runningCount + completedCount) {
         timeoutEvents.add(new EventHandler.TimeoutEvent(runnableName, expectedCount.getCount(),
-                                                                   runningCount, expectedCount.getTimestamp()));
+                                                        runningCount, expectedCount.getTimestamp()));
       }
     }
 
@@ -610,9 +633,9 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
         // TODO: Allow user to set priority?
         LOG.info("Request {} container with capability {} for runnable {}", newContainers, capability, name);
         String requestId = amClient.addContainerRequest(capability, newContainers)
-                .addHosts(hosts)
-                .addRacks(racks)
-                .setPriority(0).apply();
+          .addHosts(hosts)
+          .addRacks(racks)
+          .setPriority(0).apply();
         provisioning.add(new ProvisionRequest(runtimeSpec, requestId, newContainers, allocationType));
       }
     }
@@ -693,7 +716,8 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
     }
 
     try (Reader reader = Files.newReader(envFile, Charsets.UTF_8)) {
-      return new Gson().fromJson(reader, new TypeToken<Map<String, Map<String, String>>>() { }.getType());
+      return new Gson().fromJson(reader, new TypeToken<Map<String, Map<String, String>>>() {
+      }.getType());
     } catch (IOException e) {
       throw Throwables.propagate(e);
     }
@@ -709,8 +733,9 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
 
   /**
    * Attempts to change the number of running instances.
+   *
    * @return {@code true} if the message does requests for changes in number of running instances of a runnable,
-   *         {@code false} otherwise.
+   * {@code false} otherwise.
    */
   private boolean handleSetInstances(final Message message, final Runnable completion) {
     if (message.getType() != Message.Type.SYSTEM || message.getScope() != Message.Scope.RUNNABLE) {
@@ -765,13 +790,14 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
             if (newCount < oldCount) {
               // Shutdown some running containers
               for (int i = 0; i < oldCount - newCount; i++) {
-                runningContainers.removeLast(runnableName);
+                runningContainers.stopLastAndWait(runnableName);
               }
             } else {
               // Increase the number of instances
               runnableContainerRequests.add(createRunnableContainerRequest(runnableName, newCount - oldCount));
             }
           } finally {
+            // Send a message to all running runnables that number of instances have changed
             runningContainers.sendToRunnable(runnableName, message, completion);
             LOG.info("Change instances request completed. From {} to {}.", oldCount, newCount);
           }
@@ -843,6 +869,7 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
 
   /**
    * Attempt to restart some instances from a runnable or some runnables.
+   *
    * @return {@code true} if the message requests restarting some instances and {@code false} otherwise.
    */
   private boolean handleRestartRunnablesInstances(final Message message, final Runnable completion) {
@@ -875,7 +902,8 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
       for (Map.Entry<String, String> option : requestCommand.getOptions().entrySet()) {
         String runnableName = option.getKey();
         Set<Integer> restartedInstanceIds = GSON.fromJson(option.getValue(),
-                                                          new TypeToken<Set<Integer>>() {}.getType());
+                                                          new TypeToken<Set<Integer>>() {
+                                                          }.getType());
 
         LOG.debug("Start restarting runnable {} instances {}", runnableName, restartedInstanceIds);
         restartRunnableInstances(runnableName, restartedInstanceIds, completion);
@@ -903,11 +931,10 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
       @Override
       public void run() {
         LOG.debug("Begin restart runnable {} instances.", runnableName);
-
-        Set<Integer> instancesToRemove = instanceIds;
+        int runningCount = runningContainers.count(runnableName);
+        Set<Integer> instancesToRemove = instanceIds == null ? null : ImmutableSet.copyOf(instanceIds);
         if (instancesToRemove == null) {
-          instancesToRemove =
-            Ranges.closedOpen(0, runningContainers.count(runnableName)).asSet(DiscreteDomains.integers());
+          instancesToRemove = Ranges.closedOpen(0, runningCount).asSet(DiscreteDomains.integers());
         }
 
         LOG.info("Restarting instances {} for runnable {}", instancesToRemove, runnableName);
@@ -916,9 +943,9 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
         runnableContainerRequests.add(containerRequest);
 
         for (int instanceId : instancesToRemove) {
-          LOG.debug("Remove instance {} for runnable {}", instanceId, runnableName);
+          LOG.debug("Stop instance {} for runnable {}", instanceId, runnableName);
           try {
-            runningContainers.removeById(runnableName, instanceId);
+            runningContainers.stopByIdAndWait(runnableName, instanceId);
           } catch (Exception ex) {
             // could be thrown if the container already stopped.
             LOG.info("Exception thrown when stopping instance {} probably already stopped.", instanceId);
@@ -928,6 +955,10 @@ public final class ApplicationMasterService extends AbstractYarnTwillService imp
         // set the container request to be ready
         containerRequest.setReadyToBeProvisioned(true);
 
+        // For all runnables that needs to re-request for containers, update the expected count timestamp
+        // so that the EventHandler would be triggered with the right expiration timestamp.
+        expectedContainers.updateRequestTime(Collections.singleton(runnableName));
+
         completion.run();
       }
     };

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunningContainers.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunningContainers.java b/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunningContainers.java
index d957768..3d1b0f3 100644
--- a/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunningContainers.java
+++ b/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunningContainers.java
@@ -23,6 +23,7 @@ import com.google.common.collect.HashBasedTable;
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Iterators;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Multimap;
@@ -55,10 +56,11 @@ import org.apache.twill.zookeeper.ZKOperations;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.util.ArrayList;
 import java.util.BitSet;
 import java.util.Collection;
 import java.util.Deque;
-import java.util.Iterator;
+import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -180,56 +182,66 @@ final class RunningContainers {
 
   /**
    * Stops and removes the last running container of the given runnable.
+   * This method blocks until handleCompleted() is run for the runnable or a timeout occurs.
    */
-  void removeLast(String runnableName) {
+  void stopLastAndWait(String runnableName) {
+    int maxInstanceId;
     containerLock.lock();
     try {
-      int maxInstanceId = getMaxInstanceId(runnableName);
+      maxInstanceId = getMaxInstanceId(runnableName);
       if (maxInstanceId < 0) {
         LOG.warn("No running container found for {}", runnableName);
         return;
       }
-      removeInstanceById(runnableName, maxInstanceId);
     } finally {
       containerLock.unlock();
     }
+    stopByIdAndWait(runnableName, maxInstanceId);
   }
 
   /**
-   * Stop and remove a container for a runnable on an id.
+   * Stop and removes a container for a runnable on an id.
+   * This method blocks until handleCompleted() is run for the runnable or a timeout occurs.
+   * Hence this call should not be made within a containerLock
    */
-  void removeById(String runnableName, int instanceId) {
+  void stopByIdAndWait(String runnableName, int instanceId) {
+    String containerId = null;
+    TwillContainerController controller = null;
     containerLock.lock();
     try {
-      removeInstanceById(runnableName, instanceId);
+      // Find the controller with particular instance id.
+      for (Map.Entry<String, TwillContainerController> entry : containers.row(runnableName).entrySet()) {
+        if (getInstanceId(entry.getValue().getRunId()) == instanceId) {
+          containerId = entry.getKey();
+          controller = entry.getValue();
+          break;
+        }
+      }
+
+      Preconditions.checkState(containerId != null,
+                               "No container found for {} with instanceId = {}", runnableName, instanceId);
+      Preconditions.checkState(controller != null,
+                               "Null controller found for {} with instanceId = {}", runnableName, instanceId);
     } finally {
       containerLock.unlock();
     }
-  }
 
-  private void removeInstanceById(String runnableName, int instanceId) {
-    String containerId = null;
-    TwillContainerController controller = null;
+    LOG.info("Stopping service: {} {}", runnableName, controller.getRunId());
+    // This call will block until handleCompleted() method runs or a timeout occurs
+    controller.stopAndWait();
 
-    // Find the controller with particular instance id.
-    for (Map.Entry<String, TwillContainerController> entry : containers.row(runnableName).entrySet()) {
-      if (getInstanceId(entry.getValue().getRunId()) == instanceId) {
-        containerId = entry.getKey();
-        controller = entry.getValue();
-        break;
+    // Remove the stopped container state if it exists (in the case of killing the container due to timeout)
+    containerLock.lock();
+    try {
+      if (removeContainerInfo(containerId)) {
+        containers.remove(runnableName, containerId);
+        removeInstanceId(runnableName, instanceId);
+        resourceReport.removeRunnableResources(runnableName, containerId);
+        containerChange.signalAll();
       }
+    } finally {
+      containerLock.unlock();
     }
-
-    Preconditions.checkState(containerId != null,
-                             "No container found for {} with instanceId = {}", runnableName, instanceId);
-
-    LOG.info("Stopping service: {} {}", runnableName, controller.getRunId());
-    controller.stopAndWait();
-    containers.remove(runnableName, containerId);
-    removeContainerInfo(containerId);
-    removeInstanceId(runnableName, instanceId);
-    resourceReport.removeRunnableResources(runnableName, containerId);
-    containerChange.signalAll();
   }
 
   /**
@@ -302,20 +314,22 @@ final class RunningContainers {
   }
 
   void sendToRunnable(String runnableName, Message message, Runnable completion) {
+    List<TwillContainerController> controllers;
     containerLock.lock();
     try {
-      Collection<TwillContainerController> controllers = containers.row(runnableName).values();
-      if (controllers.isEmpty()) {
-        completion.run();
-      }
-
-      AtomicInteger count = new AtomicInteger(controllers.size());
-      for (TwillContainerController controller : controllers) {
-        sendMessage(runnableName, message, controller, count, completion);
-      }
+      controllers = new ArrayList<>(containers.row(runnableName).values());
     } finally {
       containerLock.unlock();
     }
+
+    if (controllers.isEmpty()) {
+      completion.run();
+    }
+
+    AtomicInteger count = new AtomicInteger(controllers.size());
+    for (TwillContainerController controller : controllers) {
+      sendMessage(runnableName, message, controller, count, completion);
+    }
   }
 
   /**
@@ -323,24 +337,38 @@ final class RunningContainers {
    */
   void stopAll() {
     containerLock.lock();
+    // Stop the runnables one by one in reverse order of start sequence
+    List<String> reverseRunnables = new LinkedList<>();
     try {
-      // Stop it one by one in reverse order of start sequence
-      Iterator<String> itor = startSequence.descendingIterator();
-      List<ListenableFuture<Service.State>> futures = Lists.newLinkedList();
-      while (itor.hasNext()) {
-        String runnableName = itor.next();
-        LOG.info("Stopping all instances of " + runnableName);
-
-        futures.clear();
-        // Parallel stops all running containers of the current runnable.
+      Iterators.addAll(reverseRunnables, startSequence.descendingIterator());
+    } finally {
+      containerLock.unlock();
+    }
+
+    List<ListenableFuture<Service.State>> futures = Lists.newLinkedList();
+    for (String runnableName : reverseRunnables) {
+      LOG.info("Stopping all instances of " + runnableName);
+
+      futures.clear();
+      // Parallel stops all running containers of the current runnable.
+      containerLock.lock();
+      try {
         for (TwillContainerController controller : containers.row(runnableName).values()) {
           futures.add(controller.stop());
         }
-        // Wait for containers to stop. Assumes the future returned by Futures.successfulAsList won't throw exception.
-        Futures.getUnchecked(Futures.successfulAsList(futures));
-
-        LOG.info("Terminated all instances of " + runnableName);
+      } finally {
+        containerLock.unlock();
       }
+      // Wait for containers to stop. Assumes the future returned by Futures.successfulAsList won't throw exception.
+      // This will block until handleCompleted() is run for the runnables or a timeout occurs.
+      Futures.getUnchecked(Futures.successfulAsList(futures));
+
+      LOG.info("Terminated all instances of " + runnableName);
+    }
+
+    // When we acquire this lock, all stopped runnables should have been cleaned up by handleCompleted() method
+    containerLock.lock();
+    try {
       containers.clear();
       runnableInstances.clear();
       containerStats.clear();
@@ -374,7 +402,7 @@ final class RunningContainers {
       removeContainerInfo(containerId);
       Map<String, TwillContainerController> lookup = containers.column(containerId);
       if (lookup.isEmpty()) {
-        // It's OK because if a container is stopped through removeLast, this would be empty.
+        // It's OK because if a container is stopped through stopByIdAndWait(), this would be empty.
         return;
       }
 
@@ -382,20 +410,16 @@ final class RunningContainers {
         LOG.warn("More than one controller found for container {}", containerId);
       }
 
-      if (exitStatus != ContainerExitCodes.SUCCESS) {
-        LOG.warn("Container {} exited abnormally with state {}, exit code {}.",
-                 containerId, state, exitStatus);
-        if (shouldRetry(exitStatus)) {
-          LOG.info("Re-request the container {} for exit code {}.", containerId, exitStatus);
-          restartRunnables.add(lookup.keySet().iterator().next());
-        }
-      } else {
-        LOG.info("Container {} exited normally with state {}", containerId, state);
-      }
-
+      boolean containerStopped = false;
       for (Map.Entry<String, TwillContainerController> completedEntry : lookup.entrySet()) {
         String runnableName = completedEntry.getKey();
         TwillContainerController controller = completedEntry.getValue();
+
+        // TODO: Can there be multiple controllers for a single container?
+        // TODO: What is the best way to determine whether to restart container when there are multiple controllers?
+        // See if the controller is stopped (this is to decide whether to retry the failed containers or not)
+        // In case of multiple controllers, even if one is stopped we will not re-request the container
+        containerStopped = containerStopped || isControllerStopped(controller);
         controller.completed(exitStatus);
 
         if (exitStatus == ContainerExitCodes.SUCCESS) {
@@ -404,10 +428,25 @@ final class RunningContainers {
           }
           completedContainerCount.put(runnableName, completedContainerCount.get(runnableName) + 1);
         }
+        // TODO: should we remove the completed instance from instanceId and resource report even on failures?
+        // TODO: won't they get added back when the container is re-requested?
         removeInstanceId(runnableName, getInstanceId(controller.getRunId()));
         resourceReport.removeRunnableResources(runnableName, containerId);
       }
 
+      if (exitStatus != ContainerExitCodes.SUCCESS) {
+        LOG.warn("Container {} exited abnormally with state {}, exit code {}.",
+                 containerId, state, exitStatus);
+        if (!containerStopped && shouldRetry(exitStatus)) {
+          LOG.info("Re-request the container {} for exit code {}.", containerId, exitStatus);
+          restartRunnables.add(lookup.keySet().iterator().next());
+        } else if (containerStopped) {
+          LOG.info("Container {} is being stopped, will not re-request", containerId);
+        }
+      } else {
+        LOG.info("Container {} exited normally with state {}", containerId, state);
+      }
+
       lookup.clear();
       containerChange.signalAll();
     } finally {
@@ -421,6 +460,10 @@ final class RunningContainers {
       && exitCode != ContainerExitCodes.INIT_FAILED;
   }
 
+  private boolean isControllerStopped(TwillContainerController controller) {
+    return controller.state() == Service.State.STOPPING || controller.state() == Service.State.TERMINATED;
+  }
+
   /**
    * Sends a command through the given {@link TwillContainerController} of a runnable. Decrements the count
    * when the sending of command completed. Triggers completion when count reaches zero.

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java b/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java
index 5d67dfa..2cac2f3 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/BaseYarnTest.java
@@ -19,6 +19,7 @@ package org.apache.twill.yarn;
 
 import com.google.common.base.Stopwatch;
 import com.google.common.collect.Iterables;
+import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport;
 import org.apache.hadoop.yarn.api.records.NodeReport;
 import org.apache.twill.api.TwillController;
 import org.apache.twill.api.TwillRunner;
@@ -133,4 +134,8 @@ public abstract class BaseYarnTest {
   public String getZKConnectionString() {
     return TWILL_TESTER.getZKConnectionString();
   }
+
+  public ApplicationResourceUsageReport getApplicationResourceReport(String appId) throws Exception {
+    return TWILL_TESTER.getApplicationResourceReport(appId);
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java b/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java
index 02075a7..211b7ba 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/EchoServerTestRun.java
@@ -102,17 +102,17 @@ public final class EchoServerTestRun extends BaseYarnTest {
     }
 
     // Increase number of instances
-    controller.changeInstances("EchoServer", 3);
+    controller.changeInstances("EchoServer", 3).get(60, TimeUnit.SECONDS);
     Assert.assertTrue(waitForSize(echoServices, 3, 120));
 
     echoServices = controller.discoverService("echo2");
 
     // Decrease number of instances
-    controller.changeInstances("EchoServer", 1);
+    controller.changeInstances("EchoServer", 1).get(60, TimeUnit.SECONDS);
     Assert.assertTrue(waitForSize(echoServices, 1, 120));
 
     // Increase number of instances again
-    controller.changeInstances("EchoServer", 2);
+    controller.changeInstances("EchoServer", 2).get(60, TimeUnit.SECONDS);
     Assert.assertTrue(waitForSize(echoServices, 2, 120));
 
     // Test restart on instances for runnable
@@ -125,7 +125,7 @@ public final class EchoServerTestRun extends BaseYarnTest {
       instanceIdToContainerId.put(twillRunResources.getInstanceId(), twillRunResources.getContainerId());
     }
 
-    controller.restartAllInstances("EchoServer");
+    controller.restartAllInstances("EchoServer").get(60, TimeUnit.SECONDS);
     Assert.assertTrue(waitForSize(echoServices, 2, 120));
 
     report = waitForAfterRestartResourceReport(controller, "EchoServer", 15L, TimeUnit.MINUTES, 2,

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-yarn/src/test/java/org/apache/twill/yarn/PlacementPolicyTestRun.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/PlacementPolicyTestRun.java b/twill-yarn/src/test/java/org/apache/twill/yarn/PlacementPolicyTestRun.java
index ec4c7bf..d65e031 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/PlacementPolicyTestRun.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/PlacementPolicyTestRun.java
@@ -185,20 +185,20 @@ public class PlacementPolicyTestRun extends BaseYarnTest {
       Assert.assertTrue(getProvisionedNodeManagerCount() >= 2);
 
       // Spawning a new instance for DISTRIBUTED runnable Alice, which should get a different node.
-      controller.changeInstances("Alice", 2);
+      controller.changeInstances("Alice", 2).get(60, TimeUnit.SECONDS);
       serviceDiscovered = controller.discoverService("DistributedTest");
       Assert.assertTrue(waitForSize(serviceDiscovered, 4, 60));
       Assert.assertTrue(getProvisionedNodeManagerCount() >= 3);
 
       // Spawning a new instance for DEFAULT runnable Eve,
       // which should not be affected by placement policies of previous runnables.
-      controller.changeInstances("Eve", 2);
+      controller.changeInstances("Eve", 2).get(60, TimeUnit.SECONDS);
       serviceDiscovered = controller.discoverService("DistributedTest");
       Assert.assertTrue(waitForSize(serviceDiscovered, 5, 60));
 
       // Spawning a new instance for DISTRIBUTED runnable Bob,
       // which will be forced to give up it's placement policy restrictions, since there are only three nodes.
-      controller.changeInstances("Bob", 2);
+      controller.changeInstances("Bob", 2).get(60, TimeUnit.SECONDS);
       serviceDiscovered = controller.discoverService("DistributedTest");
       Assert.assertTrue(waitForSize(serviceDiscovered, 6, 60));
       Assert.assertTrue(getProvisionedNodeManagerCount() >= 3);
@@ -272,22 +272,22 @@ public class PlacementPolicyTestRun extends BaseYarnTest {
       Assert.assertTrue(waitForSize(serviceDiscovered, 4, 60));
 
       // Increasing the instance count for runnable Alice by 2.
-      controller.changeInstances("Alice", 4);
+      controller.changeInstances("Alice", 4).get(60, TimeUnit.SECONDS);
       serviceDiscovered = controller.discoverService("DistributedTest");
       Assert.assertTrue(waitForSize(serviceDiscovered, 6, 60));
 
       // Decreasing instance count for runnable Alice by 3.
-      controller.changeInstances("Alice", 1);
+      controller.changeInstances("Alice", 1).get(60, TimeUnit.SECONDS);
       serviceDiscovered = controller.discoverService("DistributedTest");
       Assert.assertTrue(waitForSize(serviceDiscovered, 3, 60));
 
       // Increasing instance count for runnable Bob by 2.
-      controller.changeInstances("Bob", 3);
+      controller.changeInstances("Bob", 3).get(60, TimeUnit.SECONDS);
       serviceDiscovered = controller.discoverService("DistributedTest");
       Assert.assertTrue(waitForSize(serviceDiscovered, 5, 60));
 
       // Increasing instance count for runnable Eve by 2.
-      controller.changeInstances("Eve", 3);
+      controller.changeInstances("Eve", 3).get(60, TimeUnit.SECONDS);
       serviceDiscovered = controller.discoverService("DistributedTest");
       Assert.assertTrue(waitForSize(serviceDiscovered, 7, 60));
     } finally {

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-yarn/src/test/java/org/apache/twill/yarn/ResourceReportTestRun.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/ResourceReportTestRun.java b/twill-yarn/src/test/java/org/apache/twill/yarn/ResourceReportTestRun.java
index 86dfeaf..32e1fd6 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/ResourceReportTestRun.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/ResourceReportTestRun.java
@@ -249,7 +249,7 @@ public final class ResourceReportTestRun extends BaseYarnTest {
     }
 
     // Decrease number of instances of echo1 from 2 to 1
-    controller.changeInstances("echo1", 1);
+    controller.changeInstances("echo1", 1).get(60, TimeUnit.SECONDS);
     echoServices = controller.discoverService("echo1");
     Assert.assertTrue(waitForSize(echoServices, 1, 60));
     report = controller.getResourceReport();

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-yarn/src/test/java/org/apache/twill/yarn/RestartRunnableTestRun.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/RestartRunnableTestRun.java b/twill-yarn/src/test/java/org/apache/twill/yarn/RestartRunnableTestRun.java
new file mode 100644
index 0000000..6dcec8f
--- /dev/null
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/RestartRunnableTestRun.java
@@ -0,0 +1,348 @@
+/*
+ * 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.twill.yarn;
+
+import com.google.common.base.Stopwatch;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.JdkFutureAdapters;
+import com.google.common.util.concurrent.ListenableFuture;
+import org.apache.twill.api.AbstractTwillRunnable;
+import org.apache.twill.api.Command;
+import org.apache.twill.api.ResourceReport;
+import org.apache.twill.api.TwillApplication;
+import org.apache.twill.api.TwillController;
+import org.apache.twill.api.TwillRunResources;
+import org.apache.twill.api.TwillSpecification;
+import org.apache.twill.api.logging.PrinterLogHandler;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.PrintWriter;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Test restarting of Twill Runnables.
+ */
+public class RestartRunnableTestRun extends BaseYarnTest {
+  private static final Logger LOG = LoggerFactory.getLogger(RestartRunnableTestRun.class);
+  private static final String HANGING_RUNNABLE = HangingRunnable.class.getSimpleName();
+  private static final String STOPPING_RUNNABLE = StoppingRunnable.class.getSimpleName();
+  private static final String HANGING_RUNNABLE_STOP_SECS = "hanging.runnable.stop.secs";
+
+  /**
+   * Command that can be sent to HangingRunnable to make it sleep while stopping.
+   */
+  private static class SleepCommand implements Command {
+    private final int sleepTime;
+
+    public SleepCommand(int sleepTime) {
+      this.sleepTime = sleepTime;
+    }
+
+    @Override
+    public String getCommand() {
+      return HANGING_RUNNABLE_STOP_SECS;
+    }
+
+    @Override
+    public Map<String, String> getOptions() {
+      return ImmutableMap.of(HANGING_RUNNABLE_STOP_SECS, Integer.toString(sleepTime));
+    }
+  }
+
+  /**
+   * This runnable hangs when it gets a stop message.
+   */
+  public static final class HangingRunnable extends AbstractTwillRunnable {
+    private volatile Thread runThread;
+    // Send SleepCommand to update sleepTime to simulate hanging
+    private final AtomicInteger sleepTime = new AtomicInteger(1);
+
+    @Override
+    public void run() {
+      this.runThread = Thread.currentThread();
+      LOG.info("Starting Runnable {}", HANGING_RUNNABLE);
+      while (!Thread.interrupted()) {
+        try {
+          TimeUnit.MILLISECONDS.sleep(200);
+        } catch (InterruptedException e) {
+          break;
+        }
+      }
+      LOG.info("Stopping Runnable {}", HANGING_RUNNABLE);
+    }
+
+    @Override
+    public void stop() {
+      // Do not stop the thread until sleepTime to simulate hanging of the runnable.
+      LOG.info("Using sleep time = {} secs", sleepTime);
+      try {
+        TimeUnit.SECONDS.sleep(sleepTime.get());
+      } catch (InterruptedException e) {
+        LOG.error("Got exception: ", e);
+      }
+      if (runThread != null) {
+        runThread.interrupt();
+      }
+    }
+
+    @Override
+    public void handleCommand(Command command) throws Exception {
+      super.handleCommand(command);
+      if (HANGING_RUNNABLE_STOP_SECS.equals(command.getCommand())) {
+        int time = Integer.parseInt(command.getOptions().get(HANGING_RUNNABLE_STOP_SECS));
+        LOG.info("Got sleep time from message = {} secs", time);
+        sleepTime.set(time);
+      }
+    }
+  }
+
+  /**
+   * This runnable stops immediately when it gets a stop message.
+   */
+  public static final class StoppingRunnable extends AbstractTwillRunnable {
+    private volatile Thread runThread;
+
+    @Override
+    public void run() {
+      this.runThread = Thread.currentThread();
+      LOG.info("Starting Runnable {}", STOPPING_RUNNABLE);
+      while (!Thread.interrupted()) {
+        try {
+          TimeUnit.MILLISECONDS.sleep(200);
+        } catch (InterruptedException e) {
+          break;
+        }
+      }
+      LOG.info("Stopping Runnable {}", STOPPING_RUNNABLE);
+    }
+
+    @Override
+    public void stop() {
+      // Interrupt the thread to stop the runnable
+      if (runThread != null) {
+        runThread.interrupt();
+      }
+    }
+  }
+
+  /**
+   * A test TwillApplication to test restarting runnables.
+   */
+  public static final class RestartTestApplication implements TwillApplication {
+
+    @Override
+    public TwillSpecification configure() {
+      return TwillSpecification.Builder.with()
+        .setName(RestartTestApplication.class.getSimpleName())
+        .withRunnable()
+        .add(HANGING_RUNNABLE, new HangingRunnable()).noLocalFiles()
+        .add(STOPPING_RUNNABLE, new StoppingRunnable()).noLocalFiles()
+        .withOrder()
+        .begin(HANGING_RUNNABLE)
+        .nextWhenStarted(STOPPING_RUNNABLE)
+        .build();
+    }
+  }
+
+  /**
+   * A test TwillApplication with a single runnable.
+   */
+  public static final class SingleRunnableApp implements TwillApplication {
+
+    @Override
+    public TwillSpecification configure() {
+      return TwillSpecification.Builder.with()
+        .setName(RestartTestApplication.class.getSimpleName())
+        .withRunnable()
+        .add(HANGING_RUNNABLE, new HangingRunnable()).noLocalFiles()
+        .anyOrder()
+        .build();
+    }
+  }
+
+  @Test
+  public void testRestartSingleRunnable() throws Exception {
+    YarnTwillRunnerService runner = getTwillRunner();
+    runner.start();
+
+    LOG.info("Starting application {}", SingleRunnableApp.class.getSimpleName());
+    TwillController controller = runner.prepare(new SingleRunnableApp())
+      .addLogHandler(new PrinterLogHandler(new PrintWriter(System.out)))
+      .start();
+
+    // Lets wait until all runnables have started
+    waitForInstance(controller, HANGING_RUNNABLE, "002", 120, TimeUnit.SECONDS);
+    waitForContainers(controller, 2, 60, TimeUnit.SECONDS);
+
+    // Now restart runnable
+    LOG.info("Restarting runnable {}", HANGING_RUNNABLE);
+    controller.restartAllInstances(HANGING_RUNNABLE);
+    waitForInstance(controller, HANGING_RUNNABLE, "003", 120, TimeUnit.SECONDS);
+    waitForContainers(controller, 2, 60, TimeUnit.SECONDS);
+
+    // Send command to HANGING_RUNNABLE to hang when stopped
+    controller.sendCommand(HANGING_RUNNABLE, new SleepCommand(1000)).get();
+    LOG.info("Restarting runnable {}", HANGING_RUNNABLE);
+    controller.restartAllInstances(HANGING_RUNNABLE);
+    waitForInstance(controller, HANGING_RUNNABLE, "004", 120, TimeUnit.SECONDS);
+    waitForContainers(controller, 2, 60, TimeUnit.SECONDS);
+  }
+
+  @SuppressWarnings("unchecked")
+  @Test
+  public void testRestartRunnable() throws Exception {
+    YarnTwillRunnerService runner = getTwillRunner();
+    runner.start();
+
+    LOG.info("Starting application {}", RestartTestApplication.class.getSimpleName());
+    TwillController controller = runner.prepare(new RestartTestApplication())
+      .addLogHandler(new PrinterLogHandler(new PrintWriter(System.out)))
+      .start();
+
+    // Lets wait until all runnables have started
+    waitForInstance(controller, HANGING_RUNNABLE, "002", 120, TimeUnit.SECONDS);
+    waitForInstance(controller, STOPPING_RUNNABLE, "003", 120, TimeUnit.SECONDS);
+    waitForContainers(controller, 3, 60, TimeUnit.SECONDS);
+
+    // Send command to first instance of HANGING_RUNNABLE to hang when stopped
+    controller.sendCommand(HANGING_RUNNABLE, new SleepCommand(1000)).get();
+
+    // Increase instances of both runnables
+    LOG.info("Increasing instances of both runnables");
+    allAsList(controller.changeInstances(HANGING_RUNNABLE, 3),
+              controller.changeInstances(STOPPING_RUNNABLE, 2)
+    ).get(120, TimeUnit.SECONDS);
+    waitForInstance(controller, HANGING_RUNNABLE, "005", 120, TimeUnit.SECONDS); // +2 containers
+    waitForInstance(controller, STOPPING_RUNNABLE, "006", 120, TimeUnit.SECONDS); // +1 container
+    waitForContainers(controller, 6, 60, TimeUnit.SECONDS);
+
+    // Now restart both runnables (002 instance of HANGING_RUNNABLE will be killed)
+    LOG.info("Restarting all instances of runnables {} and {}", HANGING_RUNNABLE, STOPPING_RUNNABLE);
+    allAsList(
+      controller.restartAllInstances(HANGING_RUNNABLE),
+      controller.restartAllInstances(STOPPING_RUNNABLE)
+    ).get(120, TimeUnit.SECONDS);
+    waitForInstance(controller, HANGING_RUNNABLE, "009", 120, TimeUnit.SECONDS);
+    waitForInstance(controller, STOPPING_RUNNABLE, "011", 120, TimeUnit.SECONDS);
+    waitForContainers(controller, 6, 60, TimeUnit.SECONDS);
+
+    // Restart a single runnable from both
+    LOG.info("Restarting a single runnable of both");
+    allAsList(
+      controller.restartInstances(HANGING_RUNNABLE, 1),
+      controller.restartInstances(ImmutableMap.of(STOPPING_RUNNABLE, Collections.singleton(0)))
+    ).get(120, TimeUnit.SECONDS);
+    waitForInstance(controller, HANGING_RUNNABLE, "012", 120, TimeUnit.SECONDS);
+    waitForInstance(controller, STOPPING_RUNNABLE, "013", 120, TimeUnit.SECONDS);
+    waitForContainers(controller, 6, 60, TimeUnit.SECONDS);
+
+    // Send command to all instances of HANGING_RUNNABLE to wait for 10 seconds when stopped
+    controller.sendCommand(HANGING_RUNNABLE, new SleepCommand(10)).get();
+
+    // Reduce instances of both runnables to 1
+    LOG.info("Decreasing instances of both runnables");
+    allAsList(controller.changeInstances(HANGING_RUNNABLE, 1),
+              controller.changeInstances(STOPPING_RUNNABLE, 1)
+    ).get(120, TimeUnit.SECONDS);
+    waitForInstance(controller, HANGING_RUNNABLE, "007", 120, TimeUnit.SECONDS);
+    waitForInstance(controller, STOPPING_RUNNABLE, "013", 120, TimeUnit.SECONDS); // instance 0 is 013 due to restart
+    waitForContainers(controller, 3, 60, TimeUnit.SECONDS);
+
+    LOG.info("Stopping application {}", RestartTestApplication.class.getSimpleName());
+    controller.terminate().get(120, TimeUnit.SECONDS);
+
+    // Sleep a bit for full cleanup
+    TimeUnit.SECONDS.sleep(2);
+  }
+
+  private void waitForContainers(TwillController controller, int count, long timeout, TimeUnit timeoutUnit)
+    throws Exception {
+    Stopwatch stopwatch = new Stopwatch();
+    stopwatch.start();
+    int yarnContainers = 0;
+    int twillContainers = 0;
+    do {
+      if (controller.getResourceReport() != null) {
+        yarnContainers =
+          getApplicationResourceReport(controller.getResourceReport().getApplicationId()).getNumUsedContainers();
+        twillContainers = getTwillContainersUsed(controller);
+        if (yarnContainers == count && twillContainers == count) {
+          return;
+        }
+      }
+      TimeUnit.SECONDS.sleep(1);
+    } while (stopwatch.elapsedTime(timeoutUnit) < timeout);
+
+    throw new TimeoutException("Timeout reached while waiting for num containers to be " +  count +
+                                 ". Yarn containers = " + yarnContainers + ", Twill containers = " + twillContainers);
+  }
+
+  private void waitForInstance(TwillController controller, String runnable, String yarnInstanceId,
+                               long timeout, TimeUnit timeoutUnit) throws InterruptedException, TimeoutException {
+    Stopwatch stopwatch = new Stopwatch();
+    stopwatch.start();
+    do {
+      ResourceReport report = controller.getResourceReport();
+      if (report != null && report.getRunnableResources(runnable) != null) {
+        for (TwillRunResources resources : report.getRunnableResources(runnable)) {
+          if (resources.getContainerId().endsWith(yarnInstanceId)) {
+            return;
+          }
+        }
+      }
+      TimeUnit.SECONDS.sleep(1);
+    } while (stopwatch.elapsedTime(timeoutUnit) < timeout);
+
+    throw new TimeoutException("Timeout reached while waiting for runnable " +
+                                 runnable + " instance " + yarnInstanceId);
+  }
+
+  private int getTwillContainersUsed(TwillController controller) {
+    if (controller.getResourceReport() == null) {
+      return 0;
+    }
+
+    int count = 1; // 1 for app master container
+    ResourceReport resourceReport = controller.getResourceReport();
+    for (Collection<TwillRunResources> resources : resourceReport.getResources().values()) {
+      count += resources.size();
+    }
+    return count;
+  }
+
+  @SafeVarargs
+  private final <V> ListenableFuture<List<V>> allAsList(Future<? extends V>... futures) {
+    ImmutableList.Builder<ListenableFuture<? extends V>> listBuilder = ImmutableList.builder();
+    for (Future<? extends V> future : futures) {
+      listBuilder.add(JdkFutureAdapters.listenInPoolThread(future));
+    }
+    return Futures.allAsList(listBuilder.build());
+  }
+}

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java b/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java
index e604cec..a896913 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java
@@ -17,13 +17,21 @@
  */
 package org.apache.twill.yarn;
 
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.Lists;
 import com.google.common.util.concurrent.Service;
 import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.hdfs.HdfsConfiguration;
 import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.hadoop.yarn.api.protocolrecords.GetApplicationReportRequest;
+import org.apache.hadoop.yarn.api.records.ApplicationId;
+import org.apache.hadoop.yarn.api.records.ApplicationResourceUsageReport;
 import org.apache.hadoop.yarn.api.records.NodeReport;
 import org.apache.hadoop.yarn.conf.YarnConfiguration;
 import org.apache.hadoop.yarn.server.MiniYARNCluster;
+import org.apache.hadoop.yarn.server.resourcemanager.ClientRMService;
+import org.apache.hadoop.yarn.util.Records;
 import org.apache.twill.api.TwillRunner;
 import org.apache.twill.api.TwillRunnerService;
 import org.apache.twill.internal.yarn.VersionDetectYarnAppClientFactory;
@@ -164,6 +172,19 @@ public class TwillTester extends ExternalResource {
     return zkServer.getConnectionStr();
   }
 
+  public ApplicationResourceUsageReport getApplicationResourceReport(String appId) throws Exception {
+    List<String> splits = Lists.newArrayList(Splitter.on('_').split(appId));
+    Preconditions.checkArgument(splits.size() == 3, "Invalid application id - " + appId);
+    ApplicationId applicationId =
+      YarnUtils.createApplicationId(Long.parseLong(splits.get(1)), Integer.parseInt(splits.get(2)));
+
+    ClientRMService clientRMService = cluster.getResourceManager().getClientRMService();
+    GetApplicationReportRequest request = Records.newRecord(GetApplicationReportRequest.class);
+    request.setApplicationId(applicationId);
+    return clientRMService.getApplicationReport(request)
+      .getApplicationReport().getApplicationResourceUsageReport();
+  }
+
   private void stopQuietly(Service service) {
     try {
       service.stopAndWait();

http://git-wip-us.apache.org/repos/asf/twill/blob/069e0289/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java b/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java
index bea99d0..f1e1ac9 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/YarnTestSuite.java
@@ -40,7 +40,8 @@ import org.junit.runners.Suite;
   ResourceReportTestRun.class,
   ServiceDiscoveryTestRun.class,
   SessionExpireTestRun.class,
-  TaskCompletedTestRun.class
+  TaskCompletedTestRun.class,
+  RestartRunnableTestRun.class
 })
 public final class YarnTestSuite extends BaseYarnTest {
 


[14/16] twill git commit: Merge branch 'branch-0.8.0'

Posted by ch...@apache.org.
Merge branch 'branch-0.8.0'


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/4074f169
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/4074f169
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/4074f169

Branch: refs/heads/site
Commit: 4074f16985993d8914e687559343052c8e357906
Parents: 2a8de33 264401f
Author: Terence Yim <ch...@apache.org>
Authored: Tue Sep 27 01:08:51 2016 -0400
Committer: Terence Yim <ch...@apache.org>
Committed: Tue Sep 27 01:08:51 2016 -0400

----------------------------------------------------------------------
 pom.xml                      | 2 +-
 twill-api/pom.xml            | 2 +-
 twill-common/pom.xml         | 2 +-
 twill-core/pom.xml           | 2 +-
 twill-discovery-api/pom.xml  | 2 +-
 twill-discovery-core/pom.xml | 2 +-
 twill-examples/echo/pom.xml  | 2 +-
 twill-examples/pom.xml       | 2 +-
 twill-examples/yarn/pom.xml  | 2 +-
 twill-ext/pom.xml            | 2 +-
 twill-java8-test/pom.xml     | 2 +-
 twill-yarn/pom.xml           | 2 +-
 twill-zookeeper/pom.xml      | 2 +-
 13 files changed, 13 insertions(+), 13 deletions(-)
----------------------------------------------------------------------



[10/16] twill git commit: TWILL-107 Add payload support for Discoverable

Posted by ch...@apache.org.
TWILL-107 Add payload support for Discoverable

Signed-off-by: Gokul Gunasekaran <go...@cask.co>

This closes #10 on Github
Signed-off-by: Terence Yim <ch...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/fd9d7266
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/fd9d7266
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/fd9d7266

Branch: refs/heads/site
Commit: fd9d72661fec724eae40cfb80f72ada941c5f3a5
Parents: 93c523d
Author: Gokul Gunasekaran <go...@cask.co>
Authored: Thu Sep 8 18:12:43 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Mon Sep 12 09:49:26 2016 -0700

----------------------------------------------------------------------
 .../org/apache/twill/api/ServiceAnnouncer.java  | 10 ++-
 .../twill/internal/BasicTwillContext.java       | 17 ++---
 .../apache/twill/discovery/Discoverable.java    | 57 +++++++++++++++-
 .../discovery/DefaultServiceDiscovered.java     | 12 +---
 .../twill/discovery/DiscoverableAdapter.java    | 20 ++----
 .../twill/discovery/DiscoverableWrapper.java    | 69 --------------------
 .../discovery/InMemoryDiscoveryService.java     |  7 +-
 .../twill/discovery/ZKDiscoveryService.java     | 11 ++--
 .../discovery/DiscoveryServiceTestBase.java     | 42 +++---------
 9 files changed, 94 insertions(+), 151 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/fd9d7266/twill-api/src/main/java/org/apache/twill/api/ServiceAnnouncer.java
----------------------------------------------------------------------
diff --git a/twill-api/src/main/java/org/apache/twill/api/ServiceAnnouncer.java b/twill-api/src/main/java/org/apache/twill/api/ServiceAnnouncer.java
index d8e4358..9513352 100644
--- a/twill-api/src/main/java/org/apache/twill/api/ServiceAnnouncer.java
+++ b/twill-api/src/main/java/org/apache/twill/api/ServiceAnnouncer.java
@@ -27,7 +27,15 @@ public interface ServiceAnnouncer {
   /**
    * Registers an endpoint that could be discovered by external party.
    * @param serviceName Name of the endpoint
-   * @param port Port of the endpoint.
+   * @param port Port of the endpoint
    */
   Cancellable announce(String serviceName, int port);
+
+  /**
+   * Registers an endpoint that could be discovered by external party with a payload
+   * @param serviceName Name of the endpoint
+   * @param port Port of the endpoint
+   * @param payload byte array payload
+   */
+  Cancellable announce(String serviceName, int port, byte[] payload);
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/fd9d7266/twill-core/src/main/java/org/apache/twill/internal/BasicTwillContext.java
----------------------------------------------------------------------
diff --git a/twill-core/src/main/java/org/apache/twill/internal/BasicTwillContext.java b/twill-core/src/main/java/org/apache/twill/internal/BasicTwillContext.java
index 370c3d3..d9cca85 100644
--- a/twill-core/src/main/java/org/apache/twill/internal/BasicTwillContext.java
+++ b/twill-core/src/main/java/org/apache/twill/internal/BasicTwillContext.java
@@ -131,17 +131,12 @@ public final class BasicTwillContext implements TwillContext {
 
   @Override
   public Cancellable announce(final String serviceName, final int port) {
-    return discoveryService.register(new Discoverable() {
-      @Override
-      public String getName() {
-        return serviceName;
-      }
-
-      @Override
-      public InetSocketAddress getSocketAddress() {
-        return new InetSocketAddress(getHost(), port);
-      }
-    });
+    return announce(serviceName, port, new byte[]{});
+  }
+
+  @Override
+  public Cancellable announce(final String serviceName, final int port, final byte[] payload) {
+    return discoveryService.register(new Discoverable(serviceName, new InetSocketAddress(getHost(), port), payload));
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/twill/blob/fd9d7266/twill-discovery-api/src/main/java/org/apache/twill/discovery/Discoverable.java
----------------------------------------------------------------------
diff --git a/twill-discovery-api/src/main/java/org/apache/twill/discovery/Discoverable.java b/twill-discovery-api/src/main/java/org/apache/twill/discovery/Discoverable.java
index a5529fe..f36a3db 100644
--- a/twill-discovery-api/src/main/java/org/apache/twill/discovery/Discoverable.java
+++ b/twill-discovery-api/src/main/java/org/apache/twill/discovery/Discoverable.java
@@ -19,19 +19,70 @@
 package org.apache.twill.discovery;
 
 import java.net.InetSocketAddress;
+import java.util.Arrays;
+import java.util.Objects;
 
 /**
  * Discoverable defines the attributes of service to be discovered.
  */
-public interface Discoverable {
+public class Discoverable {
+  private final String name;
+  private final InetSocketAddress address;
+  private final byte[] payload;
+
+  public Discoverable(String name, InetSocketAddress address, byte[] payload) {
+    this.name = name;
+    this.address = address;
+    this.payload = payload;
+  }
+
+  public Discoverable(String name, InetSocketAddress address) {
+    this(name, address, new byte[]{});
+  }
 
   /**
    * @return Name of the service
    */
-  String getName();
+  public String getName() {
+    return name;
+  }
 
   /**
    * @return An {@link InetSocketAddress} representing the host+port of the service.
    */
-  InetSocketAddress getSocketAddress();
+  public InetSocketAddress getSocketAddress() {
+    return address;
+  }
+
+  /**
+   * @return A payload represented as a byte array
+   */
+  public byte[] getPayload() {
+    return payload;
+  }
+
+  @Override
+  public String toString() {
+    return "{name=" + name + ", address=" + address + ", payload=" + payload + "}";
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    if (o == null || getClass() != o.getClass()) {
+      return false;
+    }
+
+    Discoverable other = (Discoverable) o;
+
+    return name.equals(other.getName()) && address.equals(other.getSocketAddress()) &&
+      Arrays.equals(payload, other.getPayload());
+  }
+
+  @Override
+  public int hashCode() {
+    return Objects.hash(name, address, payload);
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/fd9d7266/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java b/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java
index 63df8ad..dbb0f7c 100644
--- a/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java
+++ b/twill-discovery-core/src/main/java/org/apache/twill/discovery/DefaultServiceDiscovered.java
@@ -96,17 +96,7 @@ final class DefaultServiceDiscovered implements ServiceDiscovered {
   @Override
   public boolean contains(Discoverable discoverable) {
     // If the name doesn't match, it shouldn't be in the list.
-    if (!discoverable.getName().equals(name)) {
-      return false;
-    }
-
-    // Wrap it if necessary for hashCode/equals comparison.
-    Discoverable target = discoverable;
-    if (!(target instanceof DiscoverableWrapper)) {
-      target = new DiscoverableWrapper(target);
-    }
-
-    return discoverables.get().contains(target);
+    return discoverable.getName().equals(name) && discoverables.get().contains(discoverable);
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/twill/blob/fd9d7266/twill-discovery-core/src/main/java/org/apache/twill/discovery/DiscoverableAdapter.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/main/java/org/apache/twill/discovery/DiscoverableAdapter.java b/twill-discovery-core/src/main/java/org/apache/twill/discovery/DiscoverableAdapter.java
index 0e4bcc3..b020dc7 100644
--- a/twill-discovery-core/src/main/java/org/apache/twill/discovery/DiscoverableAdapter.java
+++ b/twill-discovery-core/src/main/java/org/apache/twill/discovery/DiscoverableAdapter.java
@@ -18,6 +18,7 @@
 package org.apache.twill.discovery;
 
 import com.google.common.base.Charsets;
+import com.google.common.reflect.TypeToken;
 import com.google.gson.Gson;
 import com.google.gson.GsonBuilder;
 import com.google.gson.JsonDeserializationContext;
@@ -38,6 +39,7 @@ final class DiscoverableAdapter {
 
   private static final Gson GSON =
     new GsonBuilder().registerTypeAdapter(Discoverable.class, new DiscoverableCodec()).create();
+  private static final Type BYTE_ARRAY_TYPE = new TypeToken<byte[]>() { }.getType();
 
   /**
    * Helper function for encoding an instance of {@link Discoverable} into array of bytes.
@@ -73,21 +75,12 @@ final class DiscoverableAdapter {
     public Discoverable deserialize(JsonElement json, Type typeOfT,
                                     JsonDeserializationContext context) throws JsonParseException {
       JsonObject jsonObj = json.getAsJsonObject();
-      final String service = jsonObj.get("service").getAsString();
+      String service = jsonObj.get("service").getAsString();
       String hostname = jsonObj.get("hostname").getAsString();
       int port = jsonObj.get("port").getAsInt();
-      final InetSocketAddress address = new InetSocketAddress(hostname, port);
-      return new DiscoverableWrapper(new Discoverable() {
-        @Override
-        public String getName() {
-          return service;
-        }
-
-        @Override
-        public InetSocketAddress getSocketAddress() {
-          return address;
-        }
-      });
+      byte[] payload = context.deserialize(jsonObj.get("payload"), BYTE_ARRAY_TYPE);
+      InetSocketAddress address = new InetSocketAddress(hostname, port);
+      return new Discoverable(service, address, payload);
     }
 
     @Override
@@ -96,6 +89,7 @@ final class DiscoverableAdapter {
       jsonObj.addProperty("service", src.getName());
       jsonObj.addProperty("hostname", src.getSocketAddress().getHostName());
       jsonObj.addProperty("port", src.getSocketAddress().getPort());
+      jsonObj.add("payload", context.serialize(src.getPayload()));
       return jsonObj;
     }
   }

http://git-wip-us.apache.org/repos/asf/twill/blob/fd9d7266/twill-discovery-core/src/main/java/org/apache/twill/discovery/DiscoverableWrapper.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/main/java/org/apache/twill/discovery/DiscoverableWrapper.java b/twill-discovery-core/src/main/java/org/apache/twill/discovery/DiscoverableWrapper.java
deleted file mode 100644
index 5fa97d1..0000000
--- a/twill-discovery-core/src/main/java/org/apache/twill/discovery/DiscoverableWrapper.java
+++ /dev/null
@@ -1,69 +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 org.apache.twill.discovery;
-
-import java.net.InetSocketAddress;
-
-/**
- * Wrapper for a discoverable.
- */
-final class DiscoverableWrapper implements Discoverable {
-  private final String name;
-  private final InetSocketAddress address;
-
-  DiscoverableWrapper(Discoverable discoverable) {
-    this.name = discoverable.getName();
-    this.address = discoverable.getSocketAddress();
-  }
-
-  @Override
-  public String getName() {
-    return name;
-  }
-
-  @Override
-  public InetSocketAddress getSocketAddress() {
-    return address;
-  }
-
-  @Override
-  public String toString() {
-    return "{name=" + name + ", address=" + address;
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) {
-      return true;
-    }
-    if (o == null || getClass() != o.getClass()) {
-      return false;
-    }
-
-    Discoverable other = (Discoverable) o;
-
-    return name.equals(other.getName()) && address.equals(other.getSocketAddress());
-  }
-
-  @Override
-  public int hashCode() {
-    int result = name.hashCode();
-    result = 31 * result + address.hashCode();
-    return result;
-  }
-}

http://git-wip-us.apache.org/repos/asf/twill/blob/fd9d7266/twill-discovery-core/src/main/java/org/apache/twill/discovery/InMemoryDiscoveryService.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/main/java/org/apache/twill/discovery/InMemoryDiscoveryService.java b/twill-discovery-core/src/main/java/org/apache/twill/discovery/InMemoryDiscoveryService.java
index 6a71855..83a6681 100644
--- a/twill-discovery-core/src/main/java/org/apache/twill/discovery/InMemoryDiscoveryService.java
+++ b/twill-discovery-core/src/main/java/org/apache/twill/discovery/InMemoryDiscoveryService.java
@@ -37,12 +37,11 @@ public class InMemoryDiscoveryService implements DiscoveryService, DiscoveryServ
 
   @Override
   public Cancellable register(final Discoverable discoverable) {
-    final Discoverable wrapper = new DiscoverableWrapper(discoverable);
-    final String serviceName = wrapper.getName();
+    final String serviceName = discoverable.getName();
 
     lock.lock();
     try {
-      services.put(serviceName, wrapper);
+      services.put(serviceName, discoverable);
 
       DefaultServiceDiscovered serviceDiscovered = serviceDiscoveredMap.get(serviceName);
       if (serviceDiscovered != null) {
@@ -57,7 +56,7 @@ public class InMemoryDiscoveryService implements DiscoveryService, DiscoveryServ
       public void cancel() {
         lock.lock();
         try {
-          services.remove(serviceName, wrapper);
+          services.remove(serviceName, discoverable);
 
           DefaultServiceDiscovered serviceDiscovered = serviceDiscoveredMap.get(serviceName);
           if (serviceDiscovered != null) {

http://git-wip-us.apache.org/repos/asf/twill/blob/fd9d7266/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java b/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java
index c563bab..4f2d0f7 100644
--- a/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java
+++ b/twill-discovery-core/src/main/java/org/apache/twill/discovery/ZKDiscoveryService.java
@@ -146,23 +146,22 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
    */
   @Override
   public Cancellable register(final Discoverable discoverable) {
-    final Discoverable wrapper = new DiscoverableWrapper(discoverable);
     final SettableFuture<String> future = SettableFuture.create();
-    final DiscoveryCancellable cancellable = new DiscoveryCancellable(wrapper);
+    final DiscoveryCancellable cancellable = new DiscoveryCancellable(discoverable);
 
     // Create the zk ephemeral node.
-    Futures.addCallback(doRegister(wrapper), new FutureCallback<String>() {
+    Futures.addCallback(doRegister(discoverable), new FutureCallback<String>() {
       @Override
       public void onSuccess(String result) {
         // Set the sequence node path to cancellable for future cancellation.
         cancellable.setPath(result);
         lock.lock();
         try {
-          discoverables.put(wrapper, cancellable);
+          discoverables.put(discoverable, cancellable);
         } finally {
           lock.unlock();
         }
-        LOG.debug("Service registered: {} {}", wrapper, result);
+        LOG.debug("Service registered: {} {}", discoverable, result);
         future.set(result);
       }
 
@@ -171,7 +170,7 @@ public class ZKDiscoveryService implements DiscoveryService, DiscoveryServiceCli
         if (t instanceof KeeperException.NodeExistsException) {
           handleRegisterFailure(discoverable, future, this, t);
         } else {
-          LOG.warn("Failed to register: {}", wrapper, t);
+          LOG.warn("Failed to register: {}", discoverable, t);
           future.setException(t);
         }
       }

http://git-wip-us.apache.org/repos/asf/twill/blob/fd9d7266/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java
----------------------------------------------------------------------
diff --git a/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java b/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java
index 23deddc..8fe5a37 100644
--- a/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java
+++ b/twill-discovery-core/src/test/java/org/apache/twill/discovery/DiscoveryServiceTestBase.java
@@ -45,28 +45,19 @@ public abstract class DiscoveryServiceTestBase {
 
   @Test
   public void simpleDiscoverable() throws Exception {
+    final String payload = "data";
     Map.Entry<DiscoveryService, DiscoveryServiceClient> entry = create();
     DiscoveryService discoveryService = entry.getKey();
     DiscoveryServiceClient discoveryServiceClient = entry.getValue();
 
     // Register one service running on one host:port
-    Cancellable cancellable = register(discoveryService, "foo", "localhost", 8090);
+    Cancellable cancellable = register(discoveryService, "foo", "localhost", 8090, payload.getBytes());
 
     // Discover that registered host:port.
     ServiceDiscovered serviceDiscovered = discoveryServiceClient.discover("foo");
     Assert.assertTrue(waitTillExpected(1, serviceDiscovered));
 
-    Discoverable discoverable = new Discoverable() {
-      @Override
-      public String getName() {
-        return "foo";
-      }
-
-      @Override
-      public InetSocketAddress getSocketAddress() {
-        return new InetSocketAddress("localhost", 8090);
-      }
-    };
+    Discoverable discoverable = new Discoverable("foo", new InetSocketAddress("localhost", 8090), payload.getBytes());
 
     // Check it exists.
     Assert.assertTrue(serviceDiscovered.contains(discoverable));
@@ -259,17 +250,7 @@ public abstract class DiscoveryServiceTestBase {
     Thread t = new Thread() {
       @Override
       public void run() {
-        service.register(new Discoverable() {
-          @Override
-          public String getName() {
-            return serviceName;
-          }
-
-          @Override
-          public InetSocketAddress getSocketAddress() {
-            return new InetSocketAddress(12345);
-          }
-        });
+        service.register(new Discoverable(serviceName, new InetSocketAddress(12345), new byte[]{}));
       }
     };
 
@@ -282,17 +263,12 @@ public abstract class DiscoveryServiceTestBase {
   }
 
   protected Cancellable register(DiscoveryService service, final String name, final String host, final int port) {
-    return service.register(new Discoverable() {
-      @Override
-      public String getName() {
-        return name;
-      }
+    return register(service, name, host, port, new byte[]{});
+  }
 
-      @Override
-      public InetSocketAddress getSocketAddress() {
-        return new InetSocketAddress(host, port);
-      }
-    });
+  protected Cancellable register(DiscoveryService service, final String name, final String host, final int port,
+                                 final byte[] payload) {
+    return service.register(new Discoverable(name, new InetSocketAddress(host, port), payload));
   }
 
   protected boolean waitTillExpected(final int expected, ServiceDiscovered serviceDiscovered) {


[09/16] twill git commit: (TWILL-173) Have EmbeddedKafkaServer restart multiple times on bind failure

Posted by ch...@apache.org.
(TWILL-173) Have EmbeddedKafkaServer restart multiple times on bind failure

- Due to potential race condition between random port generation vs actual binding, there is a possibility that the binding would fail.

Signed-off-by: Terence Yim <ch...@apache.org>

This closes #9 on Github


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/93c523d0
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/93c523d0
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/93c523d0

Branch: refs/heads/site
Commit: 93c523d022cfd021d5ad7f1cffa87b460cd5cd1b
Parents: 2d617d2
Author: Terence Yim <ch...@apache.org>
Authored: Wed Aug 31 14:38:19 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Thu Sep 1 10:08:38 2016 -0700

----------------------------------------------------------------------
 .../internal/kafka/EmbeddedKafkaServer.java     | 42 +++++++++++++++++---
 .../appmaster/ApplicationMasterMain.java        |  6 ---
 .../org/apache/twill/yarn/LogLevelTestRun.java  |  2 +-
 3 files changed, 37 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/93c523d0/twill-core/src/main/java/org/apache/twill/internal/kafka/EmbeddedKafkaServer.java
----------------------------------------------------------------------
diff --git a/twill-core/src/main/java/org/apache/twill/internal/kafka/EmbeddedKafkaServer.java b/twill-core/src/main/java/org/apache/twill/internal/kafka/EmbeddedKafkaServer.java
index cd86dcb..be6121d 100644
--- a/twill-core/src/main/java/org/apache/twill/internal/kafka/EmbeddedKafkaServer.java
+++ b/twill-core/src/main/java/org/apache/twill/internal/kafka/EmbeddedKafkaServer.java
@@ -17,16 +17,21 @@
  */
 package org.apache.twill.internal.kafka;
 
+import com.google.common.base.Preconditions;
 import com.google.common.base.Throwables;
 import com.google.common.util.concurrent.AbstractIdleService;
 import kafka.server.KafkaConfig;
 import kafka.server.KafkaServer;
 import kafka.utils.Time;
 import org.I0Itec.zkclient.exception.ZkTimeoutException;
+import org.apache.twill.internal.utils.Networks;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.net.BindException;
 import java.util.Properties;
+import java.util.Random;
+import java.util.concurrent.TimeUnit;
 
 /**
  * A {@link com.google.common.util.concurrent.Service} implementation for running an instance of Kafka server in
@@ -34,25 +39,27 @@ import java.util.Properties;
  */
 public final class EmbeddedKafkaServer extends AbstractIdleService {
 
-  public static final String START_TIMEOUT_RETRIES = "twill.kafka.start.timeout.retries";
+  public static final String START_RETRIES = "twill.kafka.start.timeout.retries";
 
   private static final Logger LOG = LoggerFactory.getLogger(EmbeddedKafkaServer.class);
-  private static final String DEFAULT_START_TIMEOUT_RETRIES = "5";
+  private static final String DEFAULT_START_RETRIES = "5";
 
   private final int startTimeoutRetries;
-  private final KafkaConfig kafkaConfig;
+  private final Properties properties;
   private KafkaServer server;
 
   public EmbeddedKafkaServer(Properties properties) {
-    this.startTimeoutRetries = Integer.parseInt(properties.getProperty(START_TIMEOUT_RETRIES,
-                                                                       DEFAULT_START_TIMEOUT_RETRIES));
-    this.kafkaConfig = new KafkaConfig(properties);
+    this.startTimeoutRetries = Integer.parseInt(properties.getProperty(START_RETRIES,
+                                                                       DEFAULT_START_RETRIES));
+    this.properties = new Properties();
+    this.properties.putAll(properties);
   }
 
   @Override
   protected void startUp() throws Exception {
     int tries = 0;
     do {
+      KafkaConfig kafkaConfig = createKafkaConfig(properties);
       KafkaServer kafkaServer = createKafkaServer(kafkaConfig);
       try {
         kafkaServer.startup();
@@ -65,9 +72,14 @@ public final class EmbeddedKafkaServer extends AbstractIdleService {
         if (rootCause instanceof ZkTimeoutException) {
           // Potentially caused by race condition bug described in TWILL-139.
           LOG.warn("Timeout when connecting to ZooKeeper from KafkaServer. Attempt number {}.", tries, rootCause);
+        } else if (rootCause instanceof BindException) {
+          LOG.warn("Kafka failed to bind to port {}. Attempt number {}.", kafkaConfig.port(), tries, rootCause);
         } else {
           throw e;
         }
+
+        // Do a random sleep of < 200ms
+        TimeUnit.MILLISECONDS.sleep(new Random().nextInt(200) + 1L);
       }
     } while (server == null && ++tries < startTimeoutRetries);
 
@@ -107,4 +119,22 @@ public final class EmbeddedKafkaServer extends AbstractIdleService {
       }
     });
   }
+
+  /**
+   * Creates a new {@link KafkaConfig} from the given {@link Properties}. If the {@code "port"} property is missing
+   * or is equals to {@code "0"}, a random port will be generated.
+   */
+  private KafkaConfig createKafkaConfig(Properties properties) {
+    Properties prop = new Properties();
+    prop.putAll(properties);
+
+    String port = prop.getProperty("port");
+    if (port == null || "0".equals(port)) {
+      int randomPort = Networks.getRandomPort();
+      Preconditions.checkState(randomPort > 0, "Failed to get random port.");
+      prop.setProperty("port", Integer.toString(randomPort));
+    }
+
+    return new KafkaConfig(prop);
+  }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/93c523d0/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterMain.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterMain.java b/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterMain.java
index 38a2463..e708fb8 100644
--- a/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterMain.java
+++ b/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/ApplicationMasterMain.java
@@ -17,7 +17,6 @@
  */
 package org.apache.twill.internal.appmaster;
 
-import com.google.common.base.Preconditions;
 import com.google.common.util.concurrent.AbstractIdleService;
 import com.google.common.util.concurrent.Futures;
 import org.apache.hadoop.conf.Configuration;
@@ -30,7 +29,6 @@ import org.apache.twill.internal.RunIds;
 import org.apache.twill.internal.ServiceMain;
 import org.apache.twill.internal.kafka.EmbeddedKafkaServer;
 import org.apache.twill.internal.logging.Loggings;
-import org.apache.twill.internal.utils.Networks;
 import org.apache.twill.internal.yarn.VersionDetectYarnAMClientFactory;
 import org.apache.twill.internal.yarn.YarnAMClient;
 import org.apache.twill.zookeeper.OperationFuture;
@@ -168,12 +166,8 @@ public final class ApplicationMasterMain extends ServiceMain {
     }
 
     private Properties generateKafkaConfig(String kafkaZKConnect) {
-      int port = Networks.getRandomPort();
-      Preconditions.checkState(port > 0, "Failed to get random port.");
-
       Properties prop = new Properties();
       prop.setProperty("log.dir", new File("kafka-logs").getAbsolutePath());
-      prop.setProperty("port", Integer.toString(port));
       prop.setProperty("broker.id", "1");
       prop.setProperty("socket.send.buffer.bytes", "1048576");
       prop.setProperty("socket.receive.buffer.bytes", "1048576");

http://git-wip-us.apache.org/repos/asf/twill/blob/93c523d0/twill-yarn/src/test/java/org/apache/twill/yarn/LogLevelTestRun.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/LogLevelTestRun.java b/twill-yarn/src/test/java/org/apache/twill/yarn/LogLevelTestRun.java
index 7990a5b..e4f789a 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/LogLevelTestRun.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/LogLevelTestRun.java
@@ -112,7 +112,7 @@ public class LogLevelTestRun extends BaseYarnTest {
     }, Threads.SAME_THREAD_EXECUTOR);
     Assert.assertTrue(running.await(200, TimeUnit.SECONDS));
 
-    LogEntry.Level logLevel = waitForLogLevel(controller, LogLevelTestRunnable.class.getSimpleName(), 5L,
+    LogEntry.Level logLevel = waitForLogLevel(controller, LogLevelTestRunnable.class.getSimpleName(), 30L,
                                               TimeUnit.SECONDS);
 
     // Verify we got DEBUG log level.


[15/16] twill git commit: Bump version to 0.9.0-SNAPSHOT

Posted by ch...@apache.org.
Bump version to 0.9.0-SNAPSHOT


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/983a14a2
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/983a14a2
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/983a14a2

Branch: refs/heads/site
Commit: 983a14a2a1caa001361f10b7526bad31dc6c00a6
Parents: 4074f16
Author: Terence Yim <ch...@apache.org>
Authored: Tue Sep 27 01:10:49 2016 -0400
Committer: Terence Yim <ch...@apache.org>
Committed: Tue Sep 27 01:10:49 2016 -0400

----------------------------------------------------------------------
 pom.xml                      | 2 +-
 twill-api/pom.xml            | 2 +-
 twill-common/pom.xml         | 2 +-
 twill-core/pom.xml           | 2 +-
 twill-discovery-api/pom.xml  | 2 +-
 twill-discovery-core/pom.xml | 2 +-
 twill-examples/echo/pom.xml  | 2 +-
 twill-examples/pom.xml       | 2 +-
 twill-examples/yarn/pom.xml  | 2 +-
 twill-ext/pom.xml            | 2 +-
 twill-java8-test/pom.xml     | 2 +-
 twill-yarn/pom.xml           | 2 +-
 twill-zookeeper/pom.xml      | 2 +-
 13 files changed, 13 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 21d15bd..864d5e1 100644
--- a/pom.xml
+++ b/pom.xml
@@ -29,7 +29,7 @@
 
     <groupId>org.apache.twill</groupId>
     <artifactId>twill-parent</artifactId>
-    <version>0.8.0</version>
+    <version>0.9.0-SNAPSHOT</version>
     <packaging>pom</packaging>
     <name>Apache Twill</name>
     <url>http://twill.apache.org</url>

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-api/pom.xml
----------------------------------------------------------------------
diff --git a/twill-api/pom.xml b/twill-api/pom.xml
index a98ef9b..f981bae 100644
--- a/twill-api/pom.xml
+++ b/twill-api/pom.xml
@@ -24,7 +24,7 @@
     <parent>
         <groupId>org.apache.twill</groupId>
         <artifactId>twill-parent</artifactId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
 
     <artifactId>twill-api</artifactId>

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-common/pom.xml
----------------------------------------------------------------------
diff --git a/twill-common/pom.xml b/twill-common/pom.xml
index 52e0539..a29ea75 100644
--- a/twill-common/pom.xml
+++ b/twill-common/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-core/pom.xml
----------------------------------------------------------------------
diff --git a/twill-core/pom.xml b/twill-core/pom.xml
index 6becc27..93327e2 100644
--- a/twill-core/pom.xml
+++ b/twill-core/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-discovery-api/pom.xml
----------------------------------------------------------------------
diff --git a/twill-discovery-api/pom.xml b/twill-discovery-api/pom.xml
index a4deea2..3d4dcbd 100644
--- a/twill-discovery-api/pom.xml
+++ b/twill-discovery-api/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-discovery-core/pom.xml
----------------------------------------------------------------------
diff --git a/twill-discovery-core/pom.xml b/twill-discovery-core/pom.xml
index 5f65067..859ec0a 100644
--- a/twill-discovery-core/pom.xml
+++ b/twill-discovery-core/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-examples/echo/pom.xml
----------------------------------------------------------------------
diff --git a/twill-examples/echo/pom.xml b/twill-examples/echo/pom.xml
index 943c9e9..87d3d55 100644
--- a/twill-examples/echo/pom.xml
+++ b/twill-examples/echo/pom.xml
@@ -25,7 +25,7 @@ limitations under the License.
     <parent>
         <artifactId>twill-examples</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
 
     <name>Apache Twill examples: Echo</name>

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-examples/pom.xml
----------------------------------------------------------------------
diff --git a/twill-examples/pom.xml b/twill-examples/pom.xml
index 59f0391..90c8dcd 100644
--- a/twill-examples/pom.xml
+++ b/twill-examples/pom.xml
@@ -25,7 +25,7 @@ limitations under the License.
     <parent>
         <groupId>org.apache.twill</groupId>
         <artifactId>twill-parent</artifactId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
 
     <artifactId>twill-examples</artifactId>

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-examples/yarn/pom.xml
----------------------------------------------------------------------
diff --git a/twill-examples/yarn/pom.xml b/twill-examples/yarn/pom.xml
index 2869e97..b19e4d2 100644
--- a/twill-examples/yarn/pom.xml
+++ b/twill-examples/yarn/pom.xml
@@ -24,7 +24,7 @@ limitations under the License.
     <parent>
         <artifactId>twill-examples</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
 
     <name>Apache Twill examples: YARN</name>

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-ext/pom.xml
----------------------------------------------------------------------
diff --git a/twill-ext/pom.xml b/twill-ext/pom.xml
index e036827..a5265b1 100644
--- a/twill-ext/pom.xml
+++ b/twill-ext/pom.xml
@@ -22,7 +22,7 @@ limitations under the License.
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
 
     <modelVersion>4.0.0</modelVersion>

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-java8-test/pom.xml
----------------------------------------------------------------------
diff --git a/twill-java8-test/pom.xml b/twill-java8-test/pom.xml
index c9d31d1..a47ddcc 100644
--- a/twill-java8-test/pom.xml
+++ b/twill-java8-test/pom.xml
@@ -24,7 +24,7 @@
     <parent>
         <groupId>org.apache.twill</groupId>
         <artifactId>twill-parent</artifactId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
 
     <artifactId>twill-java8-test</artifactId>

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-yarn/pom.xml
----------------------------------------------------------------------
diff --git a/twill-yarn/pom.xml b/twill-yarn/pom.xml
index 5ef06a2..5039617 100644
--- a/twill-yarn/pom.xml
+++ b/twill-yarn/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/983a14a2/twill-zookeeper/pom.xml
----------------------------------------------------------------------
diff --git a/twill-zookeeper/pom.xml b/twill-zookeeper/pom.xml
index 2f018e2..d264a44 100644
--- a/twill-zookeeper/pom.xml
+++ b/twill-zookeeper/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0</version>
+        <version>0.9.0-SNAPSHOT</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 


[03/16] twill git commit: Fix the LocationTest unit tests

Posted by ch...@apache.org.
Fix the LocationTest unit tests

- Hadoop 2.0-alhpa doesn\u2019t support \u201cx\u201d mode in file permission.

This closes #5 on Github

Signed-off-by: Terence Yim <ch...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/9d346aed
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/9d346aed
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/9d346aed

Branch: refs/heads/site
Commit: 9d346aed58de2caf984f94fd9dfd7b6533787107
Parents: 66e4439
Author: Terence Yim <ch...@apache.org>
Authored: Thu Aug 25 19:21:20 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Fri Aug 26 10:10:52 2016 -0700

----------------------------------------------------------------------
 .../twill/filesystem/LocationTestBase.java      | 24 ++++++++++----------
 1 file changed, 12 insertions(+), 12 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/9d346aed/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java b/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java
index 15c28f4..34b7f09 100644
--- a/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java
+++ b/twill-yarn/src/test/java/org/apache/twill/filesystem/LocationTestBase.java
@@ -208,12 +208,12 @@ public abstract class LocationTestBase {
     Assert.assertEquals("rw-rw----", location.getPermissions());
     Assert.assertFalse(location.createNew("600"));
 
-    location = factory.create("test755-1");
-    Assert.assertTrue(location.createNew("755"));
-    Assert.assertEquals("rwxr-xr-x", location.getPermissions());
-    location = factory.create("test755-2");
-    Assert.assertTrue(location.createNew("rwxr-xr-x"));
-    Assert.assertEquals("rwxr-xr-x", location.getPermissions());
+    location = factory.create("test644-1");
+    Assert.assertTrue(location.createNew("644"));
+    Assert.assertEquals("rw-r--r--", location.getPermissions());
+    location = factory.create("test644-2");
+    Assert.assertTrue(location.createNew("rw-r--r--"));
+    Assert.assertEquals("rw-r--r--", location.getPermissions());
     Assert.assertFalse(location.createNew("600"));
 
     // Test permissions setting on getOutputStream calls
@@ -233,12 +233,12 @@ public abstract class LocationTestBase {
     location.getOutputStream("rw-rw----").close();
     Assert.assertEquals("rw-rw----", location.getPermissions());
 
-    location = factory.create("test755-1");
-    location.getOutputStream("755").close();
-    Assert.assertEquals("rwxr-xr-x", location.getPermissions());
-    location = factory.create("test755-2");
-    location.getOutputStream("rwxr-xr-x").close();
-    Assert.assertEquals("rwxr-xr-x", location.getPermissions());
+    location = factory.create("test644-1");
+    location.getOutputStream("644").close();
+    Assert.assertEquals("rw-r--r--", location.getPermissions());
+    location = factory.create("test644-2");
+    location.getOutputStream("rw-r--r--").close();
+    Assert.assertEquals("rw-r--r--", location.getPermissions());
 
     // Test permissions setting on setPermission method
     factory = locationFactoryCache.getUnchecked("permission3");


[06/16] twill git commit: TWILL-175 Avoid caching a YarnClient, since each YarnClient is fixed to a particular UserGroupInformation.

Posted by ch...@apache.org.
TWILL-175 Avoid caching a YarnClient, since each YarnClient is fixed to a particular UserGroupInformation.

This closes #6 on Github

Signed-off-by: Terence Yim <ch...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/4dfd4496
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/4dfd4496
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/4dfd4496

Branch: refs/heads/site
Commit: 4dfd44968452518af73380497d5330d15ed28df6
Parents: 44e6dfd
Author: Ali Anwar <an...@berkeley.edu>
Authored: Thu Aug 25 23:45:39 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Mon Aug 29 15:59:55 2016 -0700

----------------------------------------------------------------------
 .../twill/internal/ProcessController.java       |  2 +-
 .../internal/yarn/Hadoop20YarnAppClient.java    | 44 ++++++++++++--------
 .../internal/yarn/Hadoop21YarnAppClient.java    | 42 +++++++++++--------
 .../appmaster/RunnableProcessLauncher.java      |  5 +++
 .../twill/internal/yarn/YarnAppClient.java      |  3 +-
 .../apache/twill/yarn/YarnTwillController.java  |  2 +-
 .../twill/yarn/YarnTwillRunnerService.java      |  2 -
 .../java/org/apache/twill/yarn/TwillTester.java |  2 -
 8 files changed, 59 insertions(+), 43 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/4dfd4496/twill-core/src/main/java/org/apache/twill/internal/ProcessController.java
----------------------------------------------------------------------
diff --git a/twill-core/src/main/java/org/apache/twill/internal/ProcessController.java b/twill-core/src/main/java/org/apache/twill/internal/ProcessController.java
index 4453838..9a4cbe7 100644
--- a/twill-core/src/main/java/org/apache/twill/internal/ProcessController.java
+++ b/twill-core/src/main/java/org/apache/twill/internal/ProcessController.java
@@ -24,7 +24,7 @@ import org.apache.twill.common.Cancellable;
  *
  * @param <R> Report type.
  */
-public interface ProcessController<R> extends Cancellable {
+public interface ProcessController<R> extends AutoCloseable, Cancellable {
 
   R getReport();
 

http://git-wip-us.apache.org/repos/asf/twill/blob/4dfd4496/twill-yarn/src/main/hadoop20/org/apache/twill/internal/yarn/Hadoop20YarnAppClient.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/hadoop20/org/apache/twill/internal/yarn/Hadoop20YarnAppClient.java b/twill-yarn/src/main/hadoop20/org/apache/twill/internal/yarn/Hadoop20YarnAppClient.java
index bfa494c..bb494d4 100644
--- a/twill-yarn/src/main/hadoop20/org/apache/twill/internal/yarn/Hadoop20YarnAppClient.java
+++ b/twill-yarn/src/main/hadoop20/org/apache/twill/internal/yarn/Hadoop20YarnAppClient.java
@@ -59,21 +59,29 @@ import javax.annotation.Nullable;
  * Apache Hadoop 2.0.
  * </p>
  */
-public final class Hadoop20YarnAppClient extends AbstractIdleService implements YarnAppClient {
+public final class Hadoop20YarnAppClient implements YarnAppClient {
 
   private static final Logger LOG = LoggerFactory.getLogger(Hadoop20YarnAppClient.class);
-  private final YarnClient yarnClient;
+  private final Configuration configuration;
   private String user;
 
   public Hadoop20YarnAppClient(Configuration configuration) {
-    this.yarnClient = new YarnClientImpl();
-    yarnClient.init(configuration);
+    this.configuration = configuration;
     this.user = System.getProperty("user.name");
   }
 
+  // Creates and starts a yarn client
+  private YarnClient createYarnClient() {
+    YarnClient yarnClient = new YarnClientImpl();
+    yarnClient.init(configuration);
+    yarnClient.start();
+    return yarnClient;
+  }
+
   @Override
   public ProcessLauncher<ApplicationMasterInfo> createLauncher(TwillSpecification twillSpec,
                                                                @Nullable String schedulerQueue) throws Exception {
+    final YarnClient yarnClient = createYarnClient();
     // Request for new application
     final GetNewApplicationResponse response = yarnClient.getNewApplication();
     final ApplicationId appId = response.getApplicationId();
@@ -100,7 +108,7 @@ public final class Hadoop20YarnAppClient extends AbstractIdleService implements
       @Override
       public ProcessController<YarnApplicationReport> submit(YarnLaunchContext launchContext) {
         ContainerLaunchContext context = launchContext.getLaunchContext();
-        addRMToken(context);
+        addRMToken(context, yarnClient);
         context.setUser(appSubmissionContext.getUser());
         context.setResource(adjustMemory(response, capability));
         appSubmissionContext.setAMContainerSpec(context);
@@ -131,7 +139,7 @@ public final class Hadoop20YarnAppClient extends AbstractIdleService implements
     return capability;
   }
 
-  private void addRMToken(ContainerLaunchContext context) {
+  private void addRMToken(ContainerLaunchContext context, YarnClient yarnClient) {
     if (!UserGroupInformation.isSecurityEnabled()) {
       return;
     }
@@ -176,22 +184,17 @@ public final class Hadoop20YarnAppClient extends AbstractIdleService implements
 
   @Override
   public ProcessController<YarnApplicationReport> createProcessController(ApplicationId appId) {
-    return new ProcessControllerImpl(yarnClient, appId);
+    return new ProcessControllerImpl(createYarnClient(), appId);
   }
 
   @Override
   public List<NodeReport> getNodeReports() throws Exception {
-    return this.yarnClient.getNodeReports();
-  }
-
-  @Override
-  protected void startUp() throws Exception {
-    yarnClient.start();
-  }
-
-  @Override
-  protected void shutDown() throws Exception {
-    yarnClient.stop();
+    YarnClient yarnClient = createYarnClient();
+    try {
+      return yarnClient.getNodeReports();
+    } finally {
+      yarnClient.stop();
+    }
   }
 
   private static final class ProcessControllerImpl implements ProcessController<YarnApplicationReport> {
@@ -222,5 +225,10 @@ public final class Hadoop20YarnAppClient extends AbstractIdleService implements
         throw Throwables.propagate(e);
       }
     }
+
+    @Override
+    public void close() throws Exception {
+      yarnClient.stop();
+    }
   }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/4dfd4496/twill-yarn/src/main/hadoop21/org/apache/twill/internal/yarn/Hadoop21YarnAppClient.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/hadoop21/org/apache/twill/internal/yarn/Hadoop21YarnAppClient.java b/twill-yarn/src/main/hadoop21/org/apache/twill/internal/yarn/Hadoop21YarnAppClient.java
index 6fd11e5..f24630f 100644
--- a/twill-yarn/src/main/hadoop21/org/apache/twill/internal/yarn/Hadoop21YarnAppClient.java
+++ b/twill-yarn/src/main/hadoop21/org/apache/twill/internal/yarn/Hadoop21YarnAppClient.java
@@ -55,19 +55,27 @@ import javax.annotation.Nullable;
  * Apache Hadoop 2.1 and beyond.
  * </p>
  */
-public final class Hadoop21YarnAppClient extends AbstractIdleService implements YarnAppClient {
+public final class Hadoop21YarnAppClient implements YarnAppClient {
 
   private static final Logger LOG = LoggerFactory.getLogger(Hadoop21YarnAppClient.class);
-  private final YarnClient yarnClient;
+  private final Configuration configuration;
 
   public Hadoop21YarnAppClient(Configuration configuration) {
-    this.yarnClient = YarnClient.createYarnClient();
+    this.configuration = configuration;
+  }
+
+  // Creates and starts a yarn client
+  private YarnClient createYarnClient() {
+    YarnClient yarnClient = YarnClient.createYarnClient();
     yarnClient.init(configuration);
+    yarnClient.start();
+    return yarnClient;
   }
 
   @Override
   public ProcessLauncher<ApplicationMasterInfo> createLauncher(TwillSpecification twillSpec,
                                                                @Nullable String schedulerQueue) throws Exception {
+    final YarnClient yarnClient = createYarnClient();
     // Request for new application
     YarnClientApplication application = yarnClient.createApplication();
     final GetNewApplicationResponse response = application.getNewApplicationResponse();
@@ -93,7 +101,7 @@ public final class Hadoop21YarnAppClient extends AbstractIdleService implements
       public ProcessController<YarnApplicationReport> submit(YarnLaunchContext context) {
         ContainerLaunchContext launchContext = context.getLaunchContext();
 
-        addRMToken(launchContext);
+        addRMToken(launchContext, yarnClient);
         appSubmissionContext.setAMContainerSpec(launchContext);
         appSubmissionContext.setResource(capability);
         appSubmissionContext.setMaxAppAttempts(2);
@@ -122,7 +130,7 @@ public final class Hadoop21YarnAppClient extends AbstractIdleService implements
     return capability;
   }
 
-  private void addRMToken(ContainerLaunchContext context) {
+  private void addRMToken(ContainerLaunchContext context, YarnClient yarnClient) {
     if (!UserGroupInformation.isSecurityEnabled()) {
       return;
     }
@@ -156,22 +164,17 @@ public final class Hadoop21YarnAppClient extends AbstractIdleService implements
 
   @Override
   public ProcessController<YarnApplicationReport> createProcessController(ApplicationId appId) {
-    return new ProcessControllerImpl(yarnClient, appId);
+    return new ProcessControllerImpl(createYarnClient(), appId);
   }
 
   @Override
   public List<NodeReport> getNodeReports() throws Exception {
-    return this.yarnClient.getNodeReports();
-  }
-
-  @Override
-  protected void startUp() throws Exception {
-    yarnClient.start();
-  }
-
-  @Override
-  protected void shutDown() throws Exception {
-    yarnClient.stop();
+    YarnClient yarnClient = createYarnClient();
+    try {
+      return yarnClient.getNodeReports();
+    } finally {
+      yarnClient.stop();
+    }
   }
 
   private static final class ProcessControllerImpl implements ProcessController<YarnApplicationReport> {
@@ -202,5 +205,10 @@ public final class Hadoop21YarnAppClient extends AbstractIdleService implements
         throw Throwables.propagate(e);
       }
     }
+
+    @Override
+    public void close() throws Exception {
+      yarnClient.stop();
+    }
   }
 }

http://git-wip-us.apache.org/repos/asf/twill/blob/4dfd4496/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunnableProcessLauncher.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunnableProcessLauncher.java b/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunnableProcessLauncher.java
index 0e3aea5..e48dcbb 100644
--- a/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunnableProcessLauncher.java
+++ b/twill-yarn/src/main/java/org/apache/twill/internal/appmaster/RunnableProcessLauncher.java
@@ -76,6 +76,11 @@ public final class RunnableProcessLauncher extends AbstractYarnProcessLauncher<Y
 
     return new ProcessController<R>() {
       @Override
+      public void close() throws Exception {
+        // no-op
+      }
+
+      @Override
       public R getReport() {
         // No reporting support for runnable launch yet.
         return null;

http://git-wip-us.apache.org/repos/asf/twill/blob/4dfd4496/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnAppClient.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnAppClient.java b/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnAppClient.java
index df956bf..fbbe350 100644
--- a/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnAppClient.java
+++ b/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnAppClient.java
@@ -17,7 +17,6 @@
  */
 package org.apache.twill.internal.yarn;
 
-import com.google.common.util.concurrent.Service;
 import org.apache.hadoop.yarn.api.records.ApplicationId;
 import org.apache.hadoop.yarn.api.records.NodeReport;
 import org.apache.twill.api.TwillSpecification;
@@ -31,7 +30,7 @@ import javax.annotation.Nullable;
 /**
  * Interface for launching Yarn application from client.
  */
-public interface YarnAppClient extends Service {
+public interface YarnAppClient {
 
   /**
    * Creates a {@link ProcessLauncher} for launching the application represented by the given spec. If scheduler queue

http://git-wip-us.apache.org/repos/asf/twill/blob/4dfd4496/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillController.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillController.java b/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillController.java
index 3efcda4..1dd6c25 100644
--- a/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillController.java
+++ b/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillController.java
@@ -154,7 +154,7 @@ final class YarnTwillController extends AbstractTwillController implements Twill
     }
 
     // Poll application status from yarn
-    try {
+    try (ProcessController<YarnApplicationReport> processController = this.processController) {
       Stopwatch stopWatch = new Stopwatch();
       stopWatch.start();
       long maxTime = TimeUnit.MILLISECONDS.convert(Constants.APPLICATION_MAX_STOP_SECONDS, TimeUnit.SECONDS);

http://git-wip-us.apache.org/repos/asf/twill/blob/4dfd4496/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java b/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java
index 67ee2ac..8c15005 100644
--- a/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java
+++ b/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java
@@ -319,7 +319,6 @@ public final class YarnTwillRunnerService implements TwillRunnerService {
   }
 
   private void startUp() throws Exception {
-    yarnAppClient.startAndWait();
     zkClientService.startAndWait();
 
     // Create the root node, so that the namespace root would get created if it is missing
@@ -357,7 +356,6 @@ public final class YarnTwillRunnerService implements TwillRunnerService {
     }
     watchCancellable.cancel();
     zkClientService.stopAndWait();
-    yarnAppClient.stopAndWait();
   }
 
   private Cancellable watchLiveApps() {

http://git-wip-us.apache.org/repos/asf/twill/blob/4dfd4496/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java b/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java
index a896913..4a2146e 100644
--- a/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java
+++ b/twill-yarn/src/test/java/org/apache/twill/yarn/TwillTester.java
@@ -118,12 +118,10 @@ public class TwillTester extends ExternalResource {
     twillRunner.start();
 
     yarnAppClient = new VersionDetectYarnAppClientFactory().create(conf);
-    yarnAppClient.startAndWait();
   }
 
   @Override
   protected void after() {
-    stopQuietly(yarnAppClient);
     try {
       twillRunner.stop();
     } catch (Exception e) {


[02/16] twill git commit: Update travis.yml to enable building of feature branch.

Posted by ch...@apache.org.
Update travis.yml to enable building of feature branch.

Prefix a branch name with \u201cfeature/\u201c to trigger travis build automatically.
This helps forked repo to run build in travis even before openly a PR.

Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/66e4439d
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/66e4439d
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/66e4439d

Branch: refs/heads/site
Commit: 66e4439dede0155ce7f7364612ca8f69989162e0
Parents: 02a374f
Author: Terence Yim <ch...@apache.org>
Authored: Thu Aug 25 09:19:47 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Thu Aug 25 09:19:47 2016 -0700

----------------------------------------------------------------------
 .travis.yml | 1 +
 1 file changed, 1 insertion(+)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/66e4439d/.travis.yml
----------------------------------------------------------------------
diff --git a/.travis.yml b/.travis.yml
index ed56152..8cb390e 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -26,6 +26,7 @@ branches:
   only:
     - master
     - /^branch\-.*$/
+    - /^feature\/.*$/
 
 script: mvn test -P $PROFILE -Dsurefire.redirectTestOutputToFile=false -Dtwill.zk.server.localhost=false
 


[07/16] twill git commit: TWILL-185 Allow user to avoid scheduling the LocationSecureStoreUpdater.

Posted by ch...@apache.org.
TWILL-185 Allow user to avoid scheduling the LocationSecureStoreUpdater.

Signed-off-by: Terence Yim <ch...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/11e29a8e
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/11e29a8e
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/11e29a8e

Branch: refs/heads/site
Commit: 11e29a8e846ccac3071401746148376223260638
Parents: 4dfd449
Author: Ali Anwar <an...@berkeley.edu>
Authored: Fri Aug 26 00:37:14 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Mon Aug 29 22:40:04 2016 -0700

----------------------------------------------------------------------
 twill-core/src/main/java/org/apache/twill/internal/Configs.java | 5 +++++
 .../main/java/org/apache/twill/yarn/YarnTwillRunnerService.java | 4 +++-
 2 files changed, 8 insertions(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/11e29a8e/twill-core/src/main/java/org/apache/twill/internal/Configs.java
----------------------------------------------------------------------
diff --git a/twill-core/src/main/java/org/apache/twill/internal/Configs.java b/twill-core/src/main/java/org/apache/twill/internal/Configs.java
index f2f9c59..5e7033e 100644
--- a/twill-core/src/main/java/org/apache/twill/internal/Configs.java
+++ b/twill-core/src/main/java/org/apache/twill/internal/Configs.java
@@ -31,6 +31,11 @@ public final class Configs {
      */
     public static final String JAVA_RESERVED_MEMORY_MB = "twill.java.reserved.memory.mb";
 
+    /**
+     * Set this to false to disable the secure store updates done by default.
+     */
+    public static final String SECURE_STORE_UPDATE_LOCATION_ENABLED = "twill.secure.store.update.location.enabled";
+
     private Keys() {
     }
   }

http://git-wip-us.apache.org/repos/asf/twill/blob/11e29a8e/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java b/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java
index 8c15005..79edc65 100644
--- a/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java
+++ b/twill-yarn/src/main/java/org/apache/twill/yarn/YarnTwillRunnerService.java
@@ -65,6 +65,7 @@ import org.apache.twill.common.Threads;
 import org.apache.twill.filesystem.FileContextLocationFactory;
 import org.apache.twill.filesystem.Location;
 import org.apache.twill.filesystem.LocationFactory;
+import org.apache.twill.internal.Configs;
 import org.apache.twill.internal.Constants;
 import org.apache.twill.internal.ProcessController;
 import org.apache.twill.internal.RunIds;
@@ -329,8 +330,9 @@ public final class YarnTwillRunnerService implements TwillRunnerService {
     watchCancellable = watchLiveApps();
     liveInfos = createLiveInfos();
 
+    boolean enableSecureStoreUpdate = yarnConfig.getBoolean(Configs.Keys.SECURE_STORE_UPDATE_LOCATION_ENABLED, true);
     // Schedule an updater for updating HDFS delegation tokens
-    if (UserGroupInformation.isSecurityEnabled()) {
+    if (UserGroupInformation.isSecurityEnabled() && enableSecureStoreUpdate) {
       long renewalInterval = yarnConfig.getLong(DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_KEY,
                                                 DFSConfigKeys.DFS_NAMENODE_DELEGATION_TOKEN_RENEW_INTERVAL_DEFAULT);
       // Schedule it five minutes before it expires.


[12/16] twill git commit: Fix a ClassCastException in YarnUtils.addDelegationTokens.

Posted by ch...@apache.org.
Fix a ClassCastException in YarnUtils.addDelegationTokens.

This closes #11

Signed-off-by: Poorna Chandra <po...@apache.org>


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/2a8de333
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/2a8de333
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/2a8de333

Branch: refs/heads/site
Commit: 2a8de333f4014fbcbcde826e507b9d8810554ffc
Parents: ced2044
Author: Ali Anwar <an...@berkeley.edu>
Authored: Tue Sep 20 22:01:25 2016 -0700
Committer: Poorna Chandra <po...@apache.org>
Committed: Tue Sep 20 23:02:52 2016 -0700

----------------------------------------------------------------------
 .../src/main/java/org/apache/twill/internal/yarn/YarnUtils.java    | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/2a8de333/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnUtils.java
----------------------------------------------------------------------
diff --git a/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnUtils.java b/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnUtils.java
index e63deed..cb81bee 100644
--- a/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnUtils.java
+++ b/twill-yarn/src/main/java/org/apache/twill/internal/yarn/YarnUtils.java
@@ -165,7 +165,7 @@ public class YarnUtils {
         tokens = ImmutableList.copyOf(fsTokens);
       }
     } else if (factory instanceof FileContextLocationFactory) {
-      FileContext fc = ((FileContextLocationFactory) locationFactory).getFileContext();
+      FileContext fc = ((FileContextLocationFactory) factory).getFileContext();
       tokens = fc.getDelegationTokens(new Path(locationFactory.create("/").toURI()), renewer);
     }
 


[05/16] twill git commit: Empty commit to close #2 on Github.

Posted by ch...@apache.org.
Empty commit to close #2 on Github.

This closes #2 on Github.


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/44e6dfd9
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/44e6dfd9
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/44e6dfd9

Branch: refs/heads/site
Commit: 44e6dfd93980f77c08ee2966d207a4a2d7ba03fa
Parents: 069e028
Author: Terence Yim <ch...@apache.org>
Authored: Fri Aug 26 10:13:30 2016 -0700
Committer: Terence Yim <ch...@apache.org>
Committed: Fri Aug 26 10:13:30 2016 -0700

----------------------------------------------------------------------

----------------------------------------------------------------------



[13/16] twill git commit: Prepare for releasing 0.8.0

Posted by ch...@apache.org.
Prepare for releasing 0.8.0


Project: http://git-wip-us.apache.org/repos/asf/twill/repo
Commit: http://git-wip-us.apache.org/repos/asf/twill/commit/264401fa
Tree: http://git-wip-us.apache.org/repos/asf/twill/tree/264401fa
Diff: http://git-wip-us.apache.org/repos/asf/twill/diff/264401fa

Branch: refs/heads/site
Commit: 264401fa60b1ec2c9a1b39e332663869942b48ca
Parents: 2a8de33
Author: Terence Yim <ch...@apache.org>
Authored: Tue Sep 27 00:44:24 2016 -0400
Committer: Terence Yim <ch...@apache.org>
Committed: Tue Sep 27 00:44:24 2016 -0400

----------------------------------------------------------------------
 pom.xml                      | 2 +-
 twill-api/pom.xml            | 2 +-
 twill-common/pom.xml         | 2 +-
 twill-core/pom.xml           | 2 +-
 twill-discovery-api/pom.xml  | 2 +-
 twill-discovery-core/pom.xml | 2 +-
 twill-examples/echo/pom.xml  | 2 +-
 twill-examples/pom.xml       | 2 +-
 twill-examples/yarn/pom.xml  | 2 +-
 twill-ext/pom.xml            | 2 +-
 twill-java8-test/pom.xml     | 2 +-
 twill-yarn/pom.xml           | 2 +-
 twill-zookeeper/pom.xml      | 2 +-
 13 files changed, 13 insertions(+), 13 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index fa60077..21d15bd 100644
--- a/pom.xml
+++ b/pom.xml
@@ -29,7 +29,7 @@
 
     <groupId>org.apache.twill</groupId>
     <artifactId>twill-parent</artifactId>
-    <version>0.8.0-SNAPSHOT</version>
+    <version>0.8.0</version>
     <packaging>pom</packaging>
     <name>Apache Twill</name>
     <url>http://twill.apache.org</url>

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-api/pom.xml
----------------------------------------------------------------------
diff --git a/twill-api/pom.xml b/twill-api/pom.xml
index da7b50e..a98ef9b 100644
--- a/twill-api/pom.xml
+++ b/twill-api/pom.xml
@@ -24,7 +24,7 @@
     <parent>
         <groupId>org.apache.twill</groupId>
         <artifactId>twill-parent</artifactId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
 
     <artifactId>twill-api</artifactId>

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-common/pom.xml
----------------------------------------------------------------------
diff --git a/twill-common/pom.xml b/twill-common/pom.xml
index 927d70b..52e0539 100644
--- a/twill-common/pom.xml
+++ b/twill-common/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-core/pom.xml
----------------------------------------------------------------------
diff --git a/twill-core/pom.xml b/twill-core/pom.xml
index 6c3d878..6becc27 100644
--- a/twill-core/pom.xml
+++ b/twill-core/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-discovery-api/pom.xml
----------------------------------------------------------------------
diff --git a/twill-discovery-api/pom.xml b/twill-discovery-api/pom.xml
index 5d183ea..a4deea2 100644
--- a/twill-discovery-api/pom.xml
+++ b/twill-discovery-api/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-discovery-core/pom.xml
----------------------------------------------------------------------
diff --git a/twill-discovery-core/pom.xml b/twill-discovery-core/pom.xml
index f2ba227..5f65067 100644
--- a/twill-discovery-core/pom.xml
+++ b/twill-discovery-core/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-examples/echo/pom.xml
----------------------------------------------------------------------
diff --git a/twill-examples/echo/pom.xml b/twill-examples/echo/pom.xml
index fe690f6..943c9e9 100644
--- a/twill-examples/echo/pom.xml
+++ b/twill-examples/echo/pom.xml
@@ -25,7 +25,7 @@ limitations under the License.
     <parent>
         <artifactId>twill-examples</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
 
     <name>Apache Twill examples: Echo</name>

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-examples/pom.xml
----------------------------------------------------------------------
diff --git a/twill-examples/pom.xml b/twill-examples/pom.xml
index d466f95..59f0391 100644
--- a/twill-examples/pom.xml
+++ b/twill-examples/pom.xml
@@ -25,7 +25,7 @@ limitations under the License.
     <parent>
         <groupId>org.apache.twill</groupId>
         <artifactId>twill-parent</artifactId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
 
     <artifactId>twill-examples</artifactId>

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-examples/yarn/pom.xml
----------------------------------------------------------------------
diff --git a/twill-examples/yarn/pom.xml b/twill-examples/yarn/pom.xml
index 0777c71..2869e97 100644
--- a/twill-examples/yarn/pom.xml
+++ b/twill-examples/yarn/pom.xml
@@ -24,7 +24,7 @@ limitations under the License.
     <parent>
         <artifactId>twill-examples</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
 
     <name>Apache Twill examples: YARN</name>

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-ext/pom.xml
----------------------------------------------------------------------
diff --git a/twill-ext/pom.xml b/twill-ext/pom.xml
index 80dc8e6..e036827 100644
--- a/twill-ext/pom.xml
+++ b/twill-ext/pom.xml
@@ -22,7 +22,7 @@ limitations under the License.
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
 
     <modelVersion>4.0.0</modelVersion>

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-java8-test/pom.xml
----------------------------------------------------------------------
diff --git a/twill-java8-test/pom.xml b/twill-java8-test/pom.xml
index 1492c60..c9d31d1 100644
--- a/twill-java8-test/pom.xml
+++ b/twill-java8-test/pom.xml
@@ -24,7 +24,7 @@
     <parent>
         <groupId>org.apache.twill</groupId>
         <artifactId>twill-parent</artifactId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
 
     <artifactId>twill-java8-test</artifactId>

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-yarn/pom.xml
----------------------------------------------------------------------
diff --git a/twill-yarn/pom.xml b/twill-yarn/pom.xml
index 5b4ca18..5ef06a2 100644
--- a/twill-yarn/pom.xml
+++ b/twill-yarn/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>
 

http://git-wip-us.apache.org/repos/asf/twill/blob/264401fa/twill-zookeeper/pom.xml
----------------------------------------------------------------------
diff --git a/twill-zookeeper/pom.xml b/twill-zookeeper/pom.xml
index 45178a9..2f018e2 100644
--- a/twill-zookeeper/pom.xml
+++ b/twill-zookeeper/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <artifactId>twill-parent</artifactId>
         <groupId>org.apache.twill</groupId>
-        <version>0.8.0-SNAPSHOT</version>
+        <version>0.8.0</version>
     </parent>
     <modelVersion>4.0.0</modelVersion>