XOS integration in cord-tester.

Change-Id: Ied9e0673ea86c8cfb87a3b6bb3e9dbab797c7293
diff --git a/src/test/setup/cord-test.py b/src/test/setup/cord-test.py
index 0ff73d9..a6e778f 100755
--- a/src/test/setup/cord-test.py
+++ b/src/test/setup/cord-test.py
@@ -28,7 +28,7 @@
 from TestManifest import TestManifest
 from docker import Client
 from docker.utils import kwargs_from_env
-
+from Xos import XosServiceProfile
 try:
     from Fabric import FabricMAAS
 except:
@@ -868,34 +868,18 @@
 
     return 0
 
-def xosContainers(args):
-    update_map = {  'xos-server' : False, 'xos-synchronizer-openstack' : False, 'openvpn' : False, 'postgresql' :False,
-                    'syndicate-ms': False, 'xos-synchronizer-onboarding' : False }
-
-    if args.xosAllContainers == True or args.xosServer == True:
-        xosServer = XosServer(prefix = Container.IMAGE_PREFIX, update = update_map['xos-server'])
-
-    if args.xosAllContainers == True or args.xosSyncOpenstack == True:
-        #Start xos base container. Builds container if required
-        xosSyncOpenstack = XosSynchronizerOpenstack(prefix = Container.IMAGE_PREFIX,
-                                                    update = update_map['xos-synchronizer-openstack'])
-
-    if args.xosAllContainers == True or args.xosOpenvpn == True:
-        xosOpenvpn = XosSynchronizerOpenvpn(prefix = Container.IMAGE_PREFIX, update = update_map['openvpn'])
-
-    if args.xosAllContainers == True or args.xosPostgresql == True:
-        xosPostgresql = XosPostgresql(prefix = Container.IMAGE_PREFIX, update = update_map['postgresql'])
-
-    if args.xosAllContainers == True or args.xosSyndicateMs == True:
-        #Start xos syndicateMs container. Builds container if required
-        xosSyndicateMs = XosSyndicateMs(prefix = Container.IMAGE_PREFIX, update = update_map['syndicate-ms'])
-
-    if args.xosAllContainers == True or args.xosSyncOnboarding == True:
-        #Start xos synchronizer Onboarding container. Builds container if required
-        xosSyncOnboarding = XosSynchronizerOnboarding(prefix = Container.IMAGE_PREFIX,
-                                                      update = update_map['xos-synchronizer-onboarding'])
-
-    print('Done building xos containers')
+def xosCommand(args):
+    update = False
+    profile = args.profile
+    if args.command == 'update':
+        update = True
+    xos = XosServiceProfile(profile = profile, update = update)
+    if args.command == 'build':
+        xos.build_images(force = True)
+    if args.command == 'start':
+        xos.start_services()
+    if args.command == 'stop':
+        xos.stop_services(rm = True)
     return 0
 
 if __name__ == '__main__':
@@ -955,15 +939,9 @@
     parser_setup.set_defaults(func=setupCordTester)
 
     parser_xos = subparser.add_parser('xos', help='Building xos into cord tester environment')
