3159609f1c28c3d271370a0ad9fc8c93a01b1f41
[releng.git] / modules / opnfv / utils / ovs_logger.py
1 ##############################################################################
2 # Copyright (c) 2015 Ericsson AB and others.
3 # Author: George Paraskevopoulos (geopar@intracom-telecom.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 opnfv.utils.OPNFVLogger as OPNFVLogger
11 import os
12 import time
13 import shutil
14
15 logger = OPNFVLogger.Logger('ovs_logger').getLogger()
16
17
18 class OVSLogger(object):
19     def __init__(self, basedir, ft_resdir):
20         self.ovs_dir = basedir
21         self.ft_resdir = ft_resdir
22         self.__mkdir_p(self.ovs_dir)
23         self.__mkdir_p(self.ft_resdir)
24
25     def __mkdir_p(self, dirpath):
26         if not os.path.exists(dirpath):
27             os.makedirs(dirpath)
28
29     def __ssh_host(self, ssh_conn, host_prefix='10.20.0'):
30         try:
31             _, stdout, _ = ssh_conn.exec_command('hostname -I')
32             hosts = stdout.readline().strip().split(' ')
33             found_host = [h for h in hosts if h.startswith(host_prefix)][0]
34             return found_host
35         except Exception, e:
36             logger.error(e)
37
38     def __dump_to_file(self, operation, host, text, timestamp=None):
39         ts = (timestamp if timestamp is not None
40               else time.strftime("%Y%m%d-%H%M%S"))
41         dumpdir = os.path.join(self.ovs_dir, ts)
42         self.__mkdir_p(dumpdir)
43         fname = '{0}_{1}'.format(operation, host)
44         with open(os.path.join(dumpdir, fname), 'w') as f:
45             f.write(text)
46
47     def __remote_cmd(self, ssh_conn, cmd):
48         try:
49             _, stdout, stderr = ssh_conn.exec_command(cmd)
50             errors = stderr.readlines()
51             if len(errors) > 0:
52                 host = self.__ssh_host(ssh_conn)
53                 logger.error(''.join(errors))
54                 raise Exception('Could not execute {0} in {1}'
55                                 .format(cmd, host))
56             output = ''.join(stdout.readlines())
57             return output
58         except Exception, e:
59             logger.error('[__remote_command(ssh_client, {0})]: {1}'
60                          .format(cmd, e))
61             return None
62
63     def create_artifact_archive(self):
64         shutil.make_archive(self.ovs_dir,
65                             'zip',
66                             root_dir=os.path.dirname(self.ovs_dir),
67                             base_dir=self.ovs_dir)
68         shutil.copy2('{0}.zip'.format(self.ovs_dir), self.ft_resdir)
69
70     def ofctl_dump_flows(self, ssh_conn, br='br-int',
71                          choose_table=None, timestamp=None):
72         try:
73             cmd = 'ovs-ofctl -OOpenFlow13 dump-flows {0}'.format(br)
74             if choose_table is not None:
75                 cmd = '{0} table={1}'.format(cmd, choose_table)
76             output = self.__remote_cmd(ssh_conn, cmd)
77             operation = 'ofctl_dump_flows'
78             host = self.__ssh_host(ssh_conn)
79             self.__dump_to_file(operation, host, output, timestamp=timestamp)
80             return output
81         except Exception, e:
82             logger.error('[ofctl_dump_flows(ssh_client, {0}, {1})]: {2}'
83                          .format(br, choose_table, e))
84             return None
85
86     def vsctl_show(self, ssh_conn, timestamp=None):
87         try:
88             cmd = 'ovs-vsctl show'
89             output = self.__remote_cmd(ssh_conn, cmd)
90             operation = 'vsctl_show'
91             host = self.__ssh_host(ssh_conn)
92             self.__dump_to_file(operation, host, output, timestamp=timestamp)
93             return output
94         except Exception, e:
95             logger.error('[vsctl_show(ssh_client)]: {0}'.format(e))
96             return None
97
98     def dump_ovs_logs(self, controller_clients, compute_clients,
99                       related_error=None, timestamp=None):
100         if timestamp is None:
101             timestamp = time.strftime("%Y%m%d-%H%M%S")
102
103         for controller_client in controller_clients:
104             self.ofctl_dump_flows(controller_client,
105                                   timestamp=timestamp)
106             self.vsctl_show(controller_client,
107                             timestamp=timestamp)
108
109         for compute_client in compute_clients:
110             self.ofctl_dump_flows(compute_client,
111                                   timestamp=timestamp)
112             self.vsctl_show(compute_client,
113                             timestamp=timestamp)
114
115         if related_error is not None:
116             dumpdir = os.path.join(self.ovs_dir, timestamp)
117             with open(os.path.join(dumpdir, 'error'), 'w') as f:
118                 f.write(related_error)