Merge "Delete functest.utils.functest_logger"
[functest.git] / functest / opnfv_tests / vnf / ims / opera_ims.py
index 073a56c..51a4dc0 100644 (file)
@@ -1,6 +1,6 @@
 #!/usr/bin/env python
 
-# Copyright (c) 2016 Orange and others.
+# Copyright (c) 2017 HUAWEI TECHNOLOGIES CO.,LTD and others.
 #
 # All rights reserved. This program and the accompanying materials
 # are made available under the terms of the Apache License, Version 2.0
 # http://www.apache.org/licenses/LICENSE-2.0
 
 import json
+import logging
 import os
-import requests
-import subprocess
 import time
 
-import functest.core.vnf_base as vnf_base
-import functest.utils.functest_logger as ft_logger
-import functest.utils.functest_utils as ft_utils
+from opera import openo_connect
+import requests
+
+import functest.opnfv_tests.vnf.ims.clearwater_ims_base as clearwater_ims_base
 from functest.utils.constants import CONST
 
 
-class ImsVnf(vnf_base.VnfOnBoardingBase):
+class OperaIms(clearwater_ims_base.ClearwaterOnBoardingBase):
 
-    def __init__(self, project='functest', case='opera_ims',
-                 repo='', cmd=''):
-        super(ImsVnf, self).__init__(project, case, repo, cmd)
-        self.logger = ft_logger.Logger("vIMS").getLogger()
-        self.case_dir = os.path.join(CONST.functest_test, 'vnf/ims/')
-        self.data_dir = CONST.dir_vIMS_data
-        self.test_dir = CONST.dir_repo_vims_test
+    def __init__(self, project='functest', case_name='opera_ims',
+                 repo=CONST.dir_repo_opera, cmd=''):
+        super(OperaIms, self).__init__(project, case_name, repo, cmd)
+        self.logger = logging.getLogger(__name__)
+        self.ellis_file = os.path.join(self.result_dir, 'ellis.info')
+        self.live_test_file = os.path.join(self.result_dir,
+                                           'live_test_report.json')
+        try:
+            self.openo_msb_endpoint = os.environ['OPENO_MSB_ENDPOINT']
+        except KeyError:
+            raise Exception('OPENO_MSB_ENDPOINT is not specified,'
+                            ' put it as <OPEN-O ip>:<port>')
+        else:
+            self.logger.info('OPEN-O endpoint is: %s', self.openo_msb_endpoint)
 
-        # vIMS Data directory creation
-        if not os.path.exists(self.data_dir):
-            os.makedirs(self.data_dir)
+    def prepare(self):
+        pass
 
-    def deploy_orchestrator(self, **kwargs):
-        # TODO
-        # deploy open-O from Functest docker located on the Jumphost
-        # you have admin rights on OpenStack SUT
-        # you can cretae a VM, spawn docker on the jumphost
-        # spawn docker on a VM in the SUT, ..up to you
-        #
-        # note: this step can be ignored
-        # if Open-O is part of the installer
-        self.logger.info("Deploy orchestrator: OK")
+    def clean(self):
+        pass
 
     def deploy_vnf(self):
-        # TODO
-        self.logger.info("Deploy VNF: OK")
-
-    def test_vnf(self):
-        # Adaptations probably needed
-        # code used for cloudify_ims
-        # ruby client on jumphost calling the vIMS on the SUT
-        script = "source {0}venv_cloudify/bin/activate; "
-        script += "cd {0}; "
-        script += "cfy status | grep -Eo \"([0-9]{{1,3}}\.){{3}}[0-9]{{1,3}}\""
-        cmd = "/bin/bash -c '" + script.format(self.data_dir) + "'"
-
         try:
