Merge branch 'master' of ssh://gerrit.onlab.us:29418/onos-next
diff --git a/cli/src/main/java/org/onlab/onos/cli/TabletAddCommand.java b/cli/src/main/java/org/onlab/onos/cli/TabletAddCommand.java
new file mode 100644
index 0000000..a7cdff7
--- /dev/null
+++ b/cli/src/main/java/org/onlab/onos/cli/TabletAddCommand.java
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2014 Open Networking Laboratory
+ *
+ * Licensed 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.onlab.onos.cli;
+
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.onlab.onos.cluster.ControllerNode;
+import org.onlab.onos.cluster.DefaultControllerNode;
+import org.onlab.onos.cluster.NodeId;
+import org.onlab.onos.store.service.DatabaseAdminService;
+import org.onlab.packet.IpAddress;
+
+/**
+ * Adds a new controller cluster node.
+ */
+@Command(scope = "onos", name = "tablet-add",
+         description = "Adds a new member to tablet")
+public class TabletAddCommand extends AbstractShellCommand {
+
+    @Argument(index = 0, name = "nodeId", description = "Node ID",
+              required = true, multiValued = false)
+    String nodeId = null;
+
+    // TODO context aware completer to get IP from ClusterService?
+    @Argument(index = 1, name = "ip", description = "Node IP address",
+              required = true, multiValued = false)
+    String ip = null;
+
+    @Argument(index = 2, name = "tcpPort", description = "Node TCP listen port",
+              required = false, multiValued = false)
+    int tcpPort = 9876;
+
+    // TODO add tablet name argument when we support multiple tablets
+
+    @Override
+    protected void execute() {
+        DatabaseAdminService service = get(DatabaseAdminService.class);
+        ControllerNode node = new DefaultControllerNode(new NodeId(nodeId),
+                                                        IpAddress.valueOf(ip),
+                                                        tcpPort);
+        service.addMember(node);
+    }
+}
diff --git a/cli/src/main/java/org/onlab/onos/cli/TabletMemberCommand.java b/cli/src/main/java/org/onlab/onos/cli/TabletMemberCommand.java
new file mode 100644
index 0000000..da42790
--- /dev/null
+++ b/cli/src/main/java/org/onlab/onos/cli/TabletMemberCommand.java
@@ -0,0 +1,72 @@
+/*
+ * Copyright 2014 Open Networking Laboratory
+ *
+ * Licensed 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.onlab.onos.cli;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+
+import org.apache.karaf.shell.commands.Command;
+import org.onlab.onos.cluster.ClusterService;
+import org.onlab.onos.cluster.ControllerNode;
+import org.onlab.onos.store.service.DatabaseAdminService;
+
+import java.util.Collections;
+import java.util.List;
+
+import static com.google.common.collect.Lists.newArrayList;
+
+/**
+ * Lists all controller cluster nodes.
+ */
+@Command(scope = "onos", name = "tablet-member",
+         description = "Lists all member nodes")
+public class TabletMemberCommand extends AbstractShellCommand {
+
+    // TODO add tablet name argument when we support multiple tablets
+
+    @Override
+    protected void execute() {
+        DatabaseAdminService service = get(DatabaseAdminService.class);
+        ClusterService clusterService = get(ClusterService.class);
+        List<ControllerNode> nodes = newArrayList(service.listMembers());
+        Collections.sort(nodes, Comparators.NODE_COMPARATOR);
+        if (outputJson()) {
+            print("%s", json(service, nodes));
+        } else {
+            ControllerNode self = clusterService.getLocalNode();
+            for (ControllerNode node : nodes) {
+                print("id=%s, address=%s:%s %s",
+                      node.id(), node.ip(), node.tcpPort(),
+                      node.equals(self) ? "*" : "");
+            }
+        }
+    }
+
+    // Produces JSON structure.
+    private JsonNode json(DatabaseAdminService service, List<ControllerNode> nodes) {
+        ObjectMapper mapper = new ObjectMapper();
+        ArrayNode result = mapper.createArrayNode();
+        for (ControllerNode node : nodes) {
+            result.add(mapper.createObjectNode()
+                               .put("id", node.id().toString())
+                               .put("ip", node.ip().toString())
+                               .put("tcpPort", node.tcpPort()));
+        }
+        return result;
+    }
+
+}
diff --git a/cli/src/main/java/org/onlab/onos/cli/TabletRemoveCommand.java b/cli/src/main/java/org/onlab/onos/cli/TabletRemoveCommand.java
new file mode 100644
index 0000000..19c669d
--- /dev/null
+++ b/cli/src/main/java/org/onlab/onos/cli/TabletRemoveCommand.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2014 Open Networking Laboratory
+ *
+ * Licensed 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.onlab.onos.cli;
+
+import org.apache.karaf.shell.commands.Argument;
+import org.apache.karaf.shell.commands.Command;
+import org.onlab.onos.cluster.ClusterService;
+import org.onlab.onos.cluster.ControllerNode;
+import org.onlab.onos.cluster.NodeId;
+import org.onlab.onos.store.service.DatabaseAdminService;
+
+/**
+ * Removes a controller cluster node.
+ */
+@Command(scope = "onos", name = "tablet-remove",
+         description = "Removes a member from tablet")
+public class TabletRemoveCommand extends AbstractShellCommand {
+
+    @Argument(index = 0, name = "nodeId", description = "Node ID",
+              required = true, multiValued = false)
+    String nodeId = null;
+
+    // TODO add tablet name argument when we support multiple tablets
+
+    @Override
+    protected void execute() {
+        DatabaseAdminService service = get(DatabaseAdminService.class);
+        ClusterService clusterService = get(ClusterService.class);
+        ControllerNode node = clusterService.getNode(new NodeId(nodeId));
+        if (node != null) {
+            service.removeMember(node);
+        }
+    }
+}
diff --git a/cli/src/main/resources/OSGI-INF/blueprint/shell-config.xml b/cli/src/main/resources/OSGI-INF/blueprint/shell-config.xml
index 2c87b18..e4ecc9d 100644
--- a/cli/src/main/resources/OSGI-INF/blueprint/shell-config.xml
+++ b/cli/src/main/resources/OSGI-INF/blueprint/shell-config.xml
@@ -20,6 +20,26 @@
             <action class="org.onlab.onos.cli.SummaryCommand"/>
         </command>
         <command>
+            <action class="org.onlab.onos.cli.TabletMemberCommand"/>
+        </command>
+        <command>
+            <action class="org.onlab.onos.cli.TabletAddCommand"/>
+            <completers>
+                <ref component-id="nodeIdCompleter"/>
+                <null/>
+                <null/>
+            </completers>
+        </command>
+        <command>
+            <action class="org.onlab.onos.cli.TabletRemoveCommand"/>
+            <completers>
+                <ref component-id="nodeIdCompleter"/>
+                <null/>
+                <null/>
+            </completers>
+        </command>
+
+        <command>
             <action class="org.onlab.onos.cli.NodesListCommand"/>
         </command>
         <command>
diff --git a/core/api/src/main/java/org/onlab/onos/store/service/DatabaseAdminService.java b/core/api/src/main/java/org/onlab/onos/store/service/DatabaseAdminService.java
index 3ec4e9b..40d12ff 100644
--- a/core/api/src/main/java/org/onlab/onos/store/service/DatabaseAdminService.java
+++ b/core/api/src/main/java/org/onlab/onos/store/service/DatabaseAdminService.java
@@ -1,7 +1,10 @@
 package org.onlab.onos.store.service;
 
+import java.util.Collection;
 import java.util.List;
 
+import org.onlab.onos.cluster.ControllerNode;
+
 /**
  * Service interface for running administrative tasks on a Database.
  */
@@ -32,4 +35,26 @@
      * Deletes all tables from the database.
      */
     public void dropAllTables();
+
+
+    /**
+     * Add member to default Tablet.
+     *
+     * @param node to add
+     */
+    public void addMember(ControllerNode node);
+
+    /**
+     * Remove member from default Tablet.
+     *
+     * @param node node to remove
+     */
+    public void removeMember(ControllerNode node);
+
+    /**
+     * List members forming default Tablet.
+     *
+     * @return Copied collection of members forming default Tablet.
+     */
+    public Collection<ControllerNode> listMembers();
 }
diff --git a/core/store/dist/src/main/java/org/onlab/onos/store/flow/package-info.java b/core/store/dist/src/main/java/org/onlab/onos/store/flow/package-info.java
new file mode 100644
index 0000000..2bf1407
--- /dev/null
+++ b/core/store/dist/src/main/java/org/onlab/onos/store/flow/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2014 Open Networking Laboratory
+ *
+ * Licensed 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.
+ */
+
+/**
+ * Definitions of events and messages pertaining to replication of flow entries.
+ */
+package org.onlab.onos.store.flow;
diff --git a/core/store/dist/src/main/java/org/onlab/onos/store/hz/StoreManager.java b/core/store/dist/src/main/java/org/onlab/onos/store/hz/StoreManager.java
index b598616..6256364 100644
--- a/core/store/dist/src/main/java/org/onlab/onos/store/hz/StoreManager.java
+++ b/core/store/dist/src/main/java/org/onlab/onos/store/hz/StoreManager.java
@@ -17,6 +17,7 @@
 
 import com.hazelcast.config.Config;
 import com.hazelcast.config.FileSystemXmlConfig;
+import com.hazelcast.config.MapConfig;
 import com.hazelcast.core.Hazelcast;
 import com.hazelcast.core.HazelcastInstance;
 
