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