2fc5449cf9c32c154b24a337872b7315f7b9bb20
[functest.git] / functest / opnfv_tests / vnf / ims / clearwater_ims_base.py
1 #!/usr/bin/env python
2 #
3 # Copyright (c) 2017 All rights reserved
4 # This program and the accompanying materials
5 # are made available under the terms of the Apache License, Version 2.0
6 # which accompanies this distribution, and is available at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 import json
10 import os
11 import shutil
12
13 import requests
14
15 import functest.core.vnf_base as vnf_base
16 from functest.utils.constants import CONST
17 import functest.utils.functest_logger as ft_logger
18 import functest.utils.functest_utils as ft_utils
19
20
21 class ClearwaterOnBoardingBase(vnf_base.VnfOnBoardingBase):
22
23     def __init__(self, project='functest', case='', repo='', cmd=''):
24         self.logger = ft_logger.Logger(__name__).getLogger()
25         super(ClearwaterOnBoardingBase, self).__init__(
26             project, case, repo, cmd)
27         self.case_dir = os.path.join(CONST.dir_functest_test, 'vnf', 'ims')
28         self.data_dir = CONST.dir_ims_data
29         self.result_dir = os.path.join(CONST.dir_results, case)
30         self.test_dir = CONST.dir_repo_vims_test
31
32         if not os.path.exists(self.data_dir):
33             os.makedirs(self.data_dir)
34         if not os.path.exists(self.result_dir):
35             os.makedirs(self.result_dir)
36
37     def config_ellis(self, ellis_ip, signup_code='secret', two_numbers=False):
38         output_dict = {}
39         self.logger.info('Configure Ellis: %s', ellis_ip)
40         output_dict['ellis_ip'] = ellis_ip
41         account_url = 'http://{0}/accounts'.format(ellis_ip)
42         params = {"password": "functest",
43                   "full_name": "opnfv functest user",
44                   "email": "functest@opnfv.org",
45                   "signup_code": signup_code}
46         rq = requests.post(account_url, data=params)
47         output_dict['login'] = params
48         if rq.status_code != 201 and rq.status_code != 409:
49             raise Exception("Unable to create an account for number provision")
50         self.logger.info('Account is created on Ellis: %s', params)
51
52         session_url = 'http://{0}/session'.format(ellis_ip)
53         session_data = {
54             'username': params['email'],
55             'password': params['password'],
56             'email': params['email']
57         }
58         rq = requests.post(session_url, data=session_data)
59         if rq.status_code != 201:
60             raise Exception('Failed to get cookie for Ellis')
61         cookies = rq.cookies
62         self.logger.info('Cookies: %s' % cookies)
63
64         number_url = 'http://{0}/accounts/{1}/numbers'.format(
65                      ellis_ip,
66                      params['email'])
67         self.logger.info('Create 1st calling number on Ellis')
68         number_res = self.create_ellis_number(number_url, cookies)
69         output_dict['number'] = number_res
70
71         if two_numbers:
72             self.logger.info('Create 2nd calling number on Ellis')
73             number_res = self.create_ellis_number(number_url, cookies)
74             output_dict['number2'] = number_res
75
76         return output_dict
77
78     def create_ellis_number(self, number_url, cookies):
79         rq = requests.post(number_url, cookies=cookies)
80
81         if rq.status_code != 200:
82             if rq and rq.json():
83                 reason = rq.json()['reason']
84             else:
85                 reason = rq
86             raise Exception("Unable to create a number: %s" % reason)
87         number_res = rq.json()
88         self.logger.info('Calling number is created: %s', number_res)
89         return number_res
90
91     def run_clearwater_live_test(self, dns_ip, public_domain,
92                                  bono_ip=None, ellis_ip=None,
93                                  signup_code='secret'):
94         self.logger.info('Run Clearwater live test')
95         nameservers = ft_utils.get_resolvconf_ns()
96         resolvconf = ['{0}{1}{2}'.format(os.linesep, 'nameserver ', ns)
97                       for ns in nameservers]
98         self.logger.debug('resolvconf: %s', resolvconf)
99         dns_file = '/etc/resolv.conf'
100         dns_file_bak = '/etc/resolv.conf.bak'
101         shutil.copy(dns_file, dns_file_bak)
102         script = ('echo -e "nameserver {0}{1}" > {2};'
103                   'source /etc/profile.d/rvm.sh;'
104                   'cd {3};'
105                   'rake test[{4}] SIGNUP_CODE={5}'
106                   .format(dns_ip,
107                           ''.join(resolvconf),
108                           dns_file,
109                           self.test_dir,
110                           public_domain,
111                           signup_code))
112         if bono_ip and ellis_ip:
113             subscript = ' PROXY={0} ELLIS={1}'.format(bono_ip, ellis_ip)
114             script = '{0}{1}'.format(script, subscript)
115         script = ('{0}{1}'.format(script, ' --trace'))
116         cmd = "/bin/bash -c '{0}'".format(script)
117         self.logger.info('Live test cmd: %s', cmd)
118         output_file = os.path.join(self.result_dir, "ims_test_output.txt")
119         ft_utils.execute_command(cmd,
120                                  error_msg='Clearwater live test failed',
121                                  output_file=output_file)
122
123         with open(dns_file_bak, 'r') as bak_file:
124             result = bak_file.read()
125             with open(dns_file, 'w') as f:
126                 f.write(result)
127
128         f = open(output_file, 'r')
129         result = f.read()
130         if result != "":
131             self.logger.debug(result)
132
133         vims_test_result = ""
134         tempFile = os.path.join(self.test_dir, "temp.json")
135         try:
136             self.logger.debug("Trying to load test results")
137             with open(tempFile) as f:
138                 vims_test_result = json.load(f)
139             f.close()
140         except Exception:
141             self.logger.error("Unable to retrieve test results")
142
143         try:
144             os.remove(tempFile)
145         except Exception:
146             self.logger.error("Deleting file failed")
147
148         return vims_test_result