@@ -46,6 +47,13 @@
     public void activate() {
         try {
             Config config = new FileSystemXmlConfig(HAZELCAST_XML_FILE);
+
+            MapConfig roles = config.getMapConfig("nodeRoles");
+            roles.setAsyncBackupCount(MapConfig.MAX_BACKUP_COUNT - roles.getBackupCount());
+
+            MapConfig terms = config.getMapConfig("terms");
+            terms.setAsyncBackupCount(MapConfig.MAX_BACKUP_COUNT - terms.getBackupCount());
+
             instance = Hazelcast.newHazelcastInstance(config);
             log.info("Started");
         } catch (FileNotFoundException e) {
diff --git a/core/store/dist/src/main/java/org/onlab/onos/store/intent/impl/package-info.java b/core/store/dist/src/main/java/org/onlab/onos/store/intent/impl/package-info.java
new file mode 100644
index 0000000..a58e86f
--- /dev/null
+++ b/core/store/dist/src/main/java/org/onlab/onos/store/intent/impl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2014 Open Networking Laboratory
+ *
+ * Licensed 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.
+ */
+
+/**
+ * Implementation of distributed intent store.
+ */
+package org.onlab.onos.store.intent.impl;
diff --git a/core/store/dist/src/main/java/org/onlab/onos/store/serializers/impl/package-info.java b/core/store/dist/src/main/java/org/onlab/onos/store/serializers/impl/package-info.java
new file mode 100644
index 0000000..fcec959
--- /dev/null
+++ b/core/store/dist/src/main/java/org/onlab/onos/store/serializers/impl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2014 Open Networking Laboratory
+ *
+ * Licensed 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.
+ */
+
+/**
+ * Cluster messaging and distributed store serializers.
+ */
+package org.onlab.onos.store.serializers.impl;
diff --git a/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/ClusterMessagingProtocol.java b/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/ClusterMessagingProtocol.java
index f8243c7..6b7b7ff 100644
--- a/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/ClusterMessagingProtocol.java
+++ b/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/ClusterMessagingProtocol.java
@@ -169,7 +169,9 @@
     @Override
     public ProtocolClient createClient(TcpMember member) {
         ControllerNode remoteNode = getControllerNode(member.host(), member.port());
-        checkNotNull(remoteNode, "A valid controller node is expected");
+        checkNotNull(remoteNode,
+                     "A valid controller node is expected for %s:%s",
+                     member.host(), member.port());
         return new ClusterMessagingProtocolClient(
                 clusterCommunicator, clusterService.getLocalNode(), remoteNode);
     }
diff --git a/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/DatabaseClient.java b/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/DatabaseClient.java
index c2beb59..c749197 100644
--- a/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/DatabaseClient.java
+++ b/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/DatabaseClient.java
@@ -1,15 +1,12 @@
 package org.onlab.onos.store.service.impl;
 
-import java.util.Arrays;
+import static com.google.common.base.Preconditions.checkNotNull;
+
 import java.util.List;
-import java.util.UUID;
 import java.util.concurrent.CompletableFuture;
 import java.util.concurrent.ExecutionException;
 
-import net.kuujo.copycat.protocol.Response.Status;
-import net.kuujo.copycat.protocol.SubmitRequest;
-import net.kuujo.copycat.protocol.SubmitResponse;
-import net.kuujo.copycat.spi.protocol.ProtocolClient;
+import net.kuujo.copycat.Copycat;
 
 import org.onlab.onos.store.service.DatabaseException;
 import org.onlab.onos.store.service.ReadRequest;
@@ -20,31 +17,17 @@
  */
 public class DatabaseClient {
 
-    private final ProtocolClient client;
+    private final Copycat copycat;
 
-    public DatabaseClient(ProtocolClient client) {
-        this.client = client;
-    }
-
-    private static String nextId() {
-        return UUID.randomUUID().toString();
+    public DatabaseClient(Copycat copycat) {
+        this.copycat = checkNotNull(copycat);
     }
 
     public boolean createTable(String tableName) {
 
-        SubmitRequest request =
-                new SubmitRequest(
-                        nextId(),
-                        "createTable",
-                        Arrays.asList(tableName));
-        CompletableFuture<SubmitResponse> future = client.submit(request);
+        CompletableFuture<Boolean> future = copycat.submit("createTable", tableName);
         try {
-            final SubmitResponse submitResponse = future.get();
-            if (submitResponse.status() == Status.OK) {
-                return (boolean) submitResponse.result();
-            } else {
-                throw new DatabaseException(submitResponse.error());
-            }
+            return future.get();
         } catch (InterruptedException | ExecutionException e) {
             throw new DatabaseException(e);
         }
@@ -52,17 +35,9 @@
 
     public void dropTable(String tableName) {
 
-        SubmitRequest request =
-                new SubmitRequest(
-                        nextId(),
-                        "dropTable",
-                        Arrays.asList(tableName));
-        CompletableFuture<SubmitResponse> future = client.submit(request);
+        CompletableFuture<Void> future = copycat.submit("dropTable", tableName);
         try {
-            if (future.get().status() != Status.OK) {
-                throw new DatabaseException(future.get().toString());
-            }
-
+            future.get();
         } catch (InterruptedException | ExecutionException e) {
             throw new DatabaseException(e);
         }
@@ -70,79 +45,39 @@
 
     public void dropAllTables() {
 
-        SubmitRequest request =
-                new SubmitRequest(
-                        nextId(),
-                        "dropAllTables",
-                        Arrays.asList());
-        CompletableFuture<SubmitResponse> future = client.submit(request);
+        CompletableFuture<Void> future = copycat.submit("dropAllTables");
         try {
-            if (future.get().status() != Status.OK) {
-                throw new DatabaseException(future.get().toString());
-            }
+            future.get();
         } catch (InterruptedException | ExecutionException e) {
             throw new DatabaseException(e);
         }
     }
 
-    @SuppressWarnings("unchecked")
     public List<String> listTables() {
 
-        SubmitRequest request =
-                new SubmitRequest(
-                        nextId(),
-                        "listTables",
-                        Arrays.asList());
-        CompletableFuture<SubmitResponse> future = client.submit(request);
+        CompletableFuture<List<String>> future = copycat.submit("listTables");
         try {
-            final SubmitResponse submitResponse = future.get();
-            if (submitResponse.status() == Status.OK) {
-                return (List<String>) submitResponse.result();
-            } else {
-                throw new DatabaseException(submitResponse.error());
-            }
+            return future.get();
         } catch (InterruptedException | ExecutionException e) {
             throw new DatabaseException(e);
         }
     }
 
-    @SuppressWarnings("unchecked")
     public List<InternalReadResult> batchRead(List<ReadRequest> requests) {
 
-        SubmitRequest request = new SubmitRequest(
-                        nextId(),
-                        "read",
-                        Arrays.asList(requests));
-
-        CompletableFuture<SubmitResponse> future = client.submit(request);
+        CompletableFuture<List<InternalReadResult>> future = copycat.submit("read", requests);
         try {
-            final SubmitResponse submitResponse = future.get();
-            if (submitResponse.status() == Status.OK) {
-                return (List<InternalReadResult>) submitResponse.result();
-            } else {
-                throw new DatabaseException(submitResponse.error());
-            }
+            return future.get();
         } catch (InterruptedException | ExecutionException e) {
             throw new DatabaseException(e);
         }
     }
 
-    @SuppressWarnings("unchecked")
     public List<InternalWriteResult> batchWrite(List<WriteRequest> requests) {
 
-        SubmitRequest request = new SubmitRequest(
-                        nextId(),
-                        "write",
-                        Arrays.asList(requests));
-
-        CompletableFuture<SubmitResponse> future = client.submit(request);
+        CompletableFuture<List<InternalWriteResult>> future = copycat.submit("write", requests);
         try {
-            final SubmitResponse submitResponse = future.get();
-            if (submitResponse.status() == Status.OK) {
-                return (List<InternalWriteResult>) submitResponse.result();
-            } else {
-                throw new DatabaseException(submitResponse.error());
-            }
+            return future.get();
         } catch (InterruptedException | ExecutionException e) {
             throw new DatabaseException(e);
         }
diff --git a/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/DatabaseManager.java b/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/DatabaseManager.java
index def56e8..0d06e08 100644
--- a/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/DatabaseManager.java
+++ b/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/DatabaseManager.java
@@ -2,15 +2,23 @@
 
 import static org.slf4j.LoggerFactory.getLogger;
 
+import java.io.File;
+import java.io.IOException;
 import java.util.ArrayList;
 import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
 import java.util.List;
+import java.util.Map;
+import java.util.Set;
 import java.util.concurrent.CountDownLatch;
 import java.util.concurrent.TimeUnit;
 
 import net.kuujo.copycat.Copycat;
 import net.kuujo.copycat.StateMachine;
 import net.kuujo.copycat.cluster.ClusterConfig;
+import net.kuujo.copycat.cluster.Member;
 import net.kuujo.copycat.cluster.TcpCluster;
 import net.kuujo.copycat.cluster.TcpClusterConfig;
 import net.kuujo.copycat.cluster.TcpMember;
@@ -27,6 +35,8 @@
 import org.onlab.onos.cluster.ClusterEventListener;
 import org.onlab.onos.cluster.ClusterService;
 import org.onlab.onos.cluster.ControllerNode;
+import org.onlab.onos.cluster.DefaultControllerNode;
+import org.onlab.onos.cluster.NodeId;
 import org.onlab.onos.store.service.DatabaseAdminService;
 import org.onlab.onos.store.service.DatabaseException;
 import org.onlab.onos.store.service.DatabaseService;
@@ -38,8 +48,11 @@
 import org.onlab.onos.store.service.WriteAborted;
 import org.onlab.onos.store.service.WriteRequest;
 import org.onlab.onos.store.service.WriteResult;
+import org.onlab.packet.IpAddress;
 import org.slf4j.Logger;
 
+import com.google.common.collect.ImmutableList;
+
 /**
  * Strongly consistent and durable state management service based on
  * Copycat implementation of Raft consensus protocol.
@@ -56,7 +69,19 @@
     @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
     protected DatabaseProtocolService copycatMessagingProtocol;
 
-    public static final String LOG_FILE_PREFIX = "/tmp/onos-copy-cat-log";
+    public static final String LOG_FILE_PREFIX = "/tmp/onos-copy-cat-log_";
+
+    // Current working dir seems to be /opt/onos/apache-karaf-3.0.2
+    // TODO: Get the path to /opt/onos/config
+    private static final String CONFIG_DIR = "../config";
+
+    private static final String DEFAULT_MEMBER_FILE = "tablets.json";
+
+    private static final String DEFAULT_TABLET = "default";
+
+    // TODO: make this configurable
+    // initial member configuration file path
+    private String initialMemberConfig = DEFAULT_MEMBER_FILE;
 
     private Copycat copycat;
     private DatabaseClient client;
@@ -65,49 +90,61 @@
     private ClusterConfig<TcpMember> clusterConfig;
 
     private CountDownLatch clusterEventLatch;
-
     private ClusterEventListener clusterEventListener;
 
+    private Map<String, Set<DefaultControllerNode>> tabletMembers;
+
+    private boolean autoAddMember = false;
+
     @Activate
     public void activate() {
 
         // TODO: Not every node should be part of the consensus ring.
 
-        final ControllerNode localNode = clusterService.getLocalNode();
-        TcpMember localMember =
-                new TcpMember(
-                        localNode.ip().toString(),
-                        localNode.tcpPort());
+        // load tablet configuration
+        File file = new File(CONFIG_DIR, initialMemberConfig);
+        log.info("Loading config: {}", file.getAbsolutePath());
+        TabletDefinitionStore tabletDef = new TabletDefinitionStore(file);
+        try {
+            tabletMembers = tabletDef.read();
+        } catch (IOException e) {
+            log.error("Failed to load tablet config {}", file);
+            throw new IllegalStateException("Failed to load tablet config", e);
+        }
 
+        // load default tablet configuration and start copycat
         clusterConfig = new TcpClusterConfig();
-        clusterConfig.setLocalMember(localMember);
+        Set<DefaultControllerNode> defaultMember = tabletMembers.get(DEFAULT_TABLET);
+        if (defaultMember == null || defaultMember.isEmpty()) {
+            log.error("No member found in [{}] tablet configuration.",
+                      DEFAULT_TABLET);
+            throw new IllegalStateException("No member found in tablet configuration");
 
-        List<TcpMember> remoteMembers = new ArrayList<>(clusterService.getNodes().size());
+        }
 
+        final ControllerNode localNode = clusterService.getLocalNode();
+        for (ControllerNode member : defaultMember) {
+            final TcpMember tcpMember = new TcpMember(member.ip().toString(),
+                                                      member.tcpPort());
+            if (localNode.equals(member)) {
+                clusterConfig.setLocalMember(tcpMember);
+            } else {
+                clusterConfig.addRemoteMember(tcpMember);
+            }
+        }
+
+        // note: from this point beyond, clusterConfig requires synchronization
         clusterEventLatch = new CountDownLatch(1);
         clusterEventListener = new InternalClusterEventListener();
         clusterService.addListener(clusterEventListener);
 
-        // note: from this point beyond, clusterConfig requires synchronization
-
-        for (ControllerNode node : clusterService.getNodes()) {
-            TcpMember member = new TcpMember(node.ip().toString(), node.tcpPort());
-            if (!member.equals(localMember)) {
-                remoteMembers.add(member);
-            }
-        }
-
-        if (remoteMembers.isEmpty()) {
-            log.info("This node is the only node in the cluster.  "
-                    + "Waiting for others to show up.");
-            // FIXME: hack trying to relax cases forming multiple consensus rings.
-            // add seed node configuration to avoid this
-
-            // If the node is alone on it's own, wait some time
-            // hoping other will come up soon
+        if (clusterService.getNodes().size() < clusterConfig.getMembers().size()) {
+            // current cluster size smaller then expected
             try {
                 if (!clusterEventLatch.await(120, TimeUnit.SECONDS)) {
-                    log.info("Starting as single node cluster");
+                    log.info("Starting with {}/{} nodes cluster",
+                             clusterService.getNodes().size(),
+                             clusterConfig.getMembers().size());
                 }
             } catch (InterruptedException e) {
                 log.info("Interrupted waiting for others", e);
@@ -116,8 +153,6 @@
 
         final TcpCluster cluster;
         synchronized (clusterConfig) {
-            clusterConfig.addRemoteMembers(remoteMembers);
-
             // Create the cluster.
             cluster = new TcpCluster(clusterConfig);
         }
@@ -125,16 +160,13 @@
 
 
         StateMachine stateMachine = new DatabaseStateMachine();
-        // Chronicle + OSGi issue
-        //Log consensusLog = new ChronicleLog(LOG_FILE_PREFIX + "_" + thisNode.id());
-        //Log consensusLog = new KryoRegisteredInMemoryLog();
         Log consensusLog = new MapDBLog(LOG_FILE_PREFIX + localNode.id(),
                                         ClusterMessagingProtocol.SERIALIZER);
 
         copycat = new Copycat(stateMachine, consensusLog, cluster, copycatMessagingProtocol);
         copycat.start();
 
-        client = new DatabaseClient(copycatMessagingProtocol.createClient(localMember));
+        client = new DatabaseClient(copycat);
 
         log.info("Started.");
     }
@@ -236,20 +268,33 @@
             final TcpMember tcpMember = new TcpMember(node.ip().toString(),
                                                       node.tcpPort());
 
-            log.trace("{}", event);
             switch (event.type()) {
             case INSTANCE_ACTIVATED:
             case INSTANCE_ADDED:
-                log.info("{} was added to the cluster", tcpMember);
-                synchronized (clusterConfig) {
-                    clusterConfig.addRemoteMember(tcpMember);
+                if (autoAddMember) {
+                    synchronized (clusterConfig) {
+                        if (!clusterConfig.getMembers().contains(tcpMember)) {
+                            log.info("{} was automatically added to the cluster", tcpMember);
+                            clusterConfig.addRemoteMember(tcpMember);
+                        }
+                    }
                 }
                 break;
             case INSTANCE_DEACTIVATED:
             case INSTANCE_REMOVED:
-                log.info("{} was removed from the cluster", tcpMember);
-                synchronized (clusterConfig) {
-                    clusterConfig.removeRemoteMember(tcpMember);
+                if (autoAddMember) {
+                    Set<DefaultControllerNode> members
+                        = tabletMembers.getOrDefault(DEFAULT_TABLET,
+                                                     Collections.emptySet());
+                    // remove only if not the initial members
+                    if (!members.contains(node)) {
+                        synchronized (clusterConfig) {
+                            if (clusterConfig.getMembers().contains(tcpMember)) {
+                                log.info("{} was automatically removed from the cluster", tcpMember);
+                                clusterConfig.removeRemoteMember(tcpMember);
+                            }
+                        }
+                    }
                 }
                 break;
             default:
@@ -309,4 +354,58 @@
             }
         }
     }
+
+    @Override
+    public void addMember(final ControllerNode node) {
+        final TcpMember tcpMember = new TcpMember(node.ip().toString(),
+                                                  node.tcpPort());
+        log.info("{} was added to the cluster", tcpMember);
+        synchronized (clusterConfig) {
+            clusterConfig.addRemoteMember(tcpMember);
+        }
+    }
+
+    @Override
+    public void removeMember(final ControllerNode node) {
+        final TcpMember tcpMember = new TcpMember(node.ip().toString(),
+                                                  node.tcpPort());
+      log.info("{} was removed from the cluster", tcpMember);
+      synchronized (clusterConfig) {
+          clusterConfig.removeRemoteMember(tcpMember);
+      }
+    }
+
+    @Override
+    public Collection<ControllerNode> listMembers() {
+        if (copycat == null) {
+            return ImmutableList.of();
+        }
+        Set<ControllerNode> members = new HashSet<>();
+        for (Member member : copycat.cluster().members()) {
+            if (member instanceof TcpMember) {
+                final TcpMember tcpMember = (TcpMember) member;
+                // TODO assuming tcpMember#host to be IP address,
+                // but if not lookup DNS, etc. first
+                IpAddress ip = IpAddress.valueOf(tcpMember.host());
+                int tcpPort = tcpMember.port();
+                NodeId id = getNodeIdFromIp(ip, tcpPort);
+                if (id == null) {
+                    log.info("No NodeId found for {}:{}", ip, tcpPort);
+                    continue;
+                }
+                members.add(new DefaultControllerNode(id, ip, tcpPort));
+            }
+        }
+        return members;
+    }
+
+    private NodeId getNodeIdFromIp(IpAddress ip, int tcpPort) {
+        for (ControllerNode node : clusterService.getNodes()) {
+            if (node.ip().equals(ip) &&
+                node.tcpPort() == tcpPort) {
+                return node.id();
+            }
+        }
+        return null;
+    }
 }
diff --git a/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/TabletDefinitionStore.java b/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/TabletDefinitionStore.java
new file mode 100644
index 0000000..6d3d45e
--- /dev/null
+++ b/core/store/dist/src/main/java/org/onlab/onos/store/service/impl/TabletDefinitionStore.java
@@ -0,0 +1,141 @@
+/*
+ * Copyright 2014 Open Networking Laboratory
+ *
+ * Licensed 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.onlab.onos.store.service.impl;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.slf4j.LoggerFactory.getLogger;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+
+import org.onlab.onos.cluster.DefaultControllerNode;
+import org.onlab.onos.cluster.NodeId;
+import org.onlab.packet.IpAddress;
+import org.slf4j.Logger;
+
+import com.fasterxml.jackson.core.JsonEncoding;
+import com.fasterxml.jackson.core.JsonFactory;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+
+/**
+ * Allows for reading and writing tablet definition as a JSON file.
+ */
+public class TabletDefinitionStore {
+
+    private final Logger log = getLogger(getClass());
+
+    private final File file;
+
+    /**
+     * Creates a reader/writer of the tablet definition file.
+     *
+     * @param filePath location of the definition file
+     */
+    public TabletDefinitionStore(String filePath) {
+        file = new File(filePath);
+    }
+
+    /**
+     * Creates a reader/writer of the tablet definition file.
+     *
+     * @param filePath location of the definition file
+     */
+    public TabletDefinitionStore(File filePath) {
+        file = checkNotNull(filePath);
+    }
+
+    /**
+     * Returns the Map from tablet name to set of initial member nodes.
+     *
+     * @return Map from tablet name to set of initial member nodes
+     * @throws IOException when I/O exception of some sort has occurred.
+     */
+    public Map<String, Set<DefaultControllerNode>> read() throws IOException {
+
+        final Map<String, Set<DefaultControllerNode>> tablets = new HashMap<>();
+
+        final ObjectMapper mapper = new ObjectMapper();
+        final ObjectNode tabletNodes = (ObjectNode) mapper.readTree(file);
+        final Iterator<Entry<String, JsonNode>> fields = tabletNodes.fields();
+        while (fields.hasNext()) {
+            final Entry<String, JsonNode> next = fields.next();
+            final Set<DefaultControllerNode> nodes = new HashSet<>();
+            final Iterator<JsonNode> elements = next.getValue().elements();
+            while (elements.hasNext()) {
+                ObjectNode nodeDef = (ObjectNode) elements.next();
+                nodes.add(new DefaultControllerNode(new NodeId(nodeDef.get("id").asText()),
+                                                    IpAddress.valueOf(nodeDef.get("ip").asText()),
+                                                    nodeDef.get("tcpPort").asInt(9876)));
+            }
+
+            tablets.put(next.getKey(), nodes);
+        }
+        return tablets;
+    }
+
+    /**
+     * Updates the Map from tablet name to set of member nodes.
+     *
+     * @param tabletName name of the tablet to update
+     * @param nodes set of initial member nodes
+     * @throws IOException when I/O exception of some sort has occurred.
+     */
+    public void write(String tabletName, Set<DefaultControllerNode> nodes) throws IOException {
+        checkNotNull(tabletName);
+        checkArgument(tabletName.isEmpty(), "Tablet name cannot be empty");
+        // TODO should validate if tabletName is allowed in JSON
+
+        // load current
+        Map<String, Set<DefaultControllerNode>> config;
+        try {
+            config = read();
+        } catch (IOException e) {
+            log.info("Reading tablet config failed, assuming empty definition.");
+            config = new HashMap<>();
+        }
+        // update with specified
+        config.put(tabletName, nodes);
+
+        // write back to file
+        final ObjectMapper mapper = new ObjectMapper();
+        final ObjectNode tabletNodes = mapper.createObjectNode();
+        for (Entry<String, Set<DefaultControllerNode>> tablet : config.entrySet()) {
+            ArrayNode nodeDefs = mapper.createArrayNode();
+            tabletNodes.set(tablet.getKey(), nodeDefs);
+
+            for (DefaultControllerNode node : tablet.getValue()) {
+                ObjectNode nodeDef = mapper.createObjectNode();
+                nodeDef.put("id", node.id().toString())
+                       .put("ip", node.ip().toString())
+                       .put("tcpPort", node.tcpPort());
+                nodeDefs.add(nodeDef);
+            }
+        }
+        mapper.writeTree(new JsonFactory().createGenerator(file, JsonEncoding.UTF8),
+                         tabletNodes);
+    }
+
+}
diff --git a/docs/pom.xml b/docs/pom.xml
index 655cc31..b49f157 100644
--- a/docs/pom.xml
+++ b/docs/pom.xml
@@ -61,7 +61,13 @@
                         <group>
                             <title>Core Subsystems</title>
                             <packages>
-                                org.onlab.onos.impl:org.onlab.onos.cluster.impl:org.onlab.onos.net.device.impl:org.onlab.onos.net.link.impl:org.onlab.onos.net.host.impl:org.onlab.onos.net.topology.impl:org.onlab.onos.net.packet.impl:org.onlab.onos.net.flow.impl:org.onlab.onos.store.trivial.*:org.onlab.onos.net.*.impl:org.onlab.onos.event.impl:org.onlab.onos.store.*:org.onlab.onos.net.intent.impl:org.onlab.onos.net.proxyarp.impl:org.onlab.onos.mastership.impl:org.onlab.onos.json:org.onlab.onos.json.*:org.onlab.onos.provider.host.impl:org.onlab.onos.provider.lldp.impl:org.onlab.onos.net.statistic.impl
+                                org.onlab.onos.impl:org.onlab.onos.core.impl:org.onlab.onos.cluster.impl:org.onlab.onos.net.device.impl:org.onlab.onos.net.link.impl:org.onlab.onos.net.host.impl:org.onlab.onos.net.topology.impl:org.onlab.onos.net.packet.impl:org.onlab.onos.net.flow.impl:org.onlab.onos.net.*.impl:org.onlab.onos.event.impl:org.onlab.onos.net.intent.impl:org.onlab.onos.net.proxyarp.impl:org.onlab.onos.mastership.impl:org.onlab.onos.net.resource.impl:org.onlab.onos.json:org.onlab.onos.json.*:org.onlab.onos.provider.host.impl:org.onlab.onos.provider.lldp.impl:org.onlab.onos.net.statistic.impl
+                            </packages>
+                        </group>
+                        <group>
+                            <title>Distributed Stores</title>
+                            <packages>
+                                org.onlab.onos.store.*
                             </packages>
                         </group>
                         <group>
@@ -92,12 +98,11 @@
                         <group>
                             <title>Test Instrumentation</title>
                             <packages>
-                                org.onlab.onos.metrics.*:org.onlab.onos.oecfg
+                                org.onlab.onos.metrics.*
                             </packages>
                         </group>
                     </groups>
-                    <excludePackageNames>org.onlab.thirdparty
-                    </excludePackageNames>
+                    <excludePackageNames>org.onlab.thirdparty:org.onlab.onos.oecfg</excludePackageNames>
                 </configuration>
             </plugin>
         </plugins>
diff --git a/tools/package/config/README b/tools/package/config/README
new file mode 100644
index 0000000..62b758d
--- /dev/null
+++ b/tools/package/config/README
@@ -0,0 +1,2 @@
+onos-config command will copy files contained in this directory to ONOS instances according to cell definition
+
diff --git a/tools/test/bin/onos-config b/tools/test/bin/onos-config
index a8ef4fe..b72bb8c 100755
--- a/tools/test/bin/onos-config
+++ b/tools/test/bin/onos-config
@@ -25,3 +25,18 @@
         >> $ONOS_INSTALL_DIR/$KARAF_DIST/etc/system.properties
 "
 scp -q $CDEF_FILE $remote:$ONOS_INSTALL_DIR/config/
+
+# Generate a default tablets.json from the ON* environment variables
+TDEF_FILE=/tmp/tablets.json
+echo "{ \"default\":[" > $TDEF_FILE
+for node in $(env | sort | egrep "OC[2-9]+" | cut -d= -f2); do
+    echo "  { \"id\": \"$node\", \"ip\": \"$node\", \"tcpPort\": 9876 }," >> $TDEF_FILE
+done
+echo "  { \"id\": \"$OC1\", \"ip\": \"$OC1\", \"tcpPort\": 9876 }" >> $TDEF_FILE
+echo "]}" >> $TDEF_FILE
+scp -q $TDEF_FILE $remote:$ONOS_INSTALL_DIR/config/
+
+
+# copy tools/package/config/ to remote
+scp -qr ${ONOS_ROOT}/tools/package/config/ $remote:$ONOS_INSTALL_DIR/
+
diff --git a/utils/misc/src/main/java/org/onlab/api/ItemNotFoundException.java b/utils/misc/src/main/java/org/onlab/util/ItemNotFoundException.java
similarity index 97%
rename from utils/misc/src/main/java/org/onlab/api/ItemNotFoundException.java
rename to utils/misc/src/main/java/org/onlab/util/ItemNotFoundException.java
index fe484d4..01440ab 100644
--- a/utils/misc/src/main/java/org/onlab/api/ItemNotFoundException.java
+++ b/utils/misc/src/main/java/org/onlab/util/ItemNotFoundException.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.onlab.api;
+package org.onlab.util;
 
 /**
  * Represents condition where an item is not found or not available.
diff --git a/web/api/src/main/java/org/onlab/onos/rest/AbstractWebResource.java b/web/api/src/main/java/org/onlab/onos/rest/AbstractWebResource.java
index ee9adb0..b36bb1b 100644
--- a/web/api/src/main/java/org/onlab/onos/rest/AbstractWebResource.java
+++ b/web/api/src/main/java/org/onlab/onos/rest/AbstractWebResource.java
@@ -17,7 +17,7 @@
 
 import com.fasterxml.jackson.databind.ObjectMapper;
 import com.fasterxml.jackson.databind.node.ObjectNode;
-import org.onlab.api.ItemNotFoundException;
+import org.onlab.util.ItemNotFoundException;
 import org.onlab.onos.codec.CodecContext;
 import org.onlab.onos.codec.CodecService;
 import org.onlab.onos.codec.JsonCodec;
@@ -69,7 +69,7 @@
      * @param message not found message
      * @param <T>     item type
      * @return item if not null
-     * @throws org.onlab.api.ItemNotFoundException if item is null
+     * @throws org.onlab.util.ItemNotFoundException if item is null
      */
     protected <T> T nullIsNotFound(T item, String message) {
         if (item == null) {
diff --git a/web/api/src/main/java/org/onlab/onos/rest/exceptions/EntityNotFoundMapper.java b/web/api/src/main/java/org/onlab/onos/rest/exceptions/EntityNotFoundMapper.java
index 4c86fe6..192a2e0 100644
--- a/web/api/src/main/java/org/onlab/onos/rest/exceptions/EntityNotFoundMapper.java
+++ b/web/api/src/main/java/org/onlab/onos/rest/exceptions/EntityNotFoundMapper.java
@@ -15,7 +15,7 @@
  */
 package org.onlab.onos.rest.exceptions;
 
-import org.onlab.api.ItemNotFoundException;
+import org.onlab.util.ItemNotFoundException;
 
 import javax.ws.rs.core.Response;
 
diff --git a/web/gui/src/main/java/org/onlab/onos/gui/TopologyMessages.java b/web/gui/src/main/java/org/onlab/onos/gui/TopologyMessages.java
new file mode 100644
index 0000000..0b54dd8
--- /dev/null
+++ b/web/gui/src/main/java/org/onlab/onos/gui/TopologyMessages.java
@@ -0,0 +1,375 @@
+/*
+ * Copyright 2014 Open Networking Laboratory
+ *
+ * Licensed 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.onlab.onos.gui;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+import com.fasterxml.jackson.databind.node.ObjectNode;
+import org.onlab.onos.cluster.ClusterEvent;
+import org.onlab.onos.cluster.ClusterService;
+import org.onlab.onos.cluster.ControllerNode;
+import org.onlab.onos.cluster.NodeId;
+import org.onlab.onos.mastership.MastershipService;
+import org.onlab.onos.net.Annotations;
+import org.onlab.onos.net.ConnectPoint;
+import org.onlab.onos.net.DefaultEdgeLink;
+import org.onlab.onos.net.Device;
+import org.onlab.onos.net.DeviceId;
+import org.onlab.onos.net.EdgeLink;
+import org.onlab.onos.net.Host;
+import org.onlab.onos.net.HostId;
+import org.onlab.onos.net.HostLocation;
+import org.onlab.onos.net.Link;
+import org.onlab.onos.net.Path;
+import org.onlab.onos.net.device.DeviceEvent;
+import org.onlab.onos.net.device.DeviceService;
+import org.onlab.onos.net.host.HostEvent;
+import org.onlab.onos.net.host.HostService;
+import org.onlab.onos.net.intent.IntentService;
+import org.onlab.onos.net.link.LinkEvent;
+import org.onlab.onos.net.link.LinkService;
+import org.onlab.onos.net.provider.ProviderId;
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.packet.IpAddress;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+
+import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onlab.onos.cluster.ClusterEvent.Type.INSTANCE_ADDED;
+import static org.onlab.onos.cluster.ClusterEvent.Type.INSTANCE_REMOVED;
+import static org.onlab.onos.cluster.ControllerNode.State.ACTIVE;
+import static org.onlab.onos.net.PortNumber.portNumber;
+import static org.onlab.onos.net.device.DeviceEvent.Type.DEVICE_ADDED;
+import static org.onlab.onos.net.device.DeviceEvent.Type.DEVICE_REMOVED;
+import static org.onlab.onos.net.host.HostEvent.Type.HOST_ADDED;
+import static org.onlab.onos.net.host.HostEvent.Type.HOST_REMOVED;
+import static org.onlab.onos.net.link.LinkEvent.Type.LINK_ADDED;
+import static org.onlab.onos.net.link.LinkEvent.Type.LINK_REMOVED;
+
+/**
+ * Facility for creating messages bound for the topology viewer.
+ */
+public abstract class TopologyMessages {
+
+    private static final ProviderId PID = new ProviderId("core", "org.onlab.onos.core", true);
+    private static final String COMPACT = "%s/%s-%s/%s";
+
+    protected final ServiceDirectory directory;
+    protected final ClusterService clusterService;
+    protected final DeviceService deviceService;
+    protected final LinkService linkService;
+    protected final HostService hostService;
+    protected final MastershipService mastershipService;
+    protected final IntentService intentService;
+
+    protected final ObjectMapper mapper = new ObjectMapper();
+
+    // TODO: extract into an external & durable state; good enough for now and demo
+    private static Map<String, ObjectNode> metaUi = new ConcurrentHashMap<>();
+
+    /**
+     * Creates a messaging facility for creating messages for topology viewer.
+     *
+     * @param directory service directory
+     */
+    protected TopologyMessages(ServiceDirectory directory) {
+        this.directory = checkNotNull(directory, "Directory cannot be null");
+        clusterService = directory.get(ClusterService.class);
+        deviceService = directory.get(DeviceService.class);
+        linkService = directory.get(LinkService.class);
+        hostService = directory.get(HostService.class);
+        mastershipService = directory.get(MastershipService.class);
+        intentService = directory.get(IntentService.class);
+    }
+
+    // Retrieves the payload from the specified event.
+    protected ObjectNode payload(ObjectNode event) {
+        return (ObjectNode) event.path("payload");
+    }
+
+    // Returns the specified node property as a number
+    protected long number(ObjectNode node, String name) {
+        return node.path(name).asLong();
+    }
+
+    // Returns the specified node property as a string.
+    protected String string(ObjectNode node, String name) {
+        return node.path(name).asText();
+    }
+
+    // Returns the specified node property as a string.
+    protected String string(ObjectNode node, String name, String defaultValue) {
+        return node.path(name).asText(defaultValue);
+    }
+
+    // Returns the specified set of IP addresses as a string.
+    private String ip(Set<IpAddress> ipAddresses) {
+        Iterator<IpAddress> it = ipAddresses.iterator();
+        return it.hasNext() ? it.next().toString() : "unknown";
+    }
+
+    // Produces JSON structure from annotations.
+    private JsonNode props(Annotations annotations) {
+        ObjectNode props = mapper.createObjectNode();
+        for (String key : annotations.keys()) {
+            props.put(key, annotations.value(key));
+        }
+        return props;
+    }
+
+    // Produces an informational log message event bound to the client.
+    protected ObjectNode info(long id, String message) {
+        return message("info", id, message);
+    }
+
+    // Produces a warning log message event bound to the client.
+    protected ObjectNode warning(long id, String message) {
+        return message("warning", id, message);
+    }
+
+    // Produces an error log message event bound to the client.
+    protected ObjectNode error(long id, String message) {
+        return message("error", id, message);
+    }
+
+    // Produces a log message event bound to the client.
+    private ObjectNode message(String severity, long id, String message) {
+        return envelope("message", id,
+                        mapper.createObjectNode()
+                                .put("severity", severity)
+                                .put("message", message));
+    }
+
+    // Puts the payload into an envelope and returns it.
+    protected ObjectNode envelope(String type, long sid, ObjectNode payload) {
+        ObjectNode event = mapper.createObjectNode();
+        event.put("event", type);
+        if (sid > 0) {
+            event.put("sid", sid);
+        }
+        event.set("payload", payload);
+        return event;
+    }
+
+    // Produces a cluster instance message to the client.
+    protected ObjectNode instanceMessage(ClusterEvent event) {
+        ControllerNode node = event.subject();
+        ObjectNode payload = mapper.createObjectNode()
+                .put("id", node.id().toString())
+                .put("online", clusterService.getState(node.id()) == ACTIVE);
+
+        ArrayNode labels = mapper.createArrayNode();
+        labels.add(node.id().toString());
+        labels.add(node.ip().toString());
+
+        // Add labels, props and stuff the payload into envelope.
+        payload.set("labels", labels);
+        addMetaUi(node.id().toString(), payload);
+
+        String type = (event.type() == INSTANCE_ADDED) ? "addInstance" :
+                ((event.type() == INSTANCE_REMOVED) ? "removeInstance" : "updateInstance");
+        return envelope(type, 0, payload);
+    }
+
+    // Produces a device event message to the client.
+    protected ObjectNode deviceMessage(DeviceEvent event) {
+        Device device = event.subject();
+        ObjectNode payload = mapper.createObjectNode()
+                .put("id", device.id().toString())
+                .put("type", device.type().toString().toLowerCase())
+                .put("online", deviceService.isAvailable(device.id()))
+                .put("master", mastershipService.getMasterFor(device.id()).toString());
+
+        // Generate labels: id, chassis id, no-label, optional-name
+        ArrayNode labels = mapper.createArrayNode();
+        labels.add(device.id().toString());
+        labels.add(device.chassisId().toString());
+        labels.add(""); // compact no-label view
+        labels.add(device.annotations().value("name"));
+
+        // Add labels, props and stuff the payload into envelope.
+        payload.set("labels", labels);
+        payload.set("props", props(device.annotations()));
+        addMetaUi(device.id().toString(), payload);
+
+        String type = (event.type() == DEVICE_ADDED) ? "addDevice" :
+                ((event.type() == DEVICE_REMOVED) ? "removeDevice" : "updateDevice");
+        return envelope(type, 0, payload);
+    }
+
+    // Produces a link event message to the client.
+    protected ObjectNode linkMessage(LinkEvent event) {
+        Link link = event.subject();
+        ObjectNode payload = mapper.createObjectNode()
+                .put("id", compactLinkString(link))
+                .put("type", link.type().toString().toLowerCase())
+                .put("linkWidth", 2)
+                .put("src", link.src().deviceId().toString())
+                .put("srcPort", link.src().port().toString())
+                .put("dst", link.dst().deviceId().toString())
+                .put("dstPort", link.dst().port().toString());
+        String type = (event.type() == LINK_ADDED) ? "addLink" :
+                ((event.type() == LINK_REMOVED) ? "removeLink" : "updateLink");
+        return envelope(type, 0, payload);
+    }
+
+    // Produces a host event message to the client.
+    protected ObjectNode hostMessage(HostEvent event) {
+        Host host = event.subject();
+        ObjectNode payload = mapper.createObjectNode()
+                .put("id", host.id().toString())
+                .put("ingress", compactLinkString(edgeLink(host, true)))
+                .put("egress", compactLinkString(edgeLink(host, false)));
+        payload.set("cp", location(mapper, host.location()));
+        payload.set("labels", labels(mapper, ip(host.ipAddresses()),
+                                     host.mac().toString()));
+        payload.set("props", props(host.annotations()));
+        addMetaUi(host.id().toString(), payload);
+
+        String type = (event.type() == HOST_ADDED) ? "addHost" :
+                ((event.type() == HOST_REMOVED) ? "removeHost" : "updateHost");
+        return envelope(type, 0, payload);
+    }
+
+    // Encodes the specified host location into a JSON object.
+    private ObjectNode location(ObjectMapper mapper, HostLocation location) {
+        return mapper.createObjectNode()
+                .put("device", location.deviceId().toString())
+                .put("port", location.port().toLong());
+    }
+
+    // Encodes the specified list of labels a JSON array.
+    private ArrayNode labels(ObjectMapper mapper, String... labels) {
+        ArrayNode json = mapper.createArrayNode();
+        for (String label : labels) {
+            json.add(label);
+        }
+        return json;
+    }
+
+    // Generates an edge link from the specified host location.
+    private EdgeLink edgeLink(Host host, boolean ingress) {
+        return new DefaultEdgeLink(PID, new ConnectPoint(host.id(), portNumber(0)),
+                                   host.location(), ingress);
+    }
+
+    // Adds meta UI information for the specified object.
+    private void addMetaUi(String id, ObjectNode payload) {
+        ObjectNode meta = metaUi.get(id);
+        if (meta != null) {
+            payload.set("metaUi", meta);
+        }
+    }
+
+    // Updates meta UI information for the specified object.
+    protected void updateMetaUi(ObjectNode event) {
+        ObjectNode payload = payload(event);
+        metaUi.put(string(payload, "id"), payload);
+    }
+
+    // Returns device details response.
+    protected ObjectNode deviceDetails(DeviceId deviceId, long sid) {
+        Device device = deviceService.getDevice(deviceId);
+        Annotations annot = device.annotations();
+        int portCount = deviceService.getPorts(deviceId).size();
+        NodeId master = mastershipService.getMasterFor(device.id());
+        return envelope("showDetails", sid,
+                        json(deviceId.toString(),
+                             device.type().toString().toLowerCase(),
+                             new Prop("Name", annot.value("name")),
+                             new Prop("Vendor", device.manufacturer()),
+                             new Prop("H/W Version", device.hwVersion()),
+                             new Prop("S/W Version", device.swVersion()),
+                             new Prop("Serial Number", device.serialNumber()),
+                             new Separator(),
+                             new Prop("Latitude", annot.value("latitude")),
+                             new Prop("Longitude", annot.value("longitude")),
+                             new Prop("Ports", Integer.toString(portCount)),
+                             new Separator(),
+                             new Prop("Master", master.toString())));
+    }
+
+    // Returns host details response.
+    protected ObjectNode hostDetails(HostId hostId, long sid) {
+        Host host = hostService.getHost(hostId);
+        Annotations annot = host.annotations();
+        return envelope("showDetails", sid,
+                        json(hostId.toString(), "host",
+                             new Prop("MAC", host.mac().toString()),
+                             new Prop("IP", host.ipAddresses().toString()),
+                             new Separator(),
+                             new Prop("Latitude", annot.value("latitude")),
+                             new Prop("Longitude", annot.value("longitude"))));
+    }
+
+
+    // Produces a path message to the client.
+    protected ObjectNode pathMessage(Path path) {
+        ObjectNode payload = mapper.createObjectNode();
+        ArrayNode links = mapper.createArrayNode();
+        for (Link link : path.links()) {
+            links.add(compactLinkString(link));
+        }
+
+        payload.set("links", links);
+        return payload;
+    }
+
+    // Produces compact string representation of a link.
+    private static String compactLinkString(Link link) {
+        return String.format(COMPACT, link.src().elementId(), link.src().port(),
+                             link.dst().elementId(), link.dst().port());
+    }
+
+    // Produces JSON property details.
+    private ObjectNode json(String id, String type, Prop... props) {
+        ObjectMapper mapper = new ObjectMapper();
+        ObjectNode result = mapper.createObjectNode()
+                .put("id", id).put("type", type);
+        ObjectNode pnode = mapper.createObjectNode();
+        ArrayNode porder = mapper.createArrayNode();
+        for (Prop p : props) {
+            porder.add(p.key);
+            pnode.put(p.key, p.value);
+        }
+        result.set("propOrder", porder);
+        result.set("props", pnode);
+        return result;
+    }
+
+    // Auxiliary key/value carrier.
+    private class Prop {
+        public final String key;
+        public final String value;
+
+        protected Prop(String key, String value) {
+            this.key = key;
+            this.value = value;
+        }
+    }
+
+    // Auxiliary properties separator
+    private class Separator extends Prop {
+        protected Separator() {
+            super("-", "");
+        }
+    }
+
+}
diff --git a/web/gui/src/main/java/org/onlab/onos/gui/TopologyWebSocket.java b/web/gui/src/main/java/org/onlab/onos/gui/TopologyWebSocket.java
index f433691..83e54b4 100644
--- a/web/gui/src/main/java/org/onlab/onos/gui/TopologyWebSocket.java
+++ b/web/gui/src/main/java/org/onlab/onos/gui/TopologyWebSocket.java
@@ -15,158 +15,94 @@
  */
 package org.onlab.onos.gui;
 
-import com.fasterxml.jackson.databind.JsonNode;
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.fasterxml.jackson.databind.node.ArrayNode;
 import com.fasterxml.jackson.databind.node.ObjectNode;
 import org.eclipse.jetty.websocket.WebSocket;
+import org.onlab.onos.cluster.ClusterEvent;
+import org.onlab.onos.cluster.ClusterEventListener;
+import org.onlab.onos.cluster.ControllerNode;
 import org.onlab.onos.core.ApplicationId;
 import org.onlab.onos.core.CoreService;
 import org.onlab.onos.mastership.MastershipEvent;
 import org.onlab.onos.mastership.MastershipListener;
-import org.onlab.onos.mastership.MastershipService;
-import org.onlab.onos.net.Annotations;
-import org.onlab.onos.net.ConnectPoint;
-import org.onlab.onos.net.DefaultEdgeLink;
 import org.onlab.onos.net.Device;
-import org.onlab.onos.net.DeviceId;
-import org.onlab.onos.net.ElementId;
 import org.onlab.onos.net.Host;
 import org.onlab.onos.net.HostId;
-import org.onlab.onos.net.HostLocation;
 import org.onlab.onos.net.Link;
 import org.onlab.onos.net.Path;
 import org.onlab.onos.net.device.DeviceEvent;
 import org.onlab.onos.net.device.DeviceListener;
-import org.onlab.onos.net.device.DeviceService;
 import org.onlab.onos.net.flow.DefaultTrafficSelector;
 import org.onlab.onos.net.flow.DefaultTrafficTreatment;
 import org.onlab.onos.net.host.HostEvent;
 import org.onlab.onos.net.host.HostListener;
-import org.onlab.onos.net.host.HostService;
 import org.onlab.onos.net.intent.HostToHostIntent;
 import org.onlab.onos.net.intent.Intent;
 import org.onlab.onos.net.intent.IntentEvent;
 import org.onlab.onos.net.intent.IntentId;
 import org.onlab.onos.net.intent.IntentListener;
-import org.onlab.onos.net.intent.IntentService;
 import org.onlab.onos.net.intent.PathIntent;
 import org.onlab.onos.net.link.LinkEvent;
 import org.onlab.onos.net.link.LinkListener;
-import org.onlab.onos.net.link.LinkService;
-import org.onlab.onos.net.provider.ProviderId;
-import org.onlab.onos.net.topology.PathService;
 import org.onlab.osgi.ServiceDirectory;
-import org.onlab.packet.IpAddress;
 
 import java.io.IOException;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.Set;
 import java.util.concurrent.ConcurrentHashMap;
 
-import static com.google.common.base.Preconditions.checkNotNull;
+import static org.onlab.onos.cluster.ClusterEvent.Type.INSTANCE_ADDED;
 import static org.onlab.onos.net.DeviceId.deviceId;
 import static org.onlab.onos.net.HostId.hostId;
-import static org.onlab.onos.net.PortNumber.portNumber;
 import static org.onlab.onos.net.device.DeviceEvent.Type.DEVICE_ADDED;
-import static org.onlab.onos.net.device.DeviceEvent.Type.DEVICE_REMOVED;
 import static org.onlab.onos.net.host.HostEvent.Type.HOST_ADDED;
-import static org.onlab.onos.net.host.HostEvent.Type.HOST_REMOVED;
 import static org.onlab.onos.net.link.LinkEvent.Type.LINK_ADDED;
-import static org.onlab.onos.net.link.LinkEvent.Type.LINK_REMOVED;
 
 /**
  * Web socket capable of interacting with the GUI topology view.
  */
-public class TopologyWebSocket implements WebSocket.OnTextMessage {
+public class TopologyWebSocket
+        extends TopologyMessages implements WebSocket.OnTextMessage {
 
     private static final String APP_ID = "org.onlab.onos.gui";
-    private static final ProviderId PID = new ProviderId("core", "org.onlab.onos.core", true);
 
     private final ApplicationId appId;
-    private final ServiceDirectory directory;
-
-    private final ObjectMapper mapper = new ObjectMapper();
 
     private Connection connection;
 
-    private final DeviceService deviceService;
-    private final LinkService linkService;
-    private final HostService hostService;
-    private final MastershipService mastershipService;
-    private final IntentService intentService;
-
+    private final ClusterEventListener clusterListener = new InternalClusterListener();
     private final DeviceListener deviceListener = new InternalDeviceListener();
     private final LinkListener linkListener = new InternalLinkListener();
     private final HostListener hostListener = new InternalHostListener();
     private final MastershipListener mastershipListener = new InternalMastershipListener();
     private final IntentListener intentListener = new InternalIntentListener();
 
-    // TODO: extract into an external & durable state; good enough for now and demo
-    private static Map<String, ObjectNode> metaUi = new ConcurrentHashMap<>();
-
     // Intents that are being monitored for the GUI
     private static Map<IntentId, Long> intentsToMonitor = new ConcurrentHashMap<>();
 
-    private static final String COMPACT = "%s/%s-%s/%s";
-
-
     /**
      * Creates a new web-socket for serving data to GUI topology view.
      *
      * @param directory service directory
      */
     public TopologyWebSocket(ServiceDirectory directory) {
-        this.directory = checkNotNull(directory, "Directory cannot be null");
-        deviceService = directory.get(DeviceService.class);
-        linkService = directory.get(LinkService.class);
-        hostService = directory.get(HostService.class);
-        mastershipService = directory.get(MastershipService.class);
-        intentService = directory.get(IntentService.class);
-
+        super(directory);
         appId = directory.get(CoreService.class).registerApplication(APP_ID);
     }
 
     @Override
     public void onOpen(Connection connection) {
         this.connection = connection;
-        deviceService.addListener(deviceListener);
-        linkService.addListener(linkListener);
-        hostService.addListener(hostListener);
-        mastershipService.addListener(mastershipListener);
-        intentService.addListener(intentListener);
+        addListeners();
 
+        sendAllInstances();
         sendAllDevices();
         sendAllLinks();
         sendAllHosts();
     }
 
-    private void sendAllHosts() {
-        for (Host host : hostService.getHosts()) {
-            sendMessage(hostMessage(new HostEvent(HOST_ADDED, host)));
-        }
-    }
-
-    private void sendAllDevices() {
-        for (Device device : deviceService.getDevices()) {
-            sendMessage(deviceMessage(new DeviceEvent(DEVICE_ADDED, device)));
-        }
-    }
-
-    private void sendAllLinks() {
-        for (Link link : linkService.getLinks()) {
-            sendMessage(linkMessage(new LinkEvent(LINK_ADDED, link)));
-        }
-    }
-
     @Override
     public void onClose(int closeCode, String message) {
-        deviceService.removeListener(deviceListener);
-        linkService.removeListener(linkListener);
-        hostService.removeListener(hostListener);
-        mastershipService.removeListener(mastershipListener);
+        removeListeners();
     }
 
     @Override
@@ -177,7 +113,7 @@
             if (type.equals("showDetails")) {
                 showDetails(event);
             } else if (type.equals("updateMeta")) {
-                updateMetaInformation(event);
+                updateMetaUi(event);
             } else if (type.equals("requestPath")) {
                 createHostIntent(event);
             } else if (type.equals("requestTraffic")) {
@@ -200,74 +136,32 @@
         }
     }
 
-    // Retrieves the payload from the specified event.
-    private ObjectNode payload(ObjectNode event) {
-        return (ObjectNode) event.path("payload");
-    }
-
-    // Returns the specified node property as a number
-    private long number(ObjectNode node, String name) {
-        return node.path(name).asLong();
-    }
-
-    // Returns the specified node property as a string.
-    private String string(ObjectNode node, String name) {
-        return node.path(name).asText();
-    }
-
-    // Returns the specified node property as a string.
-    private String string(ObjectNode node, String name, String defaultValue) {
-        return node.path(name).asText(defaultValue);
-    }
-
-    // Returns the specified set of IP addresses as a string.
-    private String ip(Set<IpAddress> ipAddresses) {
-        Iterator<IpAddress> it = ipAddresses.iterator();
-        return it.hasNext() ? it.next().toString() : "unknown";
-    }
-
-    // Encodes the specified host location into a JSON object.
-    private ObjectNode location(ObjectMapper mapper, HostLocation location) {
-        return mapper.createObjectNode()
-                .put("device", location.deviceId().toString())
-                .put("port", location.port().toLong());
-    }
-
-    // Encodes the specified list of labels a JSON array.
-    private ArrayNode labels(ObjectMapper mapper, String... labels) {
-        ArrayNode json = mapper.createArrayNode();
-        for (String label : labels) {
-            json.add(label);
+    // Sends all controller nodes to the client as node-added messages.
+    private void sendAllInstances() {
+        for (ControllerNode node : clusterService.getNodes()) {
+            sendMessage(instanceMessage(new ClusterEvent(INSTANCE_ADDED, node)));
         }
-        return json;
     }
 
-    // Produces JSON structure from annotations.
-    private JsonNode props(Annotations annotations) {
-        ObjectNode props = mapper.createObjectNode();
-        for (String key : annotations.keys()) {
-            props.put(key, annotations.value(key));
+    // Sends all devices to the client as device-added messages.
+    private void sendAllDevices() {
+        for (Device device : deviceService.getDevices()) {
+            sendMessage(deviceMessage(new DeviceEvent(DEVICE_ADDED, device)));
         }
-        return props;
     }
 
-    // Produces a log message event bound to the client.
-    private ObjectNode message(String severity, long id, String message) {
-        return envelope("message", id,
-                        mapper.createObjectNode()
-                                .put("severity", severity)
-                                .put("message", message));
-    }
-
-    // Puts the payload into an envelope and returns it.
-    private ObjectNode envelope(String type, long sid, ObjectNode payload) {
-        ObjectNode event = mapper.createObjectNode();
-        event.put("event", type);
-        if (sid > 0) {
-            event.put("sid", sid);
+    // Sends all links to the client as link-added messages.
+    private void sendAllLinks() {
+        for (Link link : linkService.getLinks()) {
+            sendMessage(linkMessage(new LinkEvent(LINK_ADDED, link)));
         }
-        event.set("payload", payload);
-        return event;
+    }
+
+    // Sends all hosts to the client as host-added messages.
+    private void sendAllHosts() {
+        for (Host host : hostService.getHosts()) {
+            sendMessage(hostMessage(new HostEvent(HOST_ADDED, host)));
+        }
     }
 
     // Sends back device or host details.
@@ -283,12 +177,6 @@
         }
     }
 
-    // Updates device/host meta information.
-    private void updateMetaInformation(ObjectNode event) {
-        ObjectNode payload = payload(event);
-        metaUi.put(string(payload, "id"), payload);
-    }
-
     // Creates host-to-host intent.
     private void createHostIntent(ObjectNode event) {
         ObjectNode payload = payload(event);
@@ -314,7 +202,7 @@
             payload.put("traffic", true);
             sendMessage(envelope("showPath", id, payload));
         } else {
-            sendMessage(message("warn", id, "No path found"));
+            sendMessage(warning(id, "No path found"));
         }
     }
 
@@ -323,178 +211,35 @@
         // TODO: implement this
     }
 
-    // Finds the path between the specified devices.
-    private ObjectNode findPath(DeviceId one, DeviceId two) {
-        PathService pathService = directory.get(PathService.class);
-        Set<Path> paths = pathService.getPaths(one, two);
-        if (paths.isEmpty()) {
-            return null;
-        } else {
-            return pathMessage(paths.iterator().next());
+
+    // Adds all internal listeners.
+    private void addListeners() {
+        clusterService.addListener(clusterListener);
+        deviceService.addListener(deviceListener);
+        linkService.addListener(linkListener);
+        hostService.addListener(hostListener);
+        mastershipService.addListener(mastershipListener);
+        intentService.addListener(intentListener);
+    }
+
+    // Removes all internal listeners.
+    private void removeListeners() {
+        clusterService.removeListener(clusterListener);
+        deviceService.removeListener(deviceListener);
+        linkService.removeListener(linkListener);
+        hostService.removeListener(hostListener);
+        mastershipService.removeListener(mastershipListener);
+    }
+
+    // Cluster event listener.
+    private class InternalClusterListener implements ClusterEventListener {
+        @Override
+        public void event(ClusterEvent event) {
+            sendMessage(instanceMessage(event));
         }
     }
 
-    // Produces a path message to the client.
-    private ObjectNode pathMessage(Path path) {
-        ObjectNode payload = mapper.createObjectNode();
-        ArrayNode links = mapper.createArrayNode();
-        for (Link link : path.links()) {
-            links.add(compactLinkString(link));
-        }
-
-        payload.set("links", links);
-        return payload;
-    }
-
-    /**
-     * Returns a compact string representing the given link.
-     *
-     * @param link infrastructure link
-     * @return formatted link string
-     */
-    public static String compactLinkString(Link link) {
-        return String.format(COMPACT, link.src().elementId(), link.src().port(),
-                             link.dst().elementId(), link.dst().port());
-    }
-
-
-    // Produces a link event message to the client.
-    private ObjectNode deviceMessage(DeviceEvent event) {
-        Device device = event.subject();
-        ObjectNode payload = mapper.createObjectNode()
-                .put("id", device.id().toString())
-                .put("type", device.type().toString().toLowerCase())
-                .put("online", deviceService.isAvailable(device.id()));
-
-        // Generate labels: id, chassis id, no-label, optional-name
-        ArrayNode labels = mapper.createArrayNode();
-        labels.add(device.id().toString());
-        labels.add(device.chassisId().toString());
-        labels.add(""); // compact no-label view
-        labels.add(device.annotations().value("name"));
-
-        // Add labels, props and stuff the payload into envelope.
-        payload.set("labels", labels);
-        payload.set("props", props(device.annotations()));
-        addMetaUi(device.id(), payload);
-
-        String type = (event.type() == DEVICE_ADDED) ? "addDevice" :
-                ((event.type() == DEVICE_REMOVED) ? "removeDevice" : "updateDevice");
-        return envelope(type, 0, payload);
-    }
-
-    // Produces a link event message to the client.
-    private ObjectNode linkMessage(LinkEvent event) {
-        Link link = event.subject();
-        ObjectNode payload = mapper.createObjectNode()
-                .put("id", compactLinkString(link))
-                .put("type", link.type().toString().toLowerCase())
-                .put("linkWidth", 2)
-                .put("src", link.src().deviceId().toString())
-                .put("srcPort", link.src().port().toString())
-                .put("dst", link.dst().deviceId().toString())
-                .put("dstPort", link.dst().port().toString());
-        String type = (event.type() == LINK_ADDED) ? "addLink" :
-                ((event.type() == LINK_REMOVED) ? "removeLink" : "updateLink");
-        return envelope(type, 0, payload);
-    }
-
-    // Produces a host event message to the client.
-    private ObjectNode hostMessage(HostEvent event) {
-        Host host = event.subject();
-        ObjectNode payload = mapper.createObjectNode()
-                .put("id", host.id().toString())
-                .put("ingress", compactLinkString(edgeLink(host, true)))
-                .put("egress", compactLinkString(edgeLink(host, false)));
-        payload.set("cp", location(mapper, host.location()));
-        payload.set("labels", labels(mapper, ip(host.ipAddresses()),
-                                     host.mac().toString()));
-        payload.set("props", props(host.annotations()));
-        addMetaUi(host.id(), payload);
-
-        String type = (event.type() == HOST_ADDED) ? "addHost" :
-                ((event.type() == HOST_REMOVED) ? "removeHost" : "updateHost");
-        return envelope(type, 0, payload);
-    }
-
-    private DefaultEdgeLink edgeLink(Host host, boolean ingress) {
-        return new DefaultEdgeLink(PID, new ConnectPoint(host.id(), portNumber(0)),
-                                   host.location(), ingress);
-    }
-
-    private void addMetaUi(ElementId id, ObjectNode payload) {
-        ObjectNode meta = metaUi.get(id.toString());
-        if (meta != null) {
-            payload.set("metaUi", meta);
-        }
-    }
-
-
-    // Returns device details response.
-    private ObjectNode deviceDetails(DeviceId deviceId, long sid) {
-        Device device = deviceService.getDevice(deviceId);
-        Annotations annot = device.annotations();
-        int portCount = deviceService.getPorts(deviceId).size();
-        return envelope("showDetails", sid,
-                        json(deviceId.toString(),
-                             device.type().toString().toLowerCase(),
-                             new Prop("Name", annot.value("name")),
-                             new Prop("Vendor", device.manufacturer()),
-                             new Prop("H/W Version", device.hwVersion()),
-                             new Prop("S/W Version", device.swVersion()),
-                             new Prop("Serial Number", device.serialNumber()),
-                             new Separator(),
-                             new Prop("Latitude", annot.value("latitude")),
-                             new Prop("Longitude", annot.value("longitude")),
-                             new Prop("Ports", Integer.toString(portCount))));
-    }
-
-    // Returns host details response.
-    private ObjectNode hostDetails(HostId hostId, long sid) {
-        Host host = hostService.getHost(hostId);
-        Annotations annot = host.annotations();
-        return envelope("showDetails", sid,
-                        json(hostId.toString(), "host",
-                             new Prop("MAC", host.mac().toString()),
-                             new Prop("IP", host.ipAddresses().toString()),
-                             new Separator(),
-                             new Prop("Latitude", annot.value("latitude")),
-                             new Prop("Longitude", annot.value("longitude"))));
-    }
-
-    // Produces JSON property details.
-    private ObjectNode json(String id, String type, Prop... props) {
-        ObjectMapper mapper = new ObjectMapper();
-        ObjectNode result = mapper.createObjectNode()
-                .put("id", id).put("type", type);
-        ObjectNode pnode = mapper.createObjectNode();
-        ArrayNode porder = mapper.createArrayNode();
-        for (Prop p : props) {
-            porder.add(p.key);
-            pnode.put(p.key, p.value);
-        }
-        result.set("propOrder", porder);
-        result.set("props", pnode);
-        return result;
-    }
-
-    // Auxiliary key/value carrier.
-    private class Prop {
-        private final String key;
-        private final String value;
-
-        protected Prop(String key, String value) {
-            this.key = key;
-            this.value = value;
-        }
-    }
-
-    private class Separator extends Prop {
-        protected Separator() {
-            super("-", "");
-        }
-    }
-
+    // Device event listener.
     private class InternalDeviceListener implements DeviceListener {
         @Override
         public void event(DeviceEvent event) {
@@ -502,6 +247,7 @@
         }
     }
 
+    // Link event listener.
     private class InternalLinkListener implements LinkListener {
         @Override
         public void event(LinkEvent event) {
@@ -509,6 +255,7 @@
         }
     }
 
+    // Host event listener.
     private class InternalHostListener implements HostListener {
         @Override
         public void event(HostEvent event) {
@@ -516,13 +263,15 @@
         }
     }
 
+    // Mastership event listener.
     private class InternalMastershipListener implements MastershipListener {
         @Override
         public void event(MastershipEvent event) {
-
+            // TODO: Is DeviceEvent.Type.DEVICE_MASTERSHIP_CHANGED the same?
         }
     }
 
+    // Intent event listener.
     private class InternalIntentListener implements IntentListener {
         @Override
         public void event(IntentEvent event) {
@@ -539,5 +288,6 @@
             }
         }
     }
+
 }
 
diff --git a/web/gui/src/main/webapp/json/ev/simple/ev_10_onos.json b/web/gui/src/main/webapp/json/ev/simple/ev_10_onos.json
new file mode 100644
index 0000000..f09cc9b
--- /dev/null
+++ b/web/gui/src/main/webapp/json/ev/simple/ev_10_onos.json
@@ -0,0 +1,15 @@
+{
+  "event": "updateLink",
+  "payload": {
+    "id": "of:0000ffffffff0003/21-of:0000ffffffff0008/20",
+    "type": "direct",
+    "linkWidth": 6,
+    "src": "of:0000ffffffff0003",
+    "srcPort": "21",
+    "dst": "of:0000ffffffff0008",
+    "dstPort": "20",
+    "props" : {
+      "BW": "512 Gb"
+    }
+  }
+}
diff --git a/web/gui/src/main/webapp/json/ev/simple/ev_11_onos.json b/web/gui/src/main/webapp/json/ev/simple/ev_11_onos.json
new file mode 100644
index 0000000..447ded3
--- /dev/null
+++ b/web/gui/src/main/webapp/json/ev/simple/ev_11_onos.json
@@ -0,0 +1,15 @@
+{
+  "event": "updateLink",
+  "payload": {
+    "id": "of:0000ffffffff0003/21-of:0000ffffffff0008/20",
+    "type": "direct",
+    "linkWidth": 2,
+    "src": "of:0000ffffffff0003",
+    "srcPort": "21",
+    "dst": "of:0000ffffffff0008",
+    "dstPort": "20",
+    "props" : {
+      "BW": "80 Gb"
+    }
+  }
+}
diff --git a/web/gui/src/main/webapp/json/ev/simple/ev_12_onos.json b/web/gui/src/main/webapp/json/ev/simple/ev_12_onos.json
new file mode 100644
index 0000000..96018f3
--- /dev/null
+++ b/web/gui/src/main/webapp/json/ev/simple/ev_12_onos.json
@@ -0,0 +1,15 @@
+{
+  "event": "removeLink",
+  "payload": {
+    "id": "of:0000ffffffff0003/21-of:0000ffffffff0008/20",
+    "type": "direct",
+    "linkWidth": 2,
+    "src": "of:0000ffffffff0003",
+    "srcPort": "21",
+    "dst": "of:0000ffffffff0008",
+    "dstPort": "20",
+    "props" : {
+      "BW": "80 Gb"
+    }
+  }
+}
diff --git a/web/gui/src/main/webapp/json/ev/simple/ev_10_ui.json b/web/gui/src/main/webapp/json/ev/simple/ev_13_ui.json
similarity index 63%
rename from web/gui/src/main/webapp/json/ev/simple/ev_10_ui.json
rename to web/gui/src/main/webapp/json/ev/simple/ev_13_ui.json
index 188bc58..9d6e737 100644
--- a/web/gui/src/main/webapp/json/ev/simple/ev_10_ui.json
+++ b/web/gui/src/main/webapp/json/ev/simple/ev_13_ui.json
@@ -1,5 +1,5 @@
 {
-  "event": "doUiThing",
+  "event": "noop",
   "payload": {
     "id": "xyyzy"
   }
diff --git a/web/gui/src/main/webapp/json/ev/simple/ev_1_onos.json b/web/gui/src/main/webapp/json/ev/simple/ev_1_onos.json
index 9874ec7..8656a90 100644
--- a/web/gui/src/main/webapp/json/ev/simple/ev_1_onos.json
+++ b/web/gui/src/main/webapp/json/ev/simple/ev_1_onos.json
@@ -11,8 +11,8 @@
       ""
     ],
     "metaUi": {
-      "x": 400,
-      "y": 280
+      "x": 520,
+      "y": 350
     }
   }
 }
diff --git a/web/gui/src/main/webapp/json/ev/simple/ev_3_onos.json b/web/gui/src/main/webapp/json/ev/simple/ev_3_onos.json
index 73013a4..56651c0 100644
--- a/web/gui/src/main/webapp/json/ev/simple/ev_3_onos.json
+++ b/web/gui/src/main/webapp/json/ev/simple/ev_3_onos.json
@@ -11,8 +11,8 @@
       ""
     ],
     "metaUi": {
-      "x": 400,
-      "y": 280
+      "x": 520,
+      "y": 350
     }
   }
 }
diff --git a/web/gui/src/main/webapp/json/ev/simple/ev_5_onos.json b/web/gui/src/main/webapp/json/ev/simple/ev_5_onos.json
index ac521c4..6f390b5 100644
--- a/web/gui/src/main/webapp/json/ev/simple/ev_5_onos.json
+++ b/web/gui/src/main/webapp/json/ev/simple/ev_5_onos.json
@@ -9,7 +9,7 @@
     "dst": "of:0000ffffffff0008",
     "dstPort": "20",
     "props" : {
-      "BW": "70 G"
+      "BW": "70 Gb"
     }
   }
 }
diff --git a/web/gui/src/main/webapp/json/ev/simple/scenario.json b/web/gui/src/main/webapp/json/ev/simple/scenario.json
index 19d6190..5fb8869 100644
--- a/web/gui/src/main/webapp/json/ev/simple/scenario.json
+++ b/web/gui/src/main/webapp/json/ev/simple/scenario.json
@@ -10,13 +10,16 @@
   "description": [
     "1. add device [8] (offline)",
     "2. add device [3] (offline)",
-    "3. update device [8] (online)",
-    "4. update device [3] (online)",
+    "3. update device [8] (online, label3 change)",
+    "4. update device [3] (online, label3 change)",
     "5. add link [3] --> [8]",
     "6. add host (to [3])",
     "7. add host (to [8])",
     "8. update host[3] (IP now 10.0.0.13)",
     "9. update host[8] (IP now 10.0.0.17)",
+    "10. update link (increase width, update props)",
+    "11. update link (reduce width, update props)",
+    "12. remove link",
     ""
   ]
 }
\ No newline at end of file
diff --git a/web/gui/src/main/webapp/topo2.js b/web/gui/src/main/webapp/topo2.js
index f6a8456..94b2e9e 100644
--- a/web/gui/src/main/webapp/topo2.js
+++ b/web/gui/src/main/webapp/topo2.js
@@ -260,36 +260,6 @@
         bgImg.style('visibility', (vis === 'hidden') ? 'visible' : 'hidden');
     }
 
-    function updateDeviceLabel(d) {
-        var label = niceLabel(deviceLabel(d)),
-            node = d.el,
-            box;
-
-        node.select('text')
-            .text(label)
-            .style('opacity', 0)
-            .transition()
-            .style('opacity', 1);
-
-        box = adjustRectToFitText(node);
-
-        node.select('rect')
-            .transition()
-            .attr(box);
-
-        node.select('image')
-            .transition()
-            .attr('x', box.x + config.icons.xoff)
-            .attr('y', box.y + config.icons.yoff);
-    }
-
-    function updateHostLabel(d) {
-        var label = hostLabel(d),
-            host = d.el;
-
-        host.select('text').text(label);
-    }
-
     function cycleLabels() {
         deviceLabelIndex = (deviceLabelIndex === network.deviceLabelCount - 1)
             ? 0 : deviceLabelIndex + 1;
@@ -371,10 +341,10 @@
         addLink: addLink,
         addHost: addHost,
         updateDevice: updateDevice,
-        updateLink: stillToImplement,
+        updateLink: updateLink,
         updateHost: updateHost,
         removeDevice: stillToImplement,
-        removeLink: stillToImplement,
+        removeLink: removeLink,
         removeHost: stillToImplement,
         showPath: showPath
     };
@@ -429,6 +399,18 @@
         }
     }
 
+    function updateLink(data) {
+        var link = data.payload,
+            id = link.id,
+            linkData = network.lookup[id];
+        if (linkData) {
+            $.extend(linkData, link);
+            updateLinkState(linkData);
+        } else {
+            logicError('updateLink lookup fail. ID = "' + id + '"');
+        }
+    }
+
     function updateHost(data) {
         var host = data.payload,
             id = host.id,
@@ -441,6 +423,17 @@
         }
     }
 
