summaryrefslogtreecommitdiff
path: root/virtinst/interface.py
blob: c1e0c88d957b65a63c52789d779f5667cc99386f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#
# Copyright 2009, 2013 Red Hat, Inc.
# Cole Robinson <crobinso@redhat.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301 USA.
"""
Classes for building and installing libvirt interface xml
"""

import logging

import libvirt

from virtinst import util
from virtinst.xmlbuilder import XMLBuilder, XMLChildProperty, XMLProperty


class _IPAddress(XMLBuilder):
    _XML_PROP_ORDER = ["address", "prefix"]
    _XML_ROOT_NAME = "ip"

    address = XMLProperty("./@address")
    prefix = XMLProperty("./@prefix", is_int=True)


class InterfaceProtocol(XMLBuilder):
    INTERFACE_PROTOCOL_FAMILY_IPV4 = "ipv4"
    INTERFACE_PROTOCOL_FAMILY_IPV6 = "ipv6"
    INTERFACE_PROTOCOL_FAMILIES = [INTERFACE_PROTOCOL_FAMILY_IPV4,
                                    INTERFACE_PROTOCOL_FAMILY_IPV6]

    _XML_ROOT_NAME = "protocol"
    _XML_PROP_ORDER = ["autoconf", "dhcp", "dhcp_peerdns", "ips", "gateway"]

    family = XMLProperty("./@family")
    dhcp = XMLProperty("./dhcp", is_bool=True, doc=_("Whether to enable DHCP"))
    dhcp_peerdns = XMLProperty("./dhcp/@peerdns", is_yesno=True)
    gateway = XMLProperty("./route/@gateway", doc=_("Network gateway address"))
    autoconf = XMLProperty("./autoconf", is_bool=True,
        doc=_("Whether to enable IPv6 autoconfiguration"))


    #####################
    # IP child handling #
    #####################

    def add_ip(self, addr, prefix=None):
        ip = _IPAddress(self.conn)
        ip.address = addr
        ip.prefix = prefix
        self._add_child(ip)
    def remove_ip(self, ip):
        self._remove_child(ip)
        ip.clear()
    ips = XMLChildProperty(_IPAddress)


