summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--data/templates/frr/bfdd.frr.tmpl16
-rw-r--r--data/templates/frr/bgpd.frr.tmpl3
-rw-r--r--data/templates/frr/isisd.frr.tmpl91
-rw-r--r--data/templates/frr/ospf6d.frr.tmpl14
-rw-r--r--data/templates/frr/ospfd.frr.tmpl19
-rw-r--r--data/templates/frr/policy.frr.tmpl7
-rw-r--r--data/templates/frr/ripd.frr.tmpl6
-rw-r--r--data/templates/frr/ripngd.frr.tmpl7
-rw-r--r--data/templates/frr/rpki.frr.tmpl1
-rw-r--r--data/templates/ipsec/swanctl/profile.tmpl2
-rw-r--r--interface-definitions/include/generic-disable-node.xml.i2
-rw-r--r--interface-definitions/include/nat-translation-options.xml.i2
-rw-r--r--interface-definitions/include/ospf/protocol-common-config.xml.i27
-rw-r--r--interface-definitions/include/ospfv3/protocol-common-config.xml.i241
-rw-r--r--interface-definitions/protocols-ospfv3.xml.in221
-rw-r--r--interface-definitions/system-option.xml.in6
-rw-r--r--interface-definitions/vrf.xml.in9
-rw-r--r--op-mode-definitions/force-root-partition-auto-resize.xml.in (renamed from op-mode-definitions/force-part-resize.xml.in)4
-rw-r--r--python/vyos/frr.py44
-rw-r--r--python/vyos/remote.py572
-rw-r--r--python/vyos/util.py14
-rw-r--r--smoketest/scripts/cli/test_container.py1
-rwxr-xr-xsmoketest/scripts/cli/test_ha_vrrp.py1
-rwxr-xr-xsmoketest/scripts/cli/test_interfaces_geneve.py1
-rwxr-xr-xsmoketest/scripts/cli/test_interfaces_openvpn.py1
-rwxr-xr-xsmoketest/scripts/cli/test_interfaces_pppoe.py1
-rwxr-xr-xsmoketest/scripts/cli/test_interfaces_vxlan.py1
-rwxr-xr-xsmoketest/scripts/cli/test_interfaces_wireguard.py1
-rwxr-xr-xsmoketest/scripts/cli/test_nat.py1
-rwxr-xr-xsmoketest/scripts/cli/test_nat66.py1
-rwxr-xr-xsmoketest/scripts/cli/test_pki.py1
-rwxr-xr-xsmoketest/scripts/cli/test_policy.py3
-rwxr-xr-xsmoketest/scripts/cli/test_protocols_bfd.py7
-rwxr-xr-xsmoketest/scripts/cli/test_protocols_igmp-proxy.py1
-rwxr-xr-xsmoketest/scripts/cli/test_protocols_isis.py9
-rwxr-xr-xsmoketest/scripts/cli/test_protocols_ospf.py115
-rwxr-xr-xsmoketest/scripts/cli/test_protocols_ospfv3.py45
-rwxr-xr-xsmoketest/scripts/cli/test_protocols_rip.py1
-rwxr-xr-xsmoketest/scripts/cli/test_protocols_ripng.py23
-rwxr-xr-xsmoketest/scripts/cli/test_protocols_rpki.py3
-rwxr-xr-xsmoketest/scripts/cli/test_protocols_static.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_bcast-relay.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_dhcp-relay.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_dhcp-server.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_dhcpv6-relay.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_dhcpv6-server.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_dns_dynamic.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_dns_forwarding.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_https.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_mdns-repeater.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_router-advert.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_snmp.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_ssh.py1
-rwxr-xr-xsmoketest/scripts/cli/test_service_webproxy.py1
-rwxr-xr-xsmoketest/scripts/cli/test_system_acceleration_qat.py1
-rwxr-xr-xsmoketest/scripts/cli/test_system_conntrack.py1
-rwxr-xr-xsmoketest/scripts/cli/test_system_flow-accounting.py80
-rwxr-xr-xsmoketest/scripts/cli/test_system_ip.py1
-rwxr-xr-xsmoketest/scripts/cli/test_system_ipv6.py1
-rwxr-xr-xsmoketest/scripts/cli/test_system_lcd.py1
-rwxr-xr-xsmoketest/scripts/cli/test_system_login.py1
-rwxr-xr-xsmoketest/scripts/cli/test_system_nameserver.py1
-rwxr-xr-xsmoketest/scripts/cli/test_system_ntp.py1
-rwxr-xr-xsmoketest/scripts/cli/test_vpn_ipsec.py2
-rwxr-xr-xsmoketest/scripts/cli/test_vpn_openconnect.py1
-rwxr-xr-xsmoketest/scripts/cli/test_vrf.py1
-rwxr-xr-xsrc/conf_mode/containers.py2
-rwxr-xr-xsrc/conf_mode/policy.py21
-rwxr-xr-xsrc/conf_mode/protocols_bfd.py16
-rwxr-xr-xsrc/conf_mode/protocols_bgp.py15
-rwxr-xr-xsrc/conf_mode/protocols_isis.py26
-rwxr-xr-xsrc/conf_mode/protocols_ospf.py27
-rwxr-xr-xsrc/conf_mode/protocols_ospfv3.py80
-rwxr-xr-xsrc/conf_mode/protocols_rip.py33
-rwxr-xr-xsrc/conf_mode/protocols_ripng.py27
-rwxr-xr-xsrc/conf_mode/protocols_rpki.py17
-rwxr-xr-xsrc/conf_mode/protocols_static.py17
-rwxr-xr-xsrc/conf_mode/system-option.py6
-rwxr-xr-xsrc/conf_mode/vrf_vni.py8
-rwxr-xr-xsrc/migration-scripts/ospf/0-to-181
-rwxr-xr-xsrc/op_mode/force_part_resize.sh72
-rwxr-xr-xsrc/op_mode/force_root-partition-auto-resize.sh60
-rwxr-xr-xsrc/op_mode/lldp_op.py3
-rw-r--r--src/services/api/graphql/README.graphql46
-rw-r--r--src/services/api/graphql/bindings.py5
-rw-r--r--src/services/api/graphql/graphql/directives.py33
-rw-r--r--src/services/api/graphql/graphql/mutations.py83
-rw-r--r--src/services/api/graphql/graphql/schema/config_file.graphql16
-rw-r--r--src/services/api/graphql/graphql/schema/dhcp_server.graphql8
-rw-r--r--src/services/api/graphql/graphql/schema/firewall_group.graphql47
-rw-r--r--src/services/api/graphql/graphql/schema/interface_ethernet.graphql8
-rw-r--r--src/services/api/graphql/graphql/schema/schema.graphql13
-rw-r--r--src/services/api/graphql/recipes/config_file.py16
-rw-r--r--src/services/api/graphql/recipes/dhcp_server.py13
-rw-r--r--src/services/api/graphql/recipes/interface_ethernet.py13
-rw-r--r--src/services/api/graphql/recipes/remove_firewall_address_group_members.py21
-rw-r--r--src/services/api/graphql/recipes/session.py (renamed from src/services/api/graphql/recipes/recipe.py)29
-rw-r--r--src/services/api/graphql/recipes/templates/create_dhcp_server.tmpl (renamed from src/services/api/graphql/recipes/templates/dhcp_server.tmpl)0
-rw-r--r--src/services/api/graphql/recipes/templates/create_firewall_address_group.tmpl4
-rw-r--r--src/services/api/graphql/recipes/templates/create_interface_ethernet.tmpl (renamed from src/services/api/graphql/recipes/templates/interface_ethernet.tmpl)0
-rw-r--r--src/services/api/graphql/recipes/templates/remove_firewall_address_group_members.tmpl3
-rw-r--r--src/services/api/graphql/recipes/templates/update_firewall_address_group_members.tmpl3
-rw-r--r--src/systemd/root-partition-auto-resize.service12
103 files changed, 1379 insertions, 1136 deletions
diff --git a/data/templates/frr/bfdd.frr.tmpl b/data/templates/frr/bfdd.frr.tmpl
index 16f8be92c..c14939677 100644
--- a/data/templates/frr/bfdd.frr.tmpl
+++ b/data/templates/frr/bfdd.frr.tmpl
@@ -1,4 +1,4 @@
-!
+{% if profile is defined or peer is defined %}
bfd
{% if profile is defined and profile is not none %}
{% for profile_name, profile_config in profile.items() %}
@@ -7,7 +7,8 @@ bfd
receive-interval {{ profile_config.interval.receive }}
transmit-interval {{ profile_config.interval.transmit }}
{% if profile_config.interval['echo-interval'] is defined and profile_config.interval['echo-interval'] is not none %}
- echo-interval {{ profile_config.interval['echo-interval'] }}
+ echo transmit-interval {{ profile_config.interval['echo-interval'] }}
+ echo receive-interval {{ profile_config.interval['echo-interval'] }}
{% endif %}
{% if profile_config['echo-mode'] is defined %}
echo-mode
@@ -17,7 +18,8 @@ bfd
{% else %}
no shutdown
{% endif %}
- exit
+ exit
+ !
{% endfor %}
{% endif %}
{% if peer is defined and peer is not none %}
@@ -27,7 +29,7 @@ bfd
receive-interval {{ peer_config.interval.receive }}
transmit-interval {{ peer_config.interval.transmit }}
{% if peer_config.interval['echo-interval'] is defined and peer_config.interval['echo-interval'] is not none %}
- echo-interval {{ peer_config.interval['echo-interval'] }}
+ echo-interval {{ peer_config.interval['echo-interval'] }}
{% endif %}
{% if peer_config['echo-mode'] is defined %}
echo-mode
@@ -37,8 +39,10 @@ bfd
{% else %}
no shutdown
{% endif %}
- exit
+ exit
+ !
{% endfor %}
{% endif %}
- end
+exit
!
+{% endif %}
diff --git a/data/templates/frr/bgpd.frr.tmpl b/data/templates/frr/bgpd.frr.tmpl
index 61936bb56..fbdbafd6e 100644
--- a/data/templates/frr/bgpd.frr.tmpl
+++ b/data/templates/frr/bgpd.frr.tmpl
@@ -524,5 +524,4 @@ router bgp {{ local_as }} {{ 'vrf ' ~ vrf if vrf is defined and vrf is not none
{% if timers is defined and timers.keepalive is defined and timers.holdtime is defined %}
timers bgp {{ timers.keepalive }} {{ timers.holdtime }}
{% endif %}
- end
-! \ No newline at end of file
+exit \ No newline at end of file
diff --git a/data/templates/frr/isisd.frr.tmpl b/data/templates/frr/isisd.frr.tmpl
index 51ac40060..fc0799e02 100644
--- a/data/templates/frr/isisd.frr.tmpl
+++ b/data/templates/frr/isisd.frr.tmpl
@@ -1,4 +1,50 @@
!
+{% if interface is defined and interface is not none %}
+{% for iface, iface_config in interface.items() %}
+interface {{ iface }} {{ 'vrf ' + vrf if vrf is defined and vrf is not none }}
+ ip router isis VyOS
+ ipv6 router isis VyOS
+{% if iface_config.bfd is defined %}
+ isis bfd
+{% endif %}
+{% if iface_config.network is defined and iface_config.network.point_to_point is defined %}
+ isis network point-to-point
+{% endif %}
+{% if iface_config.circuit_type is defined %}
+ isis circuit-type {{ iface_config.circuit_type }}
+{% endif %}
+{% if iface_config.hello_interval is defined and iface_config.hello_interval is not none %}
+ isis hello-interval {{ iface_config.hello_interval }}
+{% endif %}
+{% if iface_config.hello_multiplier is defined and iface_config.hello_multiplier is not none %}
+ isis hello-multiplier {{ iface_config.hello_multiplier }}
+{% endif %}
+{% if iface_config.hello_padding is defined %}
+ isis hello padding
+{% endif %}
+{% if iface_config.metric is defined and iface_config.metric is not none %}
+ isis metric {{ iface_config.metric }}
+{% endif %}
+{% if iface_config.passive is defined %}
+ isis passive
+{% endif %}
+{% if iface_config.password is defined and iface_config.password.plaintext_password is defined and iface_config.password.plaintext_password is not none %}
+ isis password clear {{ iface_config.password.plaintext_password }}
+{% endif %}
+{% if iface_config.priority is defined and iface_config.priority is not none %}
+ isis priority {{ iface_config.priority }}
+{% endif %}
+{% if iface_config.psnp_interval is defined and iface_config.psnp_interval is not none %}
+ isis psnp-interval {{ iface_config.psnp_interval }}
+{% endif %}
+{% if iface_config.no_three_way_handshake is defined %}
+ no isis three-way-handshake
+{% endif %}
+exit
+!
+{% endfor %}
+{% endif %}
+!
router isis VyOS {{ 'vrf ' + vrf if vrf is defined and vrf is not none }}
net {{ net }}
{% if dynamic_hostname is defined %}
@@ -151,48 +197,5 @@ router isis VyOS {{ 'vrf ' + vrf if vrf is defined and vrf is not none }}
is-type {{ level }}
{% endif %}
{% endif %}
-!
-{% if interface is defined and interface is not none %}
-{% for iface, iface_config in interface.items() %}
-interface {{ iface }} {{ 'vrf ' + vrf if vrf is defined and vrf is not none }}
- ip router isis VyOS
- ipv6 router isis VyOS
-{% if iface_config.bfd is defined %}
- isis bfd
-{% endif %}
-{% if iface_config.network is defined and iface_config.network.point_to_point is defined %}
- isis network point-to-point
-{% endif %}
-{% if iface_config.circuit_type is defined %}
- isis circuit-type {{ iface_config.circuit_type }}
-{% endif %}
-{% if iface_config.hello_interval is defined and iface_config.hello_interval is not none %}
- isis hello-interval {{ iface_config.hello_interval }}
-{% endif %}
-{% if iface_config.hello_multiplier is defined and iface_config.hello_multiplier is not none %}
- isis hello-multiplier {{ iface_config.hello_multiplier }}
-{% endif %}
-{% if iface_config.hello_padding is defined %}
- isis hello padding
-{% endif %}
-{% if iface_config.metric is defined and iface_config.metric is not none %}
- isis metric {{ iface_config.metric }}
-{% endif %}
-{% if iface_config.passive is defined %}
- isis passive
-{% endif %}
-{% if iface_config.password is defined and iface_config.password.plaintext_password is defined and iface_config.password.plaintext_password is not none %}
- isis password clear {{ iface_config.password.plaintext_password }}
-{% endif %}
-{% if iface_config.priority is defined and iface_config.priority is not none %}
- isis priority {{ iface_config.priority }}
-{% endif %}
-{% if iface_config.psnp_interval is defined and iface_config.psnp_interval is not none %}
- isis psnp-interval {{ iface_config.psnp_interval }}
-{% endif %}
-{% if iface_config.no_three_way_handshake is defined %}
- no isis three-way-handshake
-{% endif %}
-{% endfor %}
-{% endif %}
+exit
! \ No newline at end of file
diff --git a/data/templates/frr/ospf6d.frr.tmpl b/data/templates/frr/ospf6d.frr.tmpl
index a8c53738f..10a6d9b4b 100644
--- a/data/templates/frr/ospf6d.frr.tmpl
+++ b/data/templates/frr/ospf6d.frr.tmpl
@@ -1,7 +1,10 @@
!
{% if interface is defined and interface is not none %}
{% for iface, iface_config in interface.items() %}
-interface {{ iface }}
+interface {{ iface }} {{ 'vrf ' + vrf if vrf is defined and vrf is not none }}
+{% if iface_config.area is defined and iface_config.area is not none %}
+ ipv6 ospf6 area {{ iface_config.area }}
+{% endif %}
{% if iface_config.cost is defined and iface_config.cost is not none %}
ipv6 ospf6 cost {{ iface_config.cost }}
{% endif %}
@@ -38,18 +41,14 @@ interface {{ iface }}
{% if iface_config.passive is defined %}
ipv6 ospf6 passive
{% endif %}
+exit
!
{% endfor %}
{% endif %}
!
-router ospf6
+router ospf6 {{ 'vrf ' + vrf if vrf is defined and vrf is not none }}
{% if area is defined and area is not none %}
{% for area_id, area_config in area.items() %}
-{% if area_config.interface is defined and area_config.interface is not none %}
-{% for interface in area_config.interface %}
- interface {{ interface }} area {{ area_id }}
-{% endfor %}
-{% endif %}
{% if area_config.area_type is defined and area_config.area_type is not none %}
{% for type, type_config in area_config.area_type.items() %}
area {{ area_id }} {{ type }} {{ 'no-summary' if type_config.no_summary is defined }}
@@ -89,4 +88,5 @@ router ospf6
redistribute {{ protocol }} {{ 'route-map ' + options.route_map if options.route_map is defined }}
{% endfor %}
{% endif %}
+exit
!
diff --git a/data/templates/frr/ospfd.frr.tmpl b/data/templates/frr/ospfd.frr.tmpl
index 90a6bbd56..a7b770f07 100644
--- a/data/templates/frr/ospfd.frr.tmpl
+++ b/data/templates/frr/ospfd.frr.tmpl
@@ -49,6 +49,10 @@ interface {{ iface }} {{ 'vrf ' + vrf if vrf is defined and vrf is not none }}
{% if iface_config.network is defined and iface_config.network is not none %}
ip ospf network {{ iface_config.network }}
{% endif %}
+{% if iface_config.passive is defined %}
+ {{ 'no ' if iface_config.passive.disable is defined }}ip ospf passive
+{% endif %}
+exit
!
{% endfor %}
{% endif %}
@@ -158,18 +162,8 @@ router ospf {{ 'vrf ' + vrf if vrf is defined and vrf is not none }}
ospf router-id {{ parameters.router_id }}
{% endif %}
{% endif %}
-{% if passive_interface is defined and passive_interface is not none %}
-{% for interface in passive_interface %}
- passive-interface {{ interface }}
-{% endfor %}
-{% endif %}
-{% if passive_interface_exclude is defined and passive_interface_exclude is not none %}
-{% for interface in passive_interface_exclude if passive_interface_exclude is defined %}
-{% if interface.startswith('vlink') %}
-{% set interface = interface.upper() %}
-{% endif %}
- no passive-interface {{ interface }}
-{% endfor %}
+{% if passive_interface is defined and passive_interface.default is defined %}
+ passive-interface default
{% endif %}
{% if redistribute is defined and redistribute is not none %}
{% for protocol, protocols_options in redistribute.items() %}
@@ -189,4 +183,5 @@ router ospf {{ 'vrf ' + vrf if vrf is defined and vrf is not none }}
{# Timer values have default values #}
timers throttle spf {{ timers.throttle.spf.delay }} {{ timers.throttle.spf.initial_holdtime }} {{ timers.throttle.spf.max_holdtime }}
{% endif %}
+exit
!
diff --git a/data/templates/frr/policy.frr.tmpl b/data/templates/frr/policy.frr.tmpl
index 51adc1902..d3d3957a5 100644
--- a/data/templates/frr/policy.frr.tmpl
+++ b/data/templates/frr/policy.frr.tmpl
@@ -1,4 +1,3 @@
-!
{% if access_list is defined and access_list is not none %}
{% for acl, acl_config in access_list.items() | natural_sort %}
{% if acl_config.description is defined and acl_config.description is not none %}
@@ -60,7 +59,7 @@ ipv6 access-list {{ acl }} seq {{ rule }} {{ rule_config.action }} {{ src }} {{
{% for acl, acl_config in as_path_list.items() | natural_sort %}
{% if acl_config.rule is defined and acl_config.rule is not none %}
{% for rule, rule_config in acl_config.rule.items() | natural_sort %}
-bgp as-path access-list {{ acl }} {{ rule_config.action }} {{ rule_config.regex }}
+bgp as-path access-list {{ acl }} seq {{ rule }} {{ rule_config.action }} {{ rule_config.regex }}
{% endfor %}
{% endif %}
{% endfor %}
@@ -314,9 +313,9 @@ route-map {{ route_map }} {{ rule_config.action }} {{ rule }}
set weight {{ rule_config.set.weight }}
{% endif %}
{% endif %}
-{% endfor %}
+exit
!
+{% endfor %}
{% endif %}
{% endfor %}
{% endif %}
-!
diff --git a/data/templates/frr/ripd.frr.tmpl b/data/templates/frr/ripd.frr.tmpl
index cabc236f0..c44bb6d27 100644
--- a/data/templates/frr/ripd.frr.tmpl
+++ b/data/templates/frr/ripd.frr.tmpl
@@ -1,4 +1,3 @@
-!
{# RIP key-chain definition #}
{% if interface is defined and interface is not none %}
{% for iface, iface_config in interface.items() %}
@@ -9,7 +8,9 @@ key chain {{ iface }}-rip
{% if key_options.password is defined and key_options.password is not none %}
key-string {{ key_options.password }}
{% endif %}
+ exit
{% endfor %}
+exit
{% endif %}
{% endfor %}
{% endif %}
@@ -31,6 +32,8 @@ interface {{ iface }}
{% if iface_config.split_horizon is defined and iface_config.split_horizon.poison_reverse is defined %}
ip rip split-horizon poisoned-reverse
{% endif %}
+exit
+!
{% endfor %}
{% endif %}
!
@@ -89,6 +92,7 @@ router rip
{% endif %}
{% endif %}
{% include 'frr/rip_ripng.frr.j2' %}
+exit
!
{% if route_map is defined and route_map is not none %}
ip protocol rip route-map {{ route_map }}
diff --git a/data/templates/frr/ripngd.frr.tmpl b/data/templates/frr/ripngd.frr.tmpl
index 25df15121..ca7b9b5fb 100644
--- a/data/templates/frr/ripngd.frr.tmpl
+++ b/data/templates/frr/ripngd.frr.tmpl
@@ -1,4 +1,3 @@
-!
{# Interface specific configuration #}
{% if interface is defined and interface is not none %}
{% for iface, iface_config in interface.items() %}
@@ -9,6 +8,7 @@ interface {{ iface }}
{% if iface_config.split_horizon is defined and iface_config.split_horizon.poison_reverse is defined %}
ipv6 rip split-horizon poisoned-reverse
{% endif %}
+exit
{% endfor %}
{% endif %}
!
@@ -57,4 +57,9 @@ router ripng
{% endif %}
{% endif %}
{% include 'frr/rip_ripng.frr.j2' %}
+exit
+!
+{% if route_map is defined and route_map is not none %}
+ipv6 protocol ripng route-map {{ route_map }}
+{% endif %}
!
diff --git a/data/templates/frr/rpki.frr.tmpl b/data/templates/frr/rpki.frr.tmpl
index fbdfa27c3..7f9823f6b 100644
--- a/data/templates/frr/rpki.frr.tmpl
+++ b/data/templates/frr/rpki.frr.tmpl
@@ -14,4 +14,5 @@ rpki
{% if polling_period is defined and polling_period is not none %}
rpki polling_period {{ polling_period }}
{% endif %}
+exit
!
diff --git a/data/templates/ipsec/swanctl/profile.tmpl b/data/templates/ipsec/swanctl/profile.tmpl
index 948dd8f87..a5cae31c0 100644
--- a/data/templates/ipsec/swanctl/profile.tmpl
+++ b/data/templates/ipsec/swanctl/profile.tmpl
@@ -7,7 +7,7 @@
dmvpn-{{ name }}-{{ interface }} {
proposals = {{ ike_group[profile_conf.ike_group] | get_esp_ike_cipher | join(',') }}
version = {{ ike.key_exchange[4:] if ike is defined and ike.key_exchange is defined else "0" }}
- life_time = {{ ike.lifetime }}s
+ rekey_time = {{ ike.lifetime }}s
keyingtries = 0
{% if profile_conf.authentication is defined and profile_conf.authentication.mode is defined and profile_conf.authentication.mode == 'pre-shared-secret' %}
local {
diff --git a/interface-definitions/include/generic-disable-node.xml.i b/interface-definitions/include/generic-disable-node.xml.i
index bb4fa5c4b..97a328ecc 100644
--- a/interface-definitions/include/generic-disable-node.xml.i
+++ b/interface-definitions/include/generic-disable-node.xml.i
@@ -1,7 +1,7 @@
<!-- include start from generic-disable-node.xml.i -->
<leafNode name="disable">
<properties>
- <help>Temporary disable</help>
+ <help>Disable instance</help>
<valueless/>
</properties>
</leafNode>
diff --git a/interface-definitions/include/nat-translation-options.xml.i b/interface-definitions/include/nat-translation-options.xml.i
index defc8c0d5..df2f76397 100644
--- a/interface-definitions/include/nat-translation-options.xml.i
+++ b/interface-definitions/include/nat-translation-options.xml.i
@@ -16,7 +16,7 @@
</valueHelp>
<valueHelp>
<format>random</format>
- <description>Random source or destination address allocation for each connection (defaut)</description>
+ <description>Random source or destination address allocation for each connection (default)</description>
</valueHelp>
<constraint>
<regex>^(persistent|random)$</regex>
diff --git a/interface-definitions/include/ospf/protocol-common-config.xml.i b/interface-definitions/include/ospf/protocol-common-config.xml.i
index 982e519a9..ac165a157 100644
--- a/interface-definitions/include/ospf/protocol-common-config.xml.i
+++ b/interface-definitions/include/ospf/protocol-common-config.xml.i
@@ -436,6 +436,14 @@
<constraintErrorMessage>Must be broadcast, non-broadcast, point-to-multipoint or point-to-point</constraintErrorMessage>
</properties>
</leafNode>
+ <node name="passive">
+ <properties>
+ <help>Suppress routing updates on an interface</help>
+ </properties>
+ <children>
+ #include <include/generic-disable-node.xml.i>
+ </children>
+ </node>
</children>
</tagNode>
#include <include/ospf/log-adjacency-changes.xml.i>
@@ -597,26 +605,19 @@
#include <include/router-id.xml.i>
</children>
</node>
-#include <include/routing-passive-interface.xml.i>
-<leafNode name="passive-interface-exclude">
+<leafNode name="passive-interface">
<properties>
- <help>Interface to exclude when using 'passive-interface default'</help>
+ <help>Suppress routing updates on an interface</help>
<completionHelp>
- <script>${vyos_completion_dir}/list_interfaces.py</script>
+ <list>default</list>
</completionHelp>
<valueHelp>
- <format>txt</format>
- <description>Interface to exclude when suppressing routing updates</description>
- </valueHelp>
- <valueHelp>
- <format>vlinkN</format>
- <description>Virtual-link interface to exclude when suppressing routing updates</description>
+ <format>default</format>
+ <description>Default to suppress routing updates on all interfaces</description>
</valueHelp>
<constraint>
- <validator name="interface-name"/>
- <regex>^(vlink[0-9]+)$</regex>
+ <regex>^(default)$</regex>
</constraint>
- <multi/>
</properties>
</leafNode>
<node name="redistribute">
diff --git a/interface-definitions/include/ospfv3/protocol-common-config.xml.i b/interface-definitions/include/ospfv3/protocol-common-config.xml.i
new file mode 100644
index 000000000..a93939a34
--- /dev/null
+++ b/interface-definitions/include/ospfv3/protocol-common-config.xml.i
@@ -0,0 +1,241 @@
+<!-- include start from ospfv3/protocol-common-config.xml.i -->
+<tagNode name="area">
+ <properties>
+ <help>OSPFv3 Area</help>
+ <valueHelp>
+ <format>u32</format>
+ <description>Area ID as a decimal value</description>
+ </valueHelp>
+ <valueHelp>
+ <format>ipv4</format>
+ <description>Area ID in IP address forma</description>
+ </valueHelp>
+ <constraint>
+ <validator name="numeric" argument="--range 0-4294967295"/>
+ <validator name="ip-address"/>
+ </constraint>
+ </properties>
+ <children>
+ <node name="area-type">
+ <properties>
+ <help>OSPFv3 Area type</help>
+ </properties>
+ <children>
+ <node name="stub">
+ <properties>
+ <help>Stub OSPFv3 area</help>
+ </properties>
+ <children>
+ <leafNode name="no-summary">
+ <properties>
+ <help>Do not inject inter-area routes into the stub</help>
+ <valueless/>
+ </properties>
+ </leafNode>
+ </children>
+ </node>
+ </children>
+ </node>
+ <leafNode name="export-list">
+ <properties>
+ <help>Name of export-list</help>
+ <completionHelp>
+ <path>policy access-list6</path>
+ </completionHelp>
+ </properties>
+ </leafNode>
+ <leafNode name="import-list">
+ <properties>
+ <help>Name of import-list</help>
+ <completionHelp>
+ <path>policy access-list6</path>
+ </completionHelp>
+ </properties>
+ </leafNode>
+ <tagNode name="range">
+ <properties>
+ <help>Specify IPv6 prefix (border routers only)</help>
+ <valueHelp>
+ <format>ipv6net</format>
+ <description>Specify IPv6 prefix (border routers only)</description>
+ </valueHelp>
+ <constraint>
+ <validator name="ipv6-prefix"/>
+ </constraint>
+ </properties>
+ <children>
+ <leafNode name="advertise">
+ <properties>
+ <help>Advertise this range</help>
+ <valueless/>
+ </properties>
+ </leafNode>
+ <leafNode name="not-advertise">
+ <properties>
+ <help>Do not advertise this range</help>
+ <valueless/>
+ </properties>
+ </leafNode>
+ </children>
+ </tagNode>
+ </children>
+</tagNode>
+<node name="distance">
+ <properties>
+ <help>Administrative distance</help>
+ </properties>
+ <children>
+ #include <include/ospf/distance-global.xml.i>
+ <node name="ospfv3">
+ <properties>
+ <help>OSPFv3 administrative distance</help>
+ </properties>
+ <children>
+ #include <include/ospf/distance-per-protocol.xml.i>
+ </children>
+ </node>
+ </children>
+</node>
+<tagNode name="interface">
+ <properties>
+ <help>Enable routing on an IPv6 interface</help>
+ <completionHelp>
+ <script>${vyos_completion_dir}/list_interfaces.py</script>
+ </completionHelp>
+ <valueHelp>
+ <format>txt</format>
+ <description>Interface used for routing information exchange</description>
+ </valueHelp>
+ <constraint>
+ <validator name="interface-name"/>
+ </constraint>
+ </properties>
+ <children>
+ <leafNode name="area">
+ <properties>
+ <help>Enable OSPF on this interface</help>
+ <completionHelp>
+ <path>protocols ospfv3 area</path>
+ </completionHelp>
+ <valueHelp>
+ <format>u32</format>
+ <description>OSPF area ID as decimal notation</description>
+ </valueHelp>
+ <valueHelp>
+ <format>ipv4</format>
+ <description>OSPF area ID in IP address notation</description>
+ </valueHelp>
+ <constraint>
+ <validator name="numeric" argument="--range 0-4294967295"/>
+ <validator name="ip-address"/>
+ </constraint>
+ </properties>
+ </leafNode>
+ #include <include/ospf/intervals.xml.i>
+ #include <include/ospf/interface-common.xml.i>
+ <leafNode name="ifmtu">
+ <properties>
+ <help>Interface MTU</help>
+ <valueHelp>
+ <format>u32:1-65535</format>
+ <description>Interface MTU</description>
+ </valueHelp>
+ <constraint>
+ <validator name="numeric" argument="--range 1-65535"/>
+ </constraint>
+ </properties>
+ </leafNode>
+ <leafNode name="instance-id">
+ <properties>
+ <help>Instance Id (default: 0)</help>
+ <valueHelp>
+ <format>u32:0-255</format>
+ <description>Instance Id</description>
+ </valueHelp>
+ <constraint>
+ <validator name="numeric" argument="--range 0-255"/>
+ </constraint>
+ </properties>
+ <defaultValue>0</defaultValue>
+ </leafNode>
+ <leafNode name="network">
+ <properties>
+ <help>Network type</help>
+ <completionHelp>
+ <list>broadcast point-to-point</list>
+ </completionHelp>
+ <valueHelp>
+ <format>broadcast</format>
+ <description>Broadcast network type</description>
+ </valueHelp>
+ <valueHelp>
+ <format>point-to-point</format>
+ <description>Point-to-point network type</description>
+ </valueHelp>
+ <constraint>
+ <regex>^(broadcast|point-to-point)$</regex>
+ </constraint>
+ <constraintErrorMessage>Must be broadcast or point-to-point</constraintErrorMessage>
+ </properties>
+ </leafNode>
+ #include <include/isis/passive.xml.i>
+ </children>
+</tagNode>
+#include <include/ospf/log-adjacency-changes.xml.i>
+<node name="parameters">
+ <properties>
+ <help>OSPFv3 specific parameters</help>
+ </properties>
+ <children>
+ #include <include/router-id.xml.i>
+ </children>
+</node>
+<node name="redistribute">
+ <properties>
+ <help>Redistribute information from another routing protocol</help>
+ </properties>
+ <children>
+ <node name="bgp">
+ <properties>
+ <help>Redistribute BGP routes</help>
+ </properties>
+ <children>
+ #include <include/route-map.xml.i>
+ </children>
+ </node>
+ <node name="connected">
+ <properties>
+ <help>Redistribute connected routes</help>
+ </properties>
+ <children>
+ #include <include/route-map.xml.i>
+ </children>
+ </node>
+ <node name="kernel">
+ <properties>
+ <help>Redistribute kernel routes</help>
+ </properties>
+ <children>
+ #include <include/route-map.xml.i>
+ </children>
+ </node>
+ <node name="ripng">
+ <properties>
+ <help>Redistribute RIPNG routes</help>
+ </properties>
+ <children>
+ #include <include/route-map.xml.i>
+ </children>
+ </node>
+ <node name="static">
+ <properties>
+ <help>Redistribute static routes</help>
+ </properties>
+ <children>
+ #include <include/route-map.xml.i>
+ </children>
+ </node>
+ </children>
+</node>
+#include <include/route-map.xml.i>
+<!-- include end -->
diff --git a/interface-definitions/protocols-ospfv3.xml.in b/interface-definitions/protocols-ospfv3.xml.in
index fffeeb9a5..2b98ffa7b 100644
--- a/interface-definitions/protocols-ospfv3.xml.in
+++ b/interface-definitions/protocols-ospfv3.xml.in
@@ -8,226 +8,7 @@
<priority>620</priority>
</properties>
<children>
- <tagNode name="area">
- <properties>
- <help>OSPFv3 Area</help>
- <valueHelp>
- <format>u32</format>
- <description>Area ID as a decimal value</description>
- </valueHelp>
- <valueHelp>
- <format>ipv4</format>
- <description>Area ID in IP address forma</description>
- </valueHelp>
- <constraint>
- <validator name="numeric" argument="--range 0-4294967295"/>
- <validator name="ip-address"/>
- </constraint>
- </properties>
- <children>
- <node name="area-type">
- <properties>
- <help>OSPFv3 Area type</help>
- </properties>
- <children>
- <node name="stub">
- <properties>
- <help>Stub OSPFv3 area</help>
- </properties>
- <children>
- <leafNode name="no-summary">
- <properties>
- <help>Do not inject inter-area routes into the stub</help>
- <valueless/>
- </properties>
- </leafNode>
- </children>
- </node>
- </children>
- </node>
- <leafNode name="export-list">
- <properties>
- <help>Name of export-list</help>
- <completionHelp>
- <path>policy access-list6</path>
- </completionHelp>
- </properties>
- </leafNode>
- <leafNode name="import-list">
- <properties>
- <help>Name of import-list</help>
- <completionHelp>
- <path>policy access-list6</path>
- </completionHelp>
- </properties>
- </leafNode>
- #include <include/generic-interface-multi.xml.i>
- <tagNode name="range">
- <properties>
- <help>Specify IPv6 prefix (border routers only)</help>
- <valueHelp>
- <format>ipv6net</format>
- <description>Specify IPv6 prefix (border routers only)</description>
- </valueHelp>
- <constraint>
- <validator name="ipv6-prefix"/>
- </constraint>
- </properties>
- <children>
- <leafNode name="advertise">
- <properties>
- <help>Advertise this range</help>
- <valueless/>
- </properties>
- </leafNode>
- <leafNode name="not-advertise">
- <properties>
- <help>Do not advertise this range</help>
- <valueless/>
- </properties>
- </leafNode>
- </children>
- </tagNode>
- </children>
- </tagNode>
- <node name="distance">
- <properties>
- <help>Administrative distance</help>
- </properties>
- <children>
- #include <include/ospf/distance-global.xml.i>
- <node name="ospfv3">
- <properties>
- <help>OSPFv3 administrative distance</help>
- </properties>
- <children>
- #include <include/ospf/distance-per-protocol.xml.i>
- </children>
- </node>
- </children>
- </node>
- <tagNode name="interface">
- <properties>
- <help>Enable routing on an IPv6 interface</help>
- <completionHelp>
- <script>${vyos_completion_dir}/list_interfaces.py</script>
- </completionHelp>
- <valueHelp>
- <format>txt</format>
- <description>Interface used for routing information exchange</description>
- </valueHelp>
- <constraint>
- <validator name="interface-name"/>
- </constraint>
- </properties>
- <children>
- #include <include/ospf/intervals.xml.i>
- #include <include/ospf/interface-common.xml.i>
- <leafNode name="ifmtu">
- <properties>
- <help>Interface MTU</help>
- <valueHelp>
- <format>u32:1-65535</format>
- <description>Interface MTU</description>
- </valueHelp>
- <constraint>
- <validator name="numeric" argument="--range 1-65535"/>
- </constraint>
- </properties>
- </leafNode>
- <leafNode name="instance-id">
- <properties>
- <help>Instance Id (default: 0)</help>
- <valueHelp>
- <format>u32:0-255</format>
- <description>Instance Id</description>
- </valueHelp>
- <constraint>
- <validator name="numeric" argument="--range 0-255"/>
- </constraint>
- </properties>
- <defaultValue>0</defaultValue>
- </leafNode>
- <leafNode name="network">
- <properties>
- <help>Network type</help>
- <completionHelp>
- <list>broadcast point-to-point</list>
- </completionHelp>
- <valueHelp>
- <format>broadcast</format>
- <description>Broadcast network type</description>
- </valueHelp>
- <valueHelp>
- <format>point-to-point</format>
- <description>Point-to-point network type</description>
- </valueHelp>
- <constraint>
- <regex>^(broadcast|point-to-point)$</regex>
- </constraint>
- <constraintErrorMessage>Must be broadcast or point-to-point</constraintErrorMessage>
- </properties>
- </leafNode>
- #include <include/isis/passive.xml.i>
- </children>
- </tagNode>
- #include <include/ospf/log-adjacency-changes.xml.i>
- <node name="parameters">
- <properties>
- <help>OSPFv3 specific parameters</help>
- </properties>
- <children>
- #include <include/router-id.xml.i>
- </children>
- </node>
- <node name="redistribute">
- <properties>
- <help>Redistribute information from another routing protocol</help>
- </properties>
- <children>
- <node name="bgp">
- <properties>
- <help>Redistribute BGP routes</help>
- </properties>
- <children>
- #include <include/route-map.xml.i>
- </children>
- </node>
- <node name="connected">
- <properties>
- <help>Redistribute connected routes</help>
- </properties>
- <children>
- #include <include/route-map.xml.i>
- </children>
- </node>
- <node name="kernel">
- <properties>
- <help>Redistribute kernel routes</help>
- </properties>
- <children>
- #include <include/route-map.xml.i>
- </children>
- </node>
- <node name="ripng">
- <properties>
- <help>Redistribute RIPNG routes</help>
- </properties>
- <children>
- #include <include/route-map.xml.i>
- </children>
- </node>
- <node name="static">
- <properties>
- <help>Redistribute static routes</help>
- </properties>
- <children>
- #include <include/route-map.xml.i>
- </children>
- </node>
- </children>
- </node>
- #include <include/route-map.xml.i>
+ #include <include/ospfv3/protocol-common-config.xml.i>
</children>
</node>
</children>
diff --git a/interface-definitions/system-option.xml.in b/interface-definitions/system-option.xml.in
index f73c1ee08..75fa67271 100644
--- a/interface-definitions/system-option.xml.in
+++ b/interface-definitions/system-option.xml.in
@@ -117,6 +117,12 @@
<valueless/>
</properties>
</leafNode>
+ <leafNode name="root-partition-auto-resize">
+ <properties>
+ <help>Enable root partition auto-extention on system boot</help>
+ <valueless/>
+ </properties>
+ </leafNode>
</children>
</node>
</children>
diff --git a/interface-definitions/vrf.xml.in b/interface-definitions/vrf.xml.in
index d6a602f53..14c31fa8a 100644
--- a/interface-definitions/vrf.xml.in
+++ b/interface-definitions/vrf.xml.in
@@ -60,6 +60,15 @@
#include <include/ospf/protocol-common-config.xml.i>
</children>
</node>
+ <node name="ospfv3" owner="${vyos_conf_scripts_dir}/protocols_ospfv3.py $VAR(../../@)">
+ <properties>
+ <help>Open Shortest Path First (OSPF) for IPv6</help>
+ <priority>621</priority>
+ </properties>
+ <children>
+ #include <include/ospfv3/protocol-common-config.xml.i>
+ </children>
+ </node>
<node name="static" owner="${vyos_conf_scripts_dir}/protocols_static.py $VAR(../../@)">
<properties>
<help>Static route parameters</help>
diff --git a/op-mode-definitions/force-part-resize.xml.in b/op-mode-definitions/force-root-partition-auto-resize.xml.in
index cb76273c7..f84c073b8 100644
--- a/op-mode-definitions/force-part-resize.xml.in
+++ b/op-mode-definitions/force-root-partition-auto-resize.xml.in
@@ -2,11 +2,11 @@
<interfaceDefinition>
<node name="force">
<children>
- <node name="resize-partition">
+ <node name="root-partition-auto-resize">
<properties>
<help>Resize the VyOS partition</help>
</properties>
- <command>${vyos_op_scripts_dir}/force_part_resize.sh</command>
+ <command>sudo ${vyos_op_scripts_dir}/force_root-partition-auto-resize.sh</command>
</node>
</children>
</node>
diff --git a/python/vyos/frr.py b/python/vyos/frr.py
index df6849472..a8f115d9a 100644
--- a/python/vyos/frr.py
+++ b/python/vyos/frr.py
@@ -84,12 +84,14 @@ if DEBUG:
LOG.addHandler(ch2)
_frr_daemons = ['zebra', 'bgpd', 'fabricd', 'isisd', 'ospf6d', 'ospfd', 'pbrd',
- 'pimd', 'ripd', 'ripngd', 'sharpd', 'staticd', 'vrrpd', 'ldpd']
+ 'pimd', 'ripd', 'ripngd', 'sharpd', 'staticd', 'vrrpd', 'ldpd',
+ 'bfdd']
path_vtysh = '/usr/bin/vtysh'
path_frr_reload = '/usr/lib/frr/frr-reload.py'
path_config = '/run/frr'
+default_add_before = r'(ip prefix-list .*|route-map .*|line vty|end)'
class FrrError(Exception):
pass
@@ -214,13 +216,8 @@ def reload_configuration(config, daemon=None):
def save_configuration():
- """Save FRR configuration to /run/frr/config/frr.conf
- It save configuration on each commit. T3217
- """
-
- cmd(f'{path_vtysh} -n -w')
-
- return
+ """ T3217: Save FRR configuration to /run/frr/config/frr.conf """
+ return cmd(f'{path_vtysh} -n -w')
def execute(command):
@@ -448,16 +445,37 @@ class FRRConfig:
mark_configuration('\n'.join(self.config))
def commit_configuration(self, daemon=None):
- '''Commit the current configuration to FRR
- daemon: str with name of the FRR daemon to commit to or
- None to use the consolidated config
+ '''
+ Commit the current configuration to FRR daemon: str with name of the
+ FRR daemon to commit to or None to use the consolidated config.
+
+ Configuration is automatically saved after apply
'''
LOG.debug('commit_configuration: Commiting configuration')
for i, e in enumerate(self.config):
LOG.debug(f'commit_configuration: new_config {i:3} {e}')
- reload_configuration('\n'.join(self.config), daemon=daemon)
- def modify_section(self, start_pattern, replacement=[], stop_pattern=r'\S+', remove_stop_mark=False, count=0):
+ # https://github.com/FRRouting/frr/issues/10132
+ # https://github.com/FRRouting/frr/issues/10133
+ count = 0
+ count_max = 5
+ while count < count_max:
+ count += 1
+ try:
+ reload_configuration('\n'.join(self.config), daemon=daemon)
+ break
+ except:
+ # we just need to re-try the commit of the configuration
+ # for the listed FRR issues above
+ pass
+ if count >= count_max:
+ raise ConfigurationNotValid(f'Config commit retry counter ({count_max}) exceeded')
+
+ # Save configuration to /run/frr/config/frr.conf
+ save_configuration()
+
+
+ def modify_section(self, start_pattern, replacement='!', stop_pattern=r'\S+', remove_stop_mark=False, count=0):
if isinstance(replacement, str):
replacement = replacement.split('\n')
elif not isinstance(replacement, list):
diff --git a/python/vyos/remote.py b/python/vyos/remote.py
index e972050b7..2419f8873 100644
--- a/python/vyos/remote.py
+++ b/python/vyos/remote.py
@@ -13,38 +13,40 @@
# 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/>.
-from ftplib import FTP
import os
import shutil
import socket
+import ssl
import stat
import sys
import tempfile
import urllib.parse
-import urllib.request as urlreq
-from vyos.template import get_ip
-from vyos.template import ip_from_cidr
-from vyos.template import is_interface
-from vyos.template import is_ipv6
-from vyos.util import cmd
+from ftplib import FTP
+from ftplib import FTP_TLS
+
+from paramiko import SSHClient
+from paramiko import MissingHostKeyPolicy
+
+from requests import Session
+from requests.adapters import HTTPAdapter
+from requests.packages.urllib3 import PoolManager
+
from vyos.util import ask_yes_no
-from vyos.util import print_error
-from vyos.util import make_progressbar
+from vyos.util import begin
+from vyos.util import cmd
from vyos.util import make_incremental_progressbar
+from vyos.util import make_progressbar
+from vyos.util import print_error
from vyos.version import get_version
-from paramiko import SSHClient
-from paramiko import SSHException
-from paramiko import MissingHostKeyPolicy
-# This is a hardcoded path and no environment variable can change it.
-KNOWN_HOSTS_FILE = os.path.expanduser('~/.ssh/known_hosts')
+
CHUNK_SIZE = 8192
class InteractivePolicy(MissingHostKeyPolicy):
"""
- Policy for interactively querying the user on whether to proceed with
- SSH connections to unknown hosts.
+ Paramiko policy for interactively querying the user on whether to proceed
+ with SSH connections to unknown hosts.
"""
def missing_host_key(self, client, hostname, key):
print_error(f"Host '{hostname}' not found in known hosts.")
@@ -57,337 +59,270 @@ class InteractivePolicy(MissingHostKeyPolicy):
else:
raise SSHException(f"Cannot connect to unknown host '{hostname}'.")
-
-## Helper routines
-def get_authentication_variables(default_username=None, default_password=None):
+class SourceAdapter(HTTPAdapter):
"""
- Return the environment variables `$REMOTE_USERNAME` and `$REMOTE_PASSWORD` and
- return the defaults provided if environment variables are empty or nonexistent.
+ urllib3 transport adapter for setting source addresses per session.
"""
- username, password = os.getenv('REMOTE_USERNAME'), os.getenv('REMOTE_PASSWORD')
- # Fall back to defaults if the username variable doesn't exist or is an empty string.
- # Note that this is different from `os.getenv('REMOTE_USERNAME', default=default_username)`,
- # as we want the username and the password to have the same behaviour.
- if not username:
- return default_username, default_password
- else:
- return username, password
-
-def get_source_address(source):
+ def __init__(self, source_pair, *args, **kwargs):
+ # A source pair is a tuple of a source host string and source port respectively.
+ # Supply '' and 0 respectively for default values.
+ self._source_pair = source_pair
+ super(SourceAdapter, self).__init__(*args, **kwargs)
+
+ def init_poolmanager(self, connections, maxsize, block=False):
+ self.poolmanager = PoolManager(
+ num_pools=connections, maxsize=maxsize,
+ block=block, source_address=self._source_pair)
+
+class WrappedFile:
+ def __init__(self, obj, size=None, chunk_size=CHUNK_SIZE):
+ self._obj = obj
+ self._progress = size and make_incremental_progressbar(chunk_size / size)
+ def read(self, size=-1):
+ if self._progress:
+ next(self._progress)
+ self._obj.read(size)
+ def write(self, size=-1):
+ if self._progress:
+ next(self._progress)
+ self._obj.write(size)
+ def __getattr__(self, attr):
+ return getattr(self._obj, attr)
+
+def check_storage(path, size):
"""
- Take a string vaguely indicating an origin source (interface, hostname or IP address),
- return a tuple in the format `(source_pair, address_family)` where
- `source_pair` is `(source_address, source_port)`.
+ Check whether `path` has enough storage space for a transfer of `size` bytes.
"""
- # TODO: Properly distinguish between IPv4 and IPv6.
- port = 0
- if is_interface(source):
- source = ip_from_cidr(get_ip(source)[0])
- if is_ipv6(source):
- return (source, port), socket.AF_INET6
+ path = os.path.abspath(os.path.expanduser(path))
+ directory = path if os.path.isdir(path) else (os.path.dirname(os.path.expanduser(path)) or os.getcwd())
+ # `size` can be None or 0 to indicate unknown size.
+ if not size:
+ print_error('Warning: Cannot determine size of remote file.')
+ print_error('Bravely continuing regardless.')
+ return
+
+ if size < 1024 * 1024:
+ print_error(f'The file is {size / 1024.0:.3f} KiB.')
else:
- return (socket.gethostbyname(source), port), socket.AF_INET
-
-def get_port_from_url(url):
- """
- Return the port number from the given `url` named tuple, fall back to
- the default if there isn't one.
- """
- defaults = {"http": 80, "https": 443, "ftp": 21, "tftp": 69,\
- "ssh": 22, "scp": 22, "sftp": 22}
- if url.port:
- return url.port
- else:
- return defaults[url.scheme]
-
-
-## FTP routines
-def upload_ftp(local_path, hostname, remote_path,\
- username='anonymous', password='', port=21,\
- source_pair=None, progressbar=False):
- size = os.path.getsize(local_path)
- with FTP(source_address=source_pair) as conn:
- conn.connect(hostname, port)
- conn.login(username, password)
- with open(local_path, 'rb') as file:
- if progressbar and size:
+ print_error(f'The file is {size / (1024.0 * 1024.0):.3f} MiB.')
+
+ # Will throw `FileNotFoundError' if `directory' is absent.
+ if size > shutil.disk_usage(directory).free:
+ raise OSError(f'Not enough disk space available in "{directory}".')
+
+
+class FtpC:
+ def __init__(self, url, progressbar=False, check_space=False, source_host='', source_port=0):
+ self.secure = url.scheme == 'ftps'
+ self.hostname = url.hostname
+ self.path = url.path
+ self.username = url.username or os.getenv('REMOTE_USERNAME', 'anonymous')
+ self.password = url.password or os.getenv('REMOTE_PASSWORD', '')
+ self.port = url.port or 21
+ self.source = (source_host, source_port)
+ self.progressbar = progressbar
+ self.check_space = check_space
+
+ def _establish(self):
+ if self.secure:
+ return FTP_TLS(source_address=self.source, context=ssl.create_default_context())
+ else:
+ return FTP(source_address=self.source)
+
+ def download(self, location: str):
+ # Open the file upfront before establishing connection.
+ with open(location, 'wb') as f, self._establish() as conn:
+ conn.connect(self.hostname, self.port)
+ conn.login(self.username, self.password)
+ # Set secure connection over TLS.
+ if self.secure:
+ conn.prot_p()
+ # Almost all FTP servers support the `SIZE' command.
+ if self.check_space:
+ check_storage(path, conn.size(self.path))
+ # No progressbar if we can't determine the size or if the file is too small.
+ if self.progressbar and size and size > CHUNK_SIZE:
progress = make_incremental_progressbar(CHUNK_SIZE / size)
next(progress)
- callback = lambda block: next(progress)
+ callback = lambda block: begin(f.write(block), next(progress))
else:
- callback = None
- conn.storbinary(f'STOR {remote_path}', file, CHUNK_SIZE, callback)
-
-def download_ftp(local_path, hostname, remote_path,\
- username='anonymous', password='', port=21,\
- source_pair=None, progressbar=False):
- with FTP(source_address=source_pair) as conn:
- conn.connect(hostname, port)
- conn.login(username, password)
- size = conn.size(remote_path)
- with open(local_path, 'wb') as file:
- # No progressbar if we can't determine the size.
- if progressbar and size:
+ callback = f.write
+ conn.retrbinary('RETR ' + self.path, callback, CHUNK_SIZE)
+
+ def upload(self, location: str):
+ size = os.path.getsize(location)
+ with open(location, 'rb') as f, self._establish() as conn:
+ conn.connect(self.hostname, self.port)
+ conn.login(self.username, self.password)
+ if self.secure:
+ conn.prot_p()
+ if self.progressbar and size and size > CHUNK_SIZE:
progress = make_incremental_progressbar(CHUNK_SIZE / size)
next(progress)
- callback = lambda block: (file.write(block), next(progress))
+ callback = lambda block: next(progress)
else:
- callback = file.write
- conn.retrbinary(f'RETR {remote_path}', callback, CHUNK_SIZE)
-
-def get_ftp_file_size(hostname, remote_path,\
- username='anonymous', password='', port=21,\
- source_pair=None):
- with FTP(source_address=source) as conn:
- conn.connect(hostname, port)
- conn.login(username, password)
- size = conn.size(remote_path)
- if size:
- return size
- else:
- # SIZE is an extension to the FTP specification, although it's extremely common.
- raise ValueError('Failed to receive file size from FTP server. \
- Perhaps the server does not implement the SIZE command?')
-
-
-## SFTP/SCP routines
-def transfer_sftp(mode, local_path, hostname, remote_path,\
- username=None, password=None, port=22,\
- source_tuple=None, progressbar=False):
- sock = None
- if source_tuple:
- (source_address, source_port), address_family = source_tuple
- sock = socket.socket(address_family, socket.SOCK_STREAM)
- sock.bind((source_address, source_port))
- sock.connect((hostname, port))
- callback = make_progressbar() if progressbar else None
- with SSHClient() as ssh:
+ callback = None
+ conn.storbinary('STOR ' + self.path, f, CHUNK_SIZE, callback)
+
+class SshC:
+ known_hosts = os.path.expanduser('~/.ssh/known_hosts')
+ def __init__(self, url, progressbar=False, check_space=False, source_host='', source_port=0):
+ self.hostname = url.hostname
+ self.path = url.path
+ self.username = url.username or os.getenv('REMOTE_USERNAME')
+ self.password = url.password or os.getenv('REMOTE_PASSWORD')
+ self.port = url.port or 22
+ self.source = (source_host, source_port)
+ self.progressbar = progressbar
+ self.check_space = check_space
+
+ def _establish(self):
+ ssh = SSHClient()
ssh.load_system_host_keys()
- if os.path.exists(KNOWN_HOSTS_FILE):
- ssh.load_host_keys(KNOWN_HOSTS_FILE)
+ # Try to load from a user-local known hosts file if one exists.
+ if os.path.exists(self.known_hosts):
+ ssh.load_host_keys(self.known_hosts)
ssh.set_missing_host_key_policy(InteractivePolicy())
- ssh.connect(hostname, port, username, password, sock=sock)
- with ssh.open_sftp() as sftp:
- if mode == 'upload':
+ # `socket.create_connection()` automatically picks a NIC and an IPv4/IPv6 address family
+ # for us on dual-stack systems.
+ sock = socket.create_connection((self.hostname, self.port), socket.getdefaulttimeout(), self.source)
+ ssh.connect(self.hostname, self.port, self.username, self.password, sock=sock)
+ return ssh
+
+ def download(self, location: str):
+ callback = make_progressbar() if self.progressbar else None
+ with self._establish() as ssh, ssh.open_sftp() as sftp:
+ if self.check_space:
+ check_storage(location, sftp.stat(self.path).st_size)
+ sftp.get(self.path, location, callback=callback)
+
+ def upload(self, location: str):
+ callback = make_progressbar() if self.progressbar else None
+ with self._establish() as ssh, ssh.open_sftp() as sftp:
+ try:
+ # If the remote path is a directory, use the original filename.
+ if stat.S_ISDIR(sftp.stat(self.path).st_mode):
+ path = os.path.join(self.path, os.path.basename(location))
+ # A file exists at this destination. We're simply going to clobber it.
+ else:
+ path = self.path
+ # This path doesn't point at any existing file. We can freely use this filename.
+ except IOError:
+ path = self.path
+ finally:
+ sftp.put(location, path, callback=callback)
+
+
+class HttpC:
+ def __init__(self, url, progressbar=False, check_space=False, source_host='', source_port=0):
+ self.urlstring = urllib.parse.urlunsplit(url)
+ self.progressbar = progressbar
+ self.check_space = check_space
+ self.source_pair = (source_host, source_port)
+ self.username = url.username or os.getenv('REMOTE_USERNAME')
+ self.password = url.password or os.getenv('REMOTE_PASSWORD')
+
+ def _establish(self):
+ session = Session()
+ session.mount(self.urlstring, SourceAdapter(self.source_pair))
+ session.headers.update({'User-Agent': 'VyOS/' + get_version()})
+ if self.username:
+ session.auth = self.username, self.password
+ return session
+
+ def download(self, location: str):
+ with self._establish() as s:
+ # We ask for uncompressed downloads so that we don't have to deal with decoding.
+ # Not only would it potentially mess up with the progress bar but
+ # `shutil.copyfileobj(request.raw, file)` does not handle automatic decoding.
+ s.headers.update({'Accept-Encoding': 'identity'})
+ with s.head(self.urlstring) as r:
+ # Abort early if the destination is inaccessible.
+ r.raise_for_status()
+ # Check for the prospective file size.
try:
- # If the remote path is a directory, use the original filename.
- if stat.S_ISDIR(sftp.stat(remote_path).st_mode):
- path = os.path.join(remote_path, os.path.basename(local_path))
- # A file exists at this destination. We're simply going to clobber it.
- else:
- path = remote_path
- # This path doesn't point at any existing file. We can freely use this filename.
- except IOError:
- path = remote_path
- finally:
- sftp.put(local_path, path, callback=callback)
- elif mode == 'download':
- sftp.get(remote_path, local_path, callback=callback)
- elif mode == 'size':
- return sftp.stat(remote_path).st_size
-
-def upload_sftp(*args, **kwargs):
- transfer_sftp('upload', *args, **kwargs)
-
-def download_sftp(*args, **kwargs):
- transfer_sftp('download', *args, **kwargs)
-
-def get_sftp_file_size(*args, **kwargs):
- return transfer_sftp('size', None, *args, **kwargs)
-
-
-## TFTP routines
-def upload_tftp(local_path, hostname, remote_path, port=69, source=None, progressbar=False):
- source_option = f'--interface {source}' if source else ''
- progress_flag = '--progress-bar' if progressbar else '-s'
- with open(local_path, 'rb') as file:
- cmd(f'curl {source_option} {progress_flag} -T - tftp://{hostname}:{port}/{remote_path}',\
- stderr=None, input=file.read()).encode()
-
-def download_tftp(local_path, hostname, remote_path, port=69, source=None, progressbar=False):
- source_option = f'--interface {source}' if source else ''
- # Not really applicable but we pass it for the sake of uniformity.
- progress_flag = '--progress-bar' if progressbar else '-s'
- with open(local_path, 'wb') as file:
- file.write(cmd(f'curl {source_option} {progress_flag} tftp://{hostname}:{port}/{remote_path}',\
- stderr=None).encode())
-
-# get_tftp_file_size() is unimplemented because there is no way to obtain a file's size through TFTP,
-# as TFTP does not specify a SIZE command.
-
-
-## HTTP(S) routines
-def install_request_opener(urlstring, username, password):
- """
- Take `username` and `password` strings and install the appropriate
- password manager to `urllib.request.urlopen()` for the given `urlstring`.
- """
- manager = urlreq.HTTPPasswordMgrWithDefaultRealm()
- manager.add_password(None, urlstring, username, password)
- urlreq.install_opener(urlreq.build_opener(urlreq.HTTPBasicAuthHandler(manager)))
-
-# upload_http() is unimplemented.
-
-def download_http(local_path, urlstring, username=None, password=None, progressbar=False):
- """
- Download the file from from `urlstring` to `local_path`.
- Optionally takes `username` and `password` for authentication.
- """
- request = urlreq.Request(urlstring, headers={'User-Agent': 'VyOS/' + get_version()})
- if username:
- install_request_opener(urlstring, username, password)
- with open(local_path, 'wb') as file, urlreq.urlopen(request) as response:
- size = response.getheader('Content-Length')
- if progressbar and size:
- progress = make_incremental_progressbar(CHUNK_SIZE / int(size))
- next(progress)
- for chunk in iter(lambda: response.read(CHUNK_SIZE), b''):
- file.write(chunk)
- next(progress)
- next(progress)
- # If we can't determine the size or if a progress bar wasn't requested,
- # we can let `shutil` take care of the copying.
- else:
- shutil.copyfileobj(response, file)
-
-def get_http_file_size(urlstring, username=None, password=None):
- """
- Return the size of the file from `urlstring` in terms of number of bytes.
- Optionally takes `username` and `password` for authentication.
- """
- request = urlreq.Request(urlstring, headers={'User-Agent': 'VyOS/' + get_version()})
- if username:
- install_request_opener(urlstring, username, password)
- with urlreq.urlopen(request) as response:
- size = response.getheader('Content-Length')
- if size:
- return int(size)
- # The server didn't send 'Content-Length' in the response headers.
- else:
- raise ValueError('Failed to receive file size from HTTP server.')
-
-
-## Dynamic dispatchers
-def download(local_path, urlstring, source=None, progressbar=False):
+ size = int(r.headers['Content-Length'])
+ # In case the server does not supply the header.
+ except KeyError:
+ size = None
+ if self.check_space:
+ check_storage(location, size)
+ with s.get(self.urlstring, stream=True) as r, open(location, 'wb') as f:
+ if self.progressbar and size:
+ progress = make_incremental_progressbar(CHUNK_SIZE / size)
+ next(progress)
+ for chunk in iter(lambda: begin(next(progress), r.raw.read(CHUNK_SIZE)), b''):
+ f.write(chunk)
+ else:
+ # We'll try to stream the download directly with `copyfileobj()` so that large
+ # files (like entire VyOS images) don't occupy much memory.
+ shutil.copyfileobj(r.raw, f)
+
+ def upload(self, location: str):
+ size = os.path.getsize(location) if self.progressbar else None
+ # Keep in mind that `data` can be a file-like or iterable object.
+ with self._establish() as s, file(location, 'rb') as f:
+ s.post(self.urlstring, data=WrappedFile(f, size))
+
+
+class TftpC:
+ # We simply allow `curl` to take over because
+ # 1. TFTP is rather simple.
+ # 2. Since there's no concept authentication, we don't need to deal with keys/passwords.
+ # 3. It would be a waste to import, audit and maintain a third-party library for TFTP.
+ # 4. I'd rather not implement the entire protocol here, no matter how simple it is.
+ def __init__(self, url, progressbar=False, check_space=False, source_host=None, source_port=0):
+ source_option = f'--interface {source_host} --local-port {source_port}' if source_host else ''
+ progress_flag = '--progress-bar' if progressbar else '-s'
+ self.command = f'curl {source_option} {progress_flag}'
+ self.urlstring = urllib.parse.urlunsplit(url)
+
+ def download(self, location: str):
+ with open(location, 'wb') as f:
+ f.write(cmd(f'{self.command} "{self.urlstring}"').encode())
+
+ def upload(self, location: str):
+ with open(location, 'rb') as f:
+ cmd(f'{self.command} -T - "{self.urlstring}"', input=f.read())
+
+
+def urlc(urlstring, *args, **kwargs):
"""
- Dispatch the appropriate download function for the given `urlstring` and save to `local_path`.
- Optionally takes a `source` address or interface (not valid for HTTP(S)).
- Supports HTTP, HTTPS, FTP, SFTP, SCP (through SFTP) and TFTP.
- Reads `$REMOTE_USERNAME` and `$REMOTE_PASSWORD` environment variables.
+ Dynamically dispatch the appropriate protocol class.
"""
- url = urllib.parse.urlparse(urlstring)
- username, password = get_authentication_variables(url.username, url.password)
- port = get_port_from_url(url)
-
- if url.scheme == 'http' or url.scheme == 'https':
- if source:
- print_error('Warning: Custom source address not supported for HTTP connections.')
- download_http(local_path, urlstring, username, password, progressbar)
- elif url.scheme == 'ftp':
- source = get_source_address(source)[0] if source else None
- username = username if username else 'anonymous'
- download_ftp(local_path, url.hostname, url.path, username, password, port, source, progressbar)
- elif url.scheme == 'sftp' or url.scheme == 'scp':
- source = get_source_address(source) if source else None
- download_sftp(local_path, url.hostname, url.path, username, password, port, source, progressbar)
- elif url.scheme == 'tftp':
- download_tftp(local_path, url.hostname, url.path, port, source, progressbar)
- else:
- raise ValueError(f'Unsupported URL scheme: {url.scheme}')
+ url_classes = {'http': HttpC, 'https': HttpC, 'ftp': FtpC, 'ftps': FtpC, \
+ 'sftp': SshC, 'ssh': SshC, 'scp': SshC, 'tftp': TftpC}
+ url = urllib.parse.urlsplit(urlstring)
+ try:
+ return url_classes[url.scheme](url, *args, **kwargs)
+ except KeyError:
+ raise ValueError(f'Unsupported URL scheme: "{url.scheme}"')
-def upload(local_path, urlstring, source=None, progressbar=False):
- """
- Dispatch the appropriate upload function for the given URL and upload from local path.
- Optionally takes a `source` address.
- Supports FTP, SFTP, SCP (through SFTP) and TFTP.
- Reads `$REMOTE_USERNAME` and `$REMOTE_PASSWORD` environment variables.
- """
- url = urllib.parse.urlparse(urlstring)
- username, password = get_authentication_variables(url.username, url.password)
- port = get_port_from_url(url)
-
- if url.scheme == 'ftp':
- username = username if username else 'anonymous'
- source = get_source_address(source)[0] if source else None
- upload_ftp(local_path, url.hostname, url.path, username, password, port, source, progressbar)
- elif url.scheme == 'sftp' or url.scheme == 'scp':
- source = get_source_address(source) if source else None
- upload_sftp(local_path, url.hostname, url.path, username, password, port, source, progressbar)
- elif url.scheme == 'tftp':
- upload_tftp(local_path, url.hostname, url.path, port, source, progressbar)
- else:
- raise ValueError(f'Unsupported URL scheme: {url.scheme}')
+def download(local_path, urlstring, *args, **kwargs):
+ urlc(urlstring, *args, **kwargs).download(local_path)
-def get_remote_file_size(urlstring, source=None):
- """
- Dispatch the appropriate function to return the size of the remote file from `urlstring`
- in terms of number of bytes.
- Optionally takes a `source` address (not valid for HTTP(S)).
- Supports HTTP, HTTPS, FTP and SFTP (through SFTP).
- Reads `$REMOTE_USERNAME` and `$REMOTE_PASSWORD` environment variables.
- """
- url = urllib.parse.urlparse(urlstring)
- username, password = get_authentication_variables(url.username, url.password)
- port = get_port_from_url(url)
-
- if url.scheme == 'http' or url.scheme == 'https':
- if source:
- print_error('Warning: Custom source address not supported for HTTP connections.')
- return get_http_file_size(urlstring, username, password)
- elif url.scheme == 'ftp':
- source = get_source_address(source)[0] if source else None
- username = username if username else 'anonymous'
- return get_ftp_file_size(url.hostname, url.path, username, password, port, source)
- elif url.scheme == 'sftp' or url.scheme == 'scp':
- source = get_source_address(source) if source else None
- return get_sftp_file_size(url.hostname, url.path, username, password, port, source)
- else:
- raise ValueError(f'Unsupported URL scheme: {url.scheme}')
+def upload(local_path, urlstring, *args, **kwargs):
+ urlc(urlstring, *args, **kwargs).upload(local_path)
-def get_remote_config(urlstring, source=None):
+def get_remote_config(urlstring, source_host='', source_port=0):
"""
- Download remote (config) file from `urlstring` and return the contents as a string.
- Args:
- remote file URI:
- tftp://<host>[:<port>]/<file>
- http[s]://<host>[:<port>]/<file>
- [scp|sftp|ftp]://[<user>[:<passwd>]@]<host>[:port]/<file>
- source address (optional):
- <interface>
- <IP address>
+ Quietly download a file and return it as a string.
"""
temp = tempfile.NamedTemporaryFile(delete=False).name
try:
- download(temp, urlstring, source)
- with open(temp, 'r') as file:
- return file.read()
+ download(temp, urlstring, False, False, source_host, source_port)
+ with open(temp, 'r') as f:
+ return f.read()
finally:
os.remove(temp)
-def friendly_download(local_path, urlstring, source=None):
+def friendly_download(local_path, urlstring, source_host='', source_port=0):
"""
- Download from `urlstring` to `local_path` in an informative way.
- Checks the storage space before attempting download.
- Intended to be called from interactive, user-facing scripts.
+ Download with a progress bar, reassuring messages and free space checks.
"""
- destination_directory = os.path.dirname(local_path)
try:
- free_space = shutil.disk_usage(destination_directory).free
- try:
- file_size = get_remote_file_size(urlstring, source)
- if file_size < 1024 * 1024:
- print_error(f'The file is {file_size / 1024.0:.3f} KiB.')
- else:
- print_error(f'The file is {file_size / (1024.0 * 1024.0):.3f} MiB.')
- if file_size > free_space:
- raise OSError(f'Not enough disk space available in "{destination_directory}".')
- except ValueError:
- # Can't do a storage check in this case, so we bravely continue.
- file_size = 0
- print_error('Could not determine the file size in advance.')
- else:
- print_error('Downloading...')
- download(local_path, urlstring, source, progressbar=file_size > 1024 * 1024)
+ print_error('Downloading...')
+ download(local_path, urlstring, True, True, source_host, source_port)
except KeyboardInterrupt:
print_error('Download aborted by user.')
sys.exit(1)
@@ -401,3 +336,4 @@ def friendly_download(local_path, urlstring, source=None):
sys.exit(1)
else:
print_error('Download complete.')
+ sys.exit(0)
diff --git a/python/vyos/util.py b/python/vyos/util.py
index 9aa1f98d2..d8e83ab8d 100644
--- a/python/vyos/util.py
+++ b/python/vyos/util.py
@@ -856,6 +856,20 @@ def make_incremental_progressbar(increment: float):
while True:
yield
+def begin(*args):
+ """
+ Evaluate arguments in order and return the result of the *last* argument.
+ For combining multiple expressions in one statement. Useful for lambdas.
+ """
+ return args[-1]
+
+def begin0(*args):
+ """
+ Evaluate arguments in order and return the result of the *first* argument.
+ For combining multiple expressions in one statement. Useful for lambdas.
+ """
+ return args[0]
+
def is_systemd_service_active(service):
""" Test is a specified systemd service is activated.
Returns True if service is active, false otherwise.
diff --git a/smoketest/scripts/cli/test_container.py b/smoketest/scripts/cli/test_container.py
index 09ca89721..cc0cdaec0 100644
--- a/smoketest/scripts/cli/test_container.py
+++ b/smoketest/scripts/cli/test_container.py
@@ -19,7 +19,6 @@ import json
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_ha_vrrp.py b/smoketest/scripts/cli/test_ha_vrrp.py
index 8c5bb86d8..2524bf2b1 100755
--- a/smoketest/scripts/cli/test_ha_vrrp.py
+++ b/smoketest/scripts/cli/test_ha_vrrp.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.ifconfig.vrrp import VRRP
from vyos.util import cmd
diff --git a/smoketest/scripts/cli/test_interfaces_geneve.py b/smoketest/scripts/cli/test_interfaces_geneve.py
index 129ee71e5..6233ade6e 100755
--- a/smoketest/scripts/cli/test_interfaces_geneve.py
+++ b/smoketest/scripts/cli/test_interfaces_geneve.py
@@ -16,7 +16,6 @@
import unittest
-from vyos.configsession import ConfigSession
from vyos.ifconfig import Interface
from vyos.util import get_interface_config
diff --git a/smoketest/scripts/cli/test_interfaces_openvpn.py b/smoketest/scripts/cli/test_interfaces_openvpn.py
index 7ce1b9872..f8a6ae986 100755
--- a/smoketest/scripts/cli/test_interfaces_openvpn.py
+++ b/smoketest/scripts/cli/test_interfaces_openvpn.py
@@ -23,7 +23,6 @@ from netifaces import interfaces
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_interfaces_pppoe.py b/smoketest/scripts/cli/test_interfaces_pppoe.py
index 67edce2a0..4f1e1ee99 100755
--- a/smoketest/scripts/cli/test_interfaces_pppoe.py
+++ b/smoketest/scripts/cli/test_interfaces_pppoe.py
@@ -20,7 +20,6 @@ import unittest
from psutil import process_iter
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
config_file = '/etc/ppp/peers/{}'
diff --git a/smoketest/scripts/cli/test_interfaces_vxlan.py b/smoketest/scripts/cli/test_interfaces_vxlan.py
index 7b420cd51..f63c850d8 100755
--- a/smoketest/scripts/cli/test_interfaces_vxlan.py
+++ b/smoketest/scripts/cli/test_interfaces_vxlan.py
@@ -16,7 +16,6 @@
import unittest
-from vyos.configsession import ConfigSession
from vyos.ifconfig import Interface
from vyos.util import get_interface_config
diff --git a/smoketest/scripts/cli/test_interfaces_wireguard.py b/smoketest/scripts/cli/test_interfaces_wireguard.py
index 3707eaac3..aaf27a2c4 100755
--- a/smoketest/scripts/cli/test_interfaces_wireguard.py
+++ b/smoketest/scripts/cli/test_interfaces_wireguard.py
@@ -18,7 +18,6 @@ import os
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
base_path = ['interfaces', 'wireguard']
diff --git a/smoketest/scripts/cli/test_nat.py b/smoketest/scripts/cli/test_nat.py
index 0706f234e..75c628244 100755
--- a/smoketest/scripts/cli/test_nat.py
+++ b/smoketest/scripts/cli/test_nat.py
@@ -20,7 +20,6 @@ import json
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
from vyos.util import dict_search
diff --git a/smoketest/scripts/cli/test_nat66.py b/smoketest/scripts/cli/test_nat66.py
index 7721105e0..8afe0da26 100755
--- a/smoketest/scripts/cli/test_nat66.py
+++ b/smoketest/scripts/cli/test_nat66.py
@@ -21,7 +21,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
from vyos.util import dict_search
diff --git a/smoketest/scripts/cli/test_pki.py b/smoketest/scripts/cli/test_pki.py
index deaf23b05..45a4bd61e 100755
--- a/smoketest/scripts/cli/test_pki.py
+++ b/smoketest/scripts/cli/test_pki.py
@@ -17,7 +17,6 @@
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
base_path = ['pki']
diff --git a/smoketest/scripts/cli/test_policy.py b/smoketest/scripts/cli/test_policy.py
index c2288a86a..5844e1ec1 100755
--- a/smoketest/scripts/cli/test_policy.py
+++ b/smoketest/scripts/cli/test_policy.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
@@ -308,7 +307,7 @@ class TestPolicy(VyOSUnitTestSHIM.TestCase):
continue
for rule, rule_config in as_path_config['rule'].items():
- tmp = f'bgp as-path access-list {as_path}'
+ tmp = f'bgp as-path access-list {as_path} seq {rule}'
if rule_config['action'] == 'permit':
tmp += ' permit'
else:
diff --git a/smoketest/scripts/cli/test_protocols_bfd.py b/smoketest/scripts/cli/test_protocols_bfd.py
index a57f8d5f2..46a019dfc 100755
--- a/smoketest/scripts/cli/test_protocols_bfd.py
+++ b/smoketest/scripts/cli/test_protocols_bfd.py
@@ -17,7 +17,6 @@
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import process_named_running
@@ -114,7 +113,8 @@ class TestProtocolsBFD(VyOSUnitTestSHIM.TestCase):
if 'echo_mode' in peer_config:
self.assertIn(f'echo-mode', peerconfig)
if 'intv_echo' in peer_config:
- self.assertIn(f'echo-interval {peer_config["intv_echo"]}', peerconfig)
+ self.assertIn(f'echo receive-interval {peer_config["intv_echo"]}', peerconfig)
+ self.assertIn(f'echo transmit-interval {peer_config["intv_echo"]}', peerconfig)
if 'intv_mult' in peer_config:
self.assertIn(f'detect-multiplier {peer_config["intv_mult"]}', peerconfig)
if 'intv_rx' in peer_config:
@@ -154,7 +154,8 @@ class TestProtocolsBFD(VyOSUnitTestSHIM.TestCase):
if 'echo_mode' in profile_config:
self.assertIn(f'echo-mode', config)
if 'intv_echo' in profile_config:
- self.assertIn(f'echo-interval {profile_config["intv_echo"]}', config)
+ self.assertIn(f'echo receive-interval {profile_config["intv_echo"]}', config)
+ self.assertIn(f'echo transmit-interval {profile_config["intv_echo"]}', config)
if 'intv_mult' in profile_config:
self.assertIn(f'detect-multiplier {profile_config["intv_mult"]}', config)
if 'intv_rx' in profile_config:
diff --git a/smoketest/scripts/cli/test_protocols_igmp-proxy.py b/smoketest/scripts/cli/test_protocols_igmp-proxy.py
index 1eaf21722..079b5bee5 100755
--- a/smoketest/scripts/cli/test_protocols_igmp-proxy.py
+++ b/smoketest/scripts/cli/test_protocols_igmp-proxy.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import read_file
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_protocols_isis.py b/smoketest/scripts/cli/test_protocols_isis.py
index 8170f2b56..e42040025 100755
--- a/smoketest/scripts/cli/test_protocols_isis.py
+++ b/smoketest/scripts/cli/test_protocols_isis.py
@@ -17,7 +17,6 @@
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.ifconfig import Section
from vyos.util import process_named_running
@@ -200,8 +199,6 @@ class TestProtocolsISIS(VyOSUnitTestSHIM.TestCase):
def test_isis_06_spf_delay(self):
- self.isis_base_config()
-
network = 'point-to-point'
holddown = '10'
init_delay = '50'
@@ -209,6 +206,7 @@ class TestProtocolsISIS(VyOSUnitTestSHIM.TestCase):
short_delay = '100'
time_to_learn = '75'
+ self.cli_set(base_path + ['net', net])
for interface in self._interfaces:
self.cli_set(base_path + ['interface', interface, 'network', network])
@@ -227,11 +225,6 @@ class TestProtocolsISIS(VyOSUnitTestSHIM.TestCase):
with self.assertRaises(ConfigSessionError):
self.cli_commit()
- self.cli_set(base_path + ['spf-delay-ietf', 'long-delay', long_delay])
- # verify() - All types of spf-delay must be configured
- with self.assertRaises(ConfigSessionError):
- self.cli_commit()
-
self.cli_set(base_path + ['spf-delay-ietf', 'short-delay', short_delay])
# verify() - All types of spf-delay must be configured
with self.assertRaises(ConfigSessionError):
diff --git a/smoketest/scripts/cli/test_protocols_ospf.py b/smoketest/scripts/cli/test_protocols_ospf.py
index 0529eefbd..04853c5fe 100755
--- a/smoketest/scripts/cli/test_protocols_ospf.py
+++ b/smoketest/scripts/cli/test_protocols_ospf.py
@@ -189,31 +189,7 @@ class TestProtocolsOSPF(VyOSUnitTestSHIM.TestCase):
for neighbor in neighbors:
self.assertIn(f' neighbor {neighbor} priority {priority} poll-interval {poll_interval}', frrconfig) # default
-
- def test_ospf_07_passive_interface(self):
- self.cli_set(base_path + ['passive-interface', 'default'])
- interfaces = Section.interfaces('ethernet')
- for interface in interfaces:
- self.cli_set(base_path + ['passive-interface-exclude', interface])
-
- # commit changes
- self.cli_commit()
-
- # Verify FRR ospfd configuration
- frrconfig = self.getFRRconfig('router ospf')
- try:
- self.assertIn(f'router ospf', frrconfig)
- self.assertIn(f' passive-interface default', frrconfig) # default
- for interface in interfaces:
- self.assertIn(f' no passive-interface {interface}', frrconfig) # default
- except:
- log.debug(frrconfig)
- log.debug(cmd('sudo dmesg'))
- log.debug(cmd('sudo cat /var/log/messages'))
- log.debug(cmd('vtysh -c "show run"'))
- self.fail('Now we can hopefully see why OSPF fails!')
-
- def test_ospf_08_redistribute(self):
+ def test_ospf_07_redistribute(self):
metric = '15'
metric_type = '1'
redistribute = ['bgp', 'connected', 'isis', 'kernel', 'rip', 'static']
@@ -238,7 +214,7 @@ class TestProtocolsOSPF(VyOSUnitTestSHIM.TestCase):
log.debug(cmd('vtysh -c "show run"'))
self.fail('Now we can hopefully see why OSPF fails!')
- def test_ospf_09_virtual_link(self):
+ def test_ospf_08_virtual_link(self):
networks = ['10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16']
area = '10'
shortcut = 'enable'
@@ -268,7 +244,7 @@ class TestProtocolsOSPF(VyOSUnitTestSHIM.TestCase):
self.assertIn(f' network {network} area {area}', frrconfig)
- def test_ospf_10_interface_configuration(self):
+ def test_ospf_09_interface_configuration(self):
interfaces = Section.interfaces('ethernet')
password = 'vyos1234'
bandwidth = '10000'
@@ -276,14 +252,17 @@ class TestProtocolsOSPF(VyOSUnitTestSHIM.TestCase):
network = 'point-to-point'
priority = '200'
+ self.cli_set(base_path + ['passive-interface', 'default'])
for interface in interfaces:
- self.cli_set(base_path + ['interface', interface, 'authentication', 'plaintext-password', password])
- self.cli_set(base_path + ['interface', interface, 'bandwidth', bandwidth])
- self.cli_set(base_path + ['interface', interface, 'bfd'])
- self.cli_set(base_path + ['interface', interface, 'cost', cost])
- self.cli_set(base_path + ['interface', interface, 'mtu-ignore'])
- self.cli_set(base_path + ['interface', interface, 'network', network])
- self.cli_set(base_path + ['interface', interface, 'priority', priority])
+ base_interface = base_path + ['interface', interface]
+ self.cli_set(base_interface + ['authentication', 'plaintext-password', password])
+ self.cli_set(base_interface + ['bandwidth', bandwidth])
+ self.cli_set(base_interface + ['bfd'])
+ self.cli_set(base_interface + ['cost', cost])
+ self.cli_set(base_interface + ['mtu-ignore'])
+ self.cli_set(base_interface + ['network', network])
+ self.cli_set(base_interface + ['priority', priority])
+ self.cli_set(base_interface + ['passive', 'disable'])
# commit changes
self.cli_commit()
@@ -297,41 +276,10 @@ class TestProtocolsOSPF(VyOSUnitTestSHIM.TestCase):
self.assertIn(f' ip ospf mtu-ignore', config)
self.assertIn(f' ip ospf network {network}', config)
self.assertIn(f' ip ospf priority {priority}', config)
+ self.assertIn(f' no ip ospf passive', config)
self.assertIn(f' bandwidth {bandwidth}', config)
-
- def test_ospf_11_vrfs(self):
- # It is safe to assume that when the basic VRF test works, all
- # other OSPF related features work, as we entirely inherit the CLI
- # templates and Jinja2 FRR template.
- table = '1000'
- vrf = 'blue'
- vrf_base = ['vrf', 'name', vrf]
- vrf_iface = 'eth1'
- self.cli_set(vrf_base + ['table', table])
- self.cli_set(vrf_base + ['protocols', 'ospf', 'interface', vrf_iface])
- self.cli_set(['interfaces', 'ethernet', vrf_iface, 'vrf', vrf])
-
- # Also set a default VRF OSPF config
- self.cli_set(base_path)
- self.cli_commit()
-
- # Verify FRR ospfd configuration
- frrconfig = self.getFRRconfig('router ospf')
- self.assertIn(f'router ospf', frrconfig)
- self.assertIn(f' auto-cost reference-bandwidth 100', frrconfig)
- self.assertIn(f' timers throttle spf 200 1000 10000', frrconfig) # defaults
-
- frrconfig = self.getFRRconfig(f'router ospf vrf {vrf}')
- self.assertIn(f'router ospf vrf {vrf}', frrconfig)
- self.assertIn(f' auto-cost reference-bandwidth 100', frrconfig)
- self.assertIn(f' timers throttle spf 200 1000 10000', frrconfig) # defaults
-
- self.cli_delete(['vrf', 'name', vrf])
- self.cli_delete(['interfaces', 'ethernet', vrf_iface, 'vrf'])
-
-
- def test_ospf_12_zebra_route_map(self):
+ def test_ospf_10_zebra_route_map(self):
# Implemented because of T3328
self.cli_set(base_path + ['route-map', route_map])
# commit changes
@@ -351,7 +299,7 @@ class TestProtocolsOSPF(VyOSUnitTestSHIM.TestCase):
frrconfig = self.getFRRconfig(zebra_route_map)
self.assertNotIn(zebra_route_map, frrconfig)
- def test_ospf_13_interface_area(self):
+ def test_ospf_11_interface_area(self):
area = '0'
interfaces = Section.interfaces('ethernet')
@@ -375,6 +323,37 @@ class TestProtocolsOSPF(VyOSUnitTestSHIM.TestCase):
self.assertIn(f'interface {interface}', config)
self.assertIn(f' ip ospf area {area}', config)
+ def test_ospf_12_vrfs(self):
+ # It is safe to assume that when the basic VRF test works, all
+ # other OSPF related features work, as we entirely inherit the CLI
+ # templates and Jinja2 FRR template.
+ table = '1000'
+ vrf = 'blue'
+ vrf_base = ['vrf', 'name', vrf]
+ vrf_iface = 'eth1'
+ self.cli_set(vrf_base + ['table', table])
+ self.cli_set(vrf_base + ['protocols', 'ospf', 'interface', vrf_iface])
+ self.cli_set(['interfaces', 'ethernet', vrf_iface, 'vrf', vrf])
+
+ # Also set a default VRF OSPF config
+ self.cli_set(base_path)
+ self.cli_commit()
+
+ # Verify FRR ospfd configuration
+ frrconfig = self.getFRRconfig('router ospf')
+ self.assertIn(f'router ospf', frrconfig)
+ self.assertIn(f' auto-cost reference-bandwidth 100', frrconfig)
+ self.assertIn(f' timers throttle spf 200 1000 10000', frrconfig) # defaults
+
+ frrconfig = self.getFRRconfig(f'router ospf vrf {vrf}')
+ self.assertIn(f'router ospf vrf {vrf}', frrconfig)
+ self.assertIn(f' auto-cost reference-bandwidth 100', frrconfig)
+ self.assertIn(f' timers throttle spf 200 1000 10000', frrconfig) # defaults
+
+ # cleanup
+ self.cli_delete(['vrf', 'name', vrf])
+ self.cli_delete(['interfaces', 'ethernet', vrf_iface, 'vrf'])
+
if __name__ == '__main__':
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
unittest.main(verbosity=2)
diff --git a/smoketest/scripts/cli/test_protocols_ospfv3.py b/smoketest/scripts/cli/test_protocols_ospfv3.py
index 0b4b01993..f0557f640 100755
--- a/smoketest/scripts/cli/test_protocols_ospfv3.py
+++ b/smoketest/scripts/cli/test_protocols_ospfv3.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.ifconfig import Section
from vyos.util import process_named_running
@@ -50,7 +49,7 @@ class TestProtocolsOSPFv3(VyOSUnitTestSHIM.TestCase):
interfaces = Section.interfaces('ethernet')
for interface in interfaces:
- self.cli_set(base_path + ['area', default_area, 'interface', interface])
+ self.cli_set(base_path + ['interface', interface, 'area', default_area])
# commit changes
self.cli_commit()
@@ -64,7 +63,8 @@ class TestProtocolsOSPFv3(VyOSUnitTestSHIM.TestCase):
self.assertIn(f' area {default_area} export-list {acl_name}', frrconfig)
for interface in interfaces:
- self.assertIn(f' interface {interface} area {default_area}', frrconfig)
+ if_config = self.getFRRconfig(f'interface {interface}')
+ self.assertIn(f'ipv6 ospf6 area {default_area}', if_config)
self.cli_delete(['policy', 'access-list6', acl_name])
@@ -167,5 +167,44 @@ class TestProtocolsOSPFv3(VyOSUnitTestSHIM.TestCase):
self.assertIn(f' area {area_stub} stub', frrconfig)
self.assertIn(f' area {area_stub_nosum} stub no-summary', frrconfig)
+
+ def test_ospfv3_06_vrfs(self):
+ # It is safe to assume that when the basic VRF test works, all
+ # other OSPF related features work, as we entirely inherit the CLI
+ # templates and Jinja2 FRR template.
+ table = '1000'
+ vrf = 'blue'
+ vrf_base = ['vrf', 'name', vrf]
+ vrf_iface = 'eth1'
+ router_id = '1.2.3.4'
+ router_id_vrf = '1.2.3.5'
+
+ self.cli_set(vrf_base + ['table', table])
+ self.cli_set(vrf_base + ['protocols', 'ospfv3', 'interface', vrf_iface, 'bfd'])
+ self.cli_set(vrf_base + ['protocols', 'ospfv3', 'parameters', 'router-id', router_id_vrf])
+
+ self.cli_set(['interfaces', 'ethernet', vrf_iface, 'vrf', vrf])
+
+ # Also set a default VRF OSPF config
+ self.cli_set(base_path + ['parameters', 'router-id', router_id])
+ self.cli_commit()
+
+ # Verify FRR ospfd configuration
+ frrconfig = self.getFRRconfig('router ospf6')
+ self.assertIn(f'router ospf6', frrconfig)
+ self.assertIn(f' ospf6 router-id {router_id}', frrconfig)
+
+ frrconfig = self.getFRRconfig(f'interface {vrf_iface} vrf {vrf}')
+ self.assertIn(f'interface {vrf_iface} vrf {vrf}', frrconfig)
+ self.assertIn(f' ipv6 ospf6 bfd', frrconfig)
+
+ frrconfig = self.getFRRconfig(f'router ospf6 vrf {vrf}')
+ self.assertIn(f'router ospf6 vrf {vrf}', frrconfig)
+ self.assertIn(f' ospf6 router-id {router_id_vrf}', frrconfig)
+
+ # cleanup
+ self.cli_delete(['vrf', 'name', vrf])
+ self.cli_delete(['interfaces', 'ethernet', vrf_iface, 'vrf'])
+
if __name__ == '__main__':
unittest.main(verbosity=2)
diff --git a/smoketest/scripts/cli/test_protocols_rip.py b/smoketest/scripts/cli/test_protocols_rip.py
index 423cd811a..80d4e79f9 100755
--- a/smoketest/scripts/cli/test_protocols_rip.py
+++ b/smoketest/scripts/cli/test_protocols_rip.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.ifconfig import Section
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_protocols_ripng.py b/smoketest/scripts/cli/test_protocols_ripng.py
index add92b73d..53336a533 100755
--- a/smoketest/scripts/cli/test_protocols_ripng.py
+++ b/smoketest/scripts/cli/test_protocols_ripng.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.ifconfig import Section
from vyos.util import process_named_running
@@ -55,7 +54,7 @@ class TestProtocolsRIPng(VyOSUnitTestSHIM.TestCase):
# Check for running process
self.assertTrue(process_named_running(PROCESS_NAME))
- def test_ripng(self):
+ def test_ripng_01_parameters(self):
metric = '8'
interfaces = Section.interfaces('ethernet')
aggregates = ['2001:db8:1000::/48', '2001:db8:2000::/48', '2001:db8:3000::/48']
@@ -122,5 +121,25 @@ class TestProtocolsRIPng(VyOSUnitTestSHIM.TestCase):
proto = 'ospf6'
self.assertIn(f' redistribute {proto} metric {metric} route-map {route_map}', frrconfig)
+ def test_ripng_02_zebra_route_map(self):
+ # Implemented because of T3328
+ self.cli_set(base_path + ['route-map', route_map])
+ # commit changes
+ self.cli_commit()
+
+ # Verify FRR configuration
+ zebra_route_map = f'ipv6 protocol ripng route-map {route_map}'
+ frrconfig = self.getFRRconfig(zebra_route_map)
+ self.assertIn(zebra_route_map, frrconfig)
+
+ # Remove the route-map again
+ self.cli_delete(base_path + ['route-map'])
+ # commit changes
+ self.cli_commit()
+
+ # Verify FRR configuration
+ frrconfig = self.getFRRconfig(zebra_route_map)
+ self.assertNotIn(zebra_route_map, frrconfig)
+
if __name__ == '__main__':
unittest.main(verbosity=2)
diff --git a/smoketest/scripts/cli/test_protocols_rpki.py b/smoketest/scripts/cli/test_protocols_rpki.py
index 6d334a9f8..e5e45565b 100755
--- a/smoketest/scripts/cli/test_protocols_rpki.py
+++ b/smoketest/scripts/cli/test_protocols_rpki.py
@@ -19,7 +19,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
from vyos.util import process_named_running
@@ -37,8 +36,6 @@ class TestProtocolsRPKI(VyOSUnitTestSHIM.TestCase):
self.cli_commit()
# Nothing RPKI specific should be left over in the config
- #
- # Disabled until T3266 is resolved
# frrconfig = self.getFRRconfig('rpki')
# self.assertNotIn('rpki', frrconfig)
diff --git a/smoketest/scripts/cli/test_protocols_static.py b/smoketest/scripts/cli/test_protocols_static.py
index 0d3228cc7..4c4eb5a7c 100755
--- a/smoketest/scripts/cli/test_protocols_static.py
+++ b/smoketest/scripts/cli/test_protocols_static.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.template import is_ipv6
from vyos.util import get_interface_config
diff --git a/smoketest/scripts/cli/test_service_bcast-relay.py b/smoketest/scripts/cli/test_service_bcast-relay.py
index 58b730ab4..87901869e 100755
--- a/smoketest/scripts/cli/test_service_bcast-relay.py
+++ b/smoketest/scripts/cli/test_service_bcast-relay.py
@@ -19,7 +19,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
from psutil import process_iter
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
base_path = ['service', 'broadcast-relay']
diff --git a/smoketest/scripts/cli/test_service_dhcp-relay.py b/smoketest/scripts/cli/test_service_dhcp-relay.py
index db2edba54..bbfd9e032 100755
--- a/smoketest/scripts/cli/test_service_dhcp-relay.py
+++ b/smoketest/scripts/cli/test_service_dhcp-relay.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.ifconfig import Section
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_service_dhcp-server.py b/smoketest/scripts/cli/test_service_dhcp-server.py
index 301f8fa31..14666db15 100755
--- a/smoketest/scripts/cli/test_service_dhcp-server.py
+++ b/smoketest/scripts/cli/test_service_dhcp-server.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import process_named_running
from vyos.util import read_file
diff --git a/smoketest/scripts/cli/test_service_dhcpv6-relay.py b/smoketest/scripts/cli/test_service_dhcpv6-relay.py
index 5a9dd1aa6..fc206435b 100755
--- a/smoketest/scripts/cli/test_service_dhcpv6-relay.py
+++ b/smoketest/scripts/cli/test_service_dhcpv6-relay.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.ifconfig import Section
from vyos.template import address_from_cidr
diff --git a/smoketest/scripts/cli/test_service_dhcpv6-server.py b/smoketest/scripts/cli/test_service_dhcpv6-server.py
index 3f9564e59..7177f1505 100755
--- a/smoketest/scripts/cli/test_service_dhcpv6-server.py
+++ b/smoketest/scripts/cli/test_service_dhcpv6-server.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.template import inc_ip
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_service_dns_dynamic.py b/smoketest/scripts/cli/test_service_dns_dynamic.py
index 134254186..90d10d40b 100755
--- a/smoketest/scripts/cli/test_service_dns_dynamic.py
+++ b/smoketest/scripts/cli/test_service_dns_dynamic.py
@@ -20,7 +20,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_service_dns_forwarding.py b/smoketest/scripts/cli/test_service_dns_forwarding.py
index 45ca618cb..5929f8cba 100755
--- a/smoketest/scripts/cli/test_service_dns_forwarding.py
+++ b/smoketest/scripts/cli/test_service_dns_forwarding.py
@@ -19,7 +19,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import read_file
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_service_https.py b/smoketest/scripts/cli/test_service_https.py
index 3af63636a..8e69efd9c 100755
--- a/smoketest/scripts/cli/test_service_https.py
+++ b/smoketest/scripts/cli/test_service_https.py
@@ -17,7 +17,6 @@
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.util import run
base_path = ['service', 'https']
diff --git a/smoketest/scripts/cli/test_service_mdns-repeater.py b/smoketest/scripts/cli/test_service_mdns-repeater.py
index 8941f065c..f99a98da1 100755
--- a/smoketest/scripts/cli/test_service_mdns-repeater.py
+++ b/smoketest/scripts/cli/test_service_mdns-repeater.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.util import process_named_running
base_path = ['service', 'mdns', 'repeater']
diff --git a/smoketest/scripts/cli/test_service_router-advert.py b/smoketest/scripts/cli/test_service_router-advert.py
index 26b4626c2..4875fb5d1 100755
--- a/smoketest/scripts/cli/test_service_router-advert.py
+++ b/smoketest/scripts/cli/test_service_router-advert.py
@@ -19,7 +19,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.util import read_file
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_service_snmp.py b/smoketest/scripts/cli/test_service_snmp.py
index e15d186bc..058835c72 100755
--- a/smoketest/scripts/cli/test_service_snmp.py
+++ b/smoketest/scripts/cli/test_service_snmp.py
@@ -19,7 +19,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.template import is_ipv4
from vyos.template import address_from_cidr
diff --git a/smoketest/scripts/cli/test_service_ssh.py b/smoketest/scripts/cli/test_service_ssh.py
index ded4d8301..a54c03919 100755
--- a/smoketest/scripts/cli/test_service_ssh.py
+++ b/smoketest/scripts/cli/test_service_ssh.py
@@ -20,7 +20,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_service_webproxy.py b/smoketest/scripts/cli/test_service_webproxy.py
index 6780a93f9..8a1a03ce7 100755
--- a/smoketest/scripts/cli/test_service_webproxy.py
+++ b/smoketest/scripts/cli/test_service_webproxy.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
from vyos.util import process_named_running
diff --git a/smoketest/scripts/cli/test_system_acceleration_qat.py b/smoketest/scripts/cli/test_system_acceleration_qat.py
index 9584888d6..9e60bb211 100755
--- a/smoketest/scripts/cli/test_system_acceleration_qat.py
+++ b/smoketest/scripts/cli/test_system_acceleration_qat.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
base_path = ['system', 'acceleration', 'qat']
diff --git a/smoketest/scripts/cli/test_system_conntrack.py b/smoketest/scripts/cli/test_system_conntrack.py
index a2380981b..b2934cf04 100755
--- a/smoketest/scripts/cli/test_system_conntrack.py
+++ b/smoketest/scripts/cli/test_system_conntrack.py
@@ -19,7 +19,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.util import cmd
from vyos.util import read_file
diff --git a/smoketest/scripts/cli/test_system_flow-accounting.py b/smoketest/scripts/cli/test_system_flow-accounting.py
new file mode 100755
index 000000000..a2b5b1481
--- /dev/null
+++ b/smoketest/scripts/cli/test_system_flow-accounting.py
@@ -0,0 +1,80 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2021 VyOS maintainers and contributors
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 or later as
+# published by the Free Software Foundation.
+#
+# This program 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+import unittest
+
+from base_vyostest_shim import VyOSUnitTestSHIM
+
+from vyos.configsession import ConfigSessionError
+from vyos.ifconfig import Section
+from vyos.util import cmd
+from vyos.util import process_named_running
+from vyos.util import read_file
+
+PROCESS_NAME = 'uacctd'
+base_path = ['system', 'flow-accounting']
+
+uacctd_conf = '/etc/pmacct/uacctd.conf'
+
+class TestSystemFlowAccounting(VyOSUnitTestSHIM.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ super(cls, cls).setUpClass()
+
+ # ensure we can also run this test on a live system - so lets clean
+ # out the current configuration :)
+ cls.cli_delete(cls, base_path)
+
+ def tearDown(self):
+ self.cli_delete(base_path)
+ self.cli_commit()
+
+ # after service removal process must no longer run
+ self.assertFalse(process_named_running(PROCESS_NAME))
+
+ def test_basic(self):
+ buffer_size = '5' # MiB
+ self.cli_set(base_path + ['buffer-size', buffer_size])
+
+ # You need to configure at least one interface for flow-accounting
+ with self.assertRaises(ConfigSessionError):
+ self.cli_commit()
+ for interface in Section.interfaces('ethernet'):
+ self.cli_set(base_path + ['interface', interface])
+
+ # commit changes
+ self.cli_commit()
+
+ # verify configuration
+ tmp = cmd('sudo iptables-save -t raw')
+ for interface in Section.interfaces('ethernet'):
+ self.assertIn(f'-A VYATTA_CT_PREROUTING_HOOK -i {interface} -m comment --comment FLOW_ACCOUNTING_RULE -j NFLOG --nflog-group 2 --nflog-size 128 --nflog-threshold 100', tmp)
+
+ uacctd = read_file(uacctd_conf)
+ # circular queue size - buffer_size
+ tmp = int(buffer_size) *1024 *1024
+ self.assertIn(f'plugin_pipe_size: {tmp}', uacctd)
+ # transfer buffer size - recommended value from pmacct developers 1/1000 of pipe size
+ tmp = int(buffer_size) *1024 *1024
+ # do an integer division
+ tmp //= 1000
+ self.assertIn(f'plugin_buffer_size: {tmp}', uacctd)
+
+ # Check for running process
+ self.assertTrue(process_named_running(PROCESS_NAME))
+
+if __name__ == '__main__':
+ unittest.main(verbosity=2)
diff --git a/smoketest/scripts/cli/test_system_ip.py b/smoketest/scripts/cli/test_system_ip.py
index e98a4e234..83df9d99e 100755
--- a/smoketest/scripts/cli/test_system_ip.py
+++ b/smoketest/scripts/cli/test_system_ip.py
@@ -17,7 +17,6 @@
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.util import read_file
base_path = ['system', 'ip']
diff --git a/smoketest/scripts/cli/test_system_ipv6.py b/smoketest/scripts/cli/test_system_ipv6.py
index c9c9e833d..1325d4b39 100755
--- a/smoketest/scripts/cli/test_system_ipv6.py
+++ b/smoketest/scripts/cli/test_system_ipv6.py
@@ -17,7 +17,6 @@
import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.util import read_file
base_path = ['system', 'ipv6']
diff --git a/smoketest/scripts/cli/test_system_lcd.py b/smoketest/scripts/cli/test_system_lcd.py
index 7a39e2986..831fba979 100755
--- a/smoketest/scripts/cli/test_system_lcd.py
+++ b/smoketest/scripts/cli/test_system_lcd.py
@@ -19,7 +19,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
from configparser import ConfigParser
-from vyos.configsession import ConfigSession
from vyos.util import process_named_running
config_file = '/run/LCDd/LCDd.conf'
diff --git a/smoketest/scripts/cli/test_system_login.py b/smoketest/scripts/cli/test_system_login.py
index 0addd630e..69a06eeac 100755
--- a/smoketest/scripts/cli/test_system_login.py
+++ b/smoketest/scripts/cli/test_system_login.py
@@ -24,7 +24,6 @@ from distutils.version import LooseVersion
from platform import release as kernel_version
from subprocess import Popen, PIPE
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import cmd
from vyos.util import read_file
diff --git a/smoketest/scripts/cli/test_system_nameserver.py b/smoketest/scripts/cli/test_system_nameserver.py
index 50dc466c2..58c84988e 100755
--- a/smoketest/scripts/cli/test_system_nameserver.py
+++ b/smoketest/scripts/cli/test_system_nameserver.py
@@ -19,7 +19,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.util import read_file
diff --git a/smoketest/scripts/cli/test_system_ntp.py b/smoketest/scripts/cli/test_system_ntp.py
index 2b86ebd7c..e8cc64463 100755
--- a/smoketest/scripts/cli/test_system_ntp.py
+++ b/smoketest/scripts/cli/test_system_ntp.py
@@ -19,7 +19,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.template import address_from_cidr
from vyos.template import netmask_from_cidr
diff --git a/smoketest/scripts/cli/test_vpn_ipsec.py b/smoketest/scripts/cli/test_vpn_ipsec.py
index 93569c4ec..c710aec6e 100755
--- a/smoketest/scripts/cli/test_vpn_ipsec.py
+++ b/smoketest/scripts/cli/test_vpn_ipsec.py
@@ -307,7 +307,7 @@ class TestVPNIPsec(VyOSUnitTestSHIM.TestCase):
swanctl_lines = [
f'proposals = aes128-sha1-modp1024,aes256-sha1-modp1024',
f'version = 1',
- f'life_time = {ike_lifetime}s',
+ f'rekey_time = {ike_lifetime}s',
f'rekey_time = {esp_lifetime}s',
f'esp_proposals = aes128-sha1-modp1024,aes256-sha1-modp1024,3des-md5-modp1024',
f'local_ts = dynamic[gre]',
diff --git a/smoketest/scripts/cli/test_vpn_openconnect.py b/smoketest/scripts/cli/test_vpn_openconnect.py
index cad3b1182..b0e859b5c 100755
--- a/smoketest/scripts/cli/test_vpn_openconnect.py
+++ b/smoketest/scripts/cli/test_vpn_openconnect.py
@@ -18,7 +18,6 @@ import unittest
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.util import process_named_running
OCSERV_CONF = '/run/ocserv/ocserv.conf'
diff --git a/smoketest/scripts/cli/test_vrf.py b/smoketest/scripts/cli/test_vrf.py
index 3a2af7bdc..5ffa9c086 100755
--- a/smoketest/scripts/cli/test_vrf.py
+++ b/smoketest/scripts/cli/test_vrf.py
@@ -22,7 +22,6 @@ import unittest
from netifaces import interfaces
from base_vyostest_shim import VyOSUnitTestSHIM
-from vyos.configsession import ConfigSession
from vyos.configsession import ConfigSessionError
from vyos.ifconfig import Interface
from vyos.ifconfig import Section
diff --git a/src/conf_mode/containers.py b/src/conf_mode/containers.py
index ab992e415..2e14e0b25 100755
--- a/src/conf_mode/containers.py
+++ b/src/conf_mode/containers.py
@@ -158,7 +158,7 @@ def verify(container):
v6_prefix = 0
# If ipv4-prefix not defined for user-defined network
if 'prefix' not in network_config:
- raise ConfigError(f'prefix for network "{net}" must be defined!')
+ raise ConfigError(f'prefix for network "{network}" must be defined!')
for prefix in network_config['prefix']:
if is_ipv4(prefix): v4_prefix += 1
diff --git a/src/conf_mode/policy.py b/src/conf_mode/policy.py
index 1a03d520b..e251396c7 100755
--- a/src/conf_mode/policy.py
+++ b/src/conf_mode/policy.py
@@ -171,9 +171,7 @@ def verify(policy):
def generate(policy):
if not policy:
- policy['new_frr_config'] = ''
return None
-
policy['new_frr_config'] = render_to_string('frr/policy.frr.tmpl', policy)
return None
@@ -190,8 +188,9 @@ def apply(policy):
frr_cfg.modify_section(r'^bgp community-list .*')
frr_cfg.modify_section(r'^bgp extcommunity-list .*')
frr_cfg.modify_section(r'^bgp large-community-list .*')
- frr_cfg.modify_section(r'^route-map .*')
- frr_cfg.add_before('^line vty', policy['new_frr_config'])
+ frr_cfg.modify_section(r'^route-map .*', stop_pattern='^exit', remove_stop_mark=True)
+ if 'new_frr_config' in policy:
+ frr_cfg.add_before(frr.default_add_before, policy['new_frr_config'])
frr_cfg.commit_configuration(bgp_daemon)
# The route-map used for the FIB (zebra) is part of the zebra daemon
@@ -200,19 +199,11 @@ def apply(policy):
frr_cfg.modify_section(r'^ipv6 access-list .*')
frr_cfg.modify_section(r'^ip prefix-list .*')
frr_cfg.modify_section(r'^ipv6 prefix-list .*')
- frr_cfg.modify_section(r'^route-map .*')
- frr_cfg.add_before('^line vty', policy['new_frr_config'])
+ frr_cfg.modify_section(r'^route-map .*', stop_pattern='^exit', remove_stop_mark=True)
+ if 'new_frr_config' in policy:
+ frr_cfg.add_before(frr.default_add_before, policy['new_frr_config'])
frr_cfg.commit_configuration(zebra_daemon)
- # If FRR config is blank, rerun the blank commit x times due to frr-reload
- # behavior/bug not properly clearing out on one commit.
- if policy['new_frr_config'] == '':
- for a in range(5):
- frr_cfg.commit_configuration(zebra_daemon)
-
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
diff --git a/src/conf_mode/protocols_bfd.py b/src/conf_mode/protocols_bfd.py
index 539fd7b8e..94825ba10 100755
--- a/src/conf_mode/protocols_bfd.py
+++ b/src/conf_mode/protocols_bfd.py
@@ -16,8 +16,6 @@
import os
-from sys import exit
-
from vyos.config import Config
from vyos.configdict import dict_merge
from vyos.template import is_ipv6
@@ -36,7 +34,6 @@ def get_config(config=None):
conf = Config()
base = ['protocols', 'bfd']
bfd = conf.get_config_dict(base, get_first_key=True)
-
# Bail out early if configuration tree does not exist
if not conf.exists(base):
return bfd
@@ -89,18 +86,19 @@ def verify(bfd):
def generate(bfd):
if not bfd:
- bfd['new_frr_config'] = ''
return None
-
bfd['new_frr_config'] = render_to_string('frr/bfdd.frr.tmpl', bfd)
def apply(bfd):
+ bfd_daemon = 'bfdd'
+
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
- frr_cfg.load_configuration()
- frr_cfg.modify_section('^bfd', '')
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', bfd['new_frr_config'])
- frr_cfg.commit_configuration()
+ frr_cfg.load_configuration(bfd_daemon)
+ frr_cfg.modify_section('^bfd', stop_pattern='^exit', remove_stop_mark=True)
+ if 'new_frr_config' in bfd:
+ frr_cfg.add_before(frr.default_add_before, bfd['new_frr_config'])
+ frr_cfg.commit_configuration(bfd_daemon)
return None
diff --git a/src/conf_mode/protocols_bgp.py b/src/conf_mode/protocols_bgp.py
index 68284e0f9..b88f0c4ef 100755
--- a/src/conf_mode/protocols_bgp.py
+++ b/src/conf_mode/protocols_bgp.py
@@ -268,8 +268,6 @@ def verify(bgp):
def generate(bgp):
if not bgp or 'deleted' in bgp:
- bgp['frr_bgpd_config'] = ''
- bgp['frr_zebra_config'] = ''
return None
bgp['protocol'] = 'bgp' # required for frr/vrf.route-map.frr.tmpl
@@ -287,8 +285,9 @@ def apply(bgp):
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
- frr_cfg.modify_section(r'(\s+)?ip protocol bgp route-map [-a-zA-Z0-9.]+$', '', '(\s|!)')
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', bgp['frr_zebra_config'])
+ frr_cfg.modify_section(r'(\s+)?ip protocol bgp route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
+ if 'frr_zebra_config' in bgp:
+ frr_cfg.add_before(frr.default_add_before, bgp['frr_zebra_config'])
frr_cfg.commit_configuration(zebra_daemon)
# Generate empty helper string which can be ammended to FRR commands, it
@@ -298,13 +297,11 @@ def apply(bgp):
vrf = ' vrf ' + bgp['vrf']
frr_cfg.load_configuration(bgp_daemon)
- frr_cfg.modify_section(f'^router bgp \d+{vrf}$', '')
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', bgp['frr_bgpd_config'])
+ frr_cfg.modify_section(f'^router bgp \d+{vrf}', stop_pattern='^exit', remove_stop_mark=True)
+ if 'frr_bgpd_config' in bgp:
+ frr_cfg.add_before(frr.default_add_before, bgp['frr_bgpd_config'])
frr_cfg.commit_configuration(bgp_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
diff --git a/src/conf_mode/protocols_isis.py b/src/conf_mode/protocols_isis.py
index 4505e2496..9b4b215de 100755
--- a/src/conf_mode/protocols_isis.py
+++ b/src/conf_mode/protocols_isis.py
@@ -56,10 +56,10 @@ def get_config(config=None):
# instead of the VRF instance.
if vrf: isis['vrf'] = vrf
- # As we no re-use this Python handler for both VRF and non VRF instances for
- # IS-IS we need to find out if any interfaces changed so properly adjust
- # the FRR configuration and not by acctident change interfaces from a
- # different VRF.
+ # FRR has VRF support for different routing daemons. As interfaces belong
+ # to VRFs - or the global VRF, we need to check for changed interfaces so
+ # that they will be properly rendered for the FRR config. Also this eases
+ # removal of interfaces from the running configuration.
interfaces_removed = node_changed(conf, base + ['interface'])
if interfaces_removed:
isis['interface_removed'] = list(interfaces_removed)
@@ -196,8 +196,6 @@ def verify(isis):
def generate(isis):
if not isis or 'deleted' in isis:
- isis['frr_isisd_config'] = ''
- isis['frr_zebra_config'] = ''
return None
isis['protocol'] = 'isis' # required for frr/vrf.route-map.frr.tmpl
@@ -214,8 +212,9 @@ def apply(isis):
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
- frr_cfg.modify_section(r'(\s+)?ip protocol isis route-map [-a-zA-Z0-9.]+$', '', '(\s|!)')
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', isis['frr_zebra_config'])
+ frr_cfg.modify_section('(\s+)?ip protocol isis route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
+ if 'frr_zebra_config' in isis:
+ frr_cfg.add_before(frr.default_add_before, isis['frr_zebra_config'])
frr_cfg.commit_configuration(zebra_daemon)
# Generate empty helper string which can be ammended to FRR commands, it
@@ -225,19 +224,18 @@ def apply(isis):
vrf = ' vrf ' + isis['vrf']
frr_cfg.load_configuration(isis_daemon)
- frr_cfg.modify_section(f'^router isis VyOS{vrf}$', '')
+ frr_cfg.modify_section(f'^router isis VyOS{vrf}', stop_pattern='^exit', remove_stop_mark=True)
for key in ['interface', 'interface_removed']:
if key not in isis:
continue
for interface in isis[key]:
- frr_cfg.modify_section(f'^interface {interface}{vrf}$', '')
+ frr_cfg.modify_section(f'^interface {interface}{vrf}', stop_pattern='^exit', remove_stop_mark=True)
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', isis['frr_isisd_config'])
- frr_cfg.commit_configuration(isis_daemon)
+ if 'frr_isisd_config' in isis:
+ frr_cfg.add_before(frr.default_add_before, isis['frr_isisd_config'])
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
+ frr_cfg.commit_configuration(isis_daemon)
return None
diff --git a/src/conf_mode/protocols_ospf.py b/src/conf_mode/protocols_ospf.py
index 6ccda2e5a..4895cde6f 100755
--- a/src/conf_mode/protocols_ospf.py
+++ b/src/conf_mode/protocols_ospf.py
@@ -56,10 +56,10 @@ def get_config(config=None):
# instead of the VRF instance.
if vrf: ospf['vrf'] = vrf
- # As we no re-use this Python handler for both VRF and non VRF instances for
- # OSPF we need to find out if any interfaces changed so properly adjust
- # the FRR configuration and not by acctident change interfaces from a
- # different VRF.
+ # FRR has VRF support for different routing daemons. As interfaces belong
+ # to VRFs - or the global VRF, we need to check for changed interfaces so
+ # that they will be properly rendered for the FRR config. Also this eases
+ # removal of interfaces from the running configuration.
interfaces_removed = node_changed(conf, base + ['interface'])
if interfaces_removed:
ospf['interface_removed'] = list(interfaces_removed)
@@ -177,11 +177,11 @@ def verify(ospf):
raise ConfigError('Can not use OSPF interface area and area ' \
'network configuration at the same time!')
- if 'vrf' in ospf:
# If interface specific options are set, we must ensure that the
# interface is bound to our requesting VRF. Due to the VyOS
# priorities the interface is bound to the VRF after creation of
# the VRF itself, and before any routing protocol is configured.
+ if 'vrf' in ospf:
vrf = ospf['vrf']
tmp = get_interface_config(interface)
if 'master' not in tmp or tmp['master'] != vrf:
@@ -191,8 +191,6 @@ def verify(ospf):
def generate(ospf):
if not ospf or 'deleted' in ospf:
- ospf['frr_ospfd_config'] = ''
- ospf['frr_zebra_config'] = ''
return None
ospf['protocol'] = 'ospf' # required for frr/vrf.route-map.frr.tmpl
@@ -209,8 +207,9 @@ def apply(ospf):
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
- frr_cfg.modify_section(r'(\s+)?ip protocol ospf route-map [-a-zA-Z0-9.]+$', '', '(\s|!)')
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', ospf['frr_zebra_config'])
+ frr_cfg.modify_section('(\s+)?ip protocol ospf route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
+ if 'frr_zebra_config' in ospf:
+ frr_cfg.add_before(frr.default_add_before, ospf['frr_zebra_config'])
frr_cfg.commit_configuration(zebra_daemon)
# Generate empty helper string which can be ammended to FRR commands, it
@@ -220,20 +219,18 @@ def apply(ospf):
vrf = ' vrf ' + ospf['vrf']
frr_cfg.load_configuration(ospf_daemon)
- frr_cfg.modify_section(f'^router ospf{vrf}$', '')
+ frr_cfg.modify_section(f'^router ospf{vrf}', stop_pattern='^exit', remove_stop_mark=True)
for key in ['interface', 'interface_removed']:
if key not in ospf:
continue
for interface in ospf[key]:
- frr_cfg.modify_section(f'^interface {interface}{vrf}$', '')
+ frr_cfg.modify_section(f'^interface {interface}{vrf}', stop_pattern='^exit', remove_stop_mark=True)
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', ospf['frr_ospfd_config'])
+ if 'frr_ospfd_config' in ospf:
+ frr_cfg.add_before(frr.default_add_before, ospf['frr_ospfd_config'])
frr_cfg.commit_configuration(ospf_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
diff --git a/src/conf_mode/protocols_ospfv3.py b/src/conf_mode/protocols_ospfv3.py
index 536ffa690..d0460b830 100755
--- a/src/conf_mode/protocols_ospfv3.py
+++ b/src/conf_mode/protocols_ospfv3.py
@@ -17,30 +17,53 @@
import os
from sys import exit
+from sys import argv
from vyos.config import Config
from vyos.configdict import dict_merge
+from vyos.configdict import node_changed
from vyos.configverify import verify_common_route_maps
from vyos.template import render_to_string
from vyos.ifconfig import Interface
+from vyos.util import get_interface_config
from vyos.xml import defaults
from vyos import ConfigError
from vyos import frr
from vyos import airbag
airbag.enable()
-frr_daemon = 'ospf6d'
-
def get_config(config=None):
if config:
conf = config
else:
conf = Config()
- base = ['protocols', 'ospfv3']
+
+ vrf = None
+ if len(argv) > 1:
+ vrf = argv[1]
+
+ base_path = ['protocols', 'ospfv3']
+
+ # eqivalent of the C foo ? 'a' : 'b' statement
+ base = vrf and ['vrf', 'name', vrf, 'protocols', 'ospfv3'] or base_path
ospfv3 = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True)
+ # Assign the name of our VRF context. This MUST be done before the return
+ # statement below, else on deletion we will delete the default instance
+ # instead of the VRF instance.
+ if vrf: ospfv3['vrf'] = vrf
+
+ # FRR has VRF support for different routing daemons. As interfaces belong
+ # to VRFs - or the global VRF, we need to check for changed interfaces so
+ # that they will be properly rendered for the FRR config. Also this eases
+ # removal of interfaces from the running configuration.
+ interfaces_removed = node_changed(conf, base + ['interface'])
+ if interfaces_removed:
+ ospfv3['interface_removed'] = list(interfaces_removed)
+
# Bail out early if configuration tree does not exist
if not conf.exists(base):
+ ospfv3.update({'deleted' : ''})
return ospfv3
# We also need some additional information from the config, prefix-lists
@@ -61,33 +84,56 @@ def verify(ospfv3):
verify_common_route_maps(ospfv3)
if 'interface' in ospfv3:
- for ifname, if_config in ospfv3['interface'].items():
- if 'ifmtu' in if_config:
- mtu = Interface(ifname).get_mtu()
- if int(if_config['ifmtu']) > int(mtu):
+ for interface, interface_config in ospfv3['interface'].items():
+ if 'ifmtu' in interface_config:
+ mtu = Interface(interface).get_mtu()
+ if int(interface_config['ifmtu']) > int(mtu):
raise ConfigError(f'OSPFv3 ifmtu can not exceed physical MTU of "{mtu}"')
+ # If interface specific options are set, we must ensure that the
+ # interface is bound to our requesting VRF. Due to the VyOS
+ # priorities the interface is bound to the VRF after creation of
+ # the VRF itself, and before any routing protocol is configured.
+ if 'vrf' in ospfv3:
+ vrf = ospfv3['vrf']
+ tmp = get_interface_config(interface)
+ if 'master' not in tmp or tmp['master'] != vrf:
+ raise ConfigError(f'Interface {interface} is not a member of VRF {vrf}!')
+
return None
def generate(ospfv3):
- if not ospfv3:
- ospfv3['new_frr_config'] = ''
+ if not ospfv3 or 'deleted' in ospfv3:
return None
ospfv3['new_frr_config'] = render_to_string('frr/ospf6d.frr.tmpl', ospfv3)
return None
def apply(ospfv3):
+ ospf6_daemon = 'ospf6d'
+
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
- frr_cfg.load_configuration(frr_daemon)
- frr_cfg.modify_section(r'^interface \S+', '')
- frr_cfg.modify_section('^router ospf6$', '')
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', ospfv3['new_frr_config'])
- frr_cfg.commit_configuration(frr_daemon)
-
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
+
+ # Generate empty helper string which can be ammended to FRR commands, it
+ # will be either empty (default VRF) or contain the "vrf <name" statement
+ vrf = ''
+ if 'vrf' in ospfv3:
+ vrf = ' vrf ' + ospfv3['vrf']
+
+ frr_cfg.load_configuration(ospf6_daemon)
+ frr_cfg.modify_section(f'^router ospf6{vrf}', stop_pattern='^exit', remove_stop_mark=True)
+
+ for key in ['interface', 'interface_removed']:
+ if key not in ospfv3:
+ continue
+ for interface in ospfv3[key]:
+ frr_cfg.modify_section(f'^interface {interface}{vrf}', stop_pattern='^exit', remove_stop_mark=True)
+
+ if 'new_frr_config' in ospfv3:
+ frr_cfg.add_before(frr.default_add_before, ospfv3['new_frr_config'])
+
+ frr_cfg.commit_configuration(ospf6_daemon)
return None
diff --git a/src/conf_mode/protocols_rip.py b/src/conf_mode/protocols_rip.py
index 6b78f6f2d..300f56489 100755
--- a/src/conf_mode/protocols_rip.py
+++ b/src/conf_mode/protocols_rip.py
@@ -20,6 +20,7 @@ from sys import exit
from vyos.config import Config
from vyos.configdict import dict_merge
+from vyos.configdict import node_changed
from vyos.configverify import verify_common_route_maps
from vyos.configverify import verify_access_list
from vyos.configverify import verify_prefix_list
@@ -39,8 +40,17 @@ def get_config(config=None):
base = ['protocols', 'rip']
rip = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True)
+ # FRR has VRF support for different routing daemons. As interfaces belong
+ # to VRFs - or the global VRF, we need to check for changed interfaces so
+ # that they will be properly rendered for the FRR config. Also this eases
+ # removal of interfaces from the running configuration.
+ interfaces_removed = node_changed(conf, base + ['interface'])
+ if interfaces_removed:
+ rip['interface_removed'] = list(interfaces_removed)
+
# Bail out early if configuration tree does not exist
if not conf.exists(base):
+ rip.update({'deleted' : ''})
return rip
# We have gathered the dict representation of the CLI, but there are default
@@ -89,12 +99,10 @@ def verify(rip):
f'with "split-horizon disable" for "{interface}"!')
def generate(rip):
- if not rip:
- rip['new_frr_config'] = ''
+ if not rip or 'deleted' in rip:
return None
rip['new_frr_config'] = render_to_string('frr/ripd.frr.tmpl', rip)
-
return None
def apply(rip):
@@ -106,19 +114,22 @@ def apply(rip):
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
- frr_cfg.modify_section(r'^ip protocol rip route-map [-a-zA-Z0-9.]+$', '')
+ frr_cfg.modify_section('^ip protocol rip route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
frr_cfg.commit_configuration(zebra_daemon)
frr_cfg.load_configuration(rip_daemon)
- frr_cfg.modify_section(r'key chain \S+', '')
- frr_cfg.modify_section(r'interface \S+', '')
- frr_cfg.modify_section('^router rip$', '')
+ frr_cfg.modify_section('^key chain \S+', stop_pattern='^exit', remove_stop_mark=True)
+ frr_cfg.modify_section('^router rip', stop_pattern='^exit', remove_stop_mark=True)
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', rip['new_frr_config'])
- frr_cfg.commit_configuration(rip_daemon)
+ for key in ['interface', 'interface_removed']:
+ if key not in rip:
+ continue
+ for interface in rip[key]:
+ frr_cfg.modify_section(f'^interface {interface}', stop_pattern='^exit', remove_stop_mark=True)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
+ if 'new_frr_config' in rip:
+ frr_cfg.add_before(frr.default_add_before, rip['new_frr_config'])
+ frr_cfg.commit_configuration(rip_daemon)
return None
diff --git a/src/conf_mode/protocols_ripng.py b/src/conf_mode/protocols_ripng.py
index bc4954f63..d9b8c0b30 100755
--- a/src/conf_mode/protocols_ripng.py
+++ b/src/conf_mode/protocols_ripng.py
@@ -31,8 +31,6 @@ from vyos import frr
from vyos import airbag
airbag.enable()
-frr_daemon = 'ripngd'
-
def get_config(config=None):
if config:
conf = config
@@ -99,17 +97,24 @@ def generate(ripng):
return None
def apply(ripng):
+ ripng_daemon = 'ripngd'
+ zebra_daemon = 'zebra'
+
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
- frr_cfg.load_configuration(frr_daemon)
- frr_cfg.modify_section(r'key chain \S+', '')
- frr_cfg.modify_section(r'interface \S+', '')
- frr_cfg.modify_section('router ripng', '')
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', ripng['new_frr_config'])
- frr_cfg.commit_configuration(frr_daemon)
-
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
+
+ # The route-map used for the FIB (zebra) is part of the zebra daemon
+ frr_cfg.load_configuration(zebra_daemon)
+ frr_cfg.modify_section('^ipv6 protocol ripng route-map [-a-zA-Z0-9.]+', stop_pattern='(\s|!)')
+ frr_cfg.commit_configuration(zebra_daemon)
+
+ frr_cfg.load_configuration(ripng_daemon)
+ frr_cfg.modify_section('key chain \S+', stop_pattern='^exit', remove_stop_mark=True)
+ frr_cfg.modify_section('interface \S+', stop_pattern='^exit', remove_stop_mark=True)
+ frr_cfg.modify_section('^router ripng', stop_pattern='^exit', remove_stop_mark=True)
+ if 'new_frr_config' in ripng:
+ frr_cfg.add_before(frr.default_add_before, ripng['new_frr_config'])
+ frr_cfg.commit_configuration(ripng_daemon)
return None
diff --git a/src/conf_mode/protocols_rpki.py b/src/conf_mode/protocols_rpki.py
index 947c8ab7a..4bd4e8650 100755
--- a/src/conf_mode/protocols_rpki.py
+++ b/src/conf_mode/protocols_rpki.py
@@ -28,8 +28,6 @@ from vyos import frr
from vyos import airbag
airbag.enable()
-frr_daemon = 'bgpd'
-
def get_config(config=None):
if config:
conf = config
@@ -38,7 +36,9 @@ def get_config(config=None):
base = ['protocols', 'rpki']
rpki = conf.get_config_dict(base, key_mangling=('-', '_'), get_first_key=True)
+ # Bail out early if configuration tree does not exist
if not conf.exists(base):
+ rpki.update({'deleted' : ''})
return rpki
# We have gathered the dict representation of the CLI, but there are default
@@ -79,17 +79,22 @@ def verify(rpki):
return None
def generate(rpki):
+ if not rpki:
+ return
rpki['new_frr_config'] = render_to_string('frr/rpki.frr.tmpl', rpki)
return None
def apply(rpki):
+ bgp_daemon = 'bgpd'
+
# Save original configuration prior to starting any commit actions
frr_cfg = frr.FRRConfig()
- frr_cfg.load_configuration(frr_daemon)
- frr_cfg.modify_section('rpki', '')
- frr_cfg.add_before(r'(ip prefix-list .*|route-map .*|line vty)', rpki['new_frr_config'])
- frr_cfg.commit_configuration(frr_daemon)
+ frr_cfg.load_configuration(bgp_daemon)
+ frr_cfg.modify_section('^rpki')
+ if 'new_frr_config' in rpki:
+ frr_cfg.add_before(frr.default_add_before, rpki['new_frr_config'])
+ frr_cfg.commit_configuration(bgp_daemon)
return None
if __name__ == '__main__':
diff --git a/src/conf_mode/protocols_static.py b/src/conf_mode/protocols_static.py
index f010141e9..c1e427b16 100755
--- a/src/conf_mode/protocols_static.py
+++ b/src/conf_mode/protocols_static.py
@@ -85,6 +85,8 @@ def verify(static):
return None
def generate(static):
+ if not static:
+ return None
static['new_frr_config'] = render_to_string('frr/staticd.frr.tmpl', static)
return None
@@ -97,24 +99,21 @@ def apply(static):
# The route-map used for the FIB (zebra) is part of the zebra daemon
frr_cfg.load_configuration(zebra_daemon)
- frr_cfg.modify_section(r'^ip protocol static route-map [-a-zA-Z0-9.]+$', '')
+ frr_cfg.modify_section(r'^ip protocol static route-map [-a-zA-Z0-9.]+', '')
frr_cfg.commit_configuration(zebra_daemon)
-
frr_cfg.load_configuration(static_daemon)
if 'vrf' in static:
vrf = static['vrf']
- frr_cfg.modify_section(f'^vrf {vrf}$', '')
+ frr_cfg.modify_section(f'^vrf {vrf}', stop_pattern='^exit', remove_stop_mark=True)
else:
- frr_cfg.modify_section(r'^ip route .*', '')
- frr_cfg.modify_section(r'^ipv6 route .*', '')
+ frr_cfg.modify_section(r'^ip route .*')
+ frr_cfg.modify_section(r'^ipv6 route .*')
- frr_cfg.add_before(r'(interface .*|line vty)', static['new_frr_config'])
+ if 'new_frr_config' in static:
+ frr_cfg.add_before(frr.default_add_before, static['new_frr_config'])
frr_cfg.commit_configuration(static_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
diff --git a/src/conf_mode/system-option.py b/src/conf_mode/system-option.py
index 55cf6b142..b1c63e316 100755
--- a/src/conf_mode/system-option.py
+++ b/src/conf_mode/system-option.py
@@ -126,6 +126,12 @@ def apply(options):
if 'keyboard_layout' in options:
cmd('loadkeys {keyboard_layout}'.format(**options))
+ # Enable/diable root-partition-auto-resize SystemD service
+ if 'root_partition_auto_resize' in options:
+ cmd('systemctl enable root-partition-auto-resize.service')
+ else:
+ cmd('systemctl disable root-partition-auto-resize.service')
+
if __name__ == '__main__':
try:
c = get_config()
diff --git a/src/conf_mode/vrf_vni.py b/src/conf_mode/vrf_vni.py
index 50d60f0dc..1a7bd1f09 100755
--- a/src/conf_mode/vrf_vni.py
+++ b/src/conf_mode/vrf_vni.py
@@ -47,13 +47,11 @@ def apply(vrf):
# add configuration to FRR
frr_cfg = frr.FRRConfig()
frr_cfg.load_configuration(frr_daemon)
- frr_cfg.modify_section(f'^vrf .+$', '')
- frr_cfg.add_before(r'(interface .*|line vty)', vrf['new_frr_config'])
+ frr_cfg.modify_section(f'^vrf .+', stop_pattern='^exit-vrf', remove_stop_mark=True)
+ if 'new_frr_config' in vrf:
+ frr_cfg.add_before(frr.default_add_before, vrf['new_frr_config'])
frr_cfg.commit_configuration(frr_daemon)
- # Save configuration to /run/frr/config/frr.conf
- frr.save_configuration()
-
return None
if __name__ == '__main__':
diff --git a/src/migration-scripts/ospf/0-to-1 b/src/migration-scripts/ospf/0-to-1
new file mode 100755
index 000000000..678569d9e
--- /dev/null
+++ b/src/migration-scripts/ospf/0-to-1
@@ -0,0 +1,81 @@
+#!/usr/bin/env python3
+#
+# Copyright (C) 2021 VyOS maintainers and contributors
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 or later as
+# published by the Free Software Foundation.
+#
+# This program 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# T3753: upgrade to FRR8 and move CLI options to better fit with the new FRR CLI
+
+from sys import argv
+from vyos.configtree import ConfigTree
+
+def ospf_passive_migration(config, ospf_base):
+ if config.exists(ospf_base):
+ if config.exists(ospf_base + ['passive-interface']):
+ default = False
+ for interface in config.return_values(ospf_base + ['passive-interface']):
+ if interface == 'default':
+ default = True
+ continue
+ config.set(ospf_base + ['interface', interface, 'passive'])
+
+ config.delete(ospf_base + ['passive-interface'])
+ config.set(ospf_base + ['passive-interface'], value='default')
+
+ if config.exists(ospf_base + ['passive-interface-exclude']):
+ for interface in config.return_values(ospf_base + ['passive-interface-exclude']):
+ config.set(ospf_base + ['interface', interface, 'passive', 'disable'])
+ config.delete(ospf_base + ['passive-interface-exclude'])
+
+if (len(argv) < 1):
+ print("Must specify file name!")
+ exit(1)
+
+file_name = argv[1]
+
+with open(file_name, 'r') as f:
+ config_file = f.read()
+
+config = ConfigTree(config_file)
+
+ospfv3_base = ['protocols', 'ospfv3']
+if config.exists(ospfv3_base):
+ area_base = ospfv3_base + ['area']
+ if config.exists(area_base):
+ for area in config.list_nodes(area_base):
+ if not config.exists(area_base + [area, 'interface']):
+ continue
+
+ for interface in config.return_values(area_base + [area, 'interface']):
+ config.set(ospfv3_base + ['interface', interface, 'area'], value=area)
+ config.set_tag(ospfv3_base + ['interface'])
+
+ config.delete(area_base + [area, 'interface'])
+
+# Migrate OSPF syntax in default VRF
+ospf_base = ['protocols', 'ospf']
+ospf_passive_migration(config, ospf_base)
+
+vrf_base = ['vrf', 'name']
+if config.exists(vrf_base):
+ for vrf in config.list_nodes(vrf_base):
+ vrf_ospf_base = vrf_base + [vrf, 'protocols', 'ospf']
+ if config.exists(vrf_ospf_base):
+ ospf_passive_migration(config, vrf_ospf_base)
+
+try:
+ with open(file_name, 'w') as f:
+ f.write(config.to_string())
+except OSError as e:
+ print(f'Failed to save the modified config: {e}')
+ exit(1)
diff --git a/src/op_mode/force_part_resize.sh b/src/op_mode/force_part_resize.sh
deleted file mode 100755
index eb0f26d8a..000000000
--- a/src/op_mode/force_part_resize.sh
+++ /dev/null
@@ -1,72 +0,0 @@
-#!/usr/bin/env bash
-#
-# Copyright (C) 2021 VyOS maintainers and contributors
-#
-# This program is free software; you can redistribute it and/or modify
-# it under the terms of the GNU General Public License version 2 as
-# published by the Free Software Foundation.
-#
-# This program 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 General Public License for more details.
-#
-# You should have received a copy of the GNU General Public License
-# along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-#
-# Function to get the vyos version from the commandline.
-#
-get_version () {
-for item in `cat /proc/cmdline`; do
- if [ "vyos-union" == "${item%=*}" ]; then
- echo ${item#*=}
- fi
-done
-}
-
-#
-# VERSION is the output of the get_version output.
-# DEVICEPART is the device partition where VyOS is mounted on.
-# DEVICEPATH is the path to the device where VyOS is mounted on.
-# DEVICE is the device of the device partition.
-# PARTNR is the device partition number used for parted.
-#
-VERSION=$(get_version)
-DEVICEPART=$(mount | grep $VERSION/grub | cut -d' ' -f1 | rev | cut -d'/' -f1 | rev)
-DEVICEPATH=$(mount | grep $VERSION/grub | cut -d' ' -f1 | rev | cut -d'/' -f2- | rev)
-DEVICE=$(lsblk -no pkname $DEVICEPATH/$DEVICEPART)
-PARTNR=$(grep -c $DEVICEPART /proc/partitions)
-
-#
-# Check if the device really exits.
-#
-fdisk -l $DEVICEPATH/$DEVICE >> /dev/null 2>&1 || (echo "could not find device $DEVICE" && exit 1)
-
-#
-# START is the partition starting sector.
-# CURSIZE is the partition start sector + the partition end sector.
-# MAXSIZE is the device end sector.
-#
-START=$(cat /sys/block/$DEVICE/$DEVICEPART/start)
-CURSIZE=$(($START+$(cat /sys/block/$DEVICE/$DEVICEPART/size)))
-MAXSIZE=$(($(cat /sys/block/$DEVICE/size)-8))
-
-#
-# Check if the device size is larger then the partition size
-# and if that is the case, resize the partition and grow the filesystem.
-#
-if [ $MAXSIZE -gt $CURSIZE ]; then
-parted "${DEVICEPATH}/${DEVICE}" ---pretend-input-tty > /dev/null 2>&1 <<EOF
-unit
-s
-resizepart
-${PARTNR}
-Yes
-"$MAXSIZE"
-quit
-EOF
- partprobe > /dev/null 2>&1
- resize2fs ${DEVICEPATH}/$DEVICEPART > /dev/null 2>&1
-fi
-
diff --git a/src/op_mode/force_root-partition-auto-resize.sh b/src/op_mode/force_root-partition-auto-resize.sh
new file mode 100755
index 000000000..b39e87560
--- /dev/null
+++ b/src/op_mode/force_root-partition-auto-resize.sh
@@ -0,0 +1,60 @@
+#!/usr/bin/env bash
+#
+# Copyright (C) 2021 VyOS maintainers and contributors
+#
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License version 2 as
+# published by the Free Software Foundation.
+#
+# This program 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 General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+# ROOT_PART_DEV – root partition device path
+# ROOT_PART_NAME – root partition device name
+# ROOT_DEV_NAME – disk device name
+# ROOT_DEV – disk device path
+# ROOT_PART_NUM – number of root partition on disk
+# ROOT_DEV_SIZE – disk total size in 512 bytes sectors
+# ROOT_PART_SIZE – root partition total size in 512 bytes sectors
+# ROOT_PART_START – number of 512 bytes sector where root partition starts
+# AVAILABLE_EXTENSION_SIZE – calculation available disk space after root partition in 512 bytes sectors
+ROOT_PART_DEV=$(findmnt /usr/lib/live/mount/persistence -o source -n)
+ROOT_PART_NAME=$(echo "$ROOT_PART_DEV" | cut -d "/" -f 3)
+ROOT_DEV_NAME=$(echo /sys/block/*/"${ROOT_PART_NAME}" | cut -d "/" -f 4)
+ROOT_DEV="/dev/${ROOT_DEV_NAME}"
+ROOT_PART_NUM=$(cat "/sys/block/${ROOT_DEV_NAME}/${ROOT_PART_NAME}/partition")
+ROOT_DEV_SIZE=$(cat "/sys/block/${ROOT_DEV_NAME}/size")
+ROOT_PART_SIZE=$(cat "/sys/block/${ROOT_DEV_NAME}/${ROOT_PART_NAME}/size")
+ROOT_PART_START=$(cat "/sys/block/${ROOT_DEV_NAME}/${ROOT_PART_NAME}/start")
+AVAILABLE_EXTENSION_SIZE=$((ROOT_DEV_SIZE - ROOT_PART_START - ROOT_PART_SIZE - 8))
+
+#
+# Check if device have space for root partition growing up.
+#
+if [ $AVAILABLE_EXTENSION_SIZE -lt 1 ]; then
+ echo "There is no available space for root partition extension"
+ exit 0;
+fi
+
+#
+# Resize the partition and grow the filesystem.
+#
+# "print" and "Fix" directives were added to fix GPT table if it corrupted after virtual drive extension.
+# If GPT table is corrupted we'll get Fix/Ignore dialogue after "print" command.
+# "Fix" will be the answer for this dialogue.
+# If GPT table is fine and no auto-fix dialogue appeared the directive "Fix" simply will print parted utility help info.
+parted -m ${ROOT_DEV} ---pretend-input-tty > /dev/null 2>&1 <<EOF
+print
+Fix
+resizepart
+${ROOT_PART_NUM}
+Yes
+100%
+EOF
+partprobe > /dev/null 2>&1
+resize2fs ${ROOT_PART_DEV} > /dev/null 2>&1
diff --git a/src/op_mode/lldp_op.py b/src/op_mode/lldp_op.py
index 731e71891..b9ebc991a 100755
--- a/src/op_mode/lldp_op.py
+++ b/src/op_mode/lldp_op.py
@@ -55,6 +55,9 @@ def parse_data(data, interface):
if interface is not None and local_if != interface:
continue
for chassis, c_value in values.get('chassis', {}).items():
+ # bail out early if no capabilities found
+ if 'capability' not in c_value:
+ continue
capabilities = c_value['capability']
if isinstance(capabilities, dict):
capabilities = [capabilities]
diff --git a/src/services/api/graphql/README.graphql b/src/services/api/graphql/README.graphql
index c91b70782..29f58f709 100644
--- a/src/services/api/graphql/README.graphql
+++ b/src/services/api/graphql/README.graphql
@@ -10,7 +10,7 @@ to run with that address as default router by requesting these 'mutations'
in the GraphQL playground:
mutation {
- createInterfaceEthernet (data: {interface: "eth1",
+ CreateInterfaceEthernet (data: {interface: "eth1",
address: "192.168.0.1/24",
description: "BOB"}) {
success
@@ -22,7 +22,7 @@ mutation {
}
mutation {
- createDhcpServer(data: {sharedNetworkName: "BOB",
+ CreateDhcpServer(data: {sharedNetworkName: "BOB",
subnet: "192.168.0.0/24",
defaultRouter: "192.168.0.1",
nameServer: "192.168.0.1",
@@ -42,8 +42,10 @@ mutation {
}
}
+To save the configuration, use the following mutation:
+
mutation {
- saveConfigFile(data: {fileName: "/config/config.boot"}) {
+ SaveConfigFile(data: {fileName: "/config/config.boot"}) {
success
errors
data {
@@ -52,11 +54,17 @@ mutation {
}
}
-N.B. fileName can be empty (fileName: "") or data can be empty (data: {}) to save to
-/config/config.boot; to save to an alternative path, specify fileName.
+N.B. fileName can be empty (fileName: "") or data can be empty (data: {}) to
+save to /config/config.boot; to save to an alternative path, specify
+fileName.
+
+Similarly, using the same 'endpoint' (meaning the form of the request and
+resolver; the actual enpoint for all GraphQL requests is
+https://hostname/graphql), one can load an arbitrary config file from a
+path.
mutation {
- loadConfigFile(data: {fileName: "/home/vyos/config.boot"}) {
+ LoadConfigFile(data: {fileName: "/home/vyos/config.boot"}) {
success
errors
data {
@@ -81,22 +89,23 @@ What's here:
services
├── api
│   └── graphql
+│   ├── bindings.py
│   ├── graphql
│   │   ├── directives.py
│   │   ├── __init__.py
│   │   ├── mutations.py
│   │   └── schema
+│   │   ├── config_file.graphql
│   │   ├── dhcp_server.graphql
│   │   ├── interface_ethernet.graphql
│   │   └── schema.graphql
+│   ├── README.graphql
│   ├── recipes
-│   │   ├── dhcp_server.py
│   │   ├── __init__.py
-│   │   ├── interface_ethernet.py
-│   │   ├── recipe.py
+│   │   ├── session.py
│   │   └── templates
-│   │   ├── dhcp_server.tmpl
-│   │   └── interface_ethernet.tmpl
+│   │   ├── create_dhcp_server.tmpl
+│   │   └── create_interface_ethernet.tmpl
│   └── state.py
├── vyos-configd
├── vyos-hostsd
@@ -114,13 +123,14 @@ the Ur-data; the GraphQL schema is produced from those files, located in
Resolvers for the schema Mutation fields are dynamically generated using a
'directive' added to the respective schema field. The directive,
-'@generate', is handled by the class 'DataDirective' in
-'api/graphql/graphql/directives.py', which calls the 'make_resolver' function in
-'api/graphql/graphql/mutations.py'; the produced resolver calls the appropriate
-wrapper in 'api/graphql/recipes', with base class doing the (overridable)
-configuration steps of calling all defined 'set'/'delete' commands.
-
-Integrating the above with vyos-http-api-server is ~10 lines of code.
+'@configure', is handled by the class 'ConfigureDirective' in
+'api/graphql/graphql/directives.py', which calls the
+'make_configure_resolver' function in 'api/graphql/graphql/mutations.py';
+the produced resolver calls the appropriate wrapper in
+'api/graphql/recipes', with base class doing the (overridable) configuration
+steps of calling all defined 'set'/'delete' commands.
+
+Integrating the above with vyos-http-api-server is 4 lines of code.
What needs to be done:
diff --git a/src/services/api/graphql/bindings.py b/src/services/api/graphql/bindings.py
index c123f68d8..1fbe13d0c 100644
--- a/src/services/api/graphql/bindings.py
+++ b/src/services/api/graphql/bindings.py
@@ -1,7 +1,6 @@
import vyos.defaults
from . graphql.mutations import mutation
-from . graphql.directives import DataDirective, ConfigFileDirective
-
+from . graphql.directives import directives_dict
from ariadne import make_executable_schema, load_schema_from_path, snake_case_fallback_resolvers
def generate_schema():
@@ -9,6 +8,6 @@ def generate_schema():
type_defs = load_schema_from_path(api_schema_dir)
- schema = make_executable_schema(type_defs, mutation, snake_case_fallback_resolvers, directives={"generate": DataDirective, "configfile": ConfigFileDirective})
+ schema = make_executable_schema(type_defs, mutation, snake_case_fallback_resolvers, directives=directives_dict)
return schema
diff --git a/src/services/api/graphql/graphql/directives.py b/src/services/api/graphql/graphql/directives.py
index 85d514de4..f5cd88acd 100644
--- a/src/services/api/graphql/graphql/directives.py
+++ b/src/services/api/graphql/graphql/directives.py
@@ -1,12 +1,11 @@
from ariadne import SchemaDirectiveVisitor, ObjectType
-from . mutations import make_resolver, make_config_file_resolver
+from . mutations import make_configure_resolver, make_config_file_resolver
-class DataDirective(SchemaDirectiveVisitor):
- """
- Class providing implementation of 'generate' directive in schema.
+def non(arg):
+ pass
- """
- def visit_field_definition(self, field, object_type):
+class VyosDirective(SchemaDirectiveVisitor):
+ def visit_field_definition(self, field, object_type, make_resolver=non):
name = f'{field.type}'
# field.type contains the return value of the mutation; trim value
# to produce canonical name
@@ -16,17 +15,23 @@ class DataDirective(SchemaDirectiveVisitor):
field.resolve = func
return field
-class ConfigFileDirective(SchemaDirectiveVisitor):
+
+class ConfigureDirective(VyosDirective):
+ """
+ Class providing implementation of 'configure' directive in schema.
+
+ """
+ def visit_field_definition(self, field, object_type):
+ super().visit_field_definition(field, object_type,
+ make_resolver=make_configure_resolver)
+
+class ConfigFileDirective(VyosDirective):
"""
Class providing implementation of 'configfile' directive in schema.
"""
def visit_field_definition(self, field, object_type):
- name = f'{field.type}'
- # field.type contains the return value of the mutation; trim value
- # to produce canonical name
- name = name.replace('Result', '', 1)
+ super().visit_field_definition(field, object_type,
+ make_resolver=make_config_file_resolver)
- func = make_config_file_resolver(name)
- field.resolve = func
- return field
+directives_dict = {"configure": ConfigureDirective, "configfile": ConfigFileDirective}
diff --git a/src/services/api/graphql/graphql/mutations.py b/src/services/api/graphql/graphql/mutations.py
index 2eb0a0b4a..8a28b13d7 100644
--- a/src/services/api/graphql/graphql/mutations.py
+++ b/src/services/api/graphql/graphql/mutations.py
@@ -6,10 +6,11 @@ from graphql import GraphQLResolveInfo
from makefun import with_signature
from .. import state
+from api.graphql.recipes.session import Session
mutation = ObjectType("Mutation")
-def make_resolver(mutation_name):
+def make_resolver(mutation_name, class_name, session_func):
"""Dynamically generate a resolver for the mutation named in the
schema by 'mutation_name'.
@@ -19,52 +20,9 @@ def make_resolver(mutation_name):
functools.wraps.
:raise Exception:
- encapsulating ConfigErrors, or internal errors
+ raising ConfigErrors, or internal errors
"""
- class_name = mutation_name.replace('create', '', 1).replace('delete', '', 1)
- func_base_name = convert_camel_case_to_snake(class_name)
- resolver_name = f'resolve_create_{func_base_name}'
- func_sig = '(obj: Any, info: GraphQLResolveInfo, data: Dict)'
-
- @mutation.field(mutation_name)
- @convert_kwargs_to_snake_case
- @with_signature(func_sig, func_name=resolver_name)
- async def func_impl(*args, **kwargs):
- try:
- if 'data' not in kwargs:
- return {
- "success": False,
- "errors": ['missing data']
- }
-
- data = kwargs['data']
- session = state.settings['app'].state.vyos_session
-
- mod = import_module(f'api.graphql.recipes.{func_base_name}')
- klass = getattr(mod, class_name)
- k = klass(session, data)
- k.configure()
-
- return {
- "success": True,
- "data": data
- }
- except Exception as error:
- return {
- "success": False,
- "errors": [str(error)]
- }
- return func_impl
-
-def make_config_file_resolver(mutation_name):
- op = ''
- if 'save' in mutation_name:
- op = 'save'
- elif 'load' in mutation_name:
- op = 'load'
-
- class_name = mutation_name.replace('save', '', 1).replace('load', '', 1)
func_base_name = convert_camel_case_to_snake(class_name)
resolver_name = f'resolve_{func_base_name}'
func_sig = '(obj: Any, info: GraphQLResolveInfo, data: Dict)'
@@ -83,18 +41,17 @@ def make_config_file_resolver(mutation_name):
data = kwargs['data']
session = state.settings['app'].state.vyos_session
- mod = import_module(f'api.graphql.recipes.{func_base_name}')
- klass = getattr(mod, class_name)
+ # one may override the session functions with a local subclass
+ try:
+ mod = import_module(f'api.graphql.recipes.{func_base_name}')
+ klass = getattr(mod, class_name)
+ except ImportError:
+ # otherwise, dynamically generate subclass to invoke subclass
+ # name based templates
+ klass = type(class_name, (Session,), {})
k = klass(session, data)
- if op == 'save':
- k.save()
- elif op == 'load':
- k.load()
- else:
- return {
- "success": False,
- "errors": ["Input must be saveConfigFile | loadConfigFile"]
- }
+ method = getattr(k, session_func)
+ method()
return {
"success": True,
@@ -107,3 +64,17 @@ def make_config_file_resolver(mutation_name):
}
return func_impl
+
+def make_configure_resolver(mutation_name):
+ class_name = mutation_name
+ return make_resolver(mutation_name, class_name, 'configure')
+
+def make_config_file_resolver(mutation_name):
+ if 'Save' in mutation_name:
+ class_name = mutation_name.replace('Save', '', 1)
+ return make_resolver(mutation_name, class_name, 'save')
+ elif 'Load' in mutation_name:
+ class_name = mutation_name.replace('Load', '', 1)
+ return make_resolver(mutation_name, class_name, 'load')
+ else:
+ raise Exception
diff --git a/src/services/api/graphql/graphql/schema/config_file.graphql b/src/services/api/graphql/graphql/schema/config_file.graphql
index 3096cf743..31ab26b9e 100644
--- a/src/services/api/graphql/graphql/schema/config_file.graphql
+++ b/src/services/api/graphql/graphql/schema/config_file.graphql
@@ -1,27 +1,27 @@
-input saveConfigFileInput {
+input SaveConfigFileInput {
fileName: String
}
-type saveConfigFile {
+type SaveConfigFile {
fileName: String
}
-type saveConfigFileResult {
- data: saveConfigFile
+type SaveConfigFileResult {
+ data: SaveConfigFile
success: Boolean!
errors: [String]
}
-input loadConfigFileInput {
+input LoadConfigFileInput {
fileName: String!
}
-type loadConfigFile {
+type LoadConfigFile {
fileName: String!
}
-type loadConfigFileResult {
- data: loadConfigFile
+type LoadConfigFileResult {
+ data: LoadConfigFile
success: Boolean!
errors: [String]
}
diff --git a/src/services/api/graphql/graphql/schema/dhcp_server.graphql b/src/services/api/graphql/graphql/schema/dhcp_server.graphql
index 9f741a0a5..25f091bfa 100644
--- a/src/services/api/graphql/graphql/schema/dhcp_server.graphql
+++ b/src/services/api/graphql/graphql/schema/dhcp_server.graphql
@@ -1,4 +1,4 @@
-input dhcpServerConfigInput {
+input DhcpServerConfigInput {
sharedNetworkName: String
subnet: String
defaultRouter: String
@@ -13,7 +13,7 @@ input dhcpServerConfigInput {
dnsForwardingListenAddress: String
}
-type dhcpServerConfig {
+type DhcpServerConfig {
sharedNetworkName: String
subnet: String
defaultRouter: String
@@ -28,8 +28,8 @@ type dhcpServerConfig {
dnsForwardingListenAddress: String
}
-type createDhcpServerResult {
- data: dhcpServerConfig
+type CreateDhcpServerResult {
+ data: DhcpServerConfig
success: Boolean!
errors: [String]
}
diff --git a/src/services/api/graphql/graphql/schema/firewall_group.graphql b/src/services/api/graphql/graphql/schema/firewall_group.graphql
new file mode 100644
index 000000000..efe7de632
--- /dev/null
+++ b/src/services/api/graphql/graphql/schema/firewall_group.graphql
@@ -0,0 +1,47 @@
+input CreateFirewallAddressGroupInput {
+ name: String!
+ address: [String]
+}
+
+type CreateFirewallAddressGroup {
+ name: String!
+ address: [String]
+}
+
+type CreateFirewallAddressGroupResult {
+ data: CreateFirewallAddressGroup
+ success: Boolean!
+ errors: [String]
+}
+
+input UpdateFirewallAddressGroupMembersInput {
+ name: String!
+ address: [String!]!
+}
+
+type UpdateFirewallAddressGroupMembers {
+ name: String!
+ address: [String!]!
+}
+
+type UpdateFirewallAddressGroupMembersResult {
+ data: UpdateFirewallAddressGroupMembers
+ success: Boolean!
+ errors: [String]
+}
+
+input RemoveFirewallAddressGroupMembersInput {
+ name: String!
+ address: [String!]!
+}
+
+type RemoveFirewallAddressGroupMembers {
+ name: String!
+ address: [String!]!
+}
+
+type RemoveFirewallAddressGroupMembersResult {
+ data: RemoveFirewallAddressGroupMembers
+ success: Boolean!
+ errors: [String]
+}
diff --git a/src/services/api/graphql/graphql/schema/interface_ethernet.graphql b/src/services/api/graphql/graphql/schema/interface_ethernet.graphql
index fdcf97bad..32438b315 100644
--- a/src/services/api/graphql/graphql/schema/interface_ethernet.graphql
+++ b/src/services/api/graphql/graphql/schema/interface_ethernet.graphql
@@ -1,18 +1,18 @@
-input interfaceEthernetConfigInput {
+input InterfaceEthernetConfigInput {
interface: String
address: String
replace: Boolean = true
description: String
}
-type interfaceEthernetConfig {
+type InterfaceEthernetConfig {
interface: String
address: String
description: String
}
-type createInterfaceEthernetResult {
- data: interfaceEthernetConfig
+type CreateInterfaceEthernetResult {
+ data: InterfaceEthernetConfig
success: Boolean!
errors: [String]
}
diff --git a/src/services/api/graphql/graphql/schema/schema.graphql b/src/services/api/graphql/graphql/schema/schema.graphql
index 70fe0d726..9e97a0d60 100644
--- a/src/services/api/graphql/graphql/schema/schema.graphql
+++ b/src/services/api/graphql/graphql/schema/schema.graphql
@@ -7,12 +7,15 @@ type Query {
_dummy: String
}
-directive @generate on FIELD_DEFINITION
+directive @configure on FIELD_DEFINITION
directive @configfile on FIELD_DEFINITION
type Mutation {
- createDhcpServer(data: dhcpServerConfigInput) : createDhcpServerResult @generate
- createInterfaceEthernet(data: interfaceEthernetConfigInput) : createInterfaceEthernetResult @generate
- saveConfigFile(data: saveConfigFileInput) : saveConfigFileResult @configfile
- loadConfigFile(data: loadConfigFileInput) : loadConfigFileResult @configfile
+ CreateDhcpServer(data: DhcpServerConfigInput) : CreateDhcpServerResult @configure
+ CreateInterfaceEthernet(data: InterfaceEthernetConfigInput) : CreateInterfaceEthernetResult @configure
+ CreateFirewallAddressGroup(data: CreateFirewallAddressGroupInput) : CreateFirewallAddressGroupResult @configure
+ UpdateFirewallAddressGroupMembers(data: UpdateFirewallAddressGroupMembersInput) : UpdateFirewallAddressGroupMembersResult @configure
+ RemoveFirewallAddressGroupMembers(data: RemoveFirewallAddressGroupMembersInput) : RemoveFirewallAddressGroupMembersResult @configure
+ SaveConfigFile(data: SaveConfigFileInput) : SaveConfigFileResult @configfile
+ LoadConfigFile(data: LoadConfigFileInput) : LoadConfigFileResult @configfile
}
diff --git a/src/services/api/graphql/recipes/config_file.py b/src/services/api/graphql/recipes/config_file.py
deleted file mode 100644
index 850e5326e..000000000
--- a/src/services/api/graphql/recipes/config_file.py
+++ /dev/null
@@ -1,16 +0,0 @@
-
-from . recipe import Recipe
-
-class ConfigFile(Recipe):
- def __init__(self, session, command_file):
- super().__init__(session, command_file)
-
- # Define any custom processing of parameters here by overriding
- # save/load:
- #
- # def save(self):
- # self.data = transform_data(self.data)
- # super().save()
- # def load(self):
- # self.data = transform_data(self.data)
- # super().load()
diff --git a/src/services/api/graphql/recipes/dhcp_server.py b/src/services/api/graphql/recipes/dhcp_server.py
deleted file mode 100644
index 3edb3028e..000000000
--- a/src/services/api/graphql/recipes/dhcp_server.py
+++ /dev/null
@@ -1,13 +0,0 @@
-
-from . recipe import Recipe
-
-class DhcpServer(Recipe):
- def __init__(self, session, command_file):
- super().__init__(session, command_file)
-
- # Define any custom processing of parameters here by overriding
- # configure:
- #
- # def configure(self):
- # self.data = transform_data(self.data)
- # super().configure()
diff --git a/src/services/api/graphql/recipes/interface_ethernet.py b/src/services/api/graphql/recipes/interface_ethernet.py
deleted file mode 100644
index f88f5924f..000000000
--- a/src/services/api/graphql/recipes/interface_ethernet.py
+++ /dev/null
@@ -1,13 +0,0 @@
-
-from . recipe import Recipe
-
-class InterfaceEthernet(Recipe):
- def __init__(self, session, command_file):
- super().__init__(session, command_file)
-
- # Define any custom processing of parameters here by overriding
- # configure:
- #
- # def configure(self):
- # self.data = transform_data(self.data)
- # super().configure()
diff --git a/src/services/api/graphql/recipes/remove_firewall_address_group_members.py b/src/services/api/graphql/recipes/remove_firewall_address_group_members.py
new file mode 100644
index 000000000..cde30c27a
--- /dev/null
+++ b/src/services/api/graphql/recipes/remove_firewall_address_group_members.py
@@ -0,0 +1,21 @@
+
+from . session import Session
+
+class RemoveFirewallAddressGroupMembers(Session):
+ def __init__(self, session, data):
+ super().__init__(session, data)
+
+ # Define any custom processing of parameters here by overriding
+ # configure:
+ #
+ # def configure(self):
+ # self._data = transform_data(self._data)
+ # super().configure()
+ # self.clean_up()
+
+ def configure(self):
+ super().configure()
+
+ group_name = self._data['name']
+ path = ['firewall', 'group', 'address-group', group_name]
+ self.delete_path_if_childless(path)
diff --git a/src/services/api/graphql/recipes/recipe.py b/src/services/api/graphql/recipes/session.py
index 91d8bd67a..b96cc1753 100644
--- a/src/services/api/graphql/recipes/recipe.py
+++ b/src/services/api/graphql/recipes/session.py
@@ -1,27 +1,17 @@
from ariadne import convert_camel_case_to_snake
import vyos.defaults
+from vyos.config import Config
from vyos.template import render
-class Recipe(object):
+class Session(object):
def __init__(self, session, data):
self._session = session
- self.data = data
+ self._data = data
self._name = convert_camel_case_to_snake(type(self).__name__)
- @property
- def data(self):
- return self.__data
-
- @data.setter
- def data(self, data):
- if isinstance(data, dict):
- self.__data = data
- else:
- raise ValueError("data must be of type dict")
-
def configure(self):
session = self._session
- data = self.data
+ data = self._data
func_base_name = self._name
tmpl_file = f'{func_base_name}.tmpl'
@@ -46,9 +36,16 @@ class Recipe(object):
except Exception as error:
raise error
+ def delete_path_if_childless(self, path):
+ session = self._session
+ config = Config(session.get_session_env())
+ if not config.list_nodes(path):
+ session.delete(path)
+ session.commit()
+
def save(self):
session = self._session
- data = self.data
+ data = self._data
if 'file_name' not in data or not data['file_name']:
data['file_name'] = '/config/config.boot'
@@ -59,7 +56,7 @@ class Recipe(object):
def load(self):
session = self._session
- data = self.data
+ data = self._data
try:
session.load_config(data['file_name'])
diff --git a/src/services/api/graphql/recipes/templates/dhcp_server.tmpl b/src/services/api/graphql/recipes/templates/create_dhcp_server.tmpl
index 70de43183..70de43183 100644
--- a/src/services/api/graphql/recipes/templates/dhcp_server.tmpl
+++ b/src/services/api/graphql/recipes/templates/create_dhcp_server.tmpl
diff --git a/src/services/api/graphql/recipes/templates/create_firewall_address_group.tmpl b/src/services/api/graphql/recipes/templates/create_firewall_address_group.tmpl
new file mode 100644
index 000000000..a890d0086
--- /dev/null
+++ b/src/services/api/graphql/recipes/templates/create_firewall_address_group.tmpl
@@ -0,0 +1,4 @@
+set firewall group address-group {{ name }}
+{% for add in address %}
+set firewall group address-group {{ name }} address {{ add }}
+{% endfor %}
diff --git a/src/services/api/graphql/recipes/templates/interface_ethernet.tmpl b/src/services/api/graphql/recipes/templates/create_interface_ethernet.tmpl
index d9d7ed691..d9d7ed691 100644
--- a/src/services/api/graphql/recipes/templates/interface_ethernet.tmpl
+++ b/src/services/api/graphql/recipes/templates/create_interface_ethernet.tmpl
diff --git a/src/services/api/graphql/recipes/templates/remove_firewall_address_group_members.tmpl b/src/services/api/graphql/recipes/templates/remove_firewall_address_group_members.tmpl
new file mode 100644
index 000000000..458f3e5fc
--- /dev/null
+++ b/src/services/api/graphql/recipes/templates/remove_firewall_address_group_members.tmpl
@@ -0,0 +1,3 @@
+{% for add in address %}
+delete firewall group address-group {{ name }} address {{ add }}
+{% endfor %}
diff --git a/src/services/api/graphql/recipes/templates/update_firewall_address_group_members.tmpl b/src/services/api/graphql/recipes/templates/update_firewall_address_group_members.tmpl
new file mode 100644
index 000000000..f56c61231
--- /dev/null
+++ b/src/services/api/graphql/recipes/templates/update_firewall_address_group_members.tmpl
@@ -0,0 +1,3 @@
+{% for add in address %}
+set firewall group address-group {{ name }} address {{ add }}
+{% endfor %}
diff --git a/src/systemd/root-partition-auto-resize.service b/src/systemd/root-partition-auto-resize.service
new file mode 100644
index 000000000..a57fbc3d8
--- /dev/null
+++ b/src/systemd/root-partition-auto-resize.service
@@ -0,0 +1,12 @@
+[Unit]
+Description=VyOS root partition auto resizing
+After=multi-user.target
+
+[Service]
+Type=oneshot
+User=root
+Group=root
+ExecStart=/usr/libexec/vyos/op_mode/force_root-partition-auto-resize.sh
+
+[Install]
+WantedBy=vyos.target \ No newline at end of file