Merge "build: select_ubuntu_repo: break on err"
[fuel.git] / deploy / cloud / deployment.py
1 ###############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 # szilard.cserey@ericsson.com
4 # All rights reserved. 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 # http://www.apache.org/licenses/LICENSE-2.0
8 ###############################################################################
9
10 import time
11 import re
12 import json
13
14 from common import (
15     N,
16     exec_cmd,
17     parse,
18     err,
19     log,
20 )
21
22 SEARCH_TEXT = '(err)'
23 LOG_FILE = '/var/log/puppet.log'
24 GREP_LINES_OF_LEADING_CONTEXT = 100
25 GREP_LINES_OF_TRAILING_CONTEXT = 100
26 LIST_OF_CHAR_TO_BE_ESCAPED = ['[', ']', '"']
27
28
29 class DeployNotStart(Exception):
30     """Unable to start deployment"""
31
32
33 class NodesGoOffline(Exception):
34     """Nodes goes offline during deployment"""
35
36
37 class Deployment(object):
38
39     def __init__(self, dea, yaml_config_dir, env_id, node_id_roles_dict,
40                  no_health_check, deploy_timeout):
41         self.dea = dea
42         self.yaml_config_dir = yaml_config_dir
43         self.env_id = env_id
44         self.node_id_roles_dict = node_id_roles_dict
45         self.no_health_check = no_health_check
46         self.deploy_timeout = deploy_timeout
47         self.pattern = re.compile(
48             '\d\d\d\d-\d\d-\d\d\s\d\d:\d\d:\d\d')
49
50     def collect_error_logs(self):
51         for node_id, roles_blade in self.node_id_roles_dict.iteritems():
52             log_list = []
53             cmd = ('ssh -q node-%s grep \'"%s"\' %s'
54                    % (node_id, SEARCH_TEXT, LOG_FILE))
55             results, _ = exec_cmd(cmd, False)
56             for result in results.splitlines():
57                 log_msg = ''
58
59                 sub_cmd = '"%s" %s' % (result, LOG_FILE)
60                 for c in LIST_OF_CHAR_TO_BE_ESCAPED:
61                     sub_cmd = sub_cmd.replace(c, '\%s' % c)
62                 grep_cmd = ('grep -B%s %s'
63                             % (GREP_LINES_OF_LEADING_CONTEXT, sub_cmd))
64                 cmd = ('ssh -q node-%s "%s"' % (node_id, grep_cmd))
65
66                 details, _ = exec_cmd(cmd, False)
67                 details_list = details.splitlines()
68
69                 found_prev_log = False
70                 for i in range(len(details_list) - 2, -1, -1):
71                     if self.pattern.match(details_list[i]):
72                         found_prev_log = True
73                         break
74                 if found_prev_log:
75                     log_msg += '\n'.join(details_list[i:-1]) + '\n'
76
77                 grep_cmd = ('grep -A%s %s'
78                             % (GREP_LINES_OF_TRAILING_CONTEXT, sub_cmd))
79                 cmd = ('ssh -q node-%s "%s"' % (node_id, grep_cmd))
80
81                 details, _ = exec_cmd(cmd, False)
82                 details_list = details.splitlines()
83
84                 found_next_log = False
85                 for i in range(1, len(details_list)):
86                     if self.pattern.match(details_list[i]):
87                         found_next_log = True
88                         break
89                 if found_next_log:
90                     log_msg += '\n'.join(details_list[:i])
91                 else:
92                     log_msg += details
93
94                 if log_msg:
95                     log_list.append(log_msg)
96
97             if log_list:
98                 role = ('controller' if 'controller' in roles_blade[0]
99                         else 'compute host')
100                 log('_' * 40 + 'Errors in node-%s %s' % (node_id, role)
101                     + '_' * 40)
102                 for log_msg in log_list:
103                     print(log_msg + '\n')
104
105     def run_deploy(self):
106         SLEEP_TIME = 60
107         abort_after = 60 * int(self.deploy_timeout)
108         start = time.time()
109
110         log('Starting deployment of environment %s' % self.env_id)
111         deploy_id = None
112         ready = False
113         timeout = False
114
115         attempts = 0
116         while attempts < 3:
117             try:
118                 if time.time() > start + abort_after:
119                     timeout = True
120                     break
121                 if not deploy_id:
122                     deploy_id = self._start_deploy_task()
123                 sts, prg, msg = self._deployment_status(deploy_id)
124                 if sts == 'error':
125                     log('Error during deployment: {}'.format(msg))
126                     break
127                 if sts == 'running':
128                     log('Environment deployment progress: {}%'.format(prg))
129                 elif sts == 'ready':
130                     ready = True
131                     break
132                 time.sleep(SLEEP_TIME)
133             except (DeployNotStart, NodesGoOffline) as e:
134                 log(e)
135                 attempts += 1
136                 deploy_id = None
137                 time.sleep(SLEEP_TIME * attempts)
138
139         if timeout:
140             err('Deployment timed out, environment %s is not operational, '
141                 'snapshot will not be performed'
142                 % self.env_id)
143         if ready:
144             log('Environment %s successfully deployed'
145                 % self.env_id)
146         else:
147             self.collect_error_logs()
148             err('Deployment failed, environment %s is not operational'
149                 % self.env_id, self.collect_logs)
150
151     def _start_deploy_task(self):
152         out, _ = exec_cmd('fuel2 env deploy {}'.format(self.env_id), False)
153         id = self._deployment_task_id(out)
154         return id
155
156     def _deployment_task_id(self, response):
157         response = str(response)
158         if response.startswith('Deployment task with id'):
159             for s in response.split():
160                 if s.isdigit():
161                     return int(s)
162         raise DeployNotStart('Unable to start deployment: {}'.format(response))
163
164     def _deployment_status(self, id):
165         task = self._task_fields(id)
166         if task['status'] == 'error':
167             if task['message'].endswith(
168                     'offline. Remove them from environment and try again.'):
169                 raise NodesGoOffline(task['message'])
170         return task['status'], task['progress'], task['message']
171
172     def _task_fields(self, id):
173         try:
174             out, _ = exec_cmd('fuel2 task show {} -f json'.format(id), False)
175             task_info = json.loads(out)
176             properties = {}
177             # for 9.0 this can be list of dicts or dict
178             # see https://bugs.launchpad.net/fuel/+bug/1625518
179             if isinstance(task_info, list):
180                 for d in task_info:
181                         properties.update({d['Field']: d['Value']})
182             else:
183                 return task_info
184             return properties
185         except ValueError as e:
186             err('Unable to fetch task info: {}'.format(e))
187
188     def collect_logs(self):
189         log('Cleaning out any previous deployment logs')
190         exec_cmd('rm -f /var/log/remote/fuel-snapshot-*', False)
191         exec_cmd('rm -f /root/deploy-*', False)
192         log('Generating Fuel deploy snap-shot')
193         if exec_cmd('fuel snapshot < /dev/null &> snapshot.log', False)[1] <> 0:
194             log('Could not create a Fuel snapshot')
195         else:
196             exec_cmd('mv /root/fuel-snapshot* /var/log/remote/', False)
197
198         log('Collecting all Fuel Snapshot & deploy log files')
199         r, _ = exec_cmd('tar -czhf /root/deploy-%s.log.tar.gz /var/log/remote' % time.strftime("%Y%m%d-%H%M%S"), False)
200         log(r)
201
202     def verify_node_status(self):
203         node_list = parse(exec_cmd('fuel --env %s node' % self.env_id))
204         failed_nodes = []
205         for node in node_list:
206             if node[N['status']] != 'ready':
207                 failed_nodes.append((node[N['id']], node[N['status']]))
208
209         if failed_nodes:
210             summary = ''
211             for node, status in failed_nodes:
212                 summary += '[node %s, status %s]\n' % (node, status)
213             err('Deployment failed: %s' % summary, self.collect_logs)
214
215     def health_check(self):
216         log('Now running sanity and smoke health checks')
217         r = exec_cmd('fuel health --env %s --check sanity,smoke --force' % self.env_id)
218         log(r)
219         if 'failure' in r:
220             err('Healthcheck failed!', self.collect_logs)
221
222     def deploy(self):
223         self.run_deploy()
224         self.verify_node_status()
225         if not self.no_health_check:
226             self.health_check()
227         self.collect_logs()