-            self.logger.debug("Trying to get clearwater manager IP ... ")
-            mgr_ip = os.popen(cmd).read()
-            mgr_ip = mgr_ip.splitlines()[0]
-        except:
-            self.step_failure("Unable to retrieve the IP of the "
-                              "cloudify manager server !")
-
-        api_url = "http://" + mgr_ip + "/api/v2"
-        dep_outputs = requests.get(api_url + "/deployments/" +
-                                   self.vnf.deployment_name + "/outputs")
-        dns_ip = dep_outputs.json()['outputs']['dns_ip']
-        ellis_ip = dep_outputs.json()['outputs']['ellis_ip']
-
-        ellis_url = "http://" + ellis_ip + "/"
-        url = ellis_url + "accounts"
-
-        params = {"password": "functest",
-                  "full_name": "opnfv functest user",
-                  "email": "functest@opnfv.fr",
-                  "signup_code": "secret"}
-
-        rq = requests.post(url, data=params)
-        i = 20
-        while rq.status_code != 201 and i > 0:
-            rq = requests.post(url, data=params)
-            i = i - 1
-            time.sleep(10)
-
-        if rq.status_code == 201:
-            url = ellis_url + "session"
-            rq = requests.post(url, data=params)
-            cookies = rq.cookies
-
-        url = ellis_url + "accounts/" + params['email'] + "/numbers"
-        if cookies != "":
-            rq = requests.post(url, cookies=cookies)
-            i = 24
-            while rq.status_code != 200 and i > 0:
-                rq = requests.post(url, cookies=cookies)
-                i = i - 1
-                time.sleep(25)
-
-        if rq.status_code != 200:
-            self.step_failure("Unable to create a number: %s"
-                              % rq.json()['reason'])
-
-        nameservers = ft_utils.get_resolvconf_ns()
-        resolvconf = ""
-        for ns in nameservers:
-            resolvconf += "\nnameserver " + ns
-
-        if dns_ip != "":
-            script = ('echo -e "nameserver ' + dns_ip + resolvconf +
-                      '" > /etc/resolv.conf; ')
-            script += 'source /etc/profile.d/rvm.sh; '
-            script += 'cd {0}; '
-            script += ('rake test[{1}] SIGNUP_CODE="secret"')
-
-            cmd = ("/bin/bash -c '" +
-                   script.format(self.data_dir, self.inputs["public_domain"]) +
-                   "'")
-            output_file = "output.txt"
-            f = open(output_file, 'w+')
-            subprocess.call(cmd, shell=True, stdout=f,
-                            stderr=subprocess.STDOUT)
-            f.close()
-
-            f = open(output_file, 'r')
-            result = f.read()
-            if result != "":
-                self.logger.debug(result)
-
-            vims_test_result = ""
-            tempFile = os.path.join(self.test_dir, "temp.json")
-            try:
-                self.logger.debug("Trying to load test results")
-                with open(tempFile) as f:
-                    vims_test_result = json.load(f)
-                f.close()
-            except:
-                self.logger.error("Unable to retrieve test results")
-
-            try:
-                os.remove(tempFile)
-            except:
-                self.logger.error("Deleting file failed")
+            openo_connect.create_service(self.openo_msb_endpoint,
+                                         'functest_opera',
+                                         'VNF for functest testing')
+        except Exception as e:
+            self.logger.error(e)
+            return {'status': 'FAIL', 'result': e}
+        else:
+            self.logger.info('vIMS deployment is kicked off')
+            return {'status': 'PASS', 'result': ''}
+
+    def dump_info(self, info_file, result):
+        with open(info_file, 'w') as f:
+            self.logger.debug('Save information to file: %s', info_file)
+            json.dump(result, f)
 
+    def test_vnf(self):
+        vnfm_ip = openo_connect.get_vnfm_ip(self.openo_msb_endpoint)
+        self.logger.info('VNFM IP: %s', vnfm_ip)
+        vnf_status_url = 'http://{0}:5000/api/v1/model/status'.format(vnfm_ip)
+        vnf_alive = False
+        retry = 15
+
+        self.logger.info('Check the VNF status')
+        while retry > 0:
+            rq = requests.get(vnf_status_url)
+            response = rq.json()
+            vnf_alive = response['vnf_alive']
+            msg = response['msg']
+            self.logger.info(msg)
+            if vnf_alive:
+                break
+            self.logger.info('check again in one minute...')
+            retry = retry - 1
+            time.sleep(60)
+
+        if not vnf_alive:
+            raise Exception('VNF failed to start: {0}'.format(msg))
+
+        ellis_config_url = ('http://{0}:5000/api/v1/model/ellis/configure'
+                            .format(vnfm_ip))
+        rq = requests.get(ellis_config_url, timeout=60)
+        if rq.json() and not rq.json()['ellis_ok']:
+            self.logger.error(rq.json()['data'])
+            raise Exception('Failed to configure Ellis')
+
+        self.logger.info('Get Clearwater deployment detail')
+        vnf_info_url = ('http://{0}:5000/api/v1/model/output'
+                        .format(vnfm_ip))
+        rq = requests.get(vnf_info_url, timeout=60)
+        data = rq.json()['data']
+        self.logger.info(data)
+        bono_ip = data['bono_ip']
+        ellis_ip = data['ellis_ip']
+        dns_ip = data['dns_ip']
+        result = self.config_ellis(ellis_ip, 'signup', True)
+        self.logger.debug('Ellis Result: %s', result)
+        self.dump_info(self.ellis_file, result)
+
+        if dns_ip:
+            vims_test_result = self.run_clearwater_live_test(
+                dns_ip,
+                'clearwater.local',
+                bono_ip,
+                ellis_ip,
+                'signup')
             if vims_test_result != '':
+                self.dump_info(self.live_test_file, vims_test_result)
                 return {'status': 'PASS', 'result': vims_test_result}
             else:
                 return {'status': 'FAIL', 'result': ''}
 
-    def clean(self):
-        # TODO
-        super(ImsVnf, self).clean()
+    def main(self, **kwargs):
+        self.logger.info("Start to run Opera vIMS VNF onboarding test")
+        self.execute()
+        self.logger.info("Opera vIMS VNF onboarding test finished")
+        if self.result is "PASS":
+            return self.EX_OK
+        else:
+            return self.EX_RUN_ERROR
+
+    def run(self):
+        kwargs = {}
+        return self.main(**kwargs)