class Interface(XMLBuilder):
    """
    Base class for building any libvirt interface object.

    Mostly meaningless to directly instantiate.
    """

    INTERFACE_TYPE_BRIDGE   = "bridge"
    INTERFACE_TYPE_BOND     = "bond"
    INTERFACE_TYPE_ETHERNET = "ethernet"
    INTERFACE_TYPE_VLAN     = "vlan"
    INTERFACE_TYPES = [INTERFACE_TYPE_BRIDGE, INTERFACE_TYPE_BOND,
                       INTERFACE_TYPE_ETHERNET, INTERFACE_TYPE_VLAN]

    INTERFACE_START_MODE_NONE    = "none"
    INTERFACE_START_MODE_ONBOOT  = "onboot"
    INTERFACE_START_MODE_HOTPLUG = "hotplug"
    INTERFACE_START_MODES = [INTERFACE_START_MODE_NONE,
                             INTERFACE_START_MODE_ONBOOT,
                             INTERFACE_START_MODE_HOTPLUG]

    INTERFACE_BOND_MODES = ["active-backup", "balance-alb", "balance-rr",
                             "balance-tlb", "balance-xor", "broadcast",
                             "802.3ad"]

    INTERFACE_BOND_MONITOR_MODE_ARP = "arpmon"
    INTERFACE_BOND_MONITOR_MODE_MII = "miimon"
    INTERFACE_BOND_MONITOR_MODES    = [INTERFACE_BOND_MONITOR_MODE_ARP,
                                        INTERFACE_BOND_MONITOR_MODE_MII]

    INTERFACE_BOND_MONITOR_MODE_ARP_VALIDATE_MODES = ["active", "backup",
                                                       "all"]

    INTERFACE_BOND_MONITOR_MODE_MII_CARRIER_TYPES = ["netif", "ioctl"]


    @staticmethod
    def find_free_name(conn, prefix):
        """
        Generate an unused interface name based on prefix. For example,
        if prefix="br", we find the first unused name such as "br0", "br1",
        etc.
        """
        return util.generate_name(prefix, conn.interfaceLookupByName, sep="",
                                  force_num=True)

    _XML_ROOT_NAME = "interface"
    _XML_PROP_ORDER = ["type", "name", "start_mode", "macaddr", "mtu",
                       "stp", "delay", "bond_mode", "arp_interval",
                       "arp_target", "arp_validate_mode", "mii_frequency",
                       "mii_downdelay", "mii_updelay", "mii_carrier_mode",
                       "tag", "parent_interface",
                       "protocols", "interfaces"]

    ##################
    # Child handling #
    ##################

    def add_interface(self, obj):
        self._add_child(obj)
    def remove_interface(self, obj):
        self._remove_child(obj)
    # 'interfaces' property is added outside this class, since it needs
    # to reference the completed Interface class

    def add_protocol(self, obj):
        self._add_child(obj)
    def remove_protocol(self, obj):
        self._remove_child(obj)
    protocols = XMLChildProperty(InterfaceProtocol)


    ######################
    # Validation helpers #
    ######################

    def _validate_name(self, name):
        if name == self.name:
            return
        try:
            self.conn.interfaceLookupByName(name)
        except libvirt.libvirtError:
            return

        raise ValueError(_("Name '%s' already in use by another interface.") %
                           name)

    def _validate_mac(self, val):
        util.validate_macaddr(val)
        return val


    ##################
    # General params #
    ##################

    type = XMLProperty("./@type")
    mtu = XMLProperty("./mtu/@size", is_int=True,
                      doc=_("Maximum transmit size in bytes"))
    start_mode = XMLProperty("./start/@mode",
                             doc=_("When the interface will be auto-started."))

    name = XMLProperty("./@name", validate_cb=_validate_name,
                       doc=_("Name for the interface object."))

    macaddr = XMLProperty("./mac/@address", validate_cb=_validate_mac,
                          doc=_("Interface MAC address"))


    #################
    # Bridge params #
    #################

    stp = XMLProperty("./bridge/@stp", is_onoff=True,
                      doc=_("Whether STP is enabled on the bridge"))
    delay = XMLProperty("./bridge/@delay",
                        doc=_("Delay in seconds before forwarding begins when "
                              "joining a network."))

    ###############
    # Bond params #
    ###############

    bond_mode = XMLProperty("./bond/@mode",
                            doc=_("Mode of operation of the bonding device"))

    arp_interval = XMLProperty("./bond/arpmon/@interval", is_int=True,
                               doc=_("ARP monitoring interval in "
                                     "milliseconds"))
    arp_target = XMLProperty("./bond/arpmon/@target",
                             doc=_("IP target used in ARP monitoring packets"))
    arp_validate_mode = XMLProperty("./bond/arpmon/@validate",
                                    doc=_("ARP monitor validation mode"))

    mii_carrier_mode = XMLProperty("./bond/miimon/@carrier",
                                   doc=_("MII monitoring method."))
    mii_frequency = XMLProperty("./bond/miimon/@freq", is_int=True,
                                doc=_("MII monitoring interval in "
                                      "milliseconds"))
    mii_updelay = XMLProperty("./bond/miimon/@updelay", is_int=True,
                              doc=_("Time in milliseconds to wait before "
                                    "enabling a slave after link recovery "))
    mii_downdelay = XMLProperty("./bond/miimon/@downdelay", is_int=True,
                                doc=_("Time in milliseconds to wait before "
                                      "disabling a slave after link failure"))


    ###############
    # VLAN params #
    ###############

    tag = XMLProperty("./vlan/@tag", is_int=True,
                      doc=_("VLAN device tag number"))
    parent_interface = XMLProperty("./vlan/interface/@name",
                                   doc=_("Parent interface to create VLAN on"))


    ##################
    # Build routines #
    ##################

    def validate(self):
        if (self.type == self.INTERFACE_TYPE_VLAN and
            (self.tag is None or self.parent_interface is None)):
            raise ValueError(_("VLAN Tag and parent interface are required."))

    def install(self, meter=None, create=True):
        """
        Install network interface xml.
        """
        xml = self.get_xml_config()
        logging.debug("Creating interface '%s' with xml:\n%s",
                      self.name, xml)

        try:
            iface = self.conn.interfaceDefineXML(xml, 0)
        except Exception, e:
            raise RuntimeError(_("Could not define interface: %s" % str(e)))

        errmsg = None
        if create and not errmsg:
            try:
                iface.create(0)
            except Exception, e:
                errmsg = _("Could not create interface: %s" % str(e))

        if errmsg:
            # Try and clean up the leftover pool
            try:
                iface.undefine()
            except Exception, e:
                logging.debug("Error cleaning up interface after failure: " +
                              "%s" % str(e))
            raise RuntimeError(errmsg)

        return iface

Interface.interfaces = XMLChildProperty(Interface,
                                        relative_xpath="./%(type)s")