Debian Codegraph @

ansible_collections/dellemc/enterprise_sonic/plugins/module_utils/network/sonic/sonic.py

raw symbols SCIP
1 # This code is part of Ansible, but is an independent component.
2 # This particular file snippet, and this file snippet only, is BSD licensed.
3 # Modules you write using this snippet, which is embedded dynamically by Ansible
4 # still belong to the author of the module, and may assign their own license
5 # to the complete work.
6 #
7 # (c) 2016 Red Hat Inc.
8 #
9 # Redistribution and use in source and binary forms, with or without modification,
10 # are permitted provided that the following conditions are met:
11 #
12 # * Redistributions of source code must retain the above copyright
13 # notice, this list of conditions and the following disclaimer.
14 # * Redistributions in binary form must reproduce the above copyright notice,
15 # this list of conditions and the following disclaimer in the documentation
16 # and/or other materials provided with the distribution.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 # IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
23 # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
26 # USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 #
28
29 from __future__ import absolute_import, division, print_function
30 __metaclass__ = type
31
32 import json
33 import re
34
35 from ansible.module_utils._text import to_text
36 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.utils import (
37 to_list,
38 ComplexList
39 )
40 from ansible.module_utils.connection import Connection, ConnectionError
41 from ansible_collections.ansible.netcommon.plugins.module_utils.network.common.config import NetworkConfig, ConfigLine
42
43 _DEVICE_CONFIGS = {}
44 STANDARD_ETH_REGEXP = r"(Eth\d+(/\d+)+)"
45
46
47 def get_connection(module):
48 if hasattr(module, "_sonic_connection"):
49 return module._sonic_connection
50
51 capabilities = get_capabilities(module)
52 network_api = capabilities.get("network_api")
53 if network_api in ["cliconf", "sonic_rest"]:
54 module._sonic_connection = Connection(module._socket_path)
55 else:
56 module.fail_json(msg="Invalid connection type %s" % network_api)
57
58 return module._sonic_connection
59
60
61 def get_capabilities(module):
62 if hasattr(module, "_sonic_capabilities"):
63 return module._sonic_capabilities
64 try:
65 capabilities = Connection(module._socket_path).get_capabilities()
66 except ConnectionError as exc:
67 module.fail_json(msg=to_text(exc, errors="surrogate_then_replace"))
68 module._sonic_capabilities = json.loads(capabilities)
69 return module._sonic_capabilities
70
71
72 def get_config(module, flags=None):
73 flags = to_list(flags)
74 flag_str = " ".join(flags)
75
76 try:
77 return _DEVICE_CONFIGS[flag_str]
78 except KeyError:
79 connection = get_connection(module)
80 try:
81 out = connection.get_config(flags=flags)
82 except ConnectionError as exc:
83 module.fail_json(msg=to_text(exc, errors="surrogate_then_replace"))
84 cfg = to_text(out, errors="surrogate_then_replace").strip()
85 _DEVICE_CONFIGS[flag_str] = cfg
86 return cfg
87
88
89 def get_sublevel_config(running_config, module):
90 contents = list()
91 current_config_contents = list()
92 running_config = NetworkConfig(contents=running_config, indent=1)
93 obj = running_config.get_object(module.params['parents'])
94 if obj:
95 contents = obj.children
96 parents = module.params['parents']
97 if parents[2:]:
98 temp = 1
99 for count, item in enumerate(parents[2:], start=2):
100 item = ' ' * temp + item
101 temp = temp + 1
102 parents[count] = item
103 contents[:0] = parents
104 indent = 0
105 for c in contents:
106 if isinstance(c, str):
107 if c in parents:
108 current_config_contents.append(c.rjust(len(c) + indent, ' '))
109 if c not in parents:
110 c = ' ' * (len(parents) - 1) + c
111 current_config_contents.append(c.rjust(len(c) + indent, ' '))
112 if isinstance(c, ConfigLine):
113 current_config_contents.append(c.raw)
114 indent = 1
115 sublevel_config = '\n'.join(current_config_contents)
116 return sublevel_config
117
118
119 def run_commands(module, commands, check_rc=True):
120 connection = get_connection(module)
121 try:
122 return connection.run_commands(commands=commands, check_rc=check_rc)
123 except ConnectionError as exc:
124 module.fail_json(msg=to_text(exc))
125
126
127 def edit_config(module, commands, skip_code=None, suppr_ntf_excp=True):
128 connection = get_connection(module)
129
130 # Start: This is to convert interface name from Eth1/1 to Eth1%2f1
131 for request in commands:
132 # This check is to differentiate between requests and commands
133 if isinstance(request, dict):
134 url = request.get("path", None)
135 if url:
136 request["path"] = update_url(url)
137 # End
138 if suppr_ntf_excp:
139 # Default: not used for cliconf
140 return connection.edit_config(commands)
141 else:
142 return connection.edit_config(commands, suppr_ntf_excp)
143
144
145 def edit_config_reboot(module, commands, skip_code=None):
146 connection = get_connection(module)
147
148 # Start: This is to convert interface name from Eth1/1 to Eth1%2f1
149 for request in commands:
150 # This check is to differentiate between REST API requests and CLI commands
151 if isinstance(request, dict):
152 url = request.get("path", None)
153 if url:
154 request["path"] = update_url(url)
155 # End
156 connection.edit_config_reboot(commands)
157
158
159 def update_url(url):
160 match = re.findall(STANDARD_ETH_REGEXP, url)
161 ret_url = url
162 if match:
163 for item in match:
164 interface_name = item[0]
165 update_interface_name = interface_name.replace("/", "%2f")
166 ret_url = ret_url.replace(interface_name, update_interface_name)
167 return ret_url
168
169
170 def to_request(module, requests):
171 transform = ComplexList(dict(path=dict(key=True), method=dict(), data=dict(type='dict')), module)
172 return transform(to_list(requests))