e1b827f9c9c0f758389c3224e8cb1f87d972bcfc
[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             (_, _, _) = ssh.exec_command_sudo(command)
104
105     @staticmethod
106     def configure_persistence(node, state):
107         """Enable or disable Honeycomb configuration data persistence.
108
109         :param node: Honeycomb node.
110         :param state: Enable or Disable.
111         :type node: dict
112         :type state: str
113         :raises ValueError: If the state argument is incorrect.
114         :raises HoneycombError: If the operation fails.
115         """
116
117         state = state.lower()
118         if state == "enable":
119             state = "true"
120         elif state == "disable":
121             state = "false"
122         else:
123             raise ValueError("Unexpected value of state argument:"
124                              " {0} provided. Must be enable or disable."
125                              .format(state))
126
127         for setting in ("persist-config", "persist-context"):
128             # find the setting, replace entire line with 'setting: state'
129             find = '\\"{setting}\\":'.format(setting=setting)
130             replace = '\\"{setting}\\": \\"{state}\\",'.format(
131                 setting=setting, state=state)
132
133             argument = '"/{0}/c\\ {1}"'.format(find, replace)
134             path = "{0}/config/honeycomb.json".format(Const.REMOTE_HC_DIR)
135             command = "sed -i {0} {1}".format(argument, path)
136
137             ssh = SSH()
138             ssh.connect(node)
139             (ret_code, _, stderr) = ssh.exec_command_sudo(command)
140             if ret_code != 0:
141                 raise HoneycombError("Failed to modify configuration on "
142                                      "node {0}, {1}".format(node, stderr))

©2016 FD.io a Linux Foundation Collaborative Project. All Rights Reserved.
Linux Foundation is a registered trademark of The Linux Foundation. Linux is a registered trademark of Linus Torvalds.
Please see our privacy policy and terms of use.