Test: Generate cluster.json for ONOS single node cluster while starting ONOS.
A default cluster.json is loaded for 172.17.0.2 (common case for cord-tester)
Otherwise its regenerated on the fly during ONOS cord-tester boot.
It also eliminates the onos.cluster.metadata.uri warning in the logs because of missing cluster.json.

Change-Id: I6e6ec85254f135d90a86cb540b68c0bdfd030b3b
diff --git a/src/test/setup/onos-config/cluster.json b/src/test/setup/onos-config/cluster.json
new file mode 100644
index 0000000..72ae4c0
--- /dev/null
+++ b/src/test/setup/onos-config/cluster.json
@@ -0,0 +1,18 @@
+{
+    "nodes": [
+        {
+            "ip": "172.17.0.2",
+            "id": "172.17.0.2",
+            "port": 9876
+        }
+    ],
+    "name": 4220150786,
+    "partitions": [
+        {
+            "id": 1,
+            "members": [
+                "172.17.0.2"
+            ]
+        }
+    ]
+}
diff --git a/src/test/setup/onos-gen-partitions b/src/test/setup/onos-gen-partitions
new file mode 100755
index 0000000..8221710
--- /dev/null
+++ b/src/test/setup/onos-gen-partitions
@@ -0,0 +1,63 @@
+#!/usr/bin/env python
+"""
+  Generate the partitions json file from the $OC* environment variables
+
+  Usage: onos-gen-partitions [output file] [node_ip ...]
+  If output file is not provided, the json is written to stdout.
+"""
+
+from os import environ
+from collections import deque, OrderedDict
+import re
+import json
+import sys
+import hashlib
+
+convert = lambda text: int(text) if text.isdigit() else text.lower()
+alphanum_key = lambda key: [convert(c) for c in re.split('([0-9]+)', key)]
+
+def get_OC_vars():
+  vars = []
+  for var in environ:
+    if re.match(r"OC[0-9]+", var):
+      vars.append(var)
+  return sorted(vars, key=alphanum_key)
+
+def get_nodes(ips=None, port=9876):
+  node = lambda k: { 'id': k, 'ip': k, 'port': port }
+  if not ips:
+    ips = [ environ[v] for v in get_OC_vars() ]
+  return [ node(v) for v in ips ]
+
+def generate_partitions(nodes, k):
+  l = deque(nodes)
+  perms = []
+  for i in range(1, len(nodes)+1):
+    part = {
+             'id': i,
+             'members': list(l)[:k]
+           }
+    perms.append(part)
+    l.rotate(-1)
+  return perms
+
+if __name__ == '__main__':
+  nodes = get_nodes(sys.argv[2:])
+  partitions = generate_partitions([v.get('id') for v in nodes], 3)
+  m = hashlib.sha256()
+  for node in nodes:
+    m.update(node['ip'])
+  name = int(m.hexdigest()[:8], base=16) # 32-bit int based on SHA256 digest
+  data = {
+           'name': name,
+           'nodes': nodes,
+           'partitions': partitions
+         }
+  output = json.dumps(data, indent=4)
+
+  if len(sys.argv) >= 2 and sys.argv[1] != '-':
+    filename = sys.argv[1]
+    with open(filename, 'w') as f:
+      f.write(output)
+  else:
+    print output
diff --git a/src/test/utils/CordContainer.py b/src/test/utils/CordContainer.py
index 9a63246..a4971d3 100644
--- a/src/test/utils/CordContainer.py
+++ b/src/test/utils/CordContainer.py
@@ -274,11 +274,22 @@
                        ('vtn', '1.0-SNAPSHOT'),
                        )
     ports = [ 8181, 8101, 9876, 6653, 6633, 2000, 2620 ]
-    host_config_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup/onos-config')
+    setup_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'setup')
+    host_config_dir = os.path.join(setup_dir, 'onos-config')
     guest_config_dir = '/root/onos/config'
+    onos_gen_partitions = os.path.join(setup_dir, 'onos-gen-partitions')
     cord_apps_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', 'apps')
     host_guest_map = ( (host_config_dir, guest_config_dir), )
     NAME = 'cord-onos'
+    ##the ip of ONOS in default cluster.json in setup/onos-config
+    CLUSTER_CFG_IP = '172.17.0.2'
+
+    @classmethod
+    def onos_generate_cluster_cfg(cls, ip):
+        try:
+            cmd = '{} {}/cluster.json {}'.format(cls.onos_gen_partitions, cls.host_config_dir, ip)
+            os.system(cmd)
+        except: pass
 
     def __init__(self, name = NAME, image = 'onosproject/onos', tag = 'latest',
                  boot_delay = 60, restart = False, network_cfg = None):
@@ -309,6 +320,20 @@
             print('Starting ONOS container %s' %self.name)
             self.start(ports = self.ports, environment = self.env,
                        host_config = host_config, volumes = volumes, tty = True)
+            if not restart:
+                ##wait a bit before fetching IP to regenerate cluster cfg
+                time.sleep(5)
+                ip = self.ip()
+                ##Just a quick hack/check to ensure we don't regenerate in the common case.
+                ##As ONOS is usually the first test container that is started
+                if ip != self.CLUSTER_CFG_IP:
+                    print('Regenerating ONOS cluster cfg for ip %s' %ip)
+                    self.onos_generate_cluster_cfg(ip)
+                    self.kill()
+                    self.remove_container(self.name, force=True)
+                    print('Restarting ONOS container %s' %self.name)
+                    self.start(ports = self.ports, environment = self.env,
+                               host_config = host_config, volumes = volumes, tty = True)
             print('Waiting %d seconds for ONOS to boot' %(boot_delay))
             time.sleep(boot_delay)