Merge "Added Search_Results Page"
[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     INSTALLER = 'installer'
99     CONTROLLER = 'controller'
100     COMPUTE = 'compute'
101     ODL = 'opendaylight'
102     ONOS = 'onos'
103
104
105 class NodeStatus():
106     STATUS_OK = 'active'
107     STATUS_INACTIVE = 'inactive'
108     STATUS_OFFLINE = 'offline'
109     STATUS_ERROR = 'error'
110     STATUS_UNUSED = 'unused'
111
112
113 class Node(object):
114
115     def __init__(self,
116                  id,
117                  ip,
118                  name,
119                  status,
120                  roles=None,
121                  ssh_client=None,
122                  info=None):
123         self.id = id
124         self.ip = ip
125         self.name = name
126         self.status = status
127         self.ssh_client = ssh_client
128         self.roles = roles
129         self.info = info
130
131         self.cpu_info = 'unknown'
132         self.memory = 'unknown'
133         self.ovs = 'unknown'
134
135         if ssh_client and Role.INSTALLER not in self.roles:
136             sys_info = self.get_system_info()
137             self.cpu_info = sys_info['cpu_info']
138             self.memory = sys_info['memory']
139             self.ovs = self.get_ovs_info()
140
141     def get_file(self, src, dest):
142         '''
143         SCP file from a node
144         '''
145         if self.status is not NodeStatus.STATUS_OK:
146             logger.info("The node %s is not active" % self.ip)
147             return 1
148         logger.info("Fetching %s from %s" % (src, self.ip))
149         get_file_result = ssh_utils.get_file(self.ssh_client, src, dest)
150         if get_file_result is None:
151             logger.error("SFTP failed to retrieve the file.")
152         else:
153             logger.info("Successfully copied %s:%s to %s" %
154                         (self.ip, src, dest))
155         return get_file_result
156
157     def put_file(self, src, dest):
158         '''
159         SCP file to a node
160         '''
161         if self.status is not NodeStatus.STATUS_OK:
162             logger.info("The node %s is not active" % self.ip)
163             return 1
164         logger.info("Copying %s to %s" % (src, self.ip))
165         put_file_result = ssh_utils.put_file(self.ssh_client, src, dest)
166         if put_file_result is None:
167             logger.error("SFTP failed to retrieve the file.")
168         else:
169             logger.info("Successfully copied %s to %s:%s" %
170                         (src, dest, self.ip))
171         return put_file_result
172
173     def run_cmd(self, cmd):
174         '''
175         Run command remotely on a node
176         '''
177         if self.status is not NodeStatus.STATUS_OK:
178             logger.error(
179                 "Error running command %s. The node %s is not active"
180                 % (cmd, self.ip))
181             return None
182         _, stdout, stderr = (self.ssh_client.exec_command(cmd))
183         error = stderr.readlines()
184         if len(error) > 0:
185             logger.error("error %s" % ''.join(error))
186             return None
187         output = ''.join(stdout.readlines()).rstrip()
188         return output
189
190     def get_dict(self):
191         '''
192         Returns a dictionary with all the attributes
193         '''
194         return {
195             'id': self.id,
196             'ip': self.ip,
197             'name': self.name,
198             'status': self.status,
199             'roles': self.roles,
200             'cpu_info': self.cpu_info,
201             'memory': self.memory,
202             'ovs': self.ovs,
203             'info': self.info
204         }
205
206     def is_active(self):
207         '''
208         Returns if the node is active
209         '''
210         if self.status == NodeStatus.STATUS_OK:
211             return True
212         return False
213
214     def is_controller(self):
215         '''
216         Returns if the node is a controller
217         '''
218         return Role.CONTROLLER in self.roles
219
220     def is_compute(self):
221         '''
222         Returns if the node is a compute
223         '''
224         return Role.COMPUTE in self.roles
225
226     def is_odl(self):
227         '''
228         Returns if the node is an opendaylight
229         '''
230         return Role.ODL in self.roles
231
232     def get_ovs_info(self):
233         '''
234         Returns the ovs version installed
235         '''
236         if self.is_active():
237             cmd = "ovs-vsctl --version|head -1| sed 's/^.*) //'"
238             return self.run_cmd(cmd)
239         return None
240
241     def get_system_info(self):
242         '''
243         Returns the ovs version installed
244         '''
245         cmd = 'grep MemTotal /proc/meminfo'
246         memory = self.run_cmd(cmd).partition('MemTotal:')[-1].strip().encode()
247
248         cpu_info = {}
249         cmd = 'lscpu'
250         result = self.run_cmd(cmd)
251         for line in result.splitlines():
252             if line.startswith('CPU(s)'):
253                 cpu_info['num_cpus'] = line.split(' ')[-1].encode()
254             elif line.startswith('Thread(s) per core'):
255                 cpu_info['threads/core'] = line.split(' ')[-1].encode()
256             elif line.startswith('Core(s) per socket'):
257                 cpu_info['cores/socket'] = line.split(' ')[-1].encode()
258             elif line.startswith('Model name'):
259                 cpu_info['model'] = line.partition(
260                     'Model name:')[-1].strip().encode()
261             elif line.startswith('Architecture'):
262                 cpu_info['arch'] = line.split(' ')[-1].encode()
263
264         return {'memory': memory, 'cpu_info': cpu_info}
265
266     def __str__(self):
267         return '''
268             name:    {name}
269             id:      {id}
270             ip:      {ip}
271             status:  {status}
272             roles:   {roles}
273             cpu:     {cpu_info}
274             memory:  {memory}
275             ovs:     {ovs}
276             info:    {info}'''.format(name=self.name,
277                                       id=self.id,
278                                       ip=self.ip,
279                                       status=self.status,
280                                       roles=self.roles,
281                                       cpu_info=self.cpu_info,
282                                       memory=self.memory,
283                                       ovs=self.ovs,
284                                       info=self.info)
285
286
287 class DeploymentHandler(object):
288
289     EX_OK = os.EX_OK
290     EX_ERROR = os.EX_SOFTWARE
291     FUNCTION_NOT_IMPLEMENTED = "Function not implemented by adapter!"
292
293     def __init__(self,
294                  installer,
295                  installer_ip,
296                  installer_user,
297                  installer_pwd=None,
298                  pkey_file=None):
299
300         self.installer = installer.lower()
301         self.installer_ip = installer_ip
302         self.installer_user = installer_user
303         self.installer_pwd = installer_pwd
304         self.pkey_file = pkey_file
305
306         if pkey_file is not None and not os.path.isfile(pkey_file):
307             raise Exception(
308                 'The private key file %s does not exist!' % pkey_file)
309
310         self.installer_connection = ssh_utils.get_ssh_client(
311             hostname=self.installer_ip,
312             username=self.installer_user,
313             password=self.installer_pwd,
314             pkey_file=self.pkey_file)
315
316         if self.installer_connection:
317             self.installer_node = Node(id='',
318                                        ip=installer_ip,
319                                        name=installer,
320                                        status=NodeStatus.STATUS_OK,
321                                        ssh_client=self.installer_connection,
322                                        roles=Role.INSTALLER)
323         else:
324             raise Exception(
325                 'Cannot establish connection to the installer node!')
326
327         self.nodes = self.get_nodes()
328
329     @abstractmethod
330     def get_openstack_version(self):
331         '''
332         Returns a string of the openstack version (nova-compute)
333         '''
334         raise Exception(DeploymentHandler.FUNCTION_NOT_IMPLEMENTED)
335
336     @abstractmethod
337     def get_sdn_version(self):
338         '''
339         Returns a string of the sdn controller and its version, if exists
340         '''
341         raise Exception(DeploymentHandler.FUNCTION_NOT_IMPLEMENTED)
342
343     @abstractmethod
344     def get_deployment_status(self):
345         '''
346         Returns a string of the status of the deployment
347         '''
348         raise Exception(DeploymentHandler.FUNCTION_NOT_IMPLEMENTED)
349
350     @abstractmethod
351     def get_nodes(self, options=None):
352         '''
353             Generates a list of all the nodes in the deployment
354         '''
355         raise Exception(DeploymentHandler.FUNCTION_NOT_IMPLEMENTED)
356
357     def get_installer_node(self):
358         '''
359             Returns the installer node object
360         '''
361         return self.installer_node
362
363     def get_arch(self):
364         '''
365             Returns the architecture of the first compute node found
366         '''
367         arch = None
368         for node in self.nodes:
369             if node.is_compute():
370                 arch = node.cpu_info.get('arch', None)
371                 if arch:
372                     break
373         return arch
374
375     def get_deployment_info(self):
376         '''
377             Returns an object of type Deployment
378         '''
379         return Deployment(installer=self.installer,
380                           installer_ip=self.installer_ip,
381                           scenario=os.getenv('DEPLOY_SCENARIO', 'Unknown'),
382                           status=self.get_deployment_status(),
383                           pod=os.getenv('NODE_NAME', 'Unknown'),
384                           openstack_version=self.get_openstack_version(),
385                           sdn_controller=self.get_sdn_version(),
386                           nodes=self.get_nodes())