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