Page MenuHomeVyOS Platform

No OneTemporary

Size
113 KB
Referenced Files
None
Subscribers
None
diff --git a/op-mode-definitions/openvpn.xml b/op-mode-definitions/openvpn.xml
index d7c4fc101..53c0157c6 100644
--- a/op-mode-definitions/openvpn.xml
+++ b/op-mode-definitions/openvpn.xml
@@ -1,140 +1,140 @@
<?xml version="1.0"?>
<interfaceDefinition>
<node name="generate">
<children>
<node name="openvpn">
<properties>
<help>OpenVPN key generation tool</help>
</properties>
<children>
<tagNode name="key">
<properties>
<help>Generate shared-secret key with specified file name</help>
<completionHelp>
<list>&lt;filename&gt;</list>
</completionHelp>
</properties>
<command>
result=1;
key_path=$4
full_path=
# Prepend /config/auth if the path is not absolute
if echo $key_path | egrep -ve '^/.*' &gt; /dev/null; then
full_path=/config/auth/$key_path
else
full_path=$key_path
fi
key_dir=`dirname $full_path`
if [ ! -d $key_dir ]; then
echo "Directory $key_dir does not exist!"
exit 1
fi
echo "Generating OpenVPN key to $full_path"
sudo /usr/sbin/openvpn --genkey --secret "$full_path"
result=$?
if [ $result = 0 ]; then
echo "Your new local OpenVPN key has been generated"
fi
/usr/libexec/vyos/validators/file-exists --directory /config/auth "$full_path"
</command>
</tagNode>
</children>
</node>
</children>
</node>
<node name="reset">
<properties>
<help>Reset a service</help>
</properties>
<children>
<node name="openvpn">
<children>
<tagNode name="client">
<properties>
<help>Reset specified OpenVPN client</help>
<completionHelp>
<script>sudo ${vyos_completion_dir}/list_openvpn_clients.py --all</script>
</completionHelp>
</properties>
<command>echo kill $4 | socat - UNIX-CONNECT:/tmp/openvpn-mgmt-intf &gt; /dev/null</command>
</tagNode>
<tagNode name="interface">
<properties>
<help>Reset OpenVPN process on interface</help>
<completionHelp>
<script>sudo ${vyos_completion_dir}/list_interfaces.py --type openvpn</script>
</completionHelp>
</properties>
<command>sudo ${vyos_op_scripts_dir}/reset_openvpn.py $4</command>
</tagNode>
</children>
</node>
</children>
</node>
<node name="show">
<children>
<node name="interfaces">
<children>
<node name="openvpn">
<properties>
<help>Show OpenVPN interface information</help>
</properties>
<children>
<leafNode name="detail">
<properties>
<help>Show detailed OpenVPN interface information</help>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf-type=openvpn --action=show</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf-type=openvpn --action=show</command>
</leafNode>
</children>
</node>
<tagNode name="openvpn">
<properties>
<help>Show OpenVPN interface information</help>
<completionHelp>
<script>sudo ${vyos_completion_dir}/list_interfaces.py --type openvpn</script>
</completionHelp>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf=$4</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf=$4</command>
<children>
<leafNode name="brief">
<properties>
<help>Show summary of specified OpenVPN interface information</help>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf="$4" --action=show-brief</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf="$4" --action=show-brief</command>
</leafNode>
</children>
</tagNode>
</children>
</node>
<node name="openvpn">
<properties>
<help>Show OpenVPN information</help>
</properties>
<children>
<leafNode name="client">
<properties>
<help>Show tunnel status for OpenVPN client interfaces</help>
</properties>
<command>sudo ${vyos_op_scripts_dir}/show_openvpn.py --mode=client</command>
</leafNode>
<leafNode name="server">
<properties>
<help>Show tunnel status for OpenVPN server interfaces</help>
</properties>
<command>sudo ${vyos_op_scripts_dir}/show_openvpn.py --mode=server</command>
</leafNode>
<leafNode name="site-to-site">
<properties>
<help>Show tunnel status for OpenVPN site-to-site interfaces</help>
</properties>
<command>sudo ${vyos_op_scripts_dir}/show_openvpn.py --mode=site-to-site</command>
</leafNode>
</children>
</node>
</children>
</node>
</interfaceDefinition>
diff --git a/op-mode-definitions/show-interfaces-pppoe.xml b/op-mode-definitions/show-interfaces-pppoe.xml
index 591ec8f5b..e68d05da9 100644
--- a/op-mode-definitions/show-interfaces-pppoe.xml
+++ b/op-mode-definitions/show-interfaces-pppoe.xml
@@ -1,45 +1,45 @@
<?xml version="1.0"?>
<interfaceDefinition>
<node name="show">
<children>
<node name="interfaces">
<children>
<tagNode name="pppoe">
<properties>
<help>Show PPPoE interface information</help>
<completionHelp>
<script>${vyos_completion_dir}/list_pppoe_peers.sh</script>
</completionHelp>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl pppoe --intf="$4"</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py pppoe --intf="$4"</command>
<children>
<node name="log">
<properties>
<help>Show PPPoE logs</help>
</properties>
<command>cat /var/log/vyatta/ppp_$4.log</command>
<children>
<leafNode name="tail">
<properties>
<help>Watch PPPoE logs</help>
</properties>
<command>tail --follow=name /var/log/vyatta/ppp_$4.log</command>
</leafNode>
</children>
</node>
<leafNode name="statistics">
<properties>
<help>Show specified wirelessmodem interface statistics</help>
<completionHelp>
<script>${vyos_completion_dir}/list_pppoe_peers.sh</script>
</completionHelp>
</properties>
<command>/usr/sbin/pppstats $4</command>
</leafNode>
</children>
</tagNode>
</children>
</node>
</children>
</node>
</interfaceDefinition>
diff --git a/op-mode-definitions/show-interfaces-wirelessmodem.xml b/op-mode-definitions/show-interfaces-wirelessmodem.xml
index 681f54f3d..c17efbc4e 100644
--- a/op-mode-definitions/show-interfaces-wirelessmodem.xml
+++ b/op-mode-definitions/show-interfaces-wirelessmodem.xml
@@ -1,45 +1,45 @@
<?xml version="1.0"?>
<interfaceDefinition>
<node name="show">
<children>
<node name="interfaces">
<children>
<tagNode name="wirelessmodem">
<properties>
<help>Show Wireless Modem (WWAN) interface information</help>
<completionHelp>
<script>${vyos_completion_dir}/list_wlm_peers.sh</script>
</completionHelp>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf="$4"</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf="$4"</command>
<children>
<node name="log">
<properties>
<help>Show PPPoE logs</help>
</properties>
<command>cat /var/log/vyatta/ppp_$4.log</command>
<children>
<leafNode name="tail">
<properties>
<help>Watch PPPoE logs</help>
</properties>
<command>tail --follow=name /var/log/vyatta/ppp_$4.log</command>
</leafNode>
</children>
</node>
<leafNode name="statistics">
<properties>
<help>Show specified wirelessmodem interface statistics</help>
<completionHelp>
<script>${vyos_completion_dir}/list_wlm_peers.sh</script>
</completionHelp>
</properties>
<command>/usr/sbin/pppstats $4</command>
</leafNode>
</children>
</tagNode>
</children>
</node>
</children>
</node>
</interfaceDefinition>
diff --git a/op-mode-definitions/wireless.xml b/op-mode-definitions/wireless.xml
index c3c6dee59..a3a9d1f55 100644
--- a/op-mode-definitions/wireless.xml
+++ b/op-mode-definitions/wireless.xml
@@ -1,119 +1,119 @@
<?xml version="1.0"?>
<interfaceDefinition>
<node name="clear">
<children>
<node name="interfaces">
<children>
<node name="wireless">
<properties>
<help>Clear wireless interface information</help>
</properties>
<children>
<leafNode name="counters">
<properties>
<help>Clear all wireless interface counters</help>
</properties>
- <command>sudo ${vyatta_bindir}/sudo-users/vyatta-show-interfaces.pl --action=clear --intf-type="$3"</command>
+ <command>sudo ${vyos_op_scripts_dir}/show_interfaces.py --action=clear --intf-type="$3"</command>
</leafNode>
</children>
</node>
<tagNode name="wireless">
<properties>
<help>Clear interface information for a given wireless interface</help>
<completionHelp>
<script>${vyos_completion_dir}/list_interfaces.py --type wireless</script>
</completionHelp>
</properties>
<children>
<leafNode name="counters">
<properties>
<help>Clear all wireless interface counters</help>
</properties>
- <command>sudo ${vyatta_bindir}/sudo-users/vyatta-show-interfaces.pl --action=clear --intf="$4"</command>
+ <command>sudo ${vyos_op_scripts_dir}/show_interfaces.py --action=clear --intf="$4"</command>
</leafNode>
</children>
</tagNode>
</children>
</node>
</children>
</node>
<node name="show">
<children>
<node name="interfaces">
<children>
<node name="wireless">
<properties>
<help>Show wireless interface information</help>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf-type=wireless --action=show-brief</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf-type=wireless --action=show-brief</command>
<children>
<leafNode name="detail">
<properties>
<help>Show detailed wireless interface information</help>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf-type=wireless --action=show</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf-type=wireless --action=show</command>
</leafNode>
<leafNode name="info">
<properties>
<help>Show wireless interface configuration</help>
</properties>
<command>${vyos_op_scripts_dir}/show_wireless.py --brief</command>
</leafNode>
</children>
</node>
<tagNode name="wireless">
<properties>
<help>Show specified wireless interface information</help>
<completionHelp>
<script>${vyos_completion_dir}/list_interfaces.py --type wireless</script>
</completionHelp>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf="$4"</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf="$4"</command>
<children>
<leafNode name="brief">
<properties>
<help>Show summary of the specified wireless interface information</help>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf="$4" --action=show-brief</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf="$4" --action=show-brief</command>
</leafNode>
<node name="scan">
<properties>
<help>Show summary of the specified wireless interface information</help>
</properties>
<command>sudo ${vyos_op_scripts_dir}/show_wireless.py --scan "$4"</command>
<children>
<leafNode name="detail">
<properties>
<help>Show detailed scan results</help>
</properties>
<command>sudo /sbin/iw dev "$4" scan ap-force</command>
</leafNode>
</children>
</node>
<leafNode name="stations">
<properties>
<help>Show specified wireless interface information</help>
</properties>
<command>${vyos_op_scripts_dir}/show_wireless.py --stations "$4"</command>
</leafNode>
<tagNode name="vif">
<properties>
<help>Show specified virtual network interface (vif) information</help>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf="$4.$6"</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf="$4.$6"</command>
<children>
<leafNode name="brief">
<properties>
<help>Show summary of specified virtual network interface (vif) information</help>
</properties>
- <command>${vyatta_bindir}/vyatta-show-interfaces.pl --intf="$4.$6" --action=show-brief</command>
+ <command>${vyos_op_scripts_dir}/show_interfaces.py --intf="$4.$6" --action=show-brief</command>
</leafNode>
</children>
</tagNode>
</children>
</tagNode>
</children>
</node>
</children>
</node>
</interfaceDefinition>
diff --git a/python/vyos/ifconfig/__init__.py b/python/vyos/ifconfig/__init__.py
index cd1696ca1..4d98901b7 100644
--- a/python/vyos/ifconfig/__init__.py
+++ b/python/vyos/ifconfig/__init__.py
@@ -1,40 +1,44 @@
# Copyright 2019 VyOS maintainers and contributors <maintainers@vyos.io>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
from vyos.ifconfig.section import Section
+from vyos.ifconfig.control import Control
from vyos.ifconfig.interface import Interface
+from vyos.ifconfig.operational import Operational
+from vyos.ifconfig.dhcp import DHCP
+from vyos.ifconfig.vrrp import VRRP
from vyos.ifconfig.bond import BondIf
from vyos.ifconfig.bridge import BridgeIf
from vyos.ifconfig.dummy import DummyIf
from vyos.ifconfig.ethernet import EthernetIf
from vyos.ifconfig.geneve import GeneveIf
from vyos.ifconfig.loopback import LoopbackIf
from vyos.ifconfig.macvlan import MACVLANIf
from vyos.ifconfig.vxlan import VXLANIf
from vyos.ifconfig.wireguard import WireGuardIf
from vyos.ifconfig.vtun import VTunIf
from vyos.ifconfig.pppoe import PPPoEIf
from vyos.ifconfig.tunnel import GREIf
from vyos.ifconfig.tunnel import GRETapIf
from vyos.ifconfig.tunnel import IP6GREIf
from vyos.ifconfig.tunnel import IPIPIf
from vyos.ifconfig.tunnel import IPIP6If
from vyos.ifconfig.tunnel import IP6IP6If
from vyos.ifconfig.tunnel import SitIf
from vyos.ifconfig.tunnel import Sit6RDIf
from vyos.ifconfig.wireless import WiFiIf
from vyos.ifconfig.l2tpv3 import L2TPv3If
diff --git a/python/vyos/ifconfig/interface.py b/python/vyos/ifconfig/interface.py
index 43f823eca..32ce1a80c 100644
--- a/python/vyos/ifconfig/interface.py
+++ b/python/vyos/ifconfig/interface.py
@@ -1,742 +1,714 @@
# Copyright 2019 VyOS maintainers and contributors <maintainers@vyos.io>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
import os
-import re
import json
-import glob
-import time
-from time import sleep
-from os.path import isfile
from copy import deepcopy
-from datetime import timedelta
-from hurry.filesize import size, alternative
-from ipaddress import IPv4Network, IPv6Address, IPv6Network
-from netifaces import ifaddresses, AF_INET, AF_INET6
-from tabulate import tabulate
+from ipaddress import IPv4Network
+from ipaddress import IPv6Address
+from ipaddress import IPv6Network
+from netifaces import ifaddresses
+# this is not the same as socket.AF_INET/INET6
+from netifaces import AF_INET
+from netifaces import AF_INET6
-from vyos.util import mac2eui64
from vyos import ConfigError
-from vyos.ifconfig.dhcp import DHCP
+from vyos.util import mac2eui64
from vyos.validate import is_ipv4
from vyos.validate import is_ipv6
from vyos.validate import is_intf_addr_assigned
from vyos.validate import assert_boolean
from vyos.validate import assert_list
from vyos.validate import assert_mac
from vyos.validate import assert_mtu
from vyos.validate import assert_positive
from vyos.validate import assert_range
from vyos.ifconfig.control import Control
+from vyos.ifconfig.dhcp import DHCP
+from vyos.ifconfig.vrrp import VRRP
+from vyos.ifconfig.operational import Operational
class Interface(Control):
+ # This is the class which will be used to create
+ # self.operational, it allows subclasses, such as
+ # WireGuard to modify their display behaviour
+ OperationalClass = Operational
+
options = []
required = []
default = {
'type': '',
'debug': True,
'create': True,
}
definition = {
'section': '',
'prefixes': [],
'vlan': False,
'bondable': False,
'broadcast': False,
'bridgeable': False,
}
_command_get = {
'admin_state': {
'shellcmd': 'ip -json link show dev {ifname}',
'format': lambda j: 'up' if 'UP' in json.loads(j)[0]['flags'] else 'down',
}
}
_command_set = {
'admin_state': {
'validate': lambda v: assert_list(v, ['up', 'down']),
'shellcmd': 'ip link set dev {ifname} {value}',
},
'mac': {
'validate': assert_mac,
'shellcmd': 'ip link set dev {ifname} address {value}',
},
'vrf': {
'convert': lambda v: f'master {v}' if v else 'nomaster',
'shellcmd': 'ip link set dev {ifname} {value}',
},
}
_sysfs_get = {
'alias': {
'location': '/sys/class/net/{ifname}/ifalias',
},
'mac': {
'location': '/sys/class/net/{ifname}/address',
},
'mtu': {
'location': '/sys/class/net/{ifname}/mtu',
},
'oper_state':{
'location': '/sys/class/net/{ifname}/operstate',
},
}
_sysfs_set = {
'alias': {
'convert': lambda name: name if name else '\0',
'location': '/sys/class/net/{ifname}/ifalias',
},
'mtu': {
'validate': assert_mtu,
'location': '/sys/class/net/{ifname}/mtu',
},
'arp_cache_tmo': {
'convert': lambda tmo: (int(tmo) * 1000),
'location': '/proc/sys/net/ipv4/neigh/{ifname}/base_reachable_time_ms',
},
'arp_filter': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_filter',
},
'arp_accept': {
'validate': lambda arp: assert_range(arp,0,2),
'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_accept',
},
'arp_announce': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_announce',
},
'arp_ignore': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/arp_ignore',
},
'ipv6_autoconf': {
'validate': lambda fwd: assert_range(fwd,0,2),
'location': '/proc/sys/net/ipv6/conf/{ifname}/autoconf',
},
'ipv6_forwarding': {
'validate': lambda fwd: assert_range(fwd,0,2),
'location': '/proc/sys/net/ipv6/conf/{ifname}/forwarding',
},
'ipv6_dad_transmits': {
'validate': assert_positive,
'location': '/proc/sys/net/ipv6/conf/{ifname}/dad_transmits',
},
'proxy_arp': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/proxy_arp',
},
'proxy_arp_pvlan': {
'validate': assert_boolean,
'location': '/proc/sys/net/ipv4/conf/{ifname}/proxy_arp_pvlan',
},
# link_detect vs link_filter name weirdness
'link_detect': {
'validate': lambda link: assert_range(link,0,3),
'location': '/proc/sys/net/ipv4/conf/{ifname}/link_filter',
},
}
+ @classmethod
+ def exists(cls, ifname):
+ return os.path.exists(f'/sys/class/net/{ifname}')
+
def __init__(self, ifname, **kargs):
"""
This is the base interface class which supports basic IP/MAC address
operations as well as DHCP(v6). Other interface which represent e.g.
and ethernet bridge are implemented as derived classes adding all
additional functionality.
For creation you will need to provide the interface type, otherwise
the existing interface is used
DEBUG:
This class has embedded debugging (print) which can be enabled by
creating the following file:
vyos@vyos# touch /tmp/vyos.ifconfig.debug
Example:
>>> from vyos.ifconfig import Interface
>>> i = Interface('eth0')
"""
self.config = deepcopy(self.default)
for k in self.options:
if k in kargs:
self.config[k] = kargs[k]
# make sure the ifname is the first argument and not from the dict
self.config['ifname'] = ifname
# we must have updated config before initialising the Interface
super().__init__(**kargs)
+ self.ifname = ifname
self.dhcp = DHCP(ifname)
- if not os.path.exists('/sys/class/net/{}'.format(self.config['ifname'])):
+ if not self.exists(ifname):
# Any instance of Interface, such as Interface('eth0')
# can be used safely to access the generic function in this class
# as 'type' is unset, the class can not be created
if not self.config['type']:
- raise Exception('interface "{}" not found'.format(self.config['ifname']))
+ raise Exception(f'interface "{ifname}" not found')
# Should an Instance of a child class (EthernetIf, DummyIf, ..)
# be required, then create should be set to False to not accidentally create it.
# In case a subclass does not define it, we use get to set the default to True
if self.config.get('create',True):
for k in self.required:
if k not in kargs:
name = self.default['type']
raise ConfigError(f'missing required option {k} for {name} {ifname} creation')
self._create()
# If we can not connect to the interface then let the caller know
# as the class could not be correctly initialised
else:
raise Exception('interface "{}" not found'.format(self.config['ifname']))
# list of assigned IP addresses
self._addr = []
+ self.operational = self.OperationalClass(ifname)
+ self.vrrp = VRRP(ifname)
+
def _create(self):
cmd = 'ip link add dev {ifname} type {type}'.format(**self.config)
self._cmd(cmd)
def remove(self):
"""
Remove interface from operating system. Removing the interface
deconfigures all assigned IP addresses and clear possible DHCP(v6)
client processes.
Example:
>>> from vyos.ifconfig import Interface
>>> i = Interface('eth0')
>>> i.remove()
"""
# stop DHCP(v6) if running
self.dhcp.v4.delete()
self.dhcp.v6.delete()
# remove all assigned IP addresses from interface - this is a bit redundant
# as the kernel will remove all addresses on interface deletion, but we
# can not delete ALL interfaces, see below
for addr in self.get_addr():
self.del_addr(addr)
# ---------------------------------------------------------------------
# A code refactoring is required as this type check is present as
# Interface implement behaviour for one of it's sub-class.
# It is required as the current pattern for vlan is:
# Interface('name').remove() to delete an interface
# The code should be modified to have a class method called connect and
# have Interface.connect('name').remove()
# each subclass should register within Interface the pattern for that
# interface ie: (ethX, etc.) and use this to create an instance of
# the right class (EthernetIf, ...)
# Ethernet interfaces can not be removed
# Commented out as nowhere in the code do we call Interface()
# This would also cause an import loop
# if self.__class__ == EthernetIf:
# return
# ---------------------------------------------------------------------
self._delete()
def _delete(self):
# NOTE (Improvement):
# after interface removal no other commands should be allowed
# to be called and instead should raise an Exception:
cmd = 'ip link del dev {}'.format(self.config['ifname'])
return self._cmd(cmd)
def get_mtu(self):
"""
Get/set interface mtu in bytes.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').get_mtu()
'1500'
"""
return self.get_interface('mtu')
def set_mtu(self, mtu):
"""
Get/set interface mtu in bytes.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_mtu(1400)
>>> Interface('eth0').get_mtu()
'1400'
"""
return self.set_interface('mtu', mtu)
def get_mac(self):
"""
Get current interface MAC (Media Access Contrl) address used.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').get_mac()
'00:50:ab:cd:ef:00'
"""
return self.get_interface('mac')
def set_mac(self, mac):
"""
Set interface MAC (Media Access Contrl) address to given value.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_mac('00:50:ab:cd:ef:01')
"""
# If MAC is unchanged, bail out early
if mac == self.get_mac():
return None
# MAC address can only be changed if interface is in 'down' state
prev_state = self.get_admin_state()
if prev_state == 'up':
self.set_admin_state('down')
self.set_interface('mac', mac)
def set_vrf(self, vrf=''):
"""
Add/Remove interface from given VRF instance.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_vrf('foo')
>>> Interface('eth0').set_vrf()
"""
self.set_interface('vrf', vrf)
def set_arp_cache_tmo(self, tmo):
"""
Set ARP cache timeout value in seconds. Internal Kernel representation
is in milliseconds.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_arp_cache_tmo(40)
"""
return self.set_interface('arp_cache_tmo', tmo)
def set_arp_filter(self, arp_filter):
"""
Filter ARP requests
1 - Allows you to have multiple network interfaces on the same
subnet, and have the ARPs for each interface be answered
based on whether or not the kernel would route a packet from
the ARP'd IP out that interface (therefore you must use source
based routing for this to work). In other words it allows control
of which cards (usually 1) will respond to an arp request.
0 - (default) The kernel can respond to arp requests with addresses
from other interfaces. This may seem wrong but it usually makes
sense, because it increases the chance of successful communication.
IP addresses are owned by the complete host on Linux, not by
particular interfaces. Only for more complex setups like load-
balancing, does this behaviour cause problems.
"""
return self.set_interface('arp_filter', arp_filter)
def set_arp_accept(self, arp_accept):
"""
Define behavior for gratuitous ARP frames who's IP is not
already present in the ARP table:
0 - don't create new entries in the ARP table
1 - create new entries in the ARP table
Both replies and requests type gratuitous arp will trigger the
ARP table to be updated, if this setting is on.
If the ARP table already contains the IP address of the
gratuitous arp frame, the arp table will be updated regardless
if this setting is on or off.
"""
return self.set_interface('arp_accept', arp_accept)
def set_arp_announce(self, arp_announce):
"""
Define different restriction levels for announcing the local
source IP address from IP packets in ARP requests sent on
interface:
0 - (default) Use any local address, configured on any interface
1 - Try to avoid local addresses that are not in the target's
subnet for this interface. This mode is useful when target
hosts reachable via this interface require the source IP
address in ARP requests to be part of their logical network
configured on the receiving interface. When we generate the
request we will check all our subnets that include the
target IP and will preserve the source address if it is from
such subnet.
Increasing the restriction level gives more chance for
receiving answer from the resolved target while decreasing
the level announces more valid sender's information.
"""
return self.set_interface('arp_announce', arp_announce)
def set_arp_ignore(self, arp_ignore):
"""
Define different modes for sending replies in response to received ARP
requests that resolve local target IP addresses:
0 - (default): reply for any local target IP address, configured
on any interface
1 - reply only if the target IP address is local address
configured on the incoming interface
"""
return self.set_interface('arp_ignore', arp_ignore)
def set_ipv6_autoconf(self, autoconf):
"""
Autoconfigure addresses using Prefix Information in Router
Advertisements.
"""
return self.set_interface('ipv6_autoconf', autoconf)
def set_ipv6_eui64_address(self, prefix):
"""
Extended Unique Identifier (EUI), as per RFC2373, allows a host to
assign iteslf a unique IPv6 address based on a given IPv6 prefix.
If prefix is passed address is assigned, if prefix is '' address is
removed from interface.
"""
# if prefix is an empty string convert it to None so mac2eui64 works
# as expected
if not prefix:
prefix = None
eui64 = mac2eui64(self.get_mac(), prefix)
if not prefix:
# if prefix is empty - thus removed - we need to walk through all
# interface IPv6 addresses and find the one with the calculated
# EUI-64 identifier. The address is then removed
for addr in self.get_addr():
addr_wo_prefix = addr.split('/')[0]
if is_ipv6(addr_wo_prefix):
if eui64 in IPv6Address(addr_wo_prefix).exploded:
self.del_addr(addr)
return None
# calculate and add EUI-64 IPv6 address
if IPv6Network(prefix):
# we also need to take the subnet length into account
prefix = prefix.split('/')[1]
eui64 = f'{eui64}/{prefix}'
self.add_addr(eui64 )
def set_ipv6_forwarding(self, forwarding):
"""
Configure IPv6 interface-specific Host/Router behaviour.
False:
By default, Host behaviour is assumed. This means:
1. IsRouter flag is not set in Neighbour Advertisements.
2. If accept_ra is TRUE (default), transmit Router
Solicitations.
3. If accept_ra is TRUE (default), accept Router
Advertisements (and do autoconfiguration).
4. If accept_redirects is TRUE (default), accept Redirects.
True:
If local forwarding is enabled, Router behaviour is assumed.
This means exactly the reverse from the above:
1. IsRouter flag is set in Neighbour Advertisements.
2. Router Solicitations are not sent unless accept_ra is 2.
3. Router Advertisements are ignored unless accept_ra is 2.
4. Redirects are ignored.
"""
return self.set_interface('ipv6_forwarding', forwarding)
def set_ipv6_dad_messages(self, dad):
"""
The amount of Duplicate Address Detection probes to send.
Default: 1
"""
return self.set_interface('ipv6_dad_transmits', dad)
def set_link_detect(self, link_filter):
"""
Configure kernel response in packets received on interfaces that are 'down'
0 - Allow packets to be received for the address on this interface
even if interface is disabled or no carrier.
1 - Ignore packets received if interface associated with the incoming
address is down.
2 - Ignore packets received if interface associated with the incoming
address is down or has no carrier.
Default value is 0. Note that some distributions enable it in startup
scripts.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_link_detect(1)
"""
return self.set_interface('link_detect', link_filter)
def get_alias(self):
"""
Get interface alias name used by e.g. SNMP
Example:
>>> Interface('eth0').get_alias()
'interface description as set by user'
"""
return self.get_interface('alias')
def set_alias(self, ifalias=''):
"""
Set interface alias name used by e.g. SNMP
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_alias('VyOS upstream interface')
to clear alias e.g. delete it use:
>>> Interface('eth0').set_ifalias('')
"""
self.set_interface('alias', ifalias)
def get_admin_state(self):
"""
Get interface administrative state. Function will return 'up' or 'down'
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').get_admin_state()
'up'
"""
return self.get_interface('admin_state')
def set_admin_state(self, state):
"""
Set interface administrative state to be 'up' or 'down'
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_admin_state('down')
>>> Interface('eth0').get_admin_state()
'down'
"""
return self.set_interface('admin_state', state)
- def get_oper_state(self):
- """
- Get interface operational state
-
- Example:
- >>> from vyos.ifconfig import Interface
- >>> Interface('eth0').get_oper_sate()
- 'up'
- """
- # https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-net
- # "unknown", "notpresent", "down", "lowerlayerdown", "testing", "dormant", "up"
- return self.get_interface('oper_state')
-
def set_proxy_arp(self, enable):
"""
Set per interface proxy ARP configuration
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_proxy_arp(1)
"""
self.set_interface('proxy_arp', enable)
def set_proxy_arp_pvlan(self, enable):
"""
Private VLAN proxy arp.
Basically allow proxy arp replies back to the same interface
(from which the ARP request/solicitation was received).
This is done to support (ethernet) switch features, like RFC
3069, where the individual ports are NOT allowed to
communicate with each other, but they are allowed to talk to
the upstream router. As described in RFC 3069, it is possible
to allow these hosts to communicate through the upstream
router by proxy_arp'ing. Don't need to be used together with
proxy_arp.
This technology is known by different names:
In RFC 3069 it is called VLAN Aggregation.
Cisco and Allied Telesyn call it Private VLAN.
Hewlett-Packard call it Source-Port filtering or port-isolation.
Ericsson call it MAC-Forced Forwarding (RFC Draft).
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').set_proxy_arp_pvlan(1)
"""
self.set_interface('proxy_arp_pvlan', enable)
def get_addr(self):
"""
Retrieve assigned IPv4 and IPv6 addresses from given interface.
This is done using the netifaces and ipaddress python modules.
Example:
>>> from vyos.ifconfig import Interface
>>> Interface('eth0').get_addrs()
['172.16.33.30/24', 'fe80::20c:29ff:fe11:a174/64']
"""
ipv4 = []
ipv6 = []
if AF_INET in ifaddresses(self.config['ifname']).keys():
for v4_addr in ifaddresses(self.config['ifname'])[AF_INET]:
# we need to manually assemble a list of IPv4 address/prefix
prefix = '/' + \
str(IPv4Network('0.0.0.0/' + v4_addr['netmask']).prefixlen)
ipv4.append(v4_addr['addr'] + prefix)
if AF_INET6 in ifaddresses(self.config['ifname']).keys():
for v6_addr in ifaddresses(self.config['ifname'])[AF_INET6]:
# Note that currently expanded netmasks are not supported. That means
# 2001:db00::0/24 is a valid argument while 2001:db00::0/ffff:ff00:: not.
# see https://docs.python.org/3/library/ipaddress.html
bits = bin(
int(v6_addr['netmask'].replace(':', ''), 16)).count('1')
prefix = '/' + str(bits)
# we alsoneed to remove the interface suffix on link local
# addresses
v6_addr['addr'] = v6_addr['addr'].split('%')[0]
ipv6.append(v6_addr['addr'] + prefix)
return ipv4 + ipv6
def add_addr(self, addr):
"""
Add IP(v6) address to interface. Address is only added if it is not
already assigned to that interface.
addr: can be an IPv4 address, IPv6 address, dhcp or dhcpv6!
IPv4: add IPv4 address to interface
IPv6: add IPv6 address to interface
dhcp: start dhclient (IPv4) on interface
dhcpv6: start dhclient (IPv6) on interface
Example:
>>> from vyos.ifconfig import Interface
>>> j = Interface('eth0')
>>> j.add_addr('192.0.2.1/24')
>>> j.add_addr('2001:db8::ffff/64')
>>> j.get_addr()
['192.0.2.1/24', '2001:db8::ffff/64']
"""
# cache new IP address which is assigned to interface
self._addr.append(addr)
# we can not have both DHCP and static IPv4 addresses assigned to an interface
if 'dhcp' in self._addr:
for addr in self._addr:
# do not change below 'if' ordering esle you will get an exception as:
# ValueError: 'dhcp' does not appear to be an IPv4 or IPv6 address
if addr != 'dhcp' and is_ipv4(addr):
raise ConfigError(
"Can't configure both static IPv4 and DHCP address on the same interface")
if addr == 'dhcp':
self.dhcp.v4.set()
elif addr == 'dhcpv6':
self.dhcp.v6.set()
else:
if not is_intf_addr_assigned(self.config['ifname'], addr):
cmd = 'ip addr add "{}" dev "{}"'.format(addr, self.config['ifname'])
return self._cmd(cmd)
def del_addr(self, addr):
"""
Delete IP(v6) address to interface. Address is only added if it is
assigned to that interface.
addr: can be an IPv4 address, IPv6 address, dhcp or dhcpv6!
IPv4: delete IPv4 address from interface
IPv6: delete IPv6 address from interface
dhcp: stop dhclient (IPv4) on interface
dhcpv6: stop dhclient (IPv6) on interface
Example:
>>> from vyos.ifconfig import Interface
>>> j = Interface('eth0')
>>> j.add_addr('2001:db8::ffff/64')
>>> j.add_addr('192.0.2.1/24')
>>> j.get_addr()
['192.0.2.1/24', '2001:db8::ffff/64']
>>> j.del_addr('192.0.2.1/24')
>>> j.get_addr()
['2001:db8::ffff/64']
"""
if addr == 'dhcp':
self.dhcp.v4.delete()
elif addr == 'dhcpv6':
self.dhcp.v6.delete()
else:
if is_intf_addr_assigned(self.config['ifname'], addr):
cmd = 'ip addr del "{}" dev "{}"'.format(addr, self.config['ifname'])
return self._cmd(cmd)
-
- def op_show_interface_stats(self):
- stats = self.get_interface_stats()
- rx = [['bytes','packets','errors','dropped','overrun','mcast'],[stats['rx_bytes'],stats['rx_packets'],stats['rx_errors'],stats['rx_dropped'],stats['rx_over_errors'],stats['multicast']]]
- tx = [['bytes','packets','errors','dropped','carrier','collisions'],[stats['tx_bytes'],stats['tx_packets'],stats['tx_errors'],stats['tx_dropped'],stats['tx_carrier_errors'],stats['collisions']]]
- output = "RX: \n"
- output += tabulate(rx,headers="firstrow",numalign="right",tablefmt="plain")
- output += "\n\nTX: \n"
- output += tabulate(tx,headers="firstrow",numalign="right",tablefmt="plain")
- print(' '.join(('\n'+output.lstrip()).splitlines(True)))
-
- def get_interface_stats(self):
- interface_stats = dict()
- devices = [f for f in glob.glob("/sys/class/net/**/statistics")]
- for dev_path in devices:
- metrics = [f for f in glob.glob(dev_path +"/**")]
- dev = re.findall(r"/sys/class/net/(.*)/statistics",dev_path)[0]
- dev_dict = dict()
- for metric_path in metrics:
- metric = metric_path.replace(dev_path+"/","")
- if isfile(metric_path):
- data = open(metric_path, 'r').read()[:-1]
- dev_dict[metric] = int(data)
- interface_stats[dev] = dev_dict
-
- return interface_stats[self.config['ifname']]
-
diff --git a/python/vyos/ifconfig/operational.py b/python/vyos/ifconfig/operational.py
new file mode 100644
index 000000000..d585c1873
--- /dev/null
+++ b/python/vyos/ifconfig/operational.py
@@ -0,0 +1,179 @@
+# Copyright 2019 VyOS maintainers and contributors <maintainers@vyos.io>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library. If not, see <http://www.gnu.org/licenses/>.
+
+import os
+from time import time
+from datetime import datetime
+from functools import reduce
+
+from tabulate import tabulate
+
+from vyos.ifconfig import Control
+
+
+class Operational(Control):
+ """
+ A class able to load Interface statistics
+ """
+
+ cache_magic = 'XYZZYX'
+
+ _stat_names = {
+ 'rx': ['bytes', 'packets', 'errors', 'dropped', 'overrun', 'mcast'],
+ 'tx': ['bytes', 'packets', 'errors', 'dropped', 'carrier', 'collisions'],
+ }
+
+ _stats_dir = {
+ 'rx': ['rx_bytes', 'rx_packets', 'rx_errors', 'rx_dropped', 'rx_over_errors', 'multicast'],
+ 'tx': ['tx_bytes', 'tx_packets', 'tx_errors', 'tx_dropped', 'tx_carrier_errors', 'collisions'],
+ }
+
+ # a list made of the content of _stats_dir['rx'] + _stats_dir['tx']
+ _stats_all = reduce(lambda x, y: x+y, _stats_dir.values())
+
+ # this is not an interface but will be able to be controlled like one
+ _sysfs_get = {
+ 'oper_state':{
+ 'location': '/sys/class/net/{ifname}/operstate',
+ },
+ }
+
+
+ @classmethod
+ def cachefile (cls, ifname):
+ # the file where we are saving the counters
+ return f'/var/run/vyatta/{ifname}.stats'
+
+
+ def __init__(self, ifname):
+ """
+ Operational provide access to the counters of an interface
+ It behave like an interface when it comes to access sysfs
+
+ interface is an instance of the interface for which we want
+ to look at (a subclass of Interface, such as EthernetIf)
+ """
+
+ # add a self.config to minic Interface behaviour and make
+ # coding similar. Perhaps part of class Interface could be
+ # moved into a shared base class.
+ self.config = {
+ 'ifname': ifname,
+ 'create': False,
+ 'debug': False,
+ }
+ super().__init__(**self.config)
+ self.ifname = ifname
+
+ # adds all the counters of an interface
+ for stat in self._stats_all:
+ self._sysfs_get[stat] = {
+ 'location': '/sys/class/net/{ifname}/statistics/'+stat,
+ }
+
+ def get_state(self):
+ """
+ Get interface operational state
+
+ Example:
+ >>> from vyos.ifconfig import Interface
+ >>> Interface('eth0').operational.get_sate()
+ 'up'
+ """
+ # https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-net
+ # "unknown", "notpresent", "down", "lowerlayerdown", "testing", "dormant", "up"
+ return self.get_interface('oper_state')
+
+ @classmethod
+ def strtime (cls, epoc):
+ """
+ represent an epoc/unix date in the format used by operation commands
+ """
+ return datetime.fromtimestamp(epoc).strftime("%a %b %d %R:%S %Z %Y")
+
+ def save_counters(self, stats):
+ """
+ record the provided stats to a file keeping vyatta compatibility
+ """
+
+ with open(self.cachefile(self.ifname), 'w') as f:
+ f.write(self.cache_magic)
+ f.write('\n')
+ f.write(str(int(time())))
+ f.write('\n')
+ for k,v in stats.items():
+ if v:
+ f.write(f'{k},{v}\n')
+
+ def load_counters(self):
+ """
+ load the stats from a file keeping vyatta compatibility
+ return a dict() with the value for each interface counter for the cache
+ """
+ ifname = self.config['ifname']
+
+ stats = {}
+ no_stats = {}
+ for name in self._stats_all:
+ stats[name] = 0
+ no_stats[name] = 0
+
+ try:
+ with open(self.cachefile(self.ifname),'r') as f:
+ magic = f.readline().strip()
+ if magic != self.cache_magic:
+ print(f'bad magic {ifname}')
+ return no_stats
+ stats['timestamp'] = f.readline().strip()
+ for line in f:
+ k, v = line.split(',')
+ stats[k] = int(v)
+ return stats
+ except IOError:
+ return no_stats
+
+ def clear_counters(self, counters=None):
+ clear = self._stats_all if counters is None else []
+ stats = self.load_counters()
+ for counter, value in stats.items():
+ stats[counter] = 0 if counter in clear else value
+ self.save_counters(stats)
+
+ def reset_counters(self):
+ os.remove(self.cachefile(self.ifname))
+
+ def get_stats(self):
+ """ return a dict() with the value for each interface counter """
+ stats = {}
+ for counter in self._stats_all:
+ stats[counter] = int(self.get_interface(counter))
+ return stats
+
+ def formated_stats(self, indent=4):
+ tabs = []
+ stats = self.get_stats()
+ for rtx in self._stats_dir:
+ tabs.append([f'{rtx.upper()}:', ] + [_ for _ in self._stat_names[rtx]])
+ tabs.append(['', ] + [stats[_] for _ in self._stats_dir[rtx]])
+
+ s = tabulate(
+ tabs,
+ stralign="right",
+ numalign="right",
+ tablefmt="plain"
+ )
+
+ p = ' '*indent
+ return f'{p}' + s.replace('\n', f'\n{p}')
diff --git a/python/vyos/ifconfig/section.py b/python/vyos/ifconfig/section.py
index ab340d247..092236fef 100644
--- a/python/vyos/ifconfig/section.py
+++ b/python/vyos/ifconfig/section.py
@@ -1,131 +1,139 @@
# Copyright 2020 VyOS maintainers and contributors <maintainers@vyos.io>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
import netifaces
class Section:
# the known interface prefixes
_prefixes = {}
_classes = []
# class need to define: definition['prefixes']
# the interface prefixes declared by a class used to name interface with
# prefix[0-9]*(\.[0-9]+)?(\.[0-9]+)?, such as lo, eth0 or eth0.1.2
@classmethod
def register(cls, klass):
"""
A function to use as decorator the interfaces classes
It register the prefix for the interface (eth, dum, vxlan, ...)
with the class which can handle it (EthernetIf, DummyIf,VXLANIf, ...)
"""
if not klass.definition.get('prefixes',[]):
raise RuntimeError(f'valid interface prefixes not defined for {klass.__name__}')
cls._classes.append(klass)
for ifprefix in klass.definition['prefixes']:
if ifprefix in cls._prefixes:
raise RuntimeError(f'only one class can be registered for prefix "{ifprefix}" type')
cls._prefixes[ifprefix] = klass
return klass
@classmethod
def _basename (cls, name, vlan):
"""
remove the number at the end of interface name
name: name of the interface
vlan: if vlan is True, do not stop at the vlan number
"""
name = name.rstrip('0123456789')
name = name.rstrip('.')
if vlan:
name = name.rstrip('0123456789')
return name
@classmethod
def section(cls, name, vlan=True):
"""
return the name of a section an interface should be under
name: name of the interface (eth0, dum1, ...)
vlan: should we try try to remove the VLAN from the number
"""
name = cls._basename(name, vlan)
if name in cls._prefixes:
return cls._prefixes[name].definition['section']
return ''
-
+
+ @classmethod
+ def sections(cls):
+ """
+ return all the sections we found under 'set interfaces'
+ """
+ return list(set([cls._prefixes[_].definition['section'] for _ in cls._prefixes]))
+
@classmethod
def klass(cls, name, vlan=True):
name = cls._basename(name, vlan)
if name in cls._prefixes:
return cls._prefixes[name]
raise ValueError(f'No type found for interface name: {name}')
@classmethod
def _intf_under_section (cls,section=''):
"""
- return a generator with the name of the interface which are under a section
+ return a generator with the name of the configured interface
+ which are under a section
"""
interfaces = netifaces.interfaces()
for ifname in interfaces:
ifsection = cls.section(ifname)
if not ifsection:
continue
if section and ifsection != section:
continue
yield ifname
@classmethod
def interfaces(cls, section=''):
"""
- return a list of the name of the interface which are under a section
+ return a list of the name of the configured interface which are under a section
if no section is provided, then it returns all configured interfaces
"""
return list(cls._intf_under_section(section))
@classmethod
def _intf_with_feature(cls, feature=''):
"""
- return a generator with the name of the interface which have
+ return a generator with the name of the configured interface which have
a particular feature set in their definition such as:
bondable, broadcast, bridgeable, ...
"""
for klass in cls._classes:
if klass.definition[feature]:
yield klass.definition['section']
@classmethod
def feature(cls, feature=''):
"""
- return list with the name of the interface which have
+ return list with the name of the configured interface which have
a particular feature set in their definition such as:
bondable, broadcast, bridgeable, ...
"""
return list(cls._intf_with_feature(feature))
@classmethod
def reserved(cls):
"""
return list with the interface name prefixes
eth, lo, vxlan, dum, ...
"""
return list(cls._prefixes.keys())
diff --git a/python/vyos/ifconfig/vrrp.py b/python/vyos/ifconfig/vrrp.py
new file mode 100644
index 000000000..29b10dd9e
--- /dev/null
+++ b/python/vyos/ifconfig/vrrp.py
@@ -0,0 +1,145 @@
+# Copyright 2019 VyOS maintainers and contributors <maintainers@vyos.io>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library. If not, see <http://www.gnu.org/licenses/>.
+
+import os
+import json
+import signal
+from time import time
+from time import sleep
+
+from tabulate import tabulate
+
+from vyos import airbag
+from vyos import util
+
+
+class VRRPError(Exception):
+ pass
+
+class VRRP(object):
+ _vrrp_prefix = '00:00:5E:00:01:'
+ location = {
+ 'pid': '/run/keepalived.pid',
+ 'fifo': '/run/keepalived_notify_fifo',
+ 'state': '/tmp/keepalived.data',
+ 'stats': '/tmp/keepalived.stats',
+ 'json': '/tmp/keepalived.json',
+ 'daemon': '/etc/default/keepalived',
+ 'config': '/etc/keepalived/keepalived.conf',
+ 'vyos': '/run/keepalived_config.dict',
+ }
+
+ _signal = {
+ 'state': signal.SIGUSR1,
+ 'stats': signal.SIGUSR2,
+ 'json': signal.SIGRTMIN + 2,
+ }
+
+ _name = {
+ 'state': 'information',
+ 'stats': 'statistics',
+ 'json': 'data',
+ }
+
+ state = {
+ 0: 'INIT',
+ 1: 'BACKUP',
+ 2: 'MASTER',
+ 3: 'FAULT',
+ # UNKNOWN
+ }
+
+ def __init__(self,ifname):
+ self.ifname = ifname
+
+ def enabled(self):
+ return self.ifname in self.active_interfaces()
+
+ @classmethod
+ def active_interfaces(cls):
+ if not os.path.exists(cls.location['pid']):
+ return []
+ data = cls.collect('json')
+ return [group['data']['ifp_ifname'] for group in json.loads(data)]
+
+ @classmethod
+ def decode_state(cls, code):
+ return cls.state.get(code,'UNKNOWN')
+
+ # used in conf mode
+ @classmethod
+ def is_running(cls):
+ if not os.path.exists(cls.location['pid']):
+ return False
+ return util.process_running(cls.location['pid'])
+
+ @classmethod
+ def collect(cls, what):
+ fname = cls.location[what]
+ try:
+ # send signal to generate the configuration file
+ pid = util.read_file(cls.location['pid'])
+ os.kill(int(pid), cls._signal[what])
+
+ # shoud look for file size change ?
+ sleep(0.2)
+ return util.read_file(fname)
+ except Exception:
+ name = cls._name[what]
+ raise VRRPError(f'VRRP {name} is not available')
+ finally:
+ if os.path.exists(fname):
+ os.remove(fname)
+
+ @classmethod
+ def disabled(cls):
+ if not os.path.exists(cls.location['vyos']):
+ return []
+
+ disabled = []
+ config = json.loads(util.readfile(cls.location['vyos']))
+
+ # add disabled groups to the list
+ for group in config['vrrp_groups']:
+ if group['disable']:
+ disabled.append(
+ [group['name'], group['interface'], group['vrid'], 'DISABLED', ''])
+
+ # return list with disabled instances
+ return disabled
+
+ @classmethod
+ def format (cls, data):
+ headers = ["Name", "Interface", "VRID", "State", "Last Transition"]
+ groups = []
+
+ data = json.loads(data)
+ for group in data:
+ data = group['data']
+
+ name = data['iname']
+ intf = data['ifp_ifname']
+ vrid = data['vrid']
+ state = cls.decode_state(data["state"])
+
+ since = int(time() - float(data['last_transition']))
+ last = util.seconds_to_human(since)
+
+ groups.append([name, intf, vrid, state, last])
+
+ # add to the active list disabled instances
+ groups.extend(cls.disabled())
+ return(tabulate(groups, headers))
+
diff --git a/python/vyos/ifconfig/wireguard.py b/python/vyos/ifconfig/wireguard.py
index e2b8a5924..ff945c9d0 100644
--- a/python/vyos/ifconfig/wireguard.py
+++ b/python/vyos/ifconfig/wireguard.py
@@ -1,222 +1,229 @@
# Copyright 2019 VyOS maintainers and contributors <maintainers@vyos.io>
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
import os
import time
from datetime import timedelta
+from hurry.filesize import size
+from hurry.filesize import alternative
+
from vyos.config import Config
-from vyos.ifconfig.interface import Interface
-from hurry.filesize import size,alternative
+from vyos.ifconfig import Interface
+from vyos.ifconfig import Operational
+
+
+class WireGuardOperational(Operational):
+ def _dump(self):
+ """Dump wireguard data in a python friendly way."""
+ last_device = None
+ output = {}
+
+ # Dump wireguard connection data
+ _f = self._cmd('wg show all dump')
+ for line in _f.split('\n'):
+ if not line:
+ # Skip empty lines and last line
+ continue
+ items = line.split('\t')
+
+ if last_device != items[0]:
+ # We are currently entering a new node
+ device, private_key, public_key, listen_port, fw_mark = items
+ last_device = device
+
+ output[device] = {
+ 'private_key': None if private_key == '(none)' else private_key,
+ 'public_key': None if public_key == '(none)' else public_key,
+ 'listen_port': int(listen_port),
+ 'fw_mark': None if fw_mark == 'off' else int(fw_mark),
+ 'peers': {},
+ }
+ else:
+ # We are entering a peer
+ device, public_key, preshared_key, endpoint, allowed_ips, latest_handshake, transfer_rx, transfer_tx, persistent_keepalive = items
+ if allowed_ips == '(none)':
+ allowed_ips = []
+ else:
+ allowed_ips = allowed_ips.split('\t')
+ output[device]['peers'][public_key] = {
+ 'preshared_key': None if preshared_key == '(none)' else preshared_key,
+ 'endpoint': None if endpoint == '(none)' else endpoint,
+ 'allowed_ips': allowed_ips,
+ 'latest_handshake': None if latest_handshake == '0' else int(latest_handshake),
+ 'transfer_rx': int(transfer_rx),
+ 'transfer_tx': int(transfer_tx),
+ 'persistent_keepalive': None if persistent_keepalive == 'off' else int(persistent_keepalive),
+ }
+ return output
+
+ def show_interface(self):
+ wgdump = self._dump().get(self.config['ifname'], None)
+
+ c = Config()
+
+ c.set_level(["interfaces", "wireguard", self.config['ifname']])
+ description = c.return_effective_value(["description"])
+ ips = c.return_effective_values(["address"])
+
+ answer = "interface: {}\n".format(self.config['ifname'])
+ if (description):
+ answer += " description: {}\n".format(description)
+ if (ips):
+ answer += " address: {}\n".format(", ".join(ips))
+
+ answer += " public key: {}\n".format(wgdump['public_key'])
+ answer += " private key: (hidden)\n"
+ answer += " listening port: {}\n".format(wgdump['listen_port'])
+ answer += "\n"
+
+ for peer in c.list_effective_nodes(["peer"]):
+ if wgdump['peers']:
+ pubkey = c.return_effective_value(["peer", peer, "pubkey"])
+ if pubkey in wgdump['peers']:
+ wgpeer = wgdump['peers'][pubkey]
+
+ answer += " peer: {}\n".format(peer)
+ answer += " public key: {}\n".format(pubkey)
+
+ """ figure out if the tunnel is recently active or not """
+ status = "inactive"
+ if (wgpeer['latest_handshake'] is None):
+ """ no handshake ever """
+ status = "inactive"
+ else:
+ if int(wgpeer['latest_handshake']) > 0:
+ delta = timedelta(seconds=int(
+ time.time() - wgpeer['latest_handshake']))
+ answer += " latest handshake: {}\n".format(delta)
+ if (time.time() - int(wgpeer['latest_handshake']) < (60*5)):
+ """ Five minutes and the tunnel is still active """
+ status = "active"
+ else:
+ """ it's been longer than 5 minutes """
+ status = "inactive"
+ elif int(wgpeer['latest_handshake']) == 0:
+ """ no handshake ever """
+ status = "inactive"
+ answer += " status: {}\n".format(status)
+
+ if wgpeer['endpoint'] is not None:
+ answer += " endpoint: {}\n".format(wgpeer['endpoint'])
+
+ if wgpeer['allowed_ips'] is not None:
+ answer += " allowed ips: {}\n".format(
+ ",".join(wgpeer['allowed_ips']).replace(",", ", "))
+
+ if wgpeer['transfer_rx'] > 0 or wgpeer['transfer_tx'] > 0:
+ rx_size = size(
+ wgpeer['transfer_rx'], system=alternative)
+ tx_size = size(
+ wgpeer['transfer_tx'], system=alternative)
+ answer += " transfer: {} received, {} sent\n".format(
+ rx_size, tx_size)
+
+ if wgpeer['persistent_keepalive'] is not None:
+ answer += " persistent keepalive: every {} seconds\n".format(
+ wgpeer['persistent_keepalive'])
+ answer += '\n'
+ return answer + super().formated_stats()
@Interface.register
class WireGuardIf(Interface):
+ OperationalClass = WireGuardOperational
+
default = {
'type': 'wireguard',
'port': 0,
'private-key': None,
'pubkey': None,
'psk': '/dev/null',
'allowed-ips': [],
'fwmark': 0x00,
'endpoint': None,
'keepalive': 0
}
definition = {
**Interface.definition,
**{
'section': 'wireguard',
'prefixes': ['wg', ],
'bridgeable': True,
}
}
options = ['port', 'private-key', 'pubkey', 'psk',
'allowed-ips', 'fwmark', 'endpoint', 'keepalive']
"""
Wireguard interface class, contains a comnfig dictionary since
wireguard VPN is being comnfigured via the wg command rather than
writing the config into a file. Otherwise if a pre-shared key is used
(symetric enryption key), it would we exposed within multiple files.
Currently it's only within the config.boot if the config was saved.
Example:
>>> from vyos.ifconfig import WireGuardIf as wg_if
>>> wg_intfc = wg_if("wg01")
>>> print (wg_intfc.wg_config)
{'private-key': None, 'keepalive': 0, 'endpoint': None, 'port': 0,
'allowed-ips': [], 'pubkey': None, 'fwmark': 0, 'psk': '/dev/null'}
>>> wg_intfc.wg_config['keepalive'] = 100
>>> print (wg_intfc.wg_config)
{'private-key': None, 'keepalive': 100, 'endpoint': None, 'port': 0,
'allowed-ips': [], 'pubkey': None, 'fwmark': 0, 'psk': '/dev/null'}
"""
def update(self):
if not self.config['private-key']:
raise ValueError("private key required")
else:
# fmask permission check?
pass
cmd = "wg set {} ".format(self.config['ifname'])
cmd += "listen-port {} ".format(self.config['port'])
cmd += "fwmark {} ".format(str(self.config['fwmark']))
cmd += "private-key {} ".format(self.config['private-key'])
cmd += "peer {} ".format(self.config['pubkey'])
cmd += " preshared-key {} ".format(self.config['psk'])
cmd += " allowed-ips "
for aip in self.config['allowed-ips']:
if aip != self.config['allowed-ips'][-1]:
cmd += aip + ","
else:
cmd += aip
if self.config['endpoint']:
cmd += " endpoint {}".format(self.config['endpoint'])
cmd += " persistent-keepalive {}".format(self.config['keepalive'])
self._cmd(cmd)
# remove psk since it isn't required anymore and is saved in the cli
# config only !!
if self.config['psk'] != '/dev/null':
if os.path.exists(self.config['psk']):
os.remove(self.config['psk'])
def remove_peer(self, peerkey):
"""
Remove a peer of an interface, peers are identified by their public key.
Giving it a readable name is a vyos feature, to remove a peer the pubkey
and the interface is needed, to remove the entry.
"""
cmd = "wg set {0} peer {1} remove".format(
self.config['ifname'], str(peerkey))
return self._cmd(cmd)
-
- def op_show_interface(self):
- wgdump = self._dump().get(
- self.config['ifname'], None)
-
- c = Config()
- c.set_level(["interfaces", "wireguard", self.config['ifname']])
- description = c.return_effective_value(["description"])
- ips = c.return_effective_values(["address"])
-
- print ("interface: {}".format(self.config['ifname']))
- if (description):
- print (" description: {}".format(description))
-
- if (ips):
- print (" address: {}".format(", ".join(ips)))
- print (" public key: {}".format(wgdump['public_key']))
- print (" private key: (hidden)")
- print (" listening port: {}".format(wgdump['listen_port']))
- print ()
-
- for peer in c.list_effective_nodes(["peer"]):
- if wgdump['peers']:
- pubkey = c.return_effective_value(["peer", peer, "pubkey"])
- if pubkey in wgdump['peers']:
- wgpeer = wgdump['peers'][pubkey]
-
- print (" peer: {}".format(peer))
- print (" public key: {}".format(pubkey))
-
- """ figure out if the tunnel is recently active or not """
- status = "inactive"
- if (wgpeer['latest_handshake'] is None):
- """ no handshake ever """
- status = "inactive"
- else:
- if int(wgpeer['latest_handshake']) > 0:
- delta = timedelta(seconds=int(
- time.time() - wgpeer['latest_handshake']))
- print (" latest handshake: {}".format(delta))
- if (time.time() - int(wgpeer['latest_handshake']) < (60*5)):
- """ Five minutes and the tunnel is still active """
- status = "active"
- else:
- """ it's been longer than 5 minutes """
- status = "inactive"
- elif int(wgpeer['latest_handshake']) == 0:
- """ no handshake ever """
- status = "inactive"
- print (" status: {}".format(status))
-
- if wgpeer['endpoint'] is not None:
- print (" endpoint: {}".format(wgpeer['endpoint']))
-
- if wgpeer['allowed_ips'] is not None:
- print (" allowed ips: {}".format(
- ",".join(wgpeer['allowed_ips']).replace(",", ", ")))
-
- if wgpeer['transfer_rx'] > 0 or wgpeer['transfer_tx'] > 0:
- rx_size = size(
- wgpeer['transfer_rx'], system=alternative)
- tx_size = size(
- wgpeer['transfer_tx'], system=alternative)
- print (" transfer: {} received, {} sent".format(
- rx_size, tx_size))
-
- if wgpeer['persistent_keepalive'] is not None:
- print (" persistent keepalive: every {} seconds".format(
- wgpeer['persistent_keepalive']))
- print()
- super().op_show_interface_stats()
-
- def _dump(self):
- """Dump wireguard data in a python friendly way."""
- last_device = None
- output = {}
-
- # Dump wireguard connection data
- _f = self._cmd('wg show all dump')
- for line in _f.split('\n'):
- if not line:
- # Skip empty lines and last line
- continue
- items = line.split('\t')
-
- if last_device != items[0]:
- # We are currently entering a new node
- device, private_key, public_key, listen_port, fw_mark = items
- last_device = device
-
- output[device] = {
- 'private_key': None if private_key == '(none)' else private_key,
- 'public_key': None if public_key == '(none)' else public_key,
- 'listen_port': int(listen_port),
- 'fw_mark': None if fw_mark == 'off' else int(fw_mark),
- 'peers': {},
- }
- else:
- # We are entering a peer
- device, public_key, preshared_key, endpoint, allowed_ips, latest_handshake, transfer_rx, transfer_tx, persistent_keepalive = items
- if allowed_ips == '(none)':
- allowed_ips = []
- else:
- allowed_ips = allowed_ips.split('\t')
- output[device]['peers'][public_key] = {
- 'preshared_key': None if preshared_key == '(none)' else preshared_key,
- 'endpoint': None if endpoint == '(none)' else endpoint,
- 'allowed_ips': allowed_ips,
- 'latest_handshake': None if latest_handshake == '0' else int(latest_handshake),
- 'transfer_rx': int(transfer_rx),
- 'transfer_tx': int(transfer_tx),
- 'persistent_keepalive': None if persistent_keepalive == 'off' else int(persistent_keepalive),
- }
- return output
diff --git a/python/vyos/keepalived.py b/python/vyos/keepalived.py
deleted file mode 100644
index 3984ca792..000000000
--- a/python/vyos/keepalived.py
+++ /dev/null
@@ -1,140 +0,0 @@
-# Copyright 2018 VyOS maintainers and contributors <maintainers@vyos.io>
-#
-# This library is free software; you can redistribute it and/or
-# modify it under the terms of the GNU Lesser General Public
-# License as published by the Free Software Foundation; either
-# version 2.1 of the License, or (at your option) any later version.
-#
-# This library is distributed in the hope that it will be useful,
-# but WITHOUT ANY WARRANTY; without even the implied warranty of
-# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-# Lesser General Public License for more details.
-#
-# You should have received a copy of the GNU Lesser General Public
-# License along with this library. If not, see <http://www.gnu.org/licenses/>.
-
-import re
-import os
-import signal
-import json
-
-import vyos.util
-
-
-pid_file = '/var/run/keepalived.pid'
-state_file = '/tmp/keepalived.data'
-stats_file = '/tmp/keepalived.stats'
-json_file = '/tmp/keepalived.json'
-
-def vrrp_running():
- if not os.path.exists(vyos.keepalived.pid_file) \
- or not vyos.util.process_running(vyos.keepalived.pid_file):
- return False
- else:
- return True
-
-def keepalived_running():
- return vyos.util.process_running(pid_file)
-
-## Clear VRRP data after showing
-def remove_vrrp_data(data_file):
- if data_file == "json" and os.path.exists(json_file):
- os.remove(json_file)
- elif data_file == "stats" and os.path.exists(stats_file):
- os.remove(stats_file)
- elif data_file == "state" and os.path.exists(state_file):
- os.remove(state_file)
-
-def force_state_data_dump():
- pid = vyos.util.read_file(pid_file)
- os.kill(int(pid), signal.SIGUSR1)
-
-def force_stats_dump():
- pid = vyos.util.read_file(pid_file)
- os.kill(int(pid), signal.SIGUSR2)
-
-def force_json_dump():
- pid = vyos.util.read_file(pid_file)
- os.kill(int(pid), signal.SIGRTMIN+2)
-
-def get_json_data():
- with open(json_file, 'r') as f:
- j = json.load(f)
- return j
-
-def get_statistics():
- return vyos.util.read_file(stats_file)
-
-def get_state_data():
- return vyos.util.read_file(state_file)
-
-def decode_state(code):
- state = None
- if code == 0:
- state = "INIT"
- elif code == 1:
- state = "BACKUP"
- elif code == 2:
- state = "MASTER"
- elif code == 3:
- state = "FAULT"
- else:
- state = "UNKNOWN"
-
- return state
-
-## These functions are for the old, and hopefully obsolete plaintext
-## (non machine-readable) data format introduced by Vyatta back in the days
-## They are kept here just in case, if JSON output option turns out or becomes
-## insufficient.
-
-def read_state_data():
- with open(state_file, 'r') as f:
- lines = f.readlines()
- return lines
-
-def parse_keepalived_data(data_lines):
- vrrp_groups = {}
-
- # Scratch variable
- group_name = None
-
- # Sadly there is no explicit end marker in that format, so we have
- # only two states, one before the first VRRP instance is encountered
- # and one after an instance/"group" was encountered
- # We'll set group_name once the first group is encountered,
- # and assume we are inside a group if it's set afterwards
- #
- # It may not be necessary since the keywords found inside groups and before
- # the VRRP Topology section seem to have no intersection,
- # but better safe than sorry.
-
- for line in data_lines:
- if re.match(r'^\s*VRRP Instance', line, re.IGNORECASE):
- # Example: "VRRP Instance = Foo"
- name = re.match(r'^\s*VRRP Instance\s+=\s+(.*)$', line, re.IGNORECASE).groups()[0].strip()
- group_name = name
- vrrp_groups[name] = {}
- elif re.match(r'^\s*State', line, re.IGNORECASE) and group_name:
- # Example: " State = MASTER"
- group_state = re.match(r'^\s*State\s+=\s+(.*)$', line, re.IGNORECASE).groups()[0].strip()
- vrrp_groups[group_name]["state"] = group_state
- elif re.match(r'^\s*Last transition', line, re.IGNORECASE) and group_name:
- # Example: " Last transition = 1532043820 (Thu Jul 19 23:43:40 2018)"
- trans_time = re.match(r'^\s*Last transition\s+=\s+(\d+)\s', line, re.IGNORECASE).groups()[0]
- vrrp_groups[group_name]["last_transition"] = trans_time
- elif re.match(r'^\s*Interface', line, re.IGNORECASE) and group_name:
- # Example: " Interface = eth0.30"
- interface = re.match(r'\s*Interface\s+=\s+(.*)$', line, re.IGNORECASE).groups()[0].strip()
- vrrp_groups[group_name]["interface"] = interface
- elif re.match(r'^\s*Virtual Router ID', line, re.IGNORECASE) and group_name:
- # Example: " Virtual Router ID = 14"
- vrid = re.match(r'^\s*Virtual Router ID\s+=\s+(.*)$', line, re.IGNORECASE).groups()[0].strip()
- vrrp_groups[group_name]["vrid"] = vrid
- elif re.match(r'^\s*------< Interfaces', line, re.IGNORECASE):
- # Interfaces section appears to always be present,
- # and there's nothing of interest for us below that section,
- # so we use it as an end of input marker
- break
-
- return vrrp_groups
diff --git a/src/conf_mode/vrrp.py b/src/conf_mode/vrrp.py
index b9b0405e2..f358891a5 100755
--- a/src/conf_mode/vrrp.py
+++ b/src/conf_mode/vrrp.py
@@ -1,257 +1,254 @@
#!/usr/bin/env python3
#
# Copyright (C) 2018-2020 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 os
from sys import exit
from ipaddress import ip_address, ip_interface, IPv4Interface, IPv6Interface, IPv4Address, IPv6Address
from json import dumps
from pathlib import Path
import vyos.config
-import vyos.keepalived
from vyos import ConfigError
from vyos.util import call
from vyos.template import render
+from vyos.ifconfig.vrrp import VRRP
-daemon_file = "/etc/default/keepalived"
-config_file = "/etc/keepalived/keepalived.conf"
-config_dict_path = "/run/keepalived_config.dict"
def get_config():
vrrp_groups = []
sync_groups = []
config = vyos.config.Config()
# Get the VRRP groups
for group_name in config.list_nodes("high-availability vrrp group"):
config.set_level("high-availability vrrp group {0}".format(group_name))
# Retrieve the values
group = {"preempt": True, "use_vmac": False, "disable": False}
if config.exists("disable"):
group["disable"] = True
group["name"] = group_name
group["vrid"] = config.return_value("vrid")
group["interface"] = config.return_value("interface")
group["description"] = config.return_value("description")
group["advertise_interval"] = config.return_value("advertise-interval")
group["priority"] = config.return_value("priority")
group["hello_source"] = config.return_value("hello-source-address")
group["peer_address"] = config.return_value("peer-address")
group["sync_group"] = config.return_value("sync-group")
group["preempt_delay"] = config.return_value("preempt-delay")
group["virtual_addresses"] = config.return_values("virtual-address")
group["auth_password"] = config.return_value("authentication password")
group["auth_type"] = config.return_value("authentication type")
group["health_check_script"] = config.return_value("health-check script")
group["health_check_interval"] = config.return_value("health-check interval")
group["health_check_count"] = config.return_value("health-check failure-count")
group["master_script"] = config.return_value("transition-script master")
group["backup_script"] = config.return_value("transition-script backup")
group["fault_script"] = config.return_value("transition-script fault")
group["stop_script"] = config.return_value("transition-script stop")
if config.exists("no-preempt"):
group["preempt"] = False
if config.exists("rfc3768-compatibility"):
group["use_vmac"] = True
# Substitute defaults where applicable
if not group["advertise_interval"]:
group["advertise_interval"] = 1
if not group["priority"]:
group["priority"] = 100
if not group["preempt_delay"]:
group["preempt_delay"] = 0
if not group["health_check_interval"]:
group["health_check_interval"] = 60
if not group["health_check_count"]:
group["health_check_count"] = 3
# FIXUP: translate our option for auth type to keepalived's syntax
# for simplicity
if group["auth_type"]:
if group["auth_type"] == "plaintext-password":
group["auth_type"] = "PASS"
else:
group["auth_type"] = "AH"
vrrp_groups.append(group)
config.set_level("")
# Get the sync group used for conntrack-sync
conntrack_sync_group = None
if config.exists("service conntrack-sync failover-mechanism vrrp"):
conntrack_sync_group = config.return_value("service conntrack-sync failover-mechanism vrrp sync-group")
# Get the sync groups
for sync_group_name in config.list_nodes("high-availability vrrp sync-group"):
config.set_level("high-availability vrrp sync-group {0}".format(sync_group_name))
sync_group = {"conntrack_sync": False}
sync_group["name"] = sync_group_name
sync_group["members"] = config.return_values("member")
if conntrack_sync_group:
if conntrack_sync_group == sync_group_name:
sync_group["conntrack_sync"] = True
# add transition script configuration
sync_group["master_script"] = config.return_value("transition-script master")
sync_group["backup_script"] = config.return_value("transition-script backup")
sync_group["fault_script"] = config.return_value("transition-script fault")
sync_group["stop_script"] = config.return_value("transition-script stop")
sync_groups.append(sync_group)
# create a file with dict with proposed configuration
- with open("{}.temp".format(config_dict_path), 'w') as dict_file:
+ with open("{}.temp".format(VRRP.location['vyos']), 'w') as dict_file:
dict_file.write(dumps({'vrrp_groups': vrrp_groups, 'sync_groups': sync_groups}))
return (vrrp_groups, sync_groups)
def verify(data):
vrrp_groups, sync_groups = data
for group in vrrp_groups:
# Check required fields
if not group["vrid"]:
raise ConfigError("vrid is required but not set in VRRP group {0}".format(group["name"]))
if not group["interface"]:
raise ConfigError("interface is required but not set in VRRP group {0}".format(group["name"]))
if not group["virtual_addresses"]:
raise ConfigError("virtual-address is required but not set in VRRP group {0}".format(group["name"]))
if group["auth_password"] and (not group["auth_type"]):
raise ConfigError("authentication type is required but not set in VRRP group {0}".format(group["name"]))
# Keepalived doesn't allow mixing IPv4 and IPv6 in one group, so we mirror that restriction
# XXX: filter on map object is destructive, so we force it to list.
# Additionally, filter objects always evaluate to True, empty or not,
# so we force them to lists as well.
vaddrs = list(map(lambda i: ip_interface(i), group["virtual_addresses"]))
vaddrs4 = list(filter(lambda x: isinstance(x, IPv4Interface), vaddrs))
vaddrs6 = list(filter(lambda x: isinstance(x, IPv6Interface), vaddrs))
if vaddrs4 and vaddrs6:
raise ConfigError("VRRP group {0} mixes IPv4 and IPv6 virtual addresses, this is not allowed. Create separate groups for IPv4 and IPv6".format(group["name"]))
if vaddrs4:
if group["hello_source"]:
hsa = ip_address(group["hello_source"])
if isinstance(hsa, IPv6Address):
raise ConfigError("VRRP group {0} uses IPv4 but its hello-source-address is IPv6".format(group["name"]))
if group["peer_address"]:
pa = ip_address(group["peer_address"])
if isinstance(pa, IPv6Address):
raise ConfigError("VRRP group {0} uses IPv4 but its peer-address is IPv6".format(group["name"]))
if vaddrs6:
if group["hello_source"]:
hsa = ip_address(group["hello_source"])
if isinstance(hsa, IPv4Address):
raise ConfigError("VRRP group {0} uses IPv6 but its hello-source-address is IPv4".format(group["name"]))
if group["peer_address"]:
pa = ip_address(group["peer_address"])
if isinstance(pa, IPv4Address):
raise ConfigError("VRRP group {0} uses IPv6 but its peer-address is IPv4".format(group["name"]))
# Disallow same VRID on multiple interfaces
_groups = sorted(vrrp_groups, key=(lambda x: x["interface"]))
count = len(_groups) - 1
index = 0
while (index < count):
if (_groups[index]["vrid"] == _groups[index + 1]["vrid"]) and (_groups[index]["interface"] == _groups[index + 1]["interface"]):
raise ConfigError("VRID {0} is used in groups {1} and {2} that both use interface {3}. Groups on the same interface must use different VRIDs".format(
_groups[index]["vrid"], _groups[index]["name"], _groups[index + 1]["name"], _groups[index]["interface"]))
else:
index += 1
# Check sync groups
vrrp_group_names = list(map(lambda x: x["name"], vrrp_groups))
for sync_group in sync_groups:
for m in sync_group["members"]:
if not (m in vrrp_group_names):
raise ConfigError("VRRP sync-group {0} refers to VRRP group {1}, but group {1} does not exist".format(sync_group["name"], m))
def generate(data):
vrrp_groups, sync_groups = data
# Remove disabled groups from the sync group member lists
for sync_group in sync_groups:
for member in sync_group["members"]:
g = list(filter(lambda x: x["name"] == member, vrrp_groups))[0]
if g["disable"]:
print("Warning: ignoring disabled VRRP group {0} in sync-group {1}".format(g["name"], sync_group["name"]))
# Filter out disabled groups
vrrp_groups = list(filter(lambda x: x["disable"] is not True, vrrp_groups))
- render(config_file, 'vrrp/keepalived.conf.tmpl',
- {"groups": vrrp_groups, "sync_groups": sync_groups})
- render(daemon_file, 'vrrp/daemon.tmpl', {})
+ render(VRRP.location['config'], 'vrrp/keepalived.conf.tmpl',
+ {"groups": vrrp_groups, "sync_groups": sync_groups})
+ render(VRRP.location['daemon'], 'vrrp/daemon.tmpl', {})
return None
def apply(data):
vrrp_groups, sync_groups = data
if vrrp_groups:
# safely rename a temporary file with configuration dict
try:
- dict_file = Path("{}.temp".format(config_dict_path))
- dict_file.rename(Path(config_dict_path))
+ dict_file = Path("{}.temp".format(VRRP.location['vyos']))
+ dict_file.rename(Path(VRRP.location['vyos']))
except Exception as err:
print("Unable to rename the file with keepalived config for FIFO pipe: {}".format(err))
- if not vyos.keepalived.vrrp_running():
+ if not VRRP.is_running():
print("Starting the VRRP process")
ret = call("sudo systemctl restart keepalived.service")
else:
print("Reloading the VRRP process")
ret = call("sudo systemctl reload keepalived.service")
if ret != 0:
raise ConfigError("keepalived failed to start")
else:
# VRRP is removed in the commit
print("Stopping the VRRP process")
call("sudo systemctl stop keepalived.service")
- os.unlink(config_file)
+ os.unlink(VRRP.location['daemon'])
return None
if __name__ == '__main__':
try:
c = get_config()
verify(c)
generate(c)
apply(c)
except ConfigError as e:
print("VRRP error: {0}".format(str(e)))
exit(1)
diff --git a/src/op_mode/show_interfaces.py b/src/op_mode/show_interfaces.py
new file mode 100755
index 000000000..8b6690b7d
--- /dev/null
+++ b/src/op_mode/show_interfaces.py
@@ -0,0 +1,267 @@
+#!/usr/bin/env python3
+
+# Copyright 2017, 2019 VyOS maintainers and contributors <maintainers@vyos.io>
+#
+# This library is free software; you can redistribute it and/or
+# modify it under the terms of the GNU Lesser General Public
+# License as published by the Free Software Foundation; either
+# version 2.1 of the License, or (at your option) any later version.
+#
+# This library is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# Lesser General Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with this library. If not, see <http://www.gnu.org/licenses/>.
+
+import os
+import re
+import sys
+import datetime
+import argparse
+import netifaces
+
+from vyos.ifconfig import Section
+from vyos.ifconfig import Interface
+from vyos.ifconfig import VRRP
+from vyos.util import cmd
+
+
+# interfaces = Sections.reserved()
+interfaces = ['eno', 'ens', 'enp', 'enx', 'eth', 'vmnet', 'lo', 'tun', 'wan', 'pppoe', 'pppoa', 'adsl']
+glob_ifnames = '/sys/class/net/({})*'.format('|'.join(interfaces))
+
+
+actions = {}
+def register (name):
+ """
+ decorator to register a function into actions with a name
+ it allows to use actions[name] to call the registered function
+ """
+ def _register(function):
+ actions[name] = function
+ return function
+ return _register
+
+
+def filtered_interfaces(ifnames, iftypes, vif, vrrp):
+ """
+ get all the interfaces from the OS and returns them
+ ifnames can be used to filter which interfaces should be considered
+
+ ifnames: a list of interfaces names to consider, empty do not filter
+ return an instance of the interface class
+ """
+ allnames = Section.interfaces()
+ allnames.sort()
+
+ vrrp_interfaces = VRRP.active_interfaces() if vrrp else []
+
+ for ifname in allnames:
+ if ifnames and ifname not in ifnames:
+ continue
+
+ # return the class which can handle this interface name
+ klass = Section.klass(ifname)
+ # connect to the interface
+ interface = klass(ifname, create=False, debug=False)
+
+ if iftypes and interface.definition['section'] not in iftypes:
+ continue
+
+ if vif and not '.' in ifname:
+ continue
+
+ if vrrp and ifname not in vrrp_interfaces:
+ continue
+
+ yield interface
+
+
+def split_text(text, used=0):
+ """
+ take a string and attempt to split it to fit with the width of the screen
+
+ text: the string to split
+ used: number of characted already used in the screen
+ """
+ returned = cmd('stty size')
+ if len(returned) == 2:
+ rows, columns = [int(_) for _ in returned]
+ else:
+ rows, columns = (40, 80)
+
+ desc_len = columns - used
+
+ line = ''
+ for word in text.split():
+ if len(line) + len(word) >= desc_len:
+ yield f'{line} {word}'[1:]
+ line = ''
+ line = f'{line} {word}'
+ yield line[1:]
+
+
+def get_vrrp_intf():
+ return [intf for intf in Section.interfaces() if intf.is_vrrp()]
+
+
+def get_counter_val(clear, now):
+ """
+ attempt to correct a counter if it wrapped, copied from perl
+
+ clear: previous counter
+ now: the current counter
+ """
+ # This function has to deal with both 32 and 64 bit counters
+ if clear == 0:
+ return now
+
+ # device is using 64 bit values assume they never wrap
+ value = now - clear
+ if (now >> 32) != 0:
+ return value
+
+ # The counter has rolled. If the counter has rolled
+ # multiple times since the clear value, then this math
+ # is meaningless.
+ if (value < 0):
+ value = (4294967296 - clear) + now
+
+ return value
+
+
+@register('help')
+def usage(*args):
+ print(f"Usage: {sys.argv[0]} [intf=NAME|intf-type=TYPE|vif|vrrp] action=ACTION")
+ print(f" NAME = " + ' | '.join(Section.interfaces()))
+ print(f" TYPE = " + ' | '.join(Section.sections()))
+ print(f" ACTION = " + ' | '.join(actions))
+ sys.exit(1)
+
+
+@register('allowed')
+def run_allowed(**kwarg):
+ sys.stdout.write(' '.join(Section.interfaces()))
+
+
+@register('show')
+def run_show_intf(ifnames, iftypes, vif, vrrp):
+ for interface in filtered_interfaces(ifnames, iftypes, vif, vrrp):
+ cache = interface.operational.load_counters()
+
+ out = cmd(f'ip addr show {interface.ifname}')
+ out = re.sub(f'^\d+:\s+','',out)
+ if re.search("link/tunnel6", out):
+ tunnel = cmd(f'ip -6 tun show {interface.ifname}')
+ # tun0: ip/ipv6 remote ::2 local ::1 encaplimit 4 hoplimit 64 tclass inherit flowlabel inherit (flowinfo 0x00000000)
+ tunnel = re.sub('.*encap', 'encap', tunnel)
+ out = re.sub('(\n\s+)(link/tunnel6)', f'\g<1>{tunnel}\g<1>\g<2>', out)
+
+ print(out)
+
+ timestamp = int(cache.get('timestamp', 0))
+ if timestamp:
+ when = interface.operational.strtime(timestamp)
+ print(f' Last clear: {when}')
+
+ description = interface.get_alias()
+ if description:
+ print(f' Description: {description}')
+
+ print()
+ print(interface.operational.formated_stats())
+
+
+@register('show-brief')
+def run_show_intf_brief(ifnames, iftypes, vif, vrrp):
+ format1 = '%-16s %-33s %-4s %s'
+ format2 = '%-16s %s'
+
+ print('Codes: S - State, L - Link, u - Up, D - Down, A - Admin Down')
+ print(format1 % ("Interface", "IP Address", "S/L", "Description"))
+ print(format1 % ("---------", "----------", "---", "-----------"))
+
+ for interface in filtered_interfaces(ifnames, iftypes, vif, vrrp):
+ oper_state = interface.operational.get_state()
+ admin_state = interface.get_admin_state()
+
+ intf = [interface.ifname,]
+ oper = ['u', ] if oper_state in ('up', 'unknown') else ['A', ]
+ admin = ['u', ] if oper_state in ('up', 'unknown') else ['D', ]
+ addrs = [_ for _ in interface.get_addr() if not _.startswith('fe80::')] or ['-', ]
+ # do not ask me why 56, it was the number in the perl code ...
+ descs = list(split_text(interface.get_alias(),56))
+
+ while intf or oper or admin or addrs or descs:
+ i = intf.pop(0) if intf else ''
+ a = addrs.pop(0) if addrs else ''
+ d = descs.pop(0) if descs else ''
+ s = [oper.pop(0)] if oper else []
+ l = [admin.pop(0)] if admin else []
+ if len(a) < 33:
+ print(format1 % (i, a, '/'.join(s+l), d))
+ else:
+ print(format2 % (i, a))
+ print(format1 % ('', '', '/'.join(s+l), d))
+
+
+@register('show-count')
+def run_show_counters(ifnames, iftypes, vif, vrrp):
+ formating = '%-12s %10s %10s %10s %10s'
+ print(formating % ('Interface', 'Rx Packets', 'Rx Bytes', 'Tx Packets', 'Tx Bytes'))
+
+ for interface in filtered_interfaces(ifnames, iftypes, vif, vrrp):
+ oper = interface.operational.get_state()
+
+ if oper not in ('up','unknown'):
+ continue
+
+ stats = interface.operational.get_stats()
+ cache = interface.operational.load_counters()
+ print(formating % (
+ interface.ifname,
+ get_counter_val(cache['rx_packets'], stats['rx_packets']),
+ get_counter_val(cache['rx_bytes'], stats['rx_bytes']),
+ get_counter_val(cache['tx_packets'], stats['tx_packets']),
+ get_counter_val(cache['tx_bytes'], stats['tx_bytes']),
+ ))
+
+
+@register('clear')
+def run_clear_intf(intf, iftypes, vif, vrrp):
+ for interface in filtered_interfaces(ifnames, iftypes, vif, vrrp):
+ print(f'Clearing {interface.ifname}')
+ interface = Interface(ifname, create=False, debug=False)
+ interface.operational.clear_counters()
+
+
+@register('reset')
+def run_reset_intf(intf, iftypes, vif, vrrp):
+ for interface in filtered_interfaces(ifnames, iftypes, vif, vrrp):
+ interface = Interface(ifname, create=False, debug=False)
+ interface.operational.reset_counters()
+
+
+if __name__ == '__main__':
+ parser = argparse.ArgumentParser(add_help=False, description='Show interface information')
+ parser.add_argument('--intf', action="store", type=str, default='', help='only show the specified interface(s)')
+ parser.add_argument('--intf-type', action="store", type=str, default='', help='only show the specified interface type')
+ parser.add_argument('--action', action="store", type=str, default='show', help='action to perform')
+ parser.add_argument('--vif', action='store_true', default=False, help="only show vif interfaces")
+ parser.add_argument('--vrrp', action='store_true', default=False, help="only show vrrp interfaces")
+ parser.add_argument('--help', action='store_true', default=False, help="show help")
+
+ args = parser.parse_args()
+
+ def missing(*args):
+ print('Invalid action [{args.action}]')
+ usage()
+
+ actions.get(args.action, missing)(
+ [_ for _ in args.intf.split(' ') if _],
+ [_ for _ in args.intf_type.split(' ') if _],
+ args.vif,
+ args.vrrp
+ )
diff --git a/src/op_mode/vrrp.py b/src/op_mode/vrrp.py
index 8a993f92c..923cfa4d4 100755
--- a/src/op_mode/vrrp.py
+++ b/src/op_mode/vrrp.py
@@ -1,125 +1,52 @@
#!/usr/bin/env python3
#
# Copyright (C) 2018 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 sys
import time
import argparse
import json
import tabulate
import vyos.keepalived
import vyos.util
-config_dict_path = '/run/keepalived_config.dict'
-
-
-# get disabled instances from a config
-def vrrp_get_disabled():
- # read the dictionary file with configuration
- with open(config_dict_path, 'r') as dict_file:
- vrrp_config_dict = json.load(dict_file)
- vrrp_disabled = []
- # add disabled groups to the list
- for vrrp_group in vrrp_config_dict['vrrp_groups']:
- if vrrp_group['disable']:
- vrrp_disabled.append([vrrp_group['name'], vrrp_group['interface'], vrrp_group['vrid'], 'DISABLED', ''])
- # return list with disabled instances
- return vrrp_disabled
-
-
-def print_summary():
- try:
- vyos.keepalived.force_json_dump()
- # Wait for keepalived to produce the data
- # Replace with inotify or similar if it proves problematic
- time.sleep(0.2)
- json_data = vyos.keepalived.get_json_data()
- vyos.keepalived.remove_vrrp_data("json")
- except:
- print("VRRP information is not available")
- sys.exit(1)
-
- groups = []
- for group in json_data:
- data = group["data"]
-
- name = data["iname"]
-
- ltrans_timestamp = float(data["last_transition"])
- ltrans_time = vyos.util.seconds_to_human(int(time.time() - ltrans_timestamp))
-
- interface = data["ifp_ifname"]
- vrid = data["vrid"]
-
- state = vyos.keepalived.decode_state(data["state"])
-
- row = [name, interface, vrid, state, ltrans_time]
- groups.append(row)
-
- # add to the active list disabled instances
- groups.extend(vrrp_get_disabled())
- headers = ["Name", "Interface", "VRID", "State", "Last Transition"]
- output = tabulate.tabulate(groups, headers)
- print(output)
-
-
-def print_statistics():
- try:
- vyos.keepalived.force_stats_dump()
- time.sleep(0.2)
- output = vyos.keepalived.get_statistics()
- print(output)
- vyos.keepalived.remove_vrrp_data("stats")
- except:
- print("VRRP statistics are not available")
- sys.exit(1)
-
-
-def print_state_data():
- try:
- vyos.keepalived.force_state_data_dump()
- time.sleep(0.2)
- output = vyos.keepalived.get_state_data()
- print(output)
- vyos.keepalived.remove_vrrp_data("state")
- except:
- print("VRRP information is not available")
- sys.exit(1)
+from vyos.ifconfig.vrrp import VRRP
+from vyos.ifconfig.vrrp import VRRPError
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
group.add_argument("-s", "--summary", action="store_true", help="Print VRRP summary")
group.add_argument("-t", "--statistics", action="store_true", help="Print VRRP statistics")
group.add_argument("-d", "--data", action="store_true", help="Print detailed VRRP data")
args = parser.parse_args()
# Exit early if VRRP is dead or not configured
-if not vyos.keepalived.vrrp_running():
- print("VRRP is not running")
+if not VRRP.is_running():
+ print('VRRP is not running')
sys.exit(0)
if args.summary:
- print_summary()
+ print(VRRP.format(VRRP.collect('json')))
elif args.statistics:
- print_statistics()
+ print(VRRP.collect('stats'))
elif args.data:
- print_state_data()
+ print(VRRP.collect('state'))
else:
parser.print_help()
sys.exit(1)
diff --git a/src/op_mode/wireguard.py b/src/op_mode/wireguard.py
index 1b90f4fa7..297ba599d 100755
--- a/src/op_mode/wireguard.py
+++ b/src/op_mode/wireguard.py
@@ -1,160 +1,160 @@
#!/usr/bin/env python3
#
# Copyright (C) 2018-2020 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 argparse
import os
import sys
import shutil
import syslog as sl
import re
from vyos.ifconfig import WireGuardIf
from vyos import ConfigError
from vyos.config import Config
from vyos.util import cmd, run
dir = r'/config/auth/wireguard'
psk = dir + '/preshared.key'
def check_kmod():
""" check if kmod is loaded, if not load it """
if not os.path.exists('/sys/module/wireguard'):
sl.syslog(sl.LOG_NOTICE, "loading wirguard kmod")
if run('sudo modprobe wireguard') != 0:
sl.syslog(sl.LOG_ERR, "modprobe wireguard failed")
raise ConfigError("modprobe wireguard failed")
def generate_keypair(pk, pub):
""" generates a keypair which is stored in /config/auth/wireguard """
old_umask = os.umask(0o027)
if run(f'wg genkey | tee {pk} | wg pubkey > {pub}') != 0:
raise ConfigError("wireguard key-pair generation failed")
else:
sl.syslog(
sl.LOG_NOTICE, "new keypair wireguard key generated in " + dir)
os.umask(old_umask)
def genkey(location):
""" helper function to check, regenerate the keypair """
pk = "{}/private.key".format(location)
pub = "{}/public.key".format(location)
old_umask = os.umask(0o027)
if os.path.exists(pk) and os.path.exists(pub):
try:
choice = input(
"You already have a wireguard key-pair, do you want to re-generate? [y/n] ")
if choice == 'y' or choice == 'Y':
generate_keypair(pk, pub)
except KeyboardInterrupt:
sys.exit(0)
else:
""" if keypair is bing executed from a running iso """
if not os.path.exists(location):
run(f'sudo mkdir -p {location}')
run(f'sudo chgrp vyattacfg {location}')
run(f'sudo chmod 750 {location}')
generate_keypair(pk, pub)
os.umask(old_umask)
def showkey(key):
""" helper function to show privkey or pubkey """
if os.path.exists(key):
print (open(key).read().strip())
else:
print ("{} not found".format(key))
def genpsk():
"""
generates a preshared key and shows it on stdout,
it's stored only in the cli config
"""
psk = cmd('wg genpsk')
print(psk)
def list_key_dirs():
""" lists all dirs under /config/auth/wireguard """
if os.path.exists(dir):
nks = next(os.walk(dir))[1]
for nk in nks:
print (nk)
def del_key_dir(kname):
""" deletes /config/auth/wireguard/<kname> """
kdir = "{0}/{1}".format(dir,kname)
if not os.path.isdir(kdir):
print ("named keypair {} not found".format(kname))
return 1
shutil.rmtree(kdir)
if __name__ == '__main__':
check_kmod()
parser = argparse.ArgumentParser(description='wireguard key management')
parser.add_argument(
'--genkey', action="store_true", help='generate key-pair')
parser.add_argument(
'--showpub', action="store_true", help='shows public key')
parser.add_argument(
'--showpriv', action="store_true", help='shows private key')
parser.add_argument(
'--genpsk', action="store_true", help='generates preshared-key')
parser.add_argument(
'--location', action="store", help='key location within {}'.format(dir))
parser.add_argument(
'--listkdir', action="store_true", help='lists named keydirectories')
parser.add_argument(
'--delkdir', action="store_true", help='removes named keydirectories')
parser.add_argument(
'--showinterface', action="store", help='shows interface details')
args = parser.parse_args()
try:
if args.genkey:
if args.location:
genkey("{0}/{1}".format(dir, args.location))
else:
genkey("{}/default".format(dir))
if args.showpub:
if args.location:
showkey("{0}/{1}/public.key".format(dir, args.location))
else:
showkey("{}/default/public.key".format(dir))
if args.showpriv:
if args.location:
showkey("{0}/{1}/private.key".format(dir, args.location))
else:
showkey("{}/default/private.key".format(dir))
if args.genpsk:
genpsk()
if args.listkdir:
list_key_dirs()
if args.showinterface:
intf = WireGuardIf(args.showinterface, create=False, debug=False)
- intf.op_show_interface()
+ print(intf.operational.show_interface())
if args.delkdir:
if args.location:
del_key_dir(args.location)
else:
del_key_dir("default")
except ConfigError as e:
print(e)
sys.exit(1)

File Metadata

Mime Type
text/x-diff
Expires
Thu, Nov 26, 8:48 PM (1 d, 13 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
4986398
Default Alt Text
(113 KB)

Event Timeline