+    function removeLink(data) {
+        var link = data.payload,
+            id = link.id,
+            linkData = network.lookup[id];
+        if (linkData) {
+            removeLinkElement(linkData);
+        } else {
+            logicError('removeLink lookup fail. ID = "' + id + '"');
+        }
+    }
+
     function showPath(data) {
         var links = data.payload.links,
             s = [ data.event + "\n" + links.length ];
@@ -483,74 +476,81 @@
         return 'translate(' + x + ',' + y + ')';
     }
 
+    function missMsg(what, id) {
+        return '\n[' + what + '] "' + id + '" missing ';
+    }
+
+    function linkEndPoints(srcId, dstId) {
+        var srcNode = network.lookup[srcId],
+            dstNode = network.lookup[dstId],
+            sMiss = !srcNode ? missMsg('src', srcId) : '',
+            dMiss = !dstNode ? missMsg('dst', dstId) : '';
+
+        if (sMiss || dMiss) {
+            logicError('Node(s) not on map for link:\n' + sMiss + dMiss);
+            return null;
+        }
+        return {
+            source: srcNode,
+            target: dstNode,
+            x1: srcNode.x,
+            y1: srcNode.y,
+            x2: dstNode.x,
+            y2: dstNode.y
+        };
+    }
+
     function createHostLink(host) {
         var src = host.id,
             dst = host.cp.device,
             id = host.ingress,
-            srcNode = network.lookup[src],
-            dstNode = network.lookup[dst],
-            lnk;
+            lnk = linkEndPoints(src, dst);
 
-        if (!dstNode) {
-            logicError('switch not on map for link\n\n' +
-                        'src = ' + src + '\ndst = ' + dst);
+        if (!lnk) {
             return null;
         }
 
-        // Compose link ...
-        lnk = {
+        // Synthesize link ...
+        $.extend(lnk, {
             id: id,
-            source: srcNode,
-            target: dstNode,
             class: 'link',
             type: 'hostLink',
             svgClass: 'link hostLink',
-            x1: srcNode.x,
-            y1: srcNode.y,
-            x2: dstNode.x,
-            y2: dstNode.y,
-            width: 1
-        }
-        return lnk;
-    }
-
-    function createLink(link) {
-        // start with the link object as is
-        var lnk = link,
-            type = link.type,
-            src = link.src,
-            dst = link.dst,
-            w = link.linkWidth,
-            srcNode = network.lookup[src],
-            dstNode = network.lookup[dst];
-
-        if (!(srcNode && dstNode)) {
-            logicError('nodes not on map for link\n\n' +
-            'src = ' + src + '\ndst = ' + dst);
-            return null;
-        }
-
-        // Augment as needed...
-        $.extend(lnk, {
-            source: srcNode,
-            target: dstNode,
-            class: 'link',
-            svgClass: type ? 'link ' + type : 'link',
-            x1: srcNode.x,
-            y1: srcNode.y,
-            x2: dstNode.x,
-            y2: dstNode.y,
-            width: w
+            linkWidth: 1
         });
         return lnk;
     }
 
-    function linkWidth(w) {
-        // w is number of links between nodes. Scale appropriately.
-        // TODO: use a d3.scale (linear, log, ... ?)
-        return w * 1.2;
+    function createLink(link) {
+        var lnk = linkEndPoints(link.src, link.dst),
+            type = link.type;
+
+        if (!lnk) {
+            return null;
+        }
+
+        // merge in remaining data
+        $.extend(lnk, link, {
+            class: 'link',
+            svgClass: type ? 'link ' + type : 'link'
+        });
+        return lnk;
     }
 
+    var widthRatio = 1.4,
+        linkScale = d3.scale.linear()
+            .domain([1, 12])
+            .range([widthRatio, 12 * widthRatio])
+            .clamp(true);
+
+    function updateLinkWidth (d) {
+        // TODO: watch out for .showPath/.showTraffic classes
+        d.el.transition()
+            .duration(1000)
+            .attr('stroke-width', linkScale(d.linkWidth));
+    }
+
+
     function updateLinks() {
         link = linkG.selectAll('.link')
             .data(network.links, function (d) { return d.id; });
@@ -572,7 +572,7 @@
             })
             .transition().duration(1000)
             .attr({
-                'stroke-width': function (d) { return linkWidth(d.width); },
+                'stroke-width': function (d) { return linkScale(d.linkWidth); },
                 stroke: '#666'      // TODO: remove explicit stroke, rather...
             });
 
@@ -589,13 +589,20 @@
         //link .foo() .bar() ...
 
         // operate on exiting links:
-        // TODO: figure out how to remove the node 'g' AND its children
+        // TODO: better transition (longer as a dashed, grey line)
         link.exit()
-            .transition()
-            .duration(750)
             .attr({
-                opacity: 0
+                'stroke-dasharray': '3, 3'
             })
+            .style('opacity', 0.4)
+            .transition()
+            .duration(2000)
+            .attr({
+                'stroke-dasharray': '3, 12'
+            })
+            .transition()
+            .duration(1000)
+            .style('opacity', 0.0)
             .remove();
     }
 
@@ -650,7 +657,6 @@
         node.y = y || network.view.height() / 2;
     }
 
-
     function iconUrl(d) {
         return 'img/' + d.type + '.png';
     }
@@ -694,12 +700,48 @@
         return (label && label.trim()) ? label : '.';
     }
 