-    parser_xos.add_argument('-x', '--xosAllContainers', action='store_true',help='Provision all containers of XOS for CORD')
-    parser_xos.add_argument('-xserver', '--xosServer',action='store_true',help='Provision xos server container')
-    parser_xos.add_argument('-xsos', '--xosSyncOpenstack',action='store_true',help='Provision xos synchronizer openstack container')
-    parser_xos.add_argument('-xo', '--xosOpenvpn',action='store_true',help='Provision xos openvpn container')
-    parser_xos.add_argument('-xp', '--xosPostgresql',action='store_true',help='Provision xos postgresql')
-    parser_xos.add_argument('-xs', '--xosSynchronizer',action='store_true',help='Provision xos synchronizer')
-    parser_xos.add_argument('-xsm', '--xosSyndicateMs',action='store_true',help='Provision xos syndicate-ms')
-    parser_xos.add_argument('-xsonb', '--xosSyncOnboarding',action='store_true',help='Provision xos synchronizer onboarding container')
-    parser_xos.set_defaults(func=xosContainers)
+    parser_xos.add_argument('command', choices=['build', 'update', 'start', 'stop'])
+    parser_xos.add_argument('-p', '--profile', default='cord-pod', type=str, help='Provide service profile')
+    parser_xos.set_defaults(func=xosCommand)
 
     parser_list = subparser.add_parser('list', help='List test cases')
     parser_list.add_argument('-t', '--test', default='all', help='Specify test type to list test cases. '
diff --git a/src/test/utils/Xos.py b/src/test/utils/Xos.py
new file mode 100644
index 0000000..20f2ee7
--- /dev/null
+++ b/src/test/utils/Xos.py
@@ -0,0 +1,93 @@
+import os,time
+from CordContainer import Container
+
+class XosBase(object):
+    workspace = '/tmp/xos_scratch_workspace'
+    image = 'xosproject/xos'
+    tag = 'latest'
+
+    @classmethod
+    def clone(cls, update = False):
+        fetch_cmd = 'mkdir -p {} && cd {} && \
+                     git clone http://gerrit.opencord.org/xos'.format(cls.workspace, cls.workspace)
+        fetch = True
+        if os.access(cls.workspace, os.F_OK):
+            fetch = update
+            if update is True:
+                os.system('rm -rf {}'.format(cls.workspace))
+        if fetch is True:
+            ##fetch the xos
+            os.system(fetch_cmd)
+
+    @classmethod
+    def build_images(cls):
+        images = ( ['xos', ('base', 'build',),],
+                   ['postgresql', ('build',),],
+                   ['synchronizer', ('build',),],
+                   ['onboarding_synchronizer', ('build',),],
+                   ['syndicate-ms', ('build',),],
+                  )
+
+        for cnt, targets in images:
+            for target in targets:
+                xos_dir = 'cd {}/xos/containers/{} && make {}'.format(cls.workspace, cnt, target)
+                os.system(xos_dir)
+
+class XosServiceProfile(XosBase):
+
+    def __init__(self, profile = 'cord-pod', update = False):
+        self.workspace = XosBase.workspace
+        self.profile = profile
+        self.service_dir = '{}/service-profile'.format(self.workspace)
+        self.profile_dir = '{}/{}'.format(self.service_dir, profile)
+        XosBase.clone(update = update)
+        self.__clone(update = update)
+
+    def __clone(self, update = False):
+        fetch_cmd = 'cd {} && git clone http://gerrit.opencord.org/service-profile'.format(self.workspace)
+        fetch = True
+        if os.access(self.service_dir, os.F_OK):
+            fetch = update
+            if update is True:
+                os.system('rm -rf {}'.format(self.service_dir))
+        if fetch:
+            os.system(fetch_cmd)
+
+    def __ssh_key_check(self):
+        id_rsa = '{}/.ssh/id_rsa'.format(os.getenv('HOME'))
+        if not os.access(id_rsa, os.F_OK):
+            return False
+        return True
+
+    def __ssh_copy_keys(self, dest):
+        cmd = 'cp -v {}/.ssh/id_rsa* {}'.format(os.getenv('HOME'), dest)
+        return os.system(cmd)
+
+    def build_images(self, force = False):
+        if force is True or not Container.image_exists('{}:{}'.format(XosBase.image, XosBase.tag)):
+            XosBase.build_images()
+
+    def start_services(self):
+        if not self.__ssh_key_check():
+            log.info('SSH keys need to be generated before building XOS service containers')
+            log.info('Use the following commands to generate ssh keys')
+            log.info('ssh-keygen -t rsa -q -N ""')
+            log.info('ssh-copy-id -i $HOME/.ssh/id_rsa ubuntu@localhost')
+            return False
+        if not os.access(self.profile_dir, os.F_OK):
+            log.error('Profile directory %s does not exist' %self.profile_dir)
+            return False
+        self.build_images()
+        ##copy the keys to the profile dir
+        self.__ssh_copy_keys(self.profile_dir)
+        service_cmd = 'cd {} && make dirs download_services bootstrap onboarding'.format(self.profile_dir)
+        return os.system(service_cmd)
+
+    def stop_services(self, rm = False):
+        if os.access(self.profile_dir, os.F_OK):
+            cmds = ['cd {}'.format(self.profile_dir), 'make stop']
+            if rm is True:
+                cmds += ['make rm']
+            cmd = ' && '.join(cmds)
+            return os.system(cmd) == 0
+        return False