Merge "Promote Linda Wang as a committer"
[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 logging
11 import os
12 import shutil
13
14 import requests
15
16 import functest.core.vnf as vnf
17 from functest.utils.constants import CONST
18 import functest.utils.functest_utils as ft_utils
19
20 __author__ = ("Valentin Boucher <valentin.boucher@orange.com>, "
21               "Helen Yao <helanyao@gmail.com>")
22
23
24 class ClearwaterOnBoardingBase(vnf.VnfOnBoarding):
25     """ vIMS clearwater base usable by several orchestrators"""
26
27     def __init__(self, **kwargs):
28         self.logger = logging.getLogger(__name__)
29         super(ClearwaterOnBoardingBase, self).__init__(**kwargs)
30         self.case_dir = os.path.join(
31             CONST.__getattribute__('dir_functest_test'),
32             'vnf',
33             'ims')
34         self.data_dir = CONST.__getattribute__('dir_ims_data')
35         self.result_dir = os.path.join(CONST.__getattribute__('dir_results'),
36                                        self.case_name)
37         self.test_dir = CONST.__getattribute__('dir_repo_vims_test')
38
39         if not os.path.exists(self.data_dir):
40             os.makedirs(self.data_dir)
41         if not os.path.exists(self.result_dir):
42             os.makedirs(self.result_dir)
43
44     def config_ellis(self, ellis_ip, signup_code='secret', two_numbers=False):
45         output_dict = {}
46         self.logger.info('Configure Ellis: %s', ellis_ip)
47         output_dict['ellis_ip'] = ellis_ip
48         account_url = 'http://{0}/accounts'.format(ellis_ip)
49         params = {"password": "functest",
50                   "full_name": "opnfv functest user",
51                   "email": "functest@opnfv.org",
52                   "signup_code": signup_code}
53         rq = requests.post(account_url, data=params)
54         output_dict['login'] = params
55         if rq.status_code != 201 and rq.status_code != 409:
56             raise Exception("Unable to create an account for number provision")
57         self.logger.info('Account is created on Ellis: %s', params)
58
59         session_url = 'http://{0}/session'.format(ellis_ip)
60         session_data = {
61             'username': params['email'],
62             'password': params['password'],
63             'email': params['email']
64         }
65         rq = requests.post(session_url, data=session_data)
66         if rq.status_code != 201:
67             raise Exception('Failed to get cookie for Ellis')
68         cookies = rq.cookies
69         self.logger.info('Cookies: %s', cookies)
70
71         number_url = 'http://{0}/accounts/{1}/numbers'.format(
72                      ellis_ip,
73                      params['email'])
74         self.logger.info('Create 1st calling number on Ellis')
75         number_res = self.create_ellis_number(number_url, cookies)
76         output_dict['number'] = number_res
77
78         if two_numbers:
79             self.logger.info('Create 2nd calling number on Ellis')
80             number_res = self.create_ellis_number(number_url, cookies)
81             output_dict['number2'] = number_res
82
83         return output_dict
84
85     def create_ellis_number(self, number_url, cookies):
86         rq = requests.post(number_url, cookies=cookies)
87
88         if rq.status_code != 200:
89             if rq and rq.json():
90                 reason = rq.json()['reason']
91             else:
92                 reason = rq
93             raise Exception("Unable to create a number: %s" % reason)
94         number_res = rq.json()
95         self.logger.info('Calling number is created: %s', number_res)
96         return number_res
97
98     def run_clearwater_live_test(self, dns_ip, public_domain,
99                                  bono_ip=None, ellis_ip=None,
100                                  signup_code='secret'):
101         self.logger.info('Run Clearwater live test')
102         nameservers = ft_utils.get_resolvconf_ns()
103         resolvconf = ['{0}{1}{2}'.format(os.linesep, 'nameserver ', ns)
104                       for ns in nameservers]
105         self.logger.debug('resolvconf: %s', resolvconf)
106         dns_file = '/etc/resolv.conf'
107         dns_file_bak = '/etc/resolv.conf.bak'
108         shutil.copy(dns_file, dns_file_bak)
109         script = ('echo -e "nameserver {0}{1}" > {2};'
110                   'source /etc/profile.d/rvm.sh;'
111                   'cd {3};'
112                   'rake test[{4}] SIGNUP_CODE={5}'
113                   .format(dns_ip,
114                           ''.join(resolvconf),
115                           dns_file,
116                           self.test_dir,
117                           public_domain,
118                           signup_code))
119         if bono_ip and ellis_ip:
120             subscript = ' PROXY={0} ELLIS={1}'.format(bono_ip, ellis_ip)
121             script = '{0}{1}'.format(script, subscript)
122         script = ('{0}{1}'.format(script, ' --trace'))
123         cmd = "/bin/bash -c '{0}'".format(script)
124         self.logger.info('Live test cmd: %s', cmd)
125         output_file = os.path.join(self.result_dir, "ims_test_output.txt")
126         ft_utils.execute_command(cmd,
127                                  error_msg='Clearwater live test failed',
128                                  output_file=output_file)
129
130         with open(dns_file_bak, 'r') as bak_file:
131             result = bak_file.read()
132             with open(dns_file, 'w') as f:
133                 f.write(result)
134
135         f = open(output_file, 'r')
136         result = f.read()
137         if result != "":
138             self.logger.debug(result)
139
140         vims_test_result = ""
141         tempFile = os.path.join(self.test_dir, "temp.json")
142         try:
143             self.logger.debug("Trying to load test results")
144             with open(tempFile) as f:
145                 vims_test_result = json.load(f)
146             f.close()
147         except Exception:
148             self.logger.error("Unable to retrieve test results")
149
150         try:
151             os.remove(tempFile)
152         except Exception:
153             self.logger.error("Deleting file failed")
154
155         return vims_test_result