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