Page MenuHomeVyOS Platform

No OneTemporary

Size
23 KB
Referenced Files
None
Subscribers
None
diff --git a/Makefile b/Makefile
index 588595e42..964c533f2 100644
--- a/Makefile
+++ b/Makefile
@@ -1,134 +1,137 @@
TMPL_DIR := templates-cfg
OP_TMPL_DIR := templates-op
BUILD_DIR := build
DATA_DIR := data
SHIM_DIR := src/shim
XDP_DIR := src/xdp
CC := gcc
LIBS := -lzmq
CFLAGS :=
src = $(wildcard interface-definitions/*.xml.in)
obj = $(src:.xml.in=.xml)
%.xml: %.xml.in
@echo Generating $(BUILD_DIR)/$@ from $<
# -ansi This turns off certain features of GCC that are incompatible
# with ISO C90. Without this regexes containing '/' as in an URL
# won't work
# -x c By default GCC guesses the input language from its file extension,
# thus XML is unknown. Force it to C language
# -E Stop after the preprocessing stage
# -undef Do not predefine any system-specific or GCC-specific macros.
# -nostdinc Do not search the standard system directories for header files
# -P Inhibit generation of linemarkers in the output from the
# preprocessor
@$(CC) -x c-header -E -undef -nostdinc -P -I$(CURDIR)/interface-definitions -o $(BUILD_DIR)/$@ -c $<
$(BUILD_DIR):
install -d -m 0755 $(BUILD_DIR)/interface-definitions
install -d -m 0755 $(BUILD_DIR)/op-mode-definitions
.PHONY: interface_definitions
.ONESHELL:
interface_definitions: $(BUILD_DIR) $(obj)
mkdir -p $(TMPL_DIR)
+ # Build "base" templates (service, interfaces, other high-level nodes)
+ $(CURDIR)/scripts/build-command-templates $(CURDIR)/interface-definitions/base/base.xml $(CURDIR)/schema/interface_definition.rng $(TMPL_DIR)
+
find $(BUILD_DIR)/interface-definitions -type f -name "*.xml" | xargs -I {} $(CURDIR)/scripts/build-command-templates {} $(CURDIR)/schema/interface_definition.rng $(TMPL_DIR) || exit 1
# XXX: delete top level node.def's that now live in other packages
rm -f $(TMPL_DIR)/firewall/node.def
rm -f $(TMPL_DIR)/interfaces/node.def
rm -f $(TMPL_DIR)/protocols/node.def
rm -rf $(TMPL_DIR)/protocols/nbgp
rm -f $(TMPL_DIR)/protocols/static/node.def
rm -f $(TMPL_DIR)/policy/node.def
rm -f $(TMPL_DIR)/system/node.def
rm -f $(TMPL_DIR)/vpn/node.def
rm -f $(TMPL_DIR)/vpn/ipsec/node.def
rm -rf $(TMPL_DIR)/vpn/nipsec
# XXX: required until OSPF and RIP is migrated from vyatta-cfg-quagga to vyos-1x
mkdir $(TMPL_DIR)/interfaces/loopback/node.tag/ipv6
mkdir $(TMPL_DIR)/interfaces/dummy/node.tag/ipv6
mkdir $(TMPL_DIR)/interfaces/openvpn/node.tag/ip
mkdir -p $(TMPL_DIR)/interfaces/vti/node.tag/ip
mkdir -p $(TMPL_DIR)/interfaces/vti/node.tag/ipv6
cp $(TMPL_DIR)/interfaces/ethernet/node.tag/ipv6/node.def $(TMPL_DIR)/interfaces/loopback/node.tag/ipv6
cp $(TMPL_DIR)/interfaces/ethernet/node.tag/ipv6/node.def $(TMPL_DIR)/interfaces/dummy/node.tag/ipv6
cp $(TMPL_DIR)/interfaces/ethernet/node.tag/ip/node.def $(TMPL_DIR)/interfaces/openvpn/node.tag/ip
cp $(TMPL_DIR)/interfaces/ethernet/node.tag/ip/node.def $(TMPL_DIR)/interfaces/vti/node.tag/ip
cp $(TMPL_DIR)/interfaces/ethernet/node.tag/ipv6/node.def $(TMPL_DIR)/interfaces/vti/node.tag/ipv6
.PHONY: op_mode_definitions
.ONESHELL:
op_mode_definitions:
mkdir -p $(OP_TMPL_DIR)
find $(CURDIR)/op-mode-definitions/ -type f -name "*.xml" | xargs -I {} $(CURDIR)/scripts/build-command-op-templates {} $(CURDIR)/schema/op-mode-definition.rng $(OP_TMPL_DIR) || exit 1
# XXX: delete top level op mode node.def's that now live in other packages
rm -f $(OP_TMPL_DIR)/add/node.def
rm -f $(OP_TMPL_DIR)/clear/interfaces/node.def
rm -f $(OP_TMPL_DIR)/clear/node.def
rm -f $(OP_TMPL_DIR)/delete/node.def
rm -f $(OP_TMPL_DIR)/generate/node.def
rm -f $(OP_TMPL_DIR)/monitor/node.def
rm -f $(OP_TMPL_DIR)/reset/vpn/node.def
rm -f $(OP_TMPL_DIR)/set/node.def
rm -f $(OP_TMPL_DIR)/show/interfaces/node.def
rm -f $(OP_TMPL_DIR)/show/node.def
rm -f $(OP_TMPL_DIR)/show/system/node.def
rm -f $(OP_TMPL_DIR)/show/vpn/node.def
# XXX: ping must be able to recursivly call itself as the
# options are provided from the script itself
ln -s ../node.tag $(OP_TMPL_DIR)/ping/node.tag/node.tag/
.PHONY: component_versions
.ONESHELL:
component_versions: $(BUILD_DIR) $(obj)
$(CURDIR)/scripts/build-component-versions $(BUILD_DIR)/interface-definitions $(DATA_DIR)
.PHONY: vyshim
vyshim:
$(MAKE) -C $(SHIM_DIR)
.PHONY: vyxdp
vyxdp:
$(MAKE) -C $(XDP_DIR)
.PHONY: all
all: clean interface_definitions op_mode_definitions component_versions vyshim vyxdp
.PHONY: clean
clean:
rm -rf $(BUILD_DIR)
rm -rf $(TMPL_DIR)
rm -rf $(OP_TMPL_DIR)
$(MAKE) -C $(SHIM_DIR) clean
$(MAKE) -C $(XDP_DIR) clean
.PHONY: test
test:
set -e; python3 -m compileall -q .
PYTHONPATH=python/ python3 -m "nose" --with-xunit src --with-coverage --cover-erase --cover-xml --cover-package src/conf_mode,src/op_mode,src/completion,src/helpers,src/validators,src/tests --verbose
.PHONY: sonar
sonar:
sonar-scanner -X -Dsonar.login=${SONAR_TOKEN}
.PHONY: docs
.ONESHELL:
docs:
sphinx-apidoc -o sphinx/source/ python/
cd sphinx/
PYTHONPATH=../python make html
deb:
dpkg-buildpackage -uc -us -tc -b
.PHONY: schema
schema:
trang -I rnc -O rng schema/interface_definition.rnc schema/interface_definition.rng
trang -I rnc -O rng schema/op-mode-definition.rnc schema/op-mode-definition.rng
diff --git a/interface-definitions/base/base.xml b/interface-definitions/base/base.xml
new file mode 100644
index 000000000..919478d45
--- /dev/null
+++ b/interface-definitions/base/base.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0"?>
+<interfaceDefinition>
+ <node name="interfaces">
+ <properties>
+ <help>Network interfaces</help>
+ </properties>
+ </node>
+ <node name="high-availability">
+ <properties>
+ <help>High availability mechanisms</help>
+ </properties>
+ </node>
+ <node name="nat">
+ <properties>
+ <help>Network address translation</help>
+ </properties>
+ </node>
+ <node name="service">
+ <properties>
+ <help>Network and system services</help>
+ </properties>
+ </node>
+</interfaceDefinition>
diff --git a/scripts/build-command-op-templates b/scripts/build-command-op-templates
index c60b32a1e..54cc07794 100755
--- a/scripts/build-command-op-templates
+++ b/scripts/build-command-op-templates
@@ -1,225 +1,226 @@
#!/usr/bin/env python3
#
# build-command-template: converts new style command definitions in XML
# to the old style (bunch of dirs and node.def's) command templates
#
# Copyright (C) 2017 VyOS maintainers <maintainers@vyos.net>
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
import sys
import os
import argparse
import copy
import functools
from lxml import etree as ET
# Defaults
validator_dir = "/opt/vyatta/libexec/validators"
default_constraint_err_msg = "Invalid value"
## Get arguments
parser = argparse.ArgumentParser(description='Converts new-style XML interface definitions to old-style command templates')
parser.add_argument('--debug', help='Enable debug information output', action='store_true')
parser.add_argument('INPUT_FILE', type=str, help="XML interface definition file")
parser.add_argument('SCHEMA_FILE', type=str, help="RelaxNG schema file")
parser.add_argument('OUTPUT_DIR', type=str, help="Output directory")
args = parser.parse_args()
input_file = args.INPUT_FILE
schema_file = args.SCHEMA_FILE
output_dir = args.OUTPUT_DIR
debug = args.debug
## Load and validate the inputs
try:
xml = ET.parse(input_file)
except Exception as e:
print("Failed to load interface definition file {0}".format(input_file))
print(e)
sys.exit(1)
try:
relaxng_xml = ET.parse(schema_file)
validator = ET.RelaxNG(relaxng_xml)
if not validator.validate(xml):
print(validator.error_log)
print("Interface definition file {0} does not match the schema!".format(input_file))
sys.exit(1)
except Exception as e:
print("Failed to load the XML schema {0}".format(schema_file))
print(e)
sys.exit(1)
if not os.access(output_dir, os.W_OK):
print("The output directory {0} is not writeable".format(output_dir))
sys.exit(1)
## If we got this far, everything must be ok and we can convert the file
def make_path(l):
path = functools.reduce(os.path.join, l)
if debug:
print(path)
return path
def get_properties(p):
props = {}
if p is None:
return props
# Get the help string
try:
props["help"] = p.find("help").text
except:
props["help"] = "No help available"
# Get the completion help strings
try:
che = p.findall("completionHelp")
ch = ""
for c in che:
scripts = c.findall("script")
paths = c.findall("path")
lists = c.findall("list")
# Current backend doesn't support multiple allowed: tags
# so we get to emulate it
comp_exprs = []
for i in lists:
comp_exprs.append("echo \"{0}\"".format(i.text))
for i in paths:
comp_exprs.append("/bin/cli-shell-api listActiveNodes {0} | sed -e \"s/'//g\" && echo".format(i.text))
for i in scripts:
comp_exprs.append("{0}".format(i.text))
comp_help = " && ".join(comp_exprs)
props["comp_help"] = comp_help
except:
props["comp_help"] = []
return props
def make_node_def(props, command):
# XXX: replace with a template processor if it grows
# out of control
node_def = ""
if "help" in props:
node_def += "help: {0}\n".format(props["help"])
if "comp_help" in props:
node_def += "allowed: {0}\n".format(props["comp_help"])
if command is not None:
node_def += "run: {0}\n".format(command.text)
if debug:
print("The contents of the node.def file:\n", node_def)
return node_def
def process_node(n, tmpl_dir):
# Avoid mangling the path from the outer call
my_tmpl_dir = copy.copy(tmpl_dir)
props_elem = n.find("properties")
children = n.find("children")
command = n.find("command")
name = n.get("name")
node_type = n.tag
my_tmpl_dir.append(name)
if debug:
print("Name of the node: {};\n Created directory: ".format(name), end="")
os.makedirs(make_path(my_tmpl_dir), exist_ok=True)
props = get_properties(props_elem)
if node_type == "node":
if debug:
print("Processing node {}".format(name))
nodedef_path = os.path.join(make_path(my_tmpl_dir), "node.def")
if not os.path.exists(nodedef_path):
with open(nodedef_path, "w") as f:
f.write(make_node_def(props, command))
else:
# Something has already generated this file
pass
if children is not None:
inner_nodes = children.iterfind("*")
for inner_n in inner_nodes:
process_node(inner_n, my_tmpl_dir)
if node_type == "tagNode":
if debug:
print("Processing tag node {}".format(name))
os.makedirs(make_path(my_tmpl_dir), exist_ok=True)
nodedef_path = os.path.join(make_path(my_tmpl_dir), "node.def")
if not os.path.exists(nodedef_path):
with open(nodedef_path, "w") as f:
f.write('help: {0}\n'.format(props['help']))
else:
# Something has already generated this file
+ print("Warning: refusing to overwrite already existing file {}".format(nodedef_path))
pass
# Create the inner node.tag part
my_tmpl_dir.append("node.tag")
os.makedirs(make_path(my_tmpl_dir), exist_ok=True)
if debug:
print("Created path for the tagNode: {}".format(make_path(my_tmpl_dir)), end="")
# Not sure if we want partially defined tag nodes, write the file unconditionally
with open(os.path.join(make_path(my_tmpl_dir), "node.def"), "w") as f:
f.write(make_node_def(props, command))
if children is not None:
inner_nodes = children.iterfind("*")
for inner_n in inner_nodes:
process_node(inner_n, my_tmpl_dir)
else:
# This is a leaf node
if debug:
print("Processing leaf node {}".format(name))
with open(os.path.join(make_path(my_tmpl_dir), "node.def"), "w") as f:
f.write(make_node_def(props, command))
root = xml.getroot()
nodes = root.iterfind("*")
for n in nodes:
process_node(n, [output_dir])
diff --git a/scripts/build-command-templates b/scripts/build-command-templates
index d6585b0cc..f09941e68 100755
--- a/scripts/build-command-templates
+++ b/scripts/build-command-templates
@@ -1,308 +1,315 @@
#!/usr/bin/env python3
#
# build-command-template: converts new style command definitions in XML
# to the old style (bunch of dirs and node.def's) command templates
#
-# Copyright (C) 2017 VyOS maintainers <maintainers@vyos.net>
+# Copyright (C) 2017,2021 VyOS maintainers <maintainers@vyos.net>
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301
# USA
import sys
import os
import argparse
import copy
import functools
from lxml import etree as ET
# Defaults
#validator_dir = "/usr/libexec/vyos/validators"
validator_dir = "${vyos_validators_dir}"
default_constraint_err_msg = "Invalid value"
## Get arguments
parser = argparse.ArgumentParser(description='Converts new-style XML interface definitions to old-style command templates')
parser.add_argument('--debug', help='Enable debug information output', action='store_true')
parser.add_argument('INPUT_FILE', type=str, help="XML interface definition file")
parser.add_argument('SCHEMA_FILE', type=str, help="RelaxNG schema file")
parser.add_argument('OUTPUT_DIR', type=str, help="Output directory")
args = parser.parse_args()
input_file = args.INPUT_FILE
schema_file = args.SCHEMA_FILE
output_dir = args.OUTPUT_DIR
debug = args.debug
#debug = True
## Load and validate the inputs
try:
xml = ET.parse(input_file)
except Exception as e:
print("Failed to load interface definition file {0}".format(input_file))
print(e)
sys.exit(1)
try:
relaxng_xml = ET.parse(schema_file)
validator = ET.RelaxNG(relaxng_xml)
if not validator.validate(xml):
print(validator.error_log)
print("Interface definition file {0} does not match the schema!".format(input_file))
sys.exit(1)
except Exception as e:
print("Failed to load the XML schema {0}".format(schema_file))
print(e)
sys.exit(1)
if not os.access(output_dir, os.W_OK):
print("The output directory {0} is not writeable".format(output_dir))
sys.exit(1)
## If we got this far, everything must be ok and we can convert the file
def make_path(l):
path = functools.reduce(os.path.join, l)
if debug:
print(path)
return path
def get_properties(p):
props = {}
if p is None:
return props
# Get the help string
try:
props["help"] = p.find("help").text
except:
pass
# Get value help strings
try:
vhe = p.findall("valueHelp")
vh = []
for v in vhe:
vh.append( (v.find("format").text, v.find("description").text) )
props["val_help"] = vh
except:
props["val_help"] = []
# Get the constraint statements
error_msg = default_constraint_err_msg
# Get the error message if it's there
try:
error_msg = p.find("constraintErrorMessage").text
except:
pass
vce = p.find("constraint")
vc = []
if vce is not None:
# The old backend doesn't support multiple validators in OR mode
# so we emulate it
regexes = []
regex_elements = vce.findall("regex")
if regex_elements is not None:
regexes = list(map(lambda e: e.text.strip().replace('\\','\\\\'), regex_elements))
if "" in regexes:
print("Warning: empty regex, node will be accepting any value")
validator_elements = vce.findall("validator")
validators = []
if validator_elements is not None:
for v in validator_elements:
v_name = os.path.join(validator_dir, v.get("name"))
# XXX: lxml returns None for empty arguments
v_argument = None
try:
v_argument = v.get("argument")
except:
pass
if v_argument is None:
v_argument = ""
validators.append("{0} {1}".format(v_name, v_argument))
regex_args = " ".join(map(lambda s: "--regex \\\'{0}\\\'".format(s), regexes))
validator_args = " ".join(map(lambda s: "--exec \\\"{0}\\\"".format(s), validators))
validator_script = '${vyos_libexec_dir}/validate-value'
validator_string = "exec \"{0} {1} {2} --value \\\'$VAR(@)\\\'\"; \"{3}\"".format(validator_script, regex_args, validator_args, error_msg)
props["constraint"] = validator_string
# Get the completion help strings
try:
che = p.findall("completionHelp")
ch = ""
for c in che:
scripts = c.findall("script")
paths = c.findall("path")
lists = c.findall("list")
# Current backend doesn't support multiple allowed: tags
# so we get to emulate it
comp_exprs = []
for i in lists:
comp_exprs.append("echo \"{0}\"".format(i.text))
for i in paths:
comp_exprs.append("/bin/cli-shell-api listNodes {0}".format(i.text))
for i in scripts:
comp_exprs.append("sh -c \"{0}\"".format(i.text))
comp_help = " && ".join(comp_exprs)
props["comp_help"] = comp_help
except:
props["comp_help"] = []
# Get priority
try:
props["priority"] = p.find("priority").text
except:
pass
# Get "multi"
if p.find("multi") is not None:
props["multi"] = True
# Get "valueless"
if p.find("valueless") is not None:
props["valueless"] = True
return props
def make_node_def(props):
# XXX: replace with a template processor if it grows
# out of control
node_def = ""
if "tag" in props:
node_def += "tag:\n"
if "multi" in props:
node_def += "multi:\n"
if "type" in props:
# Will always be txt in practice if it's set
node_def += "type: {0}\n".format(props["type"])
if "priority" in props:
node_def += "priority: {0}\n".format(props["priority"])
if "help" in props:
node_def += "help: {0}\n".format(props["help"])
if "val_help" in props:
for v in props["val_help"]:
node_def += "val_help: {0}; {1}\n".format(v[0], v[1])
if "comp_help" in props:
node_def += "allowed: {0}\n".format(props["comp_help"])
if "constraint" in props:
node_def += "syntax:expression: {0}\n".format(props["constraint"])
shim = '${vyshim}'
if "owner" in props:
if "tag" in props:
node_def += "end: sudo sh -c \"{1} VYOS_TAGNODE_VALUE='$VAR(@)' {0}\"\n".format(props["owner"], shim)
else:
node_def += "end: sudo sh -c \"{1} {0}\"\n".format(props["owner"], shim)
if debug:
print("The contents of the node.def file:\n", node_def)
return node_def
def process_node(n, tmpl_dir):
# Avoid mangling the path from the outer call
my_tmpl_dir = copy.copy(tmpl_dir)
props_elem = n.find("properties")
children = n.find("children")
name = n.get("name")
owner = n.get("owner")
node_type = n.tag
my_tmpl_dir.append(name)
if debug:
print("Name of the node: {0}. Created directory: {1}\n".format(name, "/".join(my_tmpl_dir)), end="")
os.makedirs(make_path(my_tmpl_dir), exist_ok=True)
props = get_properties(props_elem)
if owner:
props["owner"] = owner
# Type should not be set for non-tag, non-leaf nodes
# For non-valueless leaf nodes, set the type to txt: to make them have some type,
# actual value validation is handled by constraints translated to syntax:expression:
if node_type != "node":
if "valueless" not in props.keys():
props["type"] = "txt"
if node_type == "tagNode":
props["tag"] = "True"
if node_type != "leafNode":
if "multi" in props:
raise ValueError("<multi/> tag is only allowed in <leafNode>")
if "valueless" in props:
raise ValueError("<valueless/> is only allowed in <leafNode>")
nodedef_path = os.path.join(make_path(my_tmpl_dir), "node.def")
if not os.path.exists(nodedef_path):
with open(nodedef_path, "w") as f:
f.write(make_node_def(props))
else:
# Something has already generated that file
+ print("Warning: refusing to overwrite already existing file {}".format(nodedef_path))
pass
- if node_type == "node":
+ if (node_type == "node") and (children is None):
+ print("Warning: non-leaf, non-tag <node> without children may be incomplete ({})".format(nodedef_path))
+ pass
+ elif node_type == "node":
inner_nodes = children.iterfind("*")
for inner_n in inner_nodes:
process_node(inner_n, my_tmpl_dir)
- if node_type == "tagNode":
+ elif node_type == "tagNode":
+ if children is None:
+ raise ValueError("A <tagNode> without children is not allowed")
+
+ inner_nodes = children.iterfind("*")
my_tmpl_dir.append("node.tag")
if debug:
print("Created path for the tagNode:", end="")
os.makedirs(make_path(my_tmpl_dir), exist_ok=True)
- inner_nodes = children.iterfind("*")
for inner_n in inner_nodes:
process_node(inner_n, my_tmpl_dir)
else:
# This is a leaf node
pass
root = xml.getroot()
nodes = root.iterfind("*")
for n in nodes:
if n.tag == "syntaxVersion":
continue
process_node(n, [output_dir])

File Metadata

Mime Type
text/x-diff
Expires
Thu, Nov 26, 9:16 PM (1 d, 22 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4987276
Default Alt Text
(23 KB)

Event Timeline