summaryrefslogtreecommitdiff
path: root/python/vyos
diff options
context:
space:
mode:
Diffstat (limited to 'python/vyos')
-rw-r--r--python/vyos/component_versions.py57
-rw-r--r--python/vyos/config.py8
-rw-r--r--python/vyos/configdict.py80
-rw-r--r--python/vyos/configtree.py71
-rw-r--r--python/vyos/limericks.py8
-rw-r--r--python/vyos/validate.py102
6 files changed, 307 insertions, 19 deletions
diff --git a/python/vyos/component_versions.py b/python/vyos/component_versions.py
new file mode 100644
index 000000000..ec54a1576
--- /dev/null
+++ b/python/vyos/component_versions.py
@@ -0,0 +1,57 @@
+# Copyright 2017 VyOS maintainers and contributors <maintainers@vyos.io>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library. If not, see <http://www.gnu.org/licenses/>.
+
+"""
+The version data looks like:
+
+/* Warning: Do not remove the following line. */
+/* === vyatta-config-version:
+"cluster@1:config-management@1:conntrack-sync@1:conntrack@1:dhcp-relay@1:dhcp-server@4:firewall@5:ipsec@4:nat@4:qos@1:quagga@2:system@8:vrrp@1:wanloadbalance@3:webgui@1:webproxy@1:zone-policy@1"
+=== */
+/* Release version: 1.2.0-rolling+201806131737 */
+"""
+
+import re
+
+def get_component_version(string_line):
+ """
+ Get component version dictionary from string
+ return empty dictionary if string contains no config information
+ or raise error if component version string malformed
+ """
+ return_value = {}
+ if re.match(r'/\* === vyatta-config-version:.+=== \*/$', string_line):
+
+ if not re.match(r'/\* === vyatta-config-version:\s+"([\w,-]+@\d+:)+([\w,-]+@\d+)"\s+=== \*/$', string_line):
+ raise ValueError("malformed configuration string: " + str(string_line))
+
+ for pair in re.findall(r'([\w,-]+)@(\d+)', string_line):
+ if pair[0] in return_value.keys():
+ raise ValueError("duplicate unit name: \"" + str(pair[0]) + "\" in string: \"" + string_line + "\"")
+ return_value[pair[0]] = int(pair[1])
+
+ return return_value
+
+
+def get_component_versions_from_file(config_file_name='/opt/vyatta/etc/config/config.boot'):
+ """
+ Get component version dictionary parsing config file line by line
+ """
+ f = open(config_file_name, 'r')
+ for line_in_config in f:
+ component_version = return_version(line_in_config)
+ if component_version:
+ return component_version
+ raise ValueError("no config string in file:", config_file_name)
diff --git a/python/vyos/config.py b/python/vyos/config.py
index 5af830480..bcf04225b 100644
--- a/python/vyos/config.py
+++ b/python/vyos/config.py
@@ -280,8 +280,8 @@ class Config(object):
else:
try:
out = self._run(self._make_command('returnValues', full_path))
- values = out.split()
- return list(map(lambda x: re.sub(r'^\'(.*)\'$', r'\1',x), values))
+ values = re.findall(r"\'(.*?)\'", out)
+ return values
except VyOSError:
return(default)
@@ -309,8 +309,8 @@ class Config(object):
if self.is_tag(path):
try:
out = self._run(self._make_command('listNodes', full_path))
- values = out.split()
- return list(map(lambda x: re.sub(r'^\'(.*)\'$', r'\1',x), values))
+ values = re.findall(r"\'(.*?)\'", out)
+ return values
except VyOSError:
return(default)
else:
diff --git a/python/vyos/configdict.py b/python/vyos/configdict.py
new file mode 100644
index 000000000..157011839
--- /dev/null
+++ b/python/vyos/configdict.py
@@ -0,0 +1,80 @@
+# Copyright 2019 VyOS maintainers and contributors <maintainers@vyos.io>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library. If not, see <http://www.gnu.org/licenses/>.
+
+"""
+A library for retrieving value dicts from VyOS configs in a declarative fashion.
+
+"""
+
+
+def retrieve_config(path_hash, base_path, config):
+ """
+ Retrieves a VyOS config as a dict according to a declarative description
+
+ The description dict, passed in the first argument, must follow this format:
+ ``field_name : <path, type, [inner_options_dict]>``.
+
+ Supported types are: ``str`` (for normal nodes),
+ ``list`` (returns a list of strings, for multi nodes),
+ ``bool`` (returns True if valueless node exists),
+ ``dict`` (for tag nodes, returns a dict indexed by node names,
+ according to description in the third item of the tuple).
+
+ Args:
+ path_hash (dict): Declarative description of the config to retrieve
+ base_path (list): A base path to prepend to all option paths
+ config (vyos.config.Config): A VyOS config object
+
+ Returns:
+ dict: config dict
+ """
+ config_hash = {}
+
+ for k in path_hash:
+
+ if type(path_hash[k]) != tuple:
+ raise ValueError("In field {0}: expected a tuple, got a value {1}".format(k, str(path_hash[k])))
+ if len(path_hash[k]) < 2:
+ raise ValueError("In field {0}: field description must be a tuple of at least two items, path (list) and type".format(k))
+
+ path = path_hash[k][0]
+ if type(path) != list:
+ raise ValueError("In field {0}: path must be a list, not a {1}".format(k, type(path)))
+
+ typ = path_hash[k][1]
+ if type(typ) != type:
+ raise ValueError("In field {0}: type must be a type, not a {1}".format(k, type(typ)))
+
+ path = base_path + path
+
+ path_str = " ".join(path)
+
+ if typ == str:
+ config_hash[k] = config.return_value(path_str)
+ elif typ == list:
+ config_hash[k] = config.return_values(path_str)
+ elif typ == bool:
+ config_hash[k] = config.exists(path_str)
+ elif typ == dict:
+ try:
+ inner_hash = path_hash[k][2]
+ except IndexError:
+ raise ValueError("The type of the \'{0}\' field is dict, but inner options hash is missing from the tuple".format(k))
+ config_hash[k] = {}
+ nodes = config.list_nodes(path_str)
+ for node in nodes:
+ config_hash[k][node] = retrieve_config(inner_hash, path + [node], config)
+
+ return config_hash
diff --git a/python/vyos/configtree.py b/python/vyos/configtree.py
index 4b46a1fb3..a812b62ec 100644
--- a/python/vyos/configtree.py
+++ b/python/vyos/configtree.py
@@ -24,6 +24,7 @@ def strip_comments(s):
IN_COMMENT = 1
i = len(s) - 1
+
state = INITIAL
config_end = 0
@@ -40,20 +41,19 @@ def strip_comments(s):
else:
config_end = 0
break
- elif (state == INITIAL) and (c == '/'):
- # A comment begins, or it's a stray slash
- try:
- if (s[i-1] == '*'):
- state = IN_COMMENT
- i -= 2
- else:
- raise ValueError("Invalid syntax")
- except:
- raise ValueError("Invalid syntax")
- elif (state == INITIAL) and (c == '}'):
- # We are not inside a comment, that's the end of the last node
+ elif (state == INITIAL) and not re.match(r'(\s|\/)', c):
+ # Assume there are no (more) trailing comments,
+ # this is an end of a node: either a brace of the last character
+ # of a leaf node value
config_end = i + 1
break
+ elif (state == INITIAL) and (c == '/'):
+ # A comment begins, or it's a stray slash
+ if (s[i-1] == '*'):
+ state = IN_COMMENT
+ i -= 2
+ else:
+ raise ValueError("Invalid syntax: stray slash at character {0}".format(i + 1))
elif (state == IN_COMMENT) and (c == '*'):
# A comment ends here
try:
@@ -61,12 +61,13 @@ def strip_comments(s):
state = INITIAL
i -= 2
except:
- raise ValueError("Invalid syntax")
+ raise ValueError("Invalid syntax: malformed commend end at character {0}".format(i + 1))
elif (state == IN_COMMENT) and (c != '*'):
# Ignore everything inside comments, including braces
i -= 1
else:
- raise ValueError("Invalid syntax")
+ # Shouldn't happen
+ raise ValueError("Invalid syntax at character {0}: invalid character {1}".format(i + 1, c))
return (s[0:config_end], s[config_end+1:])
@@ -92,6 +93,10 @@ class ConfigTree(object):
self.__from_string.argtypes = [c_char_p]
self.__from_string.restype = c_void_p
+ self.__get_error = self.__lib.get_error
+ self.__get_error.argtypes = []
+ self.__get_error.restype = c_char_p
+
self.__to_string = self.__lib.to_string
self.__to_string.argtypes = [c_void_p]
self.__to_string.restype = c_char_p
@@ -112,6 +117,14 @@ class ConfigTree(object):
self.__delete.argtypes = [c_void_p, c_char_p]
self.__delete.restype = c_int
+ self.__rename = self.__lib.rename_node
+ self.__rename.argtypes = [c_void_p, c_char_p, c_char_p]
+ self.__rename.restype = c_int
+
+ self.__copy = self.__lib.copy_node
+ self.__copy.argtypes = [c_void_p, c_char_p, c_char_p]
+ self.__copy.restype = c_int
+
self.__set_replace_value = self.__lib.set_replace_value
self.__set_replace_value.argtypes = [c_void_p, c_char_p, c_char_p]
self.__set_replace_value.restype = c_int
@@ -150,10 +163,12 @@ class ConfigTree(object):
config_section, comments_section = strip_comments(config_string)
config = self.__from_string(config_section.encode())
if config is None:
- raise ValueError("Parse error")
+ msg = self.__get_error().decode()
+ raise ValueError("Failed to parse config: {0}".format(msg))
else:
self.__config = config
self.__comments = comments_section
+
def __del__(self):
if self.__config is not None:
self.__destroy(self.__config)
@@ -193,6 +208,32 @@ class ConfigTree(object):
self.__delete_value(self.__config, path_str, value.encode())
+ def rename(self, path, new_name):
+ check_path(path)
+ path_str = " ".join(map(str, path)).encode()
+ newname_str = new_name.encode()
+
+ # Check if a node with intended new name already exists
+ new_path = path[:-1] + [new_name]
+ if self.exists(new_path):
+ raise ConfigTreeError()
+ res = self.__rename(self.__config, path_str, newname_str)
+ if (res != 0):
+ raise ConfigTreeError("Path [{}] doesn't exist".format(oldpath))
+
+ def copy(self, old_path, new_path):
+ check_path(old_path)
+ check_path(new_path)
+ oldpath_str = " ".join(map(str, old_path)).encode()
+ newpath_str = " ".join(map(str, new_path)).encode()
+
+ # Check if a node with intended new name already exists
+ if self.exists(new_path):
+ raise ConfigTreeError()
+ res = self.__copy(self.__config, oldpath_str, newpath_str)
+ if (res != 0):
+ raise ConfigTreeError("Path [{}] doesn't exist".format(oldpath))
+
def exists(self, path):
check_path(path)
path_str = " ".join(map(str, path)).encode()
diff --git a/python/vyos/limericks.py b/python/vyos/limericks.py
index 97bb5ae76..e03ccd32b 100644
--- a/python/vyos/limericks.py
+++ b/python/vyos/limericks.py
@@ -55,6 +55,14 @@ greeted friends with a three-way handshake
and refused to proceed
if they didn't complete it,
that standards-compliant guy Drake.
+""",
+
+"""
+A network admin from Nantucket
+used hierarchy token buckets.
+Bandwidth limits he set
+slowed down his net,
+users drove him away from Nantucket.
"""
]
diff --git a/python/vyos/validate.py b/python/vyos/validate.py
new file mode 100644
index 000000000..8def0a510
--- /dev/null
+++ b/python/vyos/validate.py
@@ -0,0 +1,102 @@
+# Copyright 2018 VyOS maintainers and contributors <maintainers@vyos.io>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library. If not, see <http://www.gnu.org/licenses/>.
+
+import netifaces
+import ipaddress
+
+def is_ipv4(addr):
+ """
+ Check addr if it is an IPv4 address/network.
+
+ Return True/False
+ """
+ if ipaddress.ip_network(addr).version == 4:
+ return True
+ else:
+ return False
+
+def is_ipv6(addr):
+ """
+ Check addr if it is an IPv6 address/network.
+
+ Return True/False
+ """
+ if ipaddress.ip_network(addr).version == 6:
+ return True
+ else:
+ return False
+
+def is_addr_assigned(addr):
+ """
+ Verify if the given IPv4/IPv6 address is assigned to any interface on this
+ system.
+
+ Return True/False
+ """
+
+ # determine IP version (AF_INET or AF_INET6) depending on passed address
+ addr_type = netifaces.AF_INET
+ if is_ipv6(addr):
+ addr_type = netifaces.AF_INET6
+
+ for interface in netifaces.interfaces():
+ # check if the requested address type is configured at all
+ if addr_type in netifaces.ifaddresses(interface).keys():
+ # Check every IP address on this interface for a match
+ for ip in netifaces.ifaddresses(interface)[addr_type]:
+ # Check if it matches to the address requested
+ if ip['addr'] == addr:
+ return True
+
+ return False
+
+def is_subnet_connected(subnet, primary=False):
+ """
+ Verify is the given IPv4/IPv6 subnet is connected to any interface on this
+ system.
+
+ primary check if the subnet is reachable via the primary IP address of this
+ interface, or in other words has a broadcast address configured. ISC DHCP
+ for instance will complain if it should listen on non broadcast interfaces.
+
+ Return True/False
+ """
+
+ # determine IP version (AF_INET or AF_INET6) depending on passed address
+ addr_type = netifaces.AF_INET
+ if is_ipv6(subnet):
+ addr_type = netifaces.AF_INET6
+
+ for interface in netifaces.interfaces():
+ # check if the requested address type is configured at all
+ if addr_type not in netifaces.ifaddresses(interface).keys():
+ continue
+
+ # An interface can have multiple addresses, but some software components
+ # only support the primary address :(
+ if primary:
+ ip = netifaces.ifaddresses(interface)[addr_type][0]['addr']
+ if ipaddress.ip_address(ip) in ipaddress.ip_network(subnet):
+ return True
+ else:
+ # Check every assigned IP address if it is connected to the subnet
+ # in question
+ for ip in netifaces.ifaddresses(interface)[addr_type]:
+ # remove interface extension (e.g. %eth0) that gets thrown on the end of _some_ addrs
+ addr = ip['addr'].split('%')[0]
+ if ipaddress.ip_address(addr) in ipaddress.ip_network(subnet):
+ return True
+
+ return False