CSIT-536 HC Test: support testing with ODL client
[csit.git] / resources / libraries / python / honeycomb / HcPersistence.py
1 # Copyright (c) 2016 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
5 #
6 #     http://www.apache.org/licenses/LICENSE-2.0
7 #
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 """Implementation of keywords for managing Honeycomb persistence files."""
15
16 from robot.api import logger
17
18 from resources.libraries.python.constants import Constants as Const
19 from resources.libraries.python.honeycomb.HoneycombUtil import HoneycombError
20 from resources.libraries.python.ssh import SSH
21 from resources.libraries.python.topology import NodeType
22
23
24 class HcPersistence(object):
25     """Implements keywords for managing Honeycomb persistence files.
26
27     The keywords implemented in this class make possible to:
28     - find and replace strings in config.json persistence file
29     """
30
31     def __init__(self):
32         pass
33
34     @staticmethod
35     def clear_persisted_honeycomb_config(*nodes):
36         """Remove configuration data persisted from last Honeycomb session.
37         Default configuration will be used instead.
38
39         :param nodes: List of DUTs to execute on.
40         :type nodes: list
41         :raises HoneycombError: If persisted configuration could not be removed.
42         """
43         cmd = "rm -rf {}/*".format(Const.REMOTE_HC_PERSIST)
44         for node in nodes:
45             if node['type'] == NodeType.DUT:
46                 ssh = SSH()
47                 ssh.connect(node)
48                 (ret_code, _, stderr) = ssh.exec_command_sudo(cmd)
49                 if ret_code != 0:
50                     if "No such file or directory" not in stderr:
51                         raise HoneycombError('Could not clear persisted '
52                                              'configuration on node {0}, {1}'
53                                              .format(node['host'], stderr))
54                     else:
55                         logger.info("Persistence data was not present on node"
56                                     " {0}".format(node['host']))
57                 else:
58                     logger.info("Persistence files removed on node {0}"
59                                 .format(node['host']))
60
61     @staticmethod
62     def modify_persistence_files(node, find, replace):
63         """Searches contents of persistence file data.json for the provided
64          string, and replaces all occurrences with another string.
65
66         :param node: Honeycomb node.
67         :param find: Text to find in file.
68         :param replace: String to replace anything found with.
69         :type node: dict
70         :type find: string
71         :type replace: string
72         :raises HoneycombError: If persistent configuration couldn't be
73         modified.
74         """
75
76         argument = "\"s/{0}/{1}/g\"".format(find, replace)
77         path = "{0}/config/data.json".format(Const.REMOTE_HC_PERSIST)
78         command = "sed -i {0} {1}".format(argument, path)
79
80         ssh = SSH()
81         ssh.connect(node)
82         (ret_code, _, stderr) = ssh.exec_command_sudo(command)
83         if ret_code != 0:
84             raise HoneycombError("Failed to modify persistence file on node"
85                                  " {0}, {1}".format(node, stderr))
86
87     @staticmethod
88     def log_persisted_configuration(node):
89         """Read contents of Honeycomb persistence files and print them to log.
90
91         :param node: Honeycomb node.
92         :type node: dict
93         """
94
95         commands = [
96             "cat {0}/config/data.json".format(Const.REMOTE_HC_PERSIST),
97             "cat {0}/context/data.json".format(Const.REMOTE_HC_PERSIST),
98         ]
99
100         ssh = SSH()
101         ssh.connect(node)
102         for command in commands:
103             (_, stdout, _) = ssh.exec_command_sudo(command)
104             logger.info(stdout)
105
106
107     @staticmethod
108     def configure_persistence(node, state):
109         """Enable or disable Honeycomb configuration data persistence.
110
111         :param node: Honeycomb node.
112         :param state: Enable or Disable.
113         :type node: dict
114         :type state: str
115         :raises ValueError: If the state argument is incorrect.
116         :raises HoneycombError: If the operation fails.
117         """
118
119         state = state.lower()
120         if state == "enable":
121             state = "true"
122         elif state == "disable":
123             state = "false"
124         else:
125             raise ValueError("Unexpected value of state argument:"
126                              " {0} provided. Must be enable or disable."
127                              .format(state))
128
129         for setting in ("persist-config", "persist-context"):
130             # find the setting, replace entire line with 'setting: state'
131             find = '\\"{setting}\\":'.format(setting=setting)
132             replace = '\\"{setting}\\": \\"{state}\\",'.format(
133                 setting=setting, state=state)
134
135             argument = '"/{0}/c\\ {1}"'.format(find, replace)
136             path = "{0}/config/honeycomb.json".format(Const.REMOTE_HC_DIR)
137             command = "sed -i {0} {1}".format(argument, path)
138
139             ssh = SSH()
140             ssh.connect(node)
141             (ret_code, _, stderr) = ssh.exec_command_sudo(command)
142             if ret_code != 0:
143                 raise HoneycombError("Failed to modify configuration on "
144                                      "node {0}, {1}".format(node, stderr))