Merge "[deployment_handler] Fix some nits and improve output"
[releng.git] / modules / opnfv / deployment / manager.py
1 ##############################################################################
2 # Copyright (c) 2017 Ericsson AB and others.
3 # Author: Jose Lausuch (jose.lausuch@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 from abc import abstractmethod
11 import os
12
13
14 from opnfv.utils import opnfv_logger as logger
15 from opnfv.utils import ssh_utils
16
17 logger = logger.Logger(__name__).getLogger()
18
19
20 class Deployment(object):
21
22     def __init__(self,
23                  installer,
24                  installer_ip,
25                  scenario,
26                  pod,
27                  status,
28                  openstack_version,
29                  sdn_controller,
30                  nodes=None):
31
32         self.deployment_info = {
33             'installer': installer,
34             'installer_ip': installer_ip,
35             'scenario': scenario,
36             'pod': pod,
37             'status': status,
38             'openstack_version': openstack_version,
39             'sdn_controller': sdn_controller,
40             'nodes': nodes
41         }
42
43     def _get_openstack_release(self):
44         '''
45         Translates an openstack version into the release name
46         '''
47         os_versions = {
48             '12': 'Liberty',
49             '13': 'Mitaka',
50             '14': 'Newton',
51             '15': 'Ocata',
52             '16': 'Pike',
53             '17': 'Queens'
54         }
55         try:
56             version = self.deployment_info['openstack_version'].split('.')[0]
57             name = os_versions[version]
58             return name
59         except Exception:
60             return 'Unknown release'
61
62     def get_dict(self):
63         '''
64         Returns a dictionary will all the attributes
65         '''
66         return self.deployment_info
67
68     def __str__(self):
69         '''
70         Override of the str method
71         '''
72         s = '''
73         INSTALLER:    {installer}
74         SCENARIO:     {scenario}
75         INSTALLER IP: {installer_ip}
76         POD:          {pod}
77         STATUS:       {status}
78         OPENSTACK:    {openstack_version} ({openstack_release})
79         SDN:          {sdn_controller}
80         NODES:
81     '''.format(installer=self.deployment_info['installer'],
82                scenario=self.deployment_info['scenario'],
83                installer_ip=self.deployment_info['installer_ip'],
84                pod=self.deployment_info['pod'],
85                status=self.deployment_info['status'],
86                openstack_version=self.deployment_info[
87             'openstack_version'],
88             openstack_release=self._get_openstack_release(),
89             sdn_controller=self.deployment_info['sdn_controller'])
90
91         for node in self.deployment_info['nodes']:
92             s += '{node_object}\n'.format(node_object=node)
93
94         return s
95
96
97 class Role():
98     CONTROLLER = 'controller'
99     COMPUTE = 'compute'
100     ODL = 'opendaylight'
101     ONOS = 'onos'
102
103
104 class NodeStatus():
105     STATUS_OK = 'active'
106     STATUS_INACTIVE = 'inactive'
107     STATUS_OFFLINE = 'offline'
108     STATUS_ERROR = 'error'
109     STATUS_UNUSED = 'unused'
110
111
112 class Node(object):
113
114     def __init__(self,
115                  id,
116                  ip,
117                  name,
118                  status,
119                  roles=None,
120                  ssh_client=None,
121                  info=None):
122         self.id = id
123         self.ip = ip
124         self.name = name
125         self.status = status
126         self.ssh_client = ssh_client
127         self.roles = roles
128         self.info = info
129
130         self.cpu_info = 'unknown'
131         self.memory = 'unknown'
132         self.ovs = 'unknown'
133
134         if ssh_client:
135             sys_info = self.get_system_info()
136             self.cpu_info = sys_info['cpu_info']
137             self.memory = sys_info['memory']
138             self.ovs = self.get_ovs_info()
139
140     def get_file(self, src, dest):
141         '''
142         SCP file from a node
143         '''
144         if self.status is not NodeStatus.STATUS_OK:
145             logger.info("The node %s is not active" % self.ip)
146             return 1
147         logger.info("Fetching %s from %s" % (src, self.ip))
148         get_file_result = ssh_utils.get_file(self.ssh_client, src, dest)
149         if get_file_result is None:
150             logger.error("SFTP failed to retrieve the file.")
151         else:
152             logger.info("Successfully copied %s:%s to %s" %
153                         (self.ip, src, dest))
154         return get_file_result
155
156     def put_file(self, src, dest):
157         '''
158         SCP file to a node
159         '''
160         if self.status is not NodeStatus.STATUS_OK:
161             logger.info("The node %s is not active" % self.ip)
162             return 1
163         logger.info("Copying %s to %s" % (src, self.ip))
164         put_file_result = ssh_utils.put_file(self.ssh_client, src, dest)
165         if put_file_result is None:
166             logger.error("SFTP failed to retrieve the file.")
167         else:
168             logger.info("Successfully copied %s to %s:%s" %
169                         (src, dest, self.ip))
170         return put_file_result
171
172     def run_cmd(self, cmd):
173         '''
174         Run command remotely on a node
175         '''
176         if self.status is not NodeStatus.STATUS_OK:
177             logger.error(
178                 "Error running command %s. The node %s is not active"
179                 % (cmd, self.ip))
180             return None
181         _, stdout, stderr = (self.ssh_client.exec_command(cmd))
182         error = stderr.readlines()
183         if len(error) > 0:
184             logger.error("error %s" % ''.join(error))
185             return None
186         output = ''.join(stdout.readlines()).rstrip()
187         return output
188
189     def get_dict(self):
190         '''
191         Returns a dictionary with all the attributes
192         '''
193         return {
194             'id': self.id,
195             'ip': self.ip,
196             'name': self.name,
197             'status': self.status,
198             'roles': self.roles,
199             'cpu_info': self.cpu_info,
200             'memory': self.memory,
201             'ovs': self.ovs,
202             'info': self.info
203         }
204
205     def is_active(self):
206         '''
207         Returns if the node is active
208         '''
209         if self.status == NodeStatus.STATUS_OK:
210             return True
211         return False
212
213     def is_controller(self):
214         '''
215         Returns if the node is a controller
216         '''
217         return Role.CONTROLLER in self.roles
218
219     def is_compute(self):
220         '''
221         Returns if the node is a compute
222         '''
223         return Role.COMPUTE in self.roles
224
225     def is_odl(self):
226         '''
227         Returns if the node is an opendaylight
228         '''
229         return Role.ODL in self.roles
230
231     def get_ovs_info(self):
232         '''
233         Returns the ovs version installed
234         '''
235         if self.is_active():
236             cmd = "ovs-vsctl --version|head -1| sed 's/^.*) //'"
237             return self.run_cmd(cmd)
238         return None
239
240     def get_system_info(self):
241         '''
242         Returns the ovs version installed
243         '''
244         cmd = 'grep MemTotal /proc/meminfo'
245         memory = self.run_cmd(cmd).partition('MemTotal:')[-1].strip().encode()
246
247         cpu_info = {}
248         cmd = 'lscpu'
249         result = self.run_cmd(cmd)
250         for line in result.splitlines():
251             if line.startswith('CPU(s)'):
252                 cpu_info['num_cpus'] = line.split(' ')[-1].encode()
253             elif line.startswith('Thread(s) per core'):
254                 cpu_info['threads/core'] = line.split(' ')[-1].encode()
255             elif line.startswith('Core(s) per socket'):
256                 cpu_info['cores/socket'] = line.split(' ')[-1].encode()
257             elif line.startswith('Model name'):
258                 cpu_info['model'] = line.partition(
259                     'Model name:')[-1].strip().encode()
260             elif line.startswith('Architecture'):
261                 cpu_info['arch'] = line.split(' ')[-1].encode()
262
263         return {'memory': memory, 'cpu_info': cpu_info}
264
265     def __str__(self):
266         return '''
267             name:    {name}
268             id:      {id}
269             ip:      {ip}
270             status:  {status}
271             roles:   {roles}
272             cpu:     {cpu_info}
273             memory:  {memory}
274             ovs:     {ovs}
275             info:    {info}'''.format(name=self.name,
276                                       id=self.id,
277                                       ip=self.ip,
278                                       status=self.status,
279                                       roles=self.roles,
280                                       cpu_info=self.cpu_info,
281                                       memory=self.memory,
282                                       ovs=self.ovs,
283                                       info=self.info)
284
285
286 class DeploymentHandler(object):
287
288     EX_OK = os.EX_OK
289     EX_ERROR = os.EX_SOFTWARE
290     FUNCTION_NOT_IMPLEMENTED = "Function not implemented by adapter!"
291
292     def __init__(self,
293                  installer,
294                  installer_ip,
295                  installer_user,
296                  installer_pwd=None,
297                  pkey_file=None):
298
299         self.installer = installer.lower()
300         self.installer_ip = installer_ip
301         self.installer_user = installer_user
302         self.installer_pwd = installer_pwd
303         self.pkey_file = pkey_file
304
305         if pkey_file is not None and not os.path.isfile(pkey_file):
306             raise Exception(
307                 'The private key file %s does not exist!' % pkey_file)
308
309         self.installer_connection = ssh_utils.get_ssh_client(
310             hostname=self.installer_ip,
311             username=self.installer_user,
312             password=self.installer_pwd,
313             pkey_file=self.pkey_file)
314
315         if self.installer_connection:
316             self.installer_node = Node(id='',
317                                        ip=installer_ip,
318                                        name=installer,
319                                        status=NodeStatus.STATUS_OK,
320                                        ssh_client=self.installer_connection,
321                                        roles='installer node')
322         else:
323             raise Exception(
324                 'Cannot establish connection to the installer node!')
325
326         self.nodes = self.get_nodes()
327
328     @abstractmethod
329     def get_openstack_version(self):
330         '''
331         Returns a string of the openstack version (nova-compute)
332         '''
333         raise Exception(DeploymentHandler.FUNCTION_NOT_IMPLEMENTED)
334
335     @abstractmethod
336     def get_sdn_version(self):
337         '''
338         Returns a string of the sdn controller and its version, if exists
339         '''
340         raise Exception(DeploymentHandler.FUNCTION_NOT_IMPLEMENTED)
341
342     @abstractmethod
343     def get_deployment_status(self):
344         '''
345         Returns a string of the status of the deployment
346         '''
347         raise Exception(DeploymentHandler.FUNCTION_NOT_IMPLEMENTED)
348
349     @abstractmethod
350     def get_nodes(self, options=None):
351         '''
352             Generates a list of all the nodes in the deployment
353         '''
354         raise Exception(DeploymentHandler.FUNCTION_NOT_IMPLEMENTED)
355
356     def get_installer_node(self):
357         '''
358             Returns the installer node object
359         '''
360         return self.installer_node
361
362     def get_deployment_info(self):
363         '''
364             Returns an object of type Deployment
365         '''
366         return Deployment(installer=self.installer,
367                           installer_ip=self.installer_ip,
368                           scenario=os.getenv('DEPLOY_SCENARIO', 'Unknown'),
369                           status=self.get_deployment_status(),
370                           pod=os.getenv('NODE_NAME', 'Unknown'),
371                           openstack_version=self.get_openstack_version(),
372                           sdn_controller=self.get_sdn_version(),
373                           nodes=self.get_nodes())