+    function updateDeviceLabel(d) {
+        var label = niceLabel(deviceLabel(d)),
+            node = d.el,
+            box;
+
+        node.select('text')
+            .text(label)
+            .style('opacity', 0)
+            .transition()
+            .style('opacity', 1);
+
+        box = adjustRectToFitText(node);
+
+        node.select('rect')
+            .transition()
+            .attr(box);
+
+        node.select('image')
+            .transition()
+            .attr('x', box.x + config.icons.xoff)
+            .attr('y', box.y + config.icons.yoff);
+    }
+
+    function updateHostLabel(d) {
+        var label = hostLabel(d),
+            host = d.el;
+
+        host.select('text').text(label);
+    }
+
     function updateDeviceState(nodeData) {
         nodeData.el.classed('online', nodeData.online);
         updateDeviceLabel(nodeData);
         // TODO: review what else might need to be updated
     }
 
+    function updateLinkState(linkData) {
+        updateLinkWidth(linkData);
+        // TODO: review what else might need to be updated
+        //  update label, if showing
+    }
+
     function updateHostState(hostData) {
         updateHostLabel(hostData);
         // TODO: review what else might need to be updated
@@ -826,6 +868,25 @@
             .remove();
     }
 
+    function find(id, array) {
+        for (var idx = 0, n = array.length; idx < n; idx++) {
+            if (array[idx].id === id) {
+                return idx;
+            }
+        }
+        return -1;
+    }
+
+    function removeLinkElement(linkData) {
+        // remove from lookup cache
+        delete network.lookup[linkData.id];
+        // remove from links array
+        var idx = find(linkData.id, network.links);
+
+        network.links.splice(linkData.index, 1);
+        // remove from SVG
+        updateLinks();
+    }
 
     function tick() {
         node.attr({
diff --git a/web/pom.xml b/web/pom.xml
index aad2134..b7f3c87 100644
--- a/web/pom.xml
+++ b/web/pom.xml
@@ -132,7 +132,7 @@
                             com.fasterxml.jackson.databind.node,
                             com.google.common.base.*,
                             org.eclipse.jetty.websocket.*,
-                            org.onlab.api.*,
+                            org.onlab.util.*,
                             org.onlab.osgi.*,
                             org.onlab.packet.*,
                             org.onlab.rest.*,