From nobody Sat Nov 23 15:37:54 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) client-ip=8.43.85.245; envelope-from=devel-bounces@lists.libvirt.org; helo=lists.libvirt.org; Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) smtp.mailfrom=devel-bounces@lists.libvirt.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.libvirt.org (lists.libvirt.org [8.43.85.245]) by mx.zohomail.com with SMTPS id 172305140389560.109082197500584; Wed, 7 Aug 2024 10:23:23 -0700 (PDT) Received: by lists.libvirt.org (Postfix, from userid 996) id BA38F108B; Wed, 7 Aug 2024 13:23:22 -0400 (EDT) Received: from lists.libvirt.org (localhost [IPv6:::1]) by lists.libvirt.org (Postfix) with ESMTP id CD773135B; Wed, 7 Aug 2024 13:16:26 -0400 (EDT) Received: by lists.libvirt.org (Postfix, from userid 996) id 276A311A8; Wed, 7 Aug 2024 13:16:13 -0400 (EDT) Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by lists.libvirt.org (Postfix) with ESMTPS id C2EA7C90 for ; Wed, 7 Aug 2024 13:16:11 -0400 (EDT) Received: from mx-prod-mc-01.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-377-mMd8lHZjPr2KEyOBfUftfw-1; Wed, 07 Aug 2024 13:16:07 -0400 Received: from mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.17]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id C876019560A6 for ; Wed, 7 Aug 2024 17:16:05 +0000 (UTC) Received: from vhost3.router.laine.org (unknown [10.22.32.31]) by mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 55BE519560A3 for ; Wed, 7 Aug 2024 17:16:05 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on lists.libvirt.org X-Spam-Level: X-Spam-Status: No, score=-0.8 required=5.0 tests=DKIM_INVALID,DKIM_SIGNED, HEADER_FROM_DIFFERENT_DOMAINS,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE, RCVD_IN_MSPIKE_H3,RCVD_IN_MSPIKE_WL,SPF_HELO_NONE autolearn=unavailable autolearn_force=no version=3.4.4 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1723050971; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=Dk3ig8V/Oj+42y38nWI+QEVkZBiEOh9aZ8n7SLgwCns=; b=O9/PL0NTkYLE6aIdIUtirLTJ/FNhzos1/yjFm1WZaCJIIw/4er0+r5IgdBVucXJxzbOupp J7LeQKMLslUgqo0mzljSv4HVwd1Wbs2FiIqwOAGFkqAvF20qkmRPT/XpNrfdqlKNIiEjgB nL0sySoOqUgQiwz/g4oXy3AtY0ODHRE= X-MC-Unique: mMd8lHZjPr2KEyOBfUftfw-1 From: Laine Stump To: devel@lists.libvirt.org Subject: [PATCH 1/7] conf: add XML config for autoaddr networks Date: Wed, 7 Aug 2024 13:15:57 -0400 Message-ID: <20240807171603.218784-2-laine@redhat.com> In-Reply-To: <20240807171603.218784-1-laine@redhat.com> References: <20240807171603.218784-1-laine@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.0 on 10.30.177.17 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: quoted-printable Message-ID-Hash: 3ZDCQNTJ6DF6OC26FO2EGMLACON3Y77C X-Message-ID-Hash: 3ZDCQNTJ6DF6OC26FO2EGMLACON3Y77C X-MailFrom: laine@redhat.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; emergency; loop; banned-address; member-moderation; header-match-config-1; header-match-config-2; header-match-config-3; header-match-devel.lists.libvirt.org-0; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; suspicious-header X-Mailman-Version: 3.2.2 Precedence: list List-Id: Development discussions about the libvirt library & tools Archived-At: List-Archive: List-Help: List-Post: List-Subscribe: List-Unsubscribe: X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1723051404220116600 Content-Type: text/plain; charset="utf-8"; x-default="true" If the element of a network has the attribute autoaddr=3D'yes', any specified IP address, netmask, prefix, or dhcp range will be used as a hint, but if the current network is already present in the host's routing table (i.e. it is in use) then libvirt will instead automatically find an unused subnet "somewhere", and use that instead. Since this patch is just the XML config bits, it has none of the details about how an unused subnet is found. That is coming later. autoaddr=3D'yes' is currently only supported for IPv4. IPv6 autoaddr should work differently (rather than selecting from a manually configured range of networks, I *think* it should semi-randomly select a network ala RFC 4193, and anyway conflicting IPv6 networks hasn't been an issue up to now). Signed-off-by: Laine Stump --- docs/formatnetwork.rst | 42 ++++++++++- src/conf/network_conf.c | 75 ++++++++++++++----- src/conf/network_conf.h | 7 ++ src/conf/schemas/network.rng | 5 ++ .../networkxml2xmlin/nat-network-autoaddr.xml | 11 +++ .../nat-network-autoaddr.xml | 11 +++ tests/networkxml2xmltest.c | 1 + 7 files changed, 132 insertions(+), 20 deletions(-) create mode 100644 tests/networkxml2xmlin/nat-network-autoaddr.xml create mode 100644 tests/networkxml2xmlout/nat-network-autoaddr.xml diff --git a/docs/formatnetwork.rst b/docs/formatnetwork.rst index 9b4ecbf31d..9c5e974002 100644 --- a/docs/formatnetwork.rst +++ b/docs/formatnetwork.rst @@ -805,8 +805,27 @@ of 'route' or 'nat'. divisible by 4 for IPv6) libvirt may be unable to compute the PTR domain automatically. The ``ip`` element is supported :since:`since 0.3.0`. IP= v6, multiple addresses on a single network, ``family``, and ``prefix`` are - supported :since:`since 0.8.7`. The ``ip`` element may contain the foll= owing - elements: + supported :since:`since 0.8.7`. + + Instead of (or in addition to) an IPv4 address and prefix (or + netmask), the attribute ``autoaddr`` can be set to ``yes``, and in + this case libvirt will search through a range of IPv4 subnets + (configured with the autoaddr_* settings in + /etc/libvirt/network.conf) to find an unused subnet :since: `since + 10.7.0`. If an address has been specified in addition to + ``autoaddr=3D'yes'`` then that address will be tried first, before + looking to the range given in network.conf. In any case, once an + unused subnet has been found, any dhcp range, static IP addresses, + or tftp boot servers will have the network part of their address + changed to the new subnet (if no ``address`` was given in the + config, the address will be set to the ".1" address on the newly + chosen network, and if there is an empty ```` subelement, it + will be given a range equal to the entire subnet exceot the ".1" + address). Once this is done, the updated network config is saved by + libvirt so that libvirt can attempt to use the same subnet the next + time the network is started. + + The ``ip`` element may contain the following sub-elements: =20 ``tftp`` The optional ``tftp`` element and its mandatory ``root`` attribute e= nable @@ -859,6 +878,11 @@ of 'route' or 'nat'. except when setting an infinite lease time (``expiry=3D'0'``). :since:`Since 6.3.0` =20 + If the ``ip`` element has ``autoaddr=3D'yes'``, then the ``dhcp`` + element can be empty, and in this case libvirt automatically + adds a ``range`` equivalent to the entire subnet (minus the .1 + address for the bridge device itself). :since: `Since 10.7.0` + Network namespaces ~~~~~~~~~~~~~~~~~~ =20 @@ -928,6 +952,20 @@ definition. =20 +And here is a NAT network that has its subnet (and thus its ip address +and dhcp range) chosen automatically by libvirt from the range of +"autoaddr" subnets configured in network.conf: + +:: + + + automagic + + + + + + IPv6 NAT based network ~~~~~~~~~~~~~~~~~~~~~~ =20 diff --git a/src/conf/network_conf.c b/src/conf/network_conf.c index 3af4e1d036..2a6b95e7ac 100644 --- a/src/conf/network_conf.c +++ b/src/conf/network_conf.c @@ -599,7 +599,8 @@ virNetworkDHCPHostDefParseXML(const char *networkName, static int virNetworkDHCPDefParseXML(const char *networkName, xmlNodePtr node, - virNetworkIPDef *def) + virNetworkIPDef *def, + bool isIPv4) { =20 g_autoptr(GPtrArray) rangeNodes =3D virXMLNodeGetSubelementList(node, = "range"); @@ -607,6 +608,7 @@ virNetworkDHCPDefParseXML(const char *networkName, xmlNodePtr bootp =3D virXMLNodeGetSubelement(node, "bootp"); size_t i; =20 + def->dhcp =3D true; for (i =3D 0; i < rangeNodes->len; i++) { virNetworkDHCPRangeDef range =3D { 0 }; =20 @@ -629,8 +631,7 @@ virNetworkDHCPDefParseXML(const char *networkName, VIR_APPEND_ELEMENT(def->hosts, def->nhosts, host); } =20 - if (bootp && - VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) { + if (bootp && isIPv4) { g_autofree char *server =3D virXMLPropString(bootp, "server"); =20 if (!(def->bootfile =3D virXMLPropStringRequired(bootp, "file"))) @@ -991,24 +992,28 @@ virNetworkIPDefParseXML(const char *networkName, g_autofree char *address =3D NULL; g_autofree char *netmask =3D NULL; int ret =3D -1; + bool isIPv4 =3D true; =20 ctxt->node =3D node; =20 /* grab raw data from XML */ def->family =3D virXPathString("string(./@family)", ctxt); + if (STREQ_NULLABLE(def->family, "ipv6")) + isIPv4 =3D false; =20 - address =3D virXPathString("string(./@address)", ctxt); - if (!address) { - virReportError(VIR_ERR_XML_ERROR, - _("Missing required address attribute in network '%= 1$s'"), - networkName); - goto cleanup; - } - if (virSocketAddrParse(&def->address, address, AF_UNSPEC) < 0) { - virReportError(VIR_ERR_XML_ERROR, - _("Invalid address '%1$s' in network '%2$s'"), - address, networkName); + if (virXMLPropTristateBool(node, "autoaddr", VIR_XML_PROP_NONE, &def->= autoaddr) < 0) goto cleanup; + + address =3D virXPathString("string(./@address)", ctxt); + + if (address) { + if (virSocketAddrParse(&def->address, address, AF_UNSPEC) < 0) { + virReportError(VIR_ERR_XML_ERROR, + _("Invalid address '%1$s' in network '%2$s'"), + address, networkName); + goto cleanup; + } + isIPv4 =3D VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET); } =20 netmask =3D virXPathString("string(./@netmask)", ctxt); @@ -1028,6 +1033,27 @@ virNetworkIPDefParseXML(const char *networkName, &def->localPTR) < 0) goto cleanup; =20 + switch (def->autoaddr) { + case VIR_TRISTATE_BOOL_NO: + case VIR_TRISTATE_BOOL_ABSENT: + case VIR_TRISTATE_BOOL_LAST: + if (!address) { + virReportError(VIR_ERR_XML_ERROR, + _("Missing required address attribute in networ= k '%1$s'"), + networkName); + goto cleanup; + } + break; + case VIR_TRISTATE_BOOL_YES: + if (!isIPv4) { + virReportError(VIR_ERR_XML_ERROR, + _("autoaddr=3D'yes' is only supported for IPv4 = in network '%1$s'"), + networkName); + goto cleanup; + } + break; + } + /* validate address, etc. for each family */ if ((def->family =3D=3D NULL) || (STREQ(def->family, "ipv4"))) { if (!(VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET) || @@ -1057,7 +1083,8 @@ virNetworkIPDefParseXML(const char *networkName, goto cleanup; } } else if (STREQ(def->family, "ipv6")) { - if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET6)) { + if (!(VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET6) || + VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_UNSPEC))) { virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("Family 'ipv6' specified for non-IPv6 address= '%1$s' in network '%2$s'"), address, networkName); @@ -1083,11 +1110,11 @@ virNetworkIPDefParseXML(const char *networkName, } =20 if ((dhcp =3D virXPathNode("./dhcp[1]", ctxt)) && - virNetworkDHCPDefParseXML(networkName, dhcp, def) < 0) + virNetworkDHCPDefParseXML(networkName, dhcp, def, isIPv4) < 0) goto cleanup; =20 if (virXPathNode("./tftp[1]", ctxt)) { - if (!VIR_SOCKET_ADDR_IS_FAMILY(&def->address, AF_INET)) { + if (!isIPv4) { virReportError(VIR_ERR_CONFIG_UNSUPPORTED, _("Unsupported element in an IPv6 elemen= t in network '%1$s'"), networkName); @@ -2045,6 +2072,11 @@ virNetworkIPDefFormat(virBuffer *buf, =20 if (def->family) virBufferAsprintf(buf, " family=3D'%s'", def->family); + + if (def->autoaddr !=3D VIR_TRISTATE_BOOL_ABSENT) + virBufferAsprintf(buf, " autoaddr=3D'%s'", + virTristateBoolTypeToString(def->autoaddr)); + if (VIR_SOCKET_ADDR_VALID(&def->address)) { g_autofree char *addr =3D virSocketAddrFormat(&def->address); if (!addr) @@ -2072,7 +2104,14 @@ virNetworkIPDefFormat(virBuffer *buf, virBufferEscapeString(buf, "\n", def->tftproot); } - if ((def->nranges || def->nhosts)) { + + if (!(def->nranges || def->nhosts)) { + /* in case an empty (with no subelements) + * was specified + */ + if (def->dhcp) + virBufferAddLit(buf, "\n"); + } else { size_t i; virBufferAddLit(buf, "\n"); virBufferAdjustIndent(buf, 2); diff --git a/src/conf/network_conf.h b/src/conf/network_conf.h index c2a4198abc..d44984e71a 100644 --- a/src/conf/network_conf.h +++ b/src/conf/network_conf.h @@ -158,6 +158,12 @@ struct _virNetworkDNSDef { typedef struct _virNetworkIPDef virNetworkIPDef; struct _virNetworkIPDef { char *family; /* ipv4 or ipv6 - default is ipv4 */ + + /* automatically determine IP address when the network is started. + * default is 'no' + */ + virTristateBool autoaddr; + virSocketAddr address; /* Bridge IP address */ =20 /* One or the other of the following two will be used for a given @@ -171,6 +177,7 @@ struct _virNetworkIPDef { =20 virTristateBool localPTR; =20 + bool dhcp; /* true if there is a element */ size_t nranges; /* Zero or more dhcp ranges */ virNetworkDHCPRangeDef *ranges; =20 diff --git a/src/conf/schemas/network.rng b/src/conf/schemas/network.rng index b7c8551fad..64d4818e96 100644 --- a/src/conf/schemas/network.rng +++ b/src/conf/schemas/network.rng @@ -354,6 +354,11 @@ + + + + + diff --git a/tests/networkxml2xmlin/nat-network-autoaddr.xml b/tests/networ= kxml2xmlin/nat-network-autoaddr.xml new file mode 100644 index 0000000000..71167285e6 --- /dev/null +++ b/tests/networkxml2xmlin/nat-network-autoaddr.xml @@ -0,0 +1,11 @@ + + default + 81ff0d90-c91e-6742-64da-4a736edb9a9b + + + + + + + + diff --git a/tests/networkxml2xmlout/nat-network-autoaddr.xml b/tests/netwo= rkxml2xmlout/nat-network-autoaddr.xml new file mode 100644 index 0000000000..629710175c --- /dev/null +++ b/tests/networkxml2xmlout/nat-network-autoaddr.xml @@ -0,0 +1,11 @@ + + default + 81ff0d90-c91e-6742-64da-4a736edb9a9b + + + + + + + + diff --git a/tests/networkxml2xmltest.c b/tests/networkxml2xmltest.c index 0783d84915..de8abefe42 100644 --- a/tests/networkxml2xmltest.c +++ b/tests/networkxml2xmltest.c @@ -137,6 +137,7 @@ mymain(void) DO_TEST("nat-network-forward-nat-address"); DO_TEST("nat-network-forward-nat-no-address"); DO_TEST("nat-network-mtu"); + DO_TEST("nat-network-autoaddr"); DO_TEST("8021Qbh-net"); DO_TEST("direct-net"); DO_TEST("host-bridge-net"); --=20 2.45.2 From nobody Sat Nov 23 15:37:54 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) client-ip=8.43.85.245; envelope-from=devel-bounces@lists.libvirt.org; helo=lists.libvirt.org; Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) smtp.mailfrom=devel-bounces@lists.libvirt.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.libvirt.org (lists.libvirt.org [8.43.85.245]) by mx.zohomail.com with SMTPS id 1723051180809151.0289403174412; Wed, 7 Aug 2024 10:19:40 -0700 (PDT) Received: by lists.libvirt.org (Postfix, from userid 996) id B2DD3D82; Wed, 7 Aug 2024 13:19:39 -0400 (EDT) Received: from lists.libvirt.org (localhost [IPv6:::1]) by lists.libvirt.org (Postfix) with ESMTP id 99CEB12B7; Wed, 7 Aug 2024 13:16:15 -0400 (EDT) Received: by lists.libvirt.org (Postfix, from userid 996) id 7C909C2F; Wed, 7 Aug 2024 13:16:09 -0400 (EDT) Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by lists.libvirt.org (Postfix) with ESMTPS id B7217C92 for ; Wed, 7 Aug 2024 13:16:08 -0400 (EDT) Received: from mx-prod-mc-02.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-447-iuB4Q-XdMo2A0nAGJVVl6w-1; Wed, 07 Aug 2024 13:16:07 -0400 Received: from mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.17]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-02.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 4DA361955F4B for ; Wed, 7 Aug 2024 17:16:06 +0000 (UTC) Received: from vhost3.router.laine.org (unknown [10.22.32.31]) by mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id E609519560A3 for ; Wed, 7 Aug 2024 17:16:05 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on lists.libvirt.org X-Spam-Level: X-Spam-Status: No, score=-0.8 required=5.0 tests=DKIM_INVALID,DKIM_SIGNED, HEADER_FROM_DIFFERENT_DOMAINS,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE, RCVD_IN_MSPIKE_H3,RCVD_IN_MSPIKE_WL,SPF_HELO_NONE autolearn=unavailable autolearn_force=no version=3.4.4 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1723050968; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=O53itCshRN1BZjRSK9zK0goqi6F/lNI0Ct/2ajpU/P0=; b=OJPReaKYdh2PF8kxWaUubZhX4G8i08eZqCTZZ9BCr4wYVCyJv/YlUMduuGn6Xd6sZI1PZw kAY3K/P2xgBak6tqXy8HDrSdVVjRBLNs4VUO7QR5g8ZgcKaCYEzdnIgmz25Be5jeLjUWhB T49a0x1fI85taLYrvkPhV0FT0T41cuo= X-MC-Unique: iuB4Q-XdMo2A0nAGJVVl6w-1 From: Laine Stump To: devel@lists.libvirt.org Subject: [PATCH 2/7] network: add configurable network autoaddr items to driver config Date: Wed, 7 Aug 2024 13:15:58 -0400 Message-ID: <20240807171603.218784-3-laine@redhat.com> In-Reply-To: <20240807171603.218784-1-laine@redhat.com> References: <20240807171603.218784-1-laine@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.0 on 10.30.177.17 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: quoted-printable Message-ID-Hash: 42EVR5F4AGQBYIH3KUWWRSIZ7ZLG6LE7 X-Message-ID-Hash: 42EVR5F4AGQBYIH3KUWWRSIZ7ZLG6LE7 X-MailFrom: laine@redhat.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; emergency; loop; banned-address; member-moderation; header-match-config-1; header-match-config-2; header-match-config-3; header-match-devel.lists.libvirt.org-0; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; suspicious-header X-Mailman-Version: 3.2.2 Precedence: list List-Id: Development discussions about the libvirt library & tools Archived-At: List-Archive: List-Help: List-Post: List-Subscribe: List-Unsubscribe: X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1723051181197116600 Content-Type: text/plain; charset="utf-8"; x-default="true" These options are added to network.conf and virNetworkDriverConfig object: autoaddr_start - start of the range of subnets to search (def: "192.168.122= .0") autoaddr_end - end of the range of subnets (def: "192.168.255.0") autoaddr_prefix - prefix of these subnets (def: 24) They will be used by the network driver when looking for unused subnets to assign to networks that have "autoaddr=3D'yes'" in one of their elements. Signed-off-by: Laine Stump --- meson.build | 14 +++++- meson_options.txt | 4 ++ src/network/bridge_driver_conf.c | 61 ++++++++++++++++++++++++ src/network/bridge_driver_conf.h | 4 ++ src/network/libvirtd_network.aug | 8 +++- src/network/meson.build | 6 +++ src/network/network.conf.in | 11 +++++ src/network/test_libvirtd_network.aug.in | 3 ++ 8 files changed, 109 insertions(+), 2 deletions(-) diff --git a/meson.build b/meson.build index 06d88ad1f3..71da7db741 100644 --- a/meson.build +++ b/meson.build @@ -1646,6 +1646,15 @@ endif if not get_option('driver_network').disabled() and conf.has('WITH_LIBVIRTD= ') conf.set('WITH_NETWORK', 1) =20 + autoaddr_start =3D get_option('autoaddr_start') + conf.set_quoted('AUTOADDR_START', autoaddr_start) + + autoaddr_end =3D get_option('autoaddr_end') + conf.set_quoted('AUTOADDR_END', autoaddr_end) + + autoaddr_prefix =3D get_option('autoaddr_prefix') + conf.set('AUTOADDR_PREFIX', autoaddr_prefix) + firewall_backend_priority =3D get_option('firewall_backend_priority') if firewall_backend_priority.length() =3D=3D 0 if host_machine.system() =3D=3D 'linux' @@ -2406,7 +2415,10 @@ misc_summary =3D { } if conf.has('WITH_NETWORK') misc_summary +=3D { - 'firewall backends': firewall_backend_priority, + 'autoaddr_start': autoaddr_start, + 'autoaddr_end': autoaddr_end, + 'autoaddr_prefix': autoaddr_prefix, + 'firewall backends': firewall_backend_priority, } endif summary(misc_summary, section: 'Miscellaneous', bool_yn: true, list_sep: '= ') diff --git a/meson_options.txt b/meson_options.txt index 2d440c63d8..7a1a86211e 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -118,6 +118,10 @@ option('firewalld', type: 'feature', value: 'auto', de= scription: 'firewalld supp # dep:firewalld option('firewalld_zone', type: 'feature', value: 'auto', description: 'whe= ther to install firewalld libvirt zone') option('firewall_backend_priority', type: 'array', choices: ['nftables', '= iptables'], value: [], description: 'order in which to try firewall backend= s') +option('autoaddr_start', type: 'string', value: '192.168.122.0', descripti= on: 'Start of range of IPv4 subnets to choose an unused subnet from') +option('autoaddr_end', type: 'string', value: '192.168.255.0', description= : 'End of range of IPv4 subnets to choose an unused subnet from') +option('autoaddr_prefix', type: 'integer', value: 24, description: 'prefix= of IPv4 subnets to choose an unused subnet from') + option('host_validate', type: 'feature', value: 'auto', description: 'buil= d virt-host-validate') option('init_script', type: 'combo', choices: ['systemd', 'openrc', 'check= ', 'none'], value: 'check', description: 'Style of init script to install') option('loader_nvram', type: 'string', value: '', description: 'Pass list = of pairs of : paths. Both pairs and list items are separated= by a colon.') diff --git a/src/network/bridge_driver_conf.c b/src/network/bridge_driver_c= onf.c index 9da5e790b7..cb2915550f 100644 --- a/src/network/bridge_driver_conf.c +++ b/src/network/bridge_driver_conf.c @@ -65,6 +65,13 @@ virNetworkLoadDriverConfig(virNetworkDriverConfig *cfg G= _GNUC_UNUSED, const char *filename) { g_autoptr(virConf) conf =3D NULL; + + const char *autoaddrStart =3D "192.168.122.0"; + const char *autoaddrEnd =3D "192.168.255.0"; + unsigned int autoaddrPrefix =3D 24; + g_autofree char *autoaddrStartFromConf =3D NULL; + g_autofree char *autoaddrEndFromConf =3D NULL; + g_autofree char *fwBackendStr =3D NULL; bool fwBackendSelected =3D false; size_t i; @@ -88,6 +95,36 @@ virNetworkLoadDriverConfig(virNetworkDriverConfig *cfg G= _GNUC_UNUSED, =20 /* use virConfGetValue*(conf, ...) functions to read any settings = into cfg */ =20 + if (virConfGetValueString(conf, "autoaddr_start", &autoaddrStartFr= omConf) < 0) + return -1; + if (autoaddrStartFromConf) { + VIR_DEBUG("autoaddr_start setting requested from config file %= s: '%s'", + filename, autoaddrStartFromConf); + autoaddrStart =3D autoaddrStartFromConf; + } + + if (virConfGetValueString(conf, "autoaddr_end", &autoaddrEndFromCo= nf) < 0) + return -1; + if (autoaddrEndFromConf) { + VIR_DEBUG("autoaddr_end setting requested from config file %s:= '%s'", + filename, autoaddrEndFromConf); + autoaddrEnd =3D autoaddrEndFromConf; + } + + switch (virConfGetValueUInt(conf, "autoaddr_prefix", &autoaddrPref= ix)) { + case 1: + VIR_DEBUG("autoaddr_prefix setting requested from config file = %s: '%u'", + filename, autoaddrPrefix); + break; + + case 0: + break; + + case -1: + default: + return -1; + } + if (virConfGetValueString(conf, "firewall_backend", &fwBackendStr)= < 0) return -1; =20 @@ -106,6 +143,30 @@ virNetworkLoadDriverConfig(virNetworkDriverConfig *cfg= G_GNUC_UNUSED, } } =20 + if (virSocketAddrParse(&cfg->autoaddrStart, autoaddrStart, AF_INET) < = 0) { + virReportError(VIR_ERR_INTERNAL_ERROR, + _("invalid autoaddr_start '%1$s' in network driver = config file %2$s, must be numeric IPv4 network address"), + autoaddrStart, filename); + return -1; + } + + if (virSocketAddrParse(&cfg->autoaddrEnd, autoaddrEnd, AF_INET) < 0) { + virReportError(VIR_ERR_INTERNAL_ERROR, + _("invalid autoaddr_end '%1$s' in network driver co= nfig file %2$s, must be numeric IPv4 network address"), + autoaddrStart, filename); + return -1; + } + + if ((cfg->autoaddrPrefix =3D autoaddrPrefix) > 32) { + virReportError(VIR_ERR_CONFIG_UNSUPPORTED, + _("Invalid IPv4 prefix '%1$u' in network driver con= fig file %2$s"), + autoaddrPrefix, filename); + return -1; + } + + VIR_INFO("autoaddr_start=3D'%s' autoaddr_end=3D'%s' autoaddr_prefix=3D= '%u'", + autoaddrStart, autoaddrEnd, autoaddrPrefix); + for (i =3D 0; i < nFwBackends && !fwBackendSelected; i++) { =20 switch ((virFirewallBackend)fwBackends[i]) { diff --git a/src/network/bridge_driver_conf.h b/src/network/bridge_driver_c= onf.h index 8f221f391e..7ebf77037d 100644 --- a/src/network/bridge_driver_conf.h +++ b/src/network/bridge_driver_conf.h @@ -39,6 +39,10 @@ struct _virNetworkDriverConfig { char *pidDir; char *dnsmasqStateDir; =20 + virSocketAddr autoaddrStart; + virSocketAddr autoaddrEnd; + unsigned int autoaddrPrefix; + virFirewallBackend firewallBackend; }; =20 diff --git a/src/network/libvirtd_network.aug b/src/network/libvirtd_networ= k.aug index 5d6d72dd92..5212505e1f 100644 --- a/src/network/libvirtd_network.aug +++ b/src/network/libvirtd_network.aug @@ -22,10 +22,16 @@ module Libvirtd_network =3D let int_entry (kw:string) =3D [ key kw . value_sep . int_val ] let str_array_entry (kw:string) =3D [ key kw . value_sep . str_array_va= l ] =20 + let autoaddr_entry =3D str_entry "autoaddr_start" + | str_entry "autoaddr_end" + | int_entry "autoaddr_prefix" + let firewall_backend_entry =3D str_entry "firewall_backend" =20 (* Each entry in the config is one of the following *) - let entry =3D firewall_backend_entry + let entry =3D autoaddr_entry + | firewall_backend_entry + let comment =3D [ label "#comment" . del /#[ \t]*/ "# " . store /([^ \= t\n][^\n]*)?/ . del /\n/ "\n" ] let empty =3D [ label "#empty" . eol ] =20 diff --git a/src/network/meson.build b/src/network/meson.build index 07cd5cda55..8faff6eb1c 100644 --- a/src/network/meson.build +++ b/src/network/meson.build @@ -51,6 +51,9 @@ if conf.has('WITH_NETWORK') } =20 network_options_conf =3D configuration_data({ + 'AUTOADDR_START': autoaddr_start, + 'AUTOADDR_END': autoaddr_end, + 'AUTOADDR_PREFIX': autoaddr_prefix, 'FIREWALL_BACKEND_PRIORITY': ', '.join(firewall_backend_priority), 'FIREWALL_BACKEND': firewall_backend_priority[0], }) @@ -62,6 +65,9 @@ if conf.has('WITH_NETWORK') ) =20 network_options_hack_conf =3D configuration_data({ + 'AUTOADDR_START': autoaddr_start, + 'AUTOADDR_END': autoaddr_end, + 'AUTOADDR_PREFIX': autoaddr_prefix, 'FIREWALL_BACKEND_PRIORITY': ', '.join(firewall_backend_priority), 'FIREWALL_BACKEND': firewall_backend_priority[0], # This hack is necessary because the output file is going to be diff --git a/src/network/network.conf.in b/src/network/network.conf.in index 5ed64a04a5..83a27df04c 100644 --- a/src/network/network.conf.in +++ b/src/network/network.conf.in @@ -27,3 +27,14 @@ # reloaded using the new backend.) # #firewall_backend =3D "@FIREWALL_BACKEND@" +# +# autoaddr_start +# autoaddr_end +# autoaddr_prefix +# +# These three setting specify the range of subnets that should be used +# for networks that have "autoaddr=3D'yes'" +# +#autoaddr_start =3D "@AUTOADDR_START@" +#autoaddr_end =3D "@AUTOADDR_END@" +#autoaddr_prefix =3D @AUTOADDR_PREFIX@ diff --git a/src/network/test_libvirtd_network.aug.in b/src/network/test_li= bvirtd_network.aug.in index 9e29a9192f..6edcbaed62 100644 --- a/src/network/test_libvirtd_network.aug.in +++ b/src/network/test_libvirtd_network.aug.in @@ -3,3 +3,6 @@ module Test_libvirtd_network =3D =20 test Libvirtd_network.lns get conf =3D { "firewall_backend" =3D "@FIREWALL_BACKEND@" } +{ "autoaddr_start" =3D "@AUTOADDR_START@" } +{ "autoaddr_end" =3D "@AUTOADDR_END@" } +{ "autoaddr_prefix" =3D "@AUTOADDR_PREFIX@" } --=20 2.45.2 From nobody Sat Nov 23 15:37:54 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) client-ip=8.43.85.245; envelope-from=devel-bounces@lists.libvirt.org; helo=lists.libvirt.org; Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) smtp.mailfrom=devel-bounces@lists.libvirt.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.libvirt.org (lists.libvirt.org [8.43.85.245]) by mx.zohomail.com with SMTPS id 1723051222562872.0306831471031; Wed, 7 Aug 2024 10:20:22 -0700 (PDT) Received: by lists.libvirt.org (Postfix, from userid 996) id 7F81E11B0; Wed, 7 Aug 2024 13:20:21 -0400 (EDT) Received: from lists.libvirt.org (localhost [IPv6:::1]) by lists.libvirt.org (Postfix) with ESMTP id 008FA12DC; Wed, 7 Aug 2024 13:16:18 -0400 (EDT) Received: by lists.libvirt.org (Postfix, from userid 996) id 9AA49C92; Wed, 7 Aug 2024 13:16:10 -0400 (EDT) Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by lists.libvirt.org (Postfix) with ESMTPS id 9F89CC17 for ; Wed, 7 Aug 2024 13:16:09 -0400 (EDT) Received: from mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-672-8TOI5S_JNHqfvV81GJBZlg-1; Wed, 07 Aug 2024 13:16:07 -0400 Received: from mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.17]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id E3D8B1955F45 for ; Wed, 7 Aug 2024 17:16:06 +0000 (UTC) Received: from vhost3.router.laine.org (unknown [10.22.32.31]) by mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 899E519560A3 for ; Wed, 7 Aug 2024 17:16:06 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on lists.libvirt.org X-Spam-Level: X-Spam-Status: No, score=-0.8 required=5.0 tests=DKIM_INVALID,DKIM_SIGNED, HEADER_FROM_DIFFERENT_DOMAINS,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE, RCVD_IN_MSPIKE_H4,RCVD_IN_MSPIKE_WL,SPF_HELO_NONE autolearn=unavailable autolearn_force=no version=3.4.4 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1723050969; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=pvSKYGnWVs/YAjCtw1PJy50TWutzIE9Gs0L30P8fpY0=; b=QRGNq4kPXxwdeOanDwv0uOVDEcSRqnHSKRrw8qLPLIJgXNPNMy8qXa4O+uKFwjJRw66Bcs HPgBURl8SP6nnz+8GAIqJ30VQo6X+cNAT38s9puVa4Cj0G4itfVzz8iC6iJxNLS+f8In7b wQMKaUuiLVZ/pekgIL+TAxuNnMeYZqc= X-MC-Unique: 8TOI5S_JNHqfvV81GJBZlg-1 From: Laine Stump To: devel@lists.libvirt.org Subject: [PATCH 3/7] network: reorganize the check for route collisions Date: Wed, 7 Aug 2024 13:15:59 -0400 Message-ID: <20240807171603.218784-4-laine@redhat.com> In-Reply-To: <20240807171603.218784-1-laine@redhat.com> References: <20240807171603.218784-1-laine@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.0 on 10.30.177.17 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: quoted-printable Message-ID-Hash: YCKI2M36ENUCLBC6J7CR3XSQSK4OY5PH X-Message-ID-Hash: YCKI2M36ENUCLBC6J7CR3XSQSK4OY5PH X-MailFrom: laine@redhat.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; emergency; loop; banned-address; member-moderation; header-match-config-1; header-match-config-2; header-match-config-3; header-match-devel.lists.libvirt.org-0; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; suspicious-header X-Mailman-Version: 3.2.2 Precedence: list List-Id: Development discussions about the libvirt library & tools Archived-At: List-Archive: List-Help: List-Post: List-Subscribe: List-Unsubscribe: X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1723051223578116600 Content-Type: text/plain; charset="utf-8"; x-default="true" The existing code was checking all ip addresses and routes of the network as each line of /proc/net/route was read. This does not lend itself well to the new autoaddr networks, as each ip address will need to be checked against all routes in /proc/net/route (i.e. the opposite order of nesting the loops) in order to determine if the address must be changed to something unused (and then change it and recheck against all routes until an unused subnet is found). Now there is a separate function (still in bridge_driver_linux.c) that reads all the entries in /proc/net/route and adds them to a hash table, and another that checks an IP/prefix against said hash table. These two functions are called by networkCheckIPAddrCollision() and networkCheckRouteCollision() (split apart and moved to bridge_driver.c) which then iterates through each IP address/route of the virtual network, checking each against all existing routes before moving on to the next. Signed-off-by: Laine Stump --- src/network/bridge_driver.c | 72 ++++++++++++++- src/network/bridge_driver_linux.c | 132 +++++++++++++++------------ src/network/bridge_driver_nop.c | 22 +++-- src/network/bridge_driver_platform.h | 5 +- 4 files changed, 164 insertions(+), 67 deletions(-) diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c index 32572c755f..b8e752f20d 100644 --- a/src/network/bridge_driver.c +++ b/src/network/bridge_driver.c @@ -1898,6 +1898,65 @@ networkAddRouteToBridge(virNetworkObj *obj, } =20 =20 +/* XXX: This function can be a lot more exhaustive, there are certainly + * other scenarios where we can ruin host network connectivity. + * XXX: Using a proper library is preferred over parsing /proc + */ +static int +networkCheckIPAddrCollision(virNetworkDef *def, GHashTable *routes) +{ + size_t i; + virNetworkIPDef *ipdef; + + /* check all IPv4 addresses of the network for conflict with + * existing routes + */ + for (i =3D 0; (ipdef =3D virNetworkDefGetIPByIndex(def, AF_INET, i)); = i++) { + unsigned int prefix =3D virNetworkIPDefPrefix(ipdef); + const char *iface =3D networkSysRoutesTableFind(routes, &ipdef->ad= dress, prefix); + + if (iface) { + g_autofree char *addrStr =3D virSocketAddrFormat(&ipdef->addre= ss); + + virReportError(VIR_ERR_INTERNAL_ERROR, + _("requested subnet %1$s/%2$u is already in use= by interface %3$s"), + NULLSTR(addrStr), prefix, iface); + return -1; + } + } + + return 0; +} + + +static int +networkCheckRouteCollision(virNetworkDef *def, GHashTable *routes) +{ + size_t i; + virNetDevIPRoute *routedef; + + /* check all IPv4 host routes that will be added for this network + * for conflict with existing host routes + */ + for (i =3D 0; (routedef =3D virNetworkDefGetRouteByIndex(def, AF_INET,= i)); i++) { + virSocketAddr *addr =3D virNetDevIPRouteGetAddress(routedef); + int prefix =3D virNetDevIPRouteGetPrefix(routedef); + const char *iface =3D networkSysRoutesTableFind(routes, addr, pref= ix); + + if (iface) { + g_autofree char *addrStr =3D virSocketAddrFormat(addr); + + virReportError(VIR_ERR_INTERNAL_ERROR, + _("requested route for %1$s/%2$u is already in = use by interface %3$s"), + NULLSTR(addrStr), prefix, iface); + return -1; + } + } + + return 0; +} + + static int networkStartNetworkVirtual(virNetworkDriverState *driver, virNetworkObj *obj) @@ -1914,10 +1973,17 @@ networkStartNetworkVirtual(virNetworkDriverState *d= river, bool firewalRulesAdded =3D false; virSocketAddr *dnsServer =3D NULL; virFirewall *fwRemoval =3D NULL; + g_autoptr(GHashTable) routes =3D networkSysRoutesTableRead(); =20 - /* Check to see if any network IP collides with an existing route */ - if (networkCheckRouteCollision(def) < 0) - return -1; + if (routes) { + /* Check to see if any network IP collides with an existing route = on the host */ + if (networkCheckIPAddrCollision(def, routes) < 0) + return -1; + + /* also check for requested routes that collide with existing rout= es */ + if (networkCheckRouteCollision(def, routes) < 0) + return -1; + } =20 /* Create and configure the bridge device */ if (!def->bridge) { diff --git a/src/network/bridge_driver_linux.c b/src/network/bridge_driver_= linux.c index fe7c6e193c..1d6635743d 100644 --- a/src/network/bridge_driver_linux.c +++ b/src/network/bridge_driver_linux.c @@ -213,21 +213,53 @@ void networkPostReloadFirewallRules(bool startup G_GN= UC_UNUSED) } =20 =20 -/* XXX: This function can be a lot more exhaustive, there are certainly - * other scenarios where we can ruin host network connectivity. - * XXX: Using a proper library is preferred over parsing /proc +static void +networkPrintRouteTableEntry(gpointer key, + gpointer value, + gpointer user_data G_GNUC_UNUSED) +{ + const gint64 *keyval =3D key; + const char *valueval =3D value; + + VIR_INFO("key: %016llx value: %s", (unsigned long long)*keyval, valuev= al); +} +/** + * networkSysRoutesTableRead:: + * + * Returns a GHashTable that contains an entry for each IPv4 route in + * the host system routing table. + * + * The key for each entry is the network address and prefix for the + * route, and the "data" is the name of the interface associated with + * the route (which is only used for error reporting if a conflict is + * found). This will later be used to determine if a given subnet is + * already "in use" (which for our purposes is defined as "there is a + * route in the system routing table with exactly the same subnet + + * prefix/netmask"). + * + * In the case that no routes are found (e.g. due to some unexpected + * changed in the format of /proc/net/route) an empty GHashTable will + * be returned, in order to be as non-disruptive as possible. + * + * The returned GHashTable must be g_hash_table_destroy()ed when the + * caller is finished with it. This can be done automatically by + * defining it as g_autoptr(GHashTable). + * */ -int networkCheckRouteCollision(virNetworkDef *def) +GHashTable * +networkSysRoutesTableRead(void) { int len; char *cur; g_autofree char *buf =3D NULL; /* allow for up to 100000 routes (each line is 128 bytes) */ enum {MAX_ROUTE_SIZE =3D 128*100000}; + g_autoptr(GHashTable) routes =3D g_hash_table_new_full(g_int64_hash, g= _int64_equal, g_free, g_free); + =20 /* Read whole routing table into memory */ if ((len =3D virFileReadAll(PROC_NET_ROUTE, MAX_ROUTE_SIZE, &buf)) < 0) - return 0; + return g_steal_pointer(&routes); =20 /* Dropping the last character shouldn't hurt */ if (len > 0) @@ -236,7 +268,7 @@ int networkCheckRouteCollision(virNetworkDef *def) VIR_DEBUG("%s output:\n%s", PROC_NET_ROUTE, buf); =20 if (!STRPREFIX(buf, "Iface")) - return 0; + return g_steal_pointer(&routes); =20 /* First line is just headings, skip it */ cur =3D strchr(buf, '\n'); @@ -245,11 +277,9 @@ int networkCheckRouteCollision(virNetworkDef *def) =20 while (cur) { char iface[17], dest[128], mask[128]; - unsigned int addr_val, mask_val; - virNetworkIPDef *ipdef; - virNetDevIPRoute *routedef; int num; - size_t i; + unsigned int addr_val, mask_val; + g_autofree gint64 *key =3D g_new(gint64, 1); =20 /* NUL-terminate the line, so sscanf doesn't go beyond a newline. = */ char *nl =3D strchr(cur, '\n'); @@ -275,60 +305,48 @@ int networkCheckRouteCollision(virNetworkDef *def) continue; } =20 - addr_val &=3D mask_val; + /* NB: addr_val and mask_val both appear in the file as + * hexadecimal strings that, when converted into integers on + * little-endian hardware, will already be in network byte + * order! (e.g., the IP address 1.2.3.4 will show up as + * "04030201" in the file). When we are later looking up an + * address in the table, we will also be using network byte + * order, so we don't need to do any htonl() here. + */ + *key =3D ((gint64)(addr_val & mask_val) << 32) + mask_val; + VIR_DEBUG("addr_val: %08u mask_val: %08u key: %016llx iface: %s", + addr_val, mask_val, (unsigned long long)*key, iface); =20 - for (i =3D 0; - (ipdef =3D virNetworkDefGetIPByIndex(def, AF_INET, i)); - i++) { + g_hash_table_replace(routes, g_steal_pointer(&key), g_strdup(iface= )); + } =20 - unsigned int net_dest; - virSocketAddr netmask; + VIR_INFO("Full Route Hash Table: sizeof(gint64): %d sizeof(long long u= nsigned): %d", + (int)sizeof(gint64), (int)sizeof(long long unsigned)); + g_hash_table_foreach(routes, networkPrintRouteTableEntry, NULL); =20 - if (virNetworkIPDefNetmask(ipdef, &netmask) < 0) { - VIR_WARN("Failed to get netmask of '%s'", - def->bridge); - continue; - } + return g_steal_pointer(&routes); +} =20 - net_dest =3D (ipdef->address.data.inet4.sin_addr.s_addr & - netmask.data.inet4.sin_addr.s_addr); =20 - if ((net_dest =3D=3D addr_val) && - (netmask.data.inet4.sin_addr.s_addr =3D=3D mask_val)) { - virReportError(VIR_ERR_INTERNAL_ERROR, - _("Network is already in use by interface %= 1$s"), - iface); - return -1; - } - } +const char * +networkSysRoutesTableFind(GHashTable *routesTable, + virSocketAddr *addr, + unsigned int prefix) +{ + virSocketAddr netaddr, netmask; + gint64 compare; =20 - for (i =3D 0; - (routedef =3D virNetworkDefGetRouteByIndex(def, AF_INET, i)); - i++) { - - virSocketAddr r_mask, r_addr; - virSocketAddr *tmp_addr =3D virNetDevIPRouteGetAddress(routede= f); - int r_prefix =3D virNetDevIPRouteGetPrefix(routedef); - - if (!tmp_addr || - virSocketAddrMaskByPrefix(tmp_addr, r_prefix, &r_addr) < 0= || - virSocketAddrPrefixToNetmask(r_prefix, &r_mask, AF_INET) <= 0) - continue; - - if ((r_addr.data.inet4.sin_addr.s_addr =3D=3D addr_val) && - (r_mask.data.inet4.sin_addr.s_addr =3D=3D mask_val)) { - g_autofree char *addr_str =3D virSocketAddrFormat(&r_addr); - if (!addr_str) - virResetLastError(); - virReportError(VIR_ERR_INTERNAL_ERROR, - _("Route address '%1$s' conflicts with IP a= ddress for '%2$s'"), - NULLSTR(addr_str), iface); - return -1; - } - } - } + if (virSocketAddrPrefixToNetmask(prefix, &netmask, AF_INET) < 0) + return false; =20 - return 0; + if (virSocketAddrMask(addr, &netmask, &netaddr) < 0) + return false; + + compare =3D ((gint64)netaddr.data.inet4.sin_addr.s_addr << 32) + + netmask.data.inet4.sin_addr.s_addr; + + VIR_DEBUG("Searching for key: %016llx", (unsigned long long)compare); + return g_hash_table_lookup(routesTable, &compare); } =20 =20 diff --git a/src/network/bridge_driver_nop.c b/src/network/bridge_driver_no= p.c index 8bf3367bff..d46aa99a5a 100644 --- a/src/network/bridge_driver_nop.c +++ b/src/network/bridge_driver_nop.c @@ -32,12 +32,6 @@ void networkPostReloadFirewallRules(bool startup G_GNUC_= UNUSED) { } =20 - -int networkCheckRouteCollision(virNetworkDef *def G_GNUC_UNUSED) -{ - return 0; -} - int networkAddFirewallRules(virNetworkDef *def G_GNUC_UNUSED, virFirewallBackend firewallBackend, virFirewall **fwRemoval G_GNUC_UNUSED) @@ -59,3 +53,19 @@ int networkAddFirewallRules(virNetworkDef *def G_GNUC_UN= USED, void networkRemoveFirewallRules(virNetworkObj *obj G_GNUC_UNUSED) { } + + +GHashTable * +networkSysRoutesTableRead(void) +{ + return NULL; +} + + +const char * +networkSysRoutesTableFind(GHashTable *routesTable G_GNUC_UNUSED, + virSocketAddr *addr G_GNUC_UNUSED, + unsigned int prefix G_GNUC_UNUSED) +{ + return NULL; +} diff --git a/src/network/bridge_driver_platform.h b/src/network/bridge_driv= er_platform.h index cd2e3fa7b5..67c3db7dca 100644 --- a/src/network/bridge_driver_platform.h +++ b/src/network/bridge_driver_platform.h @@ -30,7 +30,10 @@ void networkPreReloadFirewallRules(virNetworkDriverState= *driver, =20 void networkPostReloadFirewallRules(bool startup); =20 -int networkCheckRouteCollision(virNetworkDef *def); +GHashTable *networkSysRoutesTableRead(void); +const char *networkSysRoutesTableFind(GHashTable *routesTable, + virSocketAddr *addr, + unsigned int prefix); =20 int networkAddFirewallRules(virNetworkDef *def, virFirewallBackend firewallBackend, --=20 2.45.2 From nobody Sat Nov 23 15:37:54 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) client-ip=8.43.85.245; envelope-from=devel-bounces@lists.libvirt.org; helo=lists.libvirt.org; Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) smtp.mailfrom=devel-bounces@lists.libvirt.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.libvirt.org (lists.libvirt.org [8.43.85.245]) by mx.zohomail.com with SMTPS id 1723051266255624.5947079748856; Wed, 7 Aug 2024 10:21:06 -0700 (PDT) Received: by lists.libvirt.org (Postfix, from userid 996) id 34F5C12BF; Wed, 7 Aug 2024 13:21:05 -0400 (EDT) Received: from lists.libvirt.org (localhost [IPv6:::1]) by lists.libvirt.org (Postfix) with ESMTP id 5AABCCEB; Wed, 7 Aug 2024 13:16:21 -0400 (EDT) Received: by lists.libvirt.org (Postfix, from userid 996) id EADA6C2F; Wed, 7 Aug 2024 13:16:10 -0400 (EDT) Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by lists.libvirt.org (Postfix) with ESMTPS id 4602CC90 for ; Wed, 7 Aug 2024 13:16:10 -0400 (EDT) Received: from mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-408-IinXWEifM4GVSIw5HvtZwQ-1; Wed, 07 Aug 2024 13:16:08 -0400 Received: from mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.17]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id A093C1945106 for ; Wed, 7 Aug 2024 17:16:07 +0000 (UTC) Received: from vhost3.router.laine.org (unknown [10.22.32.31]) by mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 2C2971956052 for ; Wed, 7 Aug 2024 17:16:07 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on lists.libvirt.org X-Spam-Level: X-Spam-Status: No, score=-0.8 required=5.0 tests=DKIM_INVALID,DKIM_SIGNED, HEADER_FROM_DIFFERENT_DOMAINS,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE, RCVD_IN_MSPIKE_H4,RCVD_IN_MSPIKE_WL,SPF_HELO_NONE autolearn=unavailable autolearn_force=no version=3.4.4 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1723050970; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=EQ6aT6IwPOhclKaIyKEzwrfS7RIOrc2Ey7AXlFyL4Tg=; b=cXqWUKCf2xviTJWoSwZJOxDRnX3GPyMNDAZejtqZT74rtkJIMiY1+2Pr9/p2rA0+eJCA8v u1NlogZoQB01A1IWHUz8/WMhXhcwaZODhaneHkiRmSTJrOicVuWZ/ZfHSEi3zr03BLf02c wTe/m6bb0npgi3Tg9TZ+gOd/fWxPUGg= X-MC-Unique: IinXWEifM4GVSIw5HvtZwQ-1 From: Laine Stump To: devel@lists.libvirt.org Subject: [PATCH 4/7] network: turn on autoaddr selection in bridge driver Date: Wed, 7 Aug 2024 13:16:00 -0400 Message-ID: <20240807171603.218784-5-laine@redhat.com> In-Reply-To: <20240807171603.218784-1-laine@redhat.com> References: <20240807171603.218784-1-laine@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.0 on 10.30.177.17 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: quoted-printable Message-ID-Hash: TQCO4AC5M7T4KMGQTRBBS3TW4OC4INJJ X-Message-ID-Hash: TQCO4AC5M7T4KMGQTRBBS3TW4OC4INJJ X-MailFrom: laine@redhat.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; emergency; loop; banned-address; member-moderation; header-match-config-1; header-match-config-2; header-match-config-3; header-match-devel.lists.libvirt.org-0; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; suspicious-header X-Mailman-Version: 3.2.2 Precedence: list List-Id: Development discussions about the libvirt library & tools Archived-At: List-Archive: List-Help: List-Post: List-Subscribe: List-Unsubscribe: X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1723051267674116600 Content-Type: text/plain; charset="utf-8"; x-default="true" When a network has an element, the network driver will look for an "unused" subnet to assign to the network. The IP address of the network bridge will then be the .1 of that network, and any DHCP range, DHCP static hosts, and tftp boot server will be changed to the new network (while retaining the same host bits). * the range of subnets (and their prefix) have a hostwide configuration in /etc/libvirt/network.conf ("autoaddr_*"). * if the network config has a element with no specified, then a range will automatically be added that starts at ${net}.2 and ends at ${net}.254 (adjusted for prefix - this is example is only if the prefix is 24). * If a network has autoaddr=3D"yes" and also has an IP address defined, then the network driver will check that IP address first, and then start looking for a new address if that initial try fails. * If a new subnet is selected, this change of IP address will be saved to the network's persistent config (along with associated changes to other elements that need to be on the same subnet). This way the next time the network is started, it will attempt to use the same subnet that it had used the previous time. Signed-off-by: Laine Stump --- src/network/bridge_driver.c | 137 ++++++++++++++++++++++++++++++++++-- 1 file changed, 133 insertions(+), 4 deletions(-) diff --git a/src/network/bridge_driver.c b/src/network/bridge_driver.c index b8e752f20d..cceeb5d941 100644 --- a/src/network/bridge_driver.c +++ b/src/network/bridge_driver.c @@ -1901,19 +1901,78 @@ networkAddRouteToBridge(virNetworkObj *obj, /* XXX: This function can be a lot more exhaustive, there are certainly * other scenarios where we can ruin host network connectivity. * XXX: Using a proper library is preferred over parsing /proc + * + * check for any host route colliding exactly with each requested IPv4 + * address/prefix, If a collision is found and autoaddr isn't set for + * the network, immediately return an error. + + * if autoaddr *is* set, iteratively try subnets using the auto_addr* + * info from the system config (in /etc/libvirt/network.conf) until an + * "unused" subnet is found, then use that subnet, and rewrite the + * persistent network config so that next time we'll start trying + * using the same address we got this time. + * + * If all subnets in the configured autoaddr range are already in use, + * then return an error. */ static int -networkCheckIPAddrCollision(virNetworkDef *def, GHashTable *routes) +networkCheckIPAddrCollision(virNetworkDriverState *driver, + virNetworkObj *obj, + GHashTable *routes) { + g_autoptr(virNetworkDriverConfig) cfg =3D virNetworkDriverGetConfig(dr= iver); + uint32_t nextNet =3D ntohl(cfg->autoaddrStart.data.inet4.sin_addr.s_ad= dr); /* next subnet to check */ + uint32_t lastNet =3D ntohl(cfg->autoaddrEnd.data.inet4.sin_addr.s_addr= ); + virNetworkDef *def =3D virNetworkObjGetDef(obj); size_t i; virNetworkIPDef *ipdef; =20 /* check all IPv4 addresses of the network for conflict with * existing routes */ - for (i =3D 0; (ipdef =3D virNetworkDefGetIPByIndex(def, AF_INET, i)); = i++) { + for (i =3D 0; (ipdef =3D virNetworkDefGetIPByIndex(def, AF_UNSPEC, i))= ; i++) { + virSocketAddr ip =3D ipdef->address; /* don't disturb the original= (yet) */ unsigned int prefix =3D virNetworkIPDefPrefix(ipdef); - const char *iface =3D networkSysRoutesTableFind(routes, &ipdef->ad= dress, prefix); + const char *iface; + bool done =3D false; + uint32_t updateNet =3D 0; /* new subnet in *host* byte order (or 0= if no change) */ + + if (VIR_SOCKET_ADDR_IS_FAMILY(&ip, AF_INET6)) + continue; /* autoaddr isn't used on IPv6 addresses */ + + do { + if (VIR_SOCKET_ADDR_IS_FAMILY(&ip, AF_INET)) + iface =3D networkSysRoutesTableFind(routes, &ip, prefix); + else + iface =3D "unset"; /* could be anything !NULL, just need t= o take upcoming else clause */ + + if (!iface || !ipdef->autoaddr) { + + done =3D true; + + } else { + g_autofree char *addrStr =3D NULL; + + if (nextNet > lastNet) { + /* we've tried all of the subnets and they're all used= , so give up */ + virReportError(VIR_ERR_INTERNAL_ERROR, + _("could not find an unused subnet for = autoaddr network '%1$s'"), + def->name); + return -1; + } + + /* this is what we'll try next time through the loop */ + updateNet =3D nextNet; + virSocketAddrSetIPv4Addr(&ip, updateNet + 1); /* + 1 for h= ost address */ + prefix =3D cfg->autoaddrPrefix; + + addrStr =3D virSocketAddrFormat(&ip); + VIR_INFO("autoaddr trying %s/%u", NULLSTR(addrStr), prefix= ); + + /* get ready for the next "new" request (the loop *after* = the next) */ + nextNet =3D ((updateNet >> (32 - prefix)) + 1) << (32 - pr= efix); + } + } while (!done); =20 if (iface) { g_autofree char *addrStr =3D virSocketAddrFormat(&ipdef->addre= ss); @@ -1923,6 +1982,76 @@ networkCheckIPAddrCollision(virNetworkDef *def, GHas= hTable *routes) NULLSTR(addrStr), prefix, iface); return -1; } + + if (updateNet) { + /* address was changed via autoaddr */ + g_autofree char *addrStr =3D virSocketAddrFormat(&ip); + + VIR_INFO("autoaddr success: %s/%u", NULLSTR(addrStr), prefix); + + /* put the newly found unused IP/prefix in the NetworkDef */ + ipdef->address =3D ip; + ipdef->prefix =3D prefix; + memset(&ipdef->netmask, 0, sizeof(ipdef->netmask)); /*in case = original had netmask */ + + /* if there is a element also add/update the DHCP + * range, tftp bootserver, and, static hosts (they will + * all have the network part of their address changed, but + * the host bits will remain the same. + */ + + if (ipdef->dhcp) { + size_t j; + uint32_t tmp; + /* in *host* order initially, since we need to use if for = some arithmetic */ + uint32_t hostmask =3D ~(0xffffffff << (32 - prefix)); + + + if (!ipdef->nranges) { + /* if there isn't any address range in the config, + * we need to setup at least one + */ + virNetworkDHCPRangeDef range =3D { 0 }; + + /* just prime them with the host bits for .2 and + * .254 (adjusted for prefix) + */ + virSocketAddrSetIPv4Addr(&range.addr.start, updateNet = + 2); + virSocketAddrSetIPv4Addr(&range.addr.end, updateNet + = hostmask - 1); + VIR_APPEND_ELEMENT(ipdef->ranges, ipdef->nranges, rang= e); + } + + updateNet =3D htonl(updateNet); + hostmask =3D htonl(hostmask); + + for (j =3D 0; j < ipdef->nranges; j++) { + tmp =3D (ipdef->ranges[j].addr.start.data.inet4.sin_ad= dr.s_addr & hostmask) | updateNet; + virSocketAddrSetIPv4AddrNetOrder(&ipdef->ranges[j].add= r.start, tmp); + + tmp =3D (ipdef->ranges[j].addr.end.data.inet4.sin_addr= .s_addr & hostmask) | updateNet; + virSocketAddrSetIPv4AddrNetOrder(&ipdef->ranges[j].add= r.end, tmp); + } + + for (j =3D 0; j < ipdef->nhosts; j++) { + tmp =3D (ipdef->hosts[j].ip.data.inet4.sin_addr.s_addr= & hostmask) | updateNet; + virSocketAddrSetIPv4AddrNetOrder(&ipdef->hosts[j].ip, = tmp); + } + + if (VIR_SOCKET_ADDR_IS_FAMILY(&ipdef->bootserver, AF_INET)= ) { + tmp =3D (ipdef->bootserver.data.inet4.sin_addr.s_addr = & hostmask) | updateNet; + virSocketAddrSetIPv4AddrNetOrder(&ipdef->bootserver, t= mp); + } + } + + /* if this network is persistent also update on disk (so + * that the discovered address is tried first the next + * time this network is started) + */ + if (virNetworkObjIsPersistent(obj) + && virNetworkSaveConfig(cfg->networkConfigDir, def, driver= ->xmlopt) < 0) { + VIR_WARN("couldn't update autoaddr in network %1$s", def->= name); + } + } } =20 return 0; @@ -1977,7 +2106,7 @@ networkStartNetworkVirtual(virNetworkDriverState *dri= ver, =20 if (routes) { /* Check to see if any network IP collides with an existing route = on the host */ - if (networkCheckIPAddrCollision(def, routes) < 0) + if (networkCheckIPAddrCollision(driver, obj, routes) < 0) return -1; =20 /* also check for requested routes that collide with existing rout= es */ --=20 2.45.2 From nobody Sat Nov 23 15:37:54 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) client-ip=8.43.85.245; envelope-from=devel-bounces@lists.libvirt.org; helo=lists.libvirt.org; Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) smtp.mailfrom=devel-bounces@lists.libvirt.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.libvirt.org (lists.libvirt.org [8.43.85.245]) by mx.zohomail.com with SMTPS id 1723051329627750.7023580110387; Wed, 7 Aug 2024 10:22:09 -0700 (PDT) Received: by lists.libvirt.org (Postfix, from userid 996) id 76178828; Wed, 7 Aug 2024 13:22:08 -0400 (EDT) Received: from lists.libvirt.org (localhost [IPv6:::1]) by lists.libvirt.org (Postfix) with ESMTP id 166331324; Wed, 7 Aug 2024 13:16:24 -0400 (EDT) Received: by lists.libvirt.org (Postfix, from userid 996) id 5725BE1E; Wed, 7 Aug 2024 13:16:12 -0400 (EDT) Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by lists.libvirt.org (Postfix) with ESMTPS id 5269DC92 for ; Wed, 7 Aug 2024 13:16:11 -0400 (EDT) Received: from mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-365-MkK3L2mNPbaXm0cDF4itZg-1; Wed, 07 Aug 2024 13:16:08 -0400 Received: from mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.17]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 3A2181955F38 for ; Wed, 7 Aug 2024 17:16:08 +0000 (UTC) Received: from vhost3.router.laine.org (unknown [10.22.32.31]) by mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id BABB319560A3 for ; Wed, 7 Aug 2024 17:16:07 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on lists.libvirt.org X-Spam-Level: X-Spam-Status: No, score=-0.8 required=5.0 tests=DKIM_INVALID,DKIM_SIGNED, HEADER_FROM_DIFFERENT_DOMAINS,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE, RCVD_IN_MSPIKE_H3,RCVD_IN_MSPIKE_WL,SPF_HELO_NONE autolearn=unavailable autolearn_force=no version=3.4.4 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1723050971; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=OiqXoWCm0Lvs1z6CoyPHVF2P+mMYmj9e7xF/OCDr2v8=; b=ATozukfXRUSGPfTb2iI0QxBaa8/2OB/LZZtEkNkMLsgSXqd4XLoKdOGndvEXFKvTNOTGTQ doAfDeZD7RPidR0sL5TuSpzsjl3p5fRlzcSGkP+IPQBZdZXpSmp1tNRWmWA2NWeEJIE7jy Sazbr4scCi0/8TZyWjJe+x3nl7KKyIg= X-MC-Unique: MkK3L2mNPbaXm0cDF4itZg-1 From: Laine Stump To: devel@lists.libvirt.org Subject: [PATCH 5/7] network: NetworkManager script to monitor/resolve conflicts with new interfaces Date: Wed, 7 Aug 2024 13:16:01 -0400 Message-ID: <20240807171603.218784-6-laine@redhat.com> In-Reply-To: <20240807171603.218784-1-laine@redhat.com> References: <20240807171603.218784-1-laine@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.0 on 10.30.177.17 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: quoted-printable Message-ID-Hash: I36WSLKO3SNG457IM5DTQKD6CBD4CCGI X-Message-ID-Hash: I36WSLKO3SNG457IM5DTQKD6CBD4CCGI X-MailFrom: laine@redhat.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; emergency; loop; banned-address; member-moderation; header-match-config-1; header-match-config-2; header-match-config-3; header-match-devel.lists.libvirt.org-0; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; suspicious-header X-Mailman-Version: 3.2.2 Precedence: list List-Id: Development discussions about the libvirt library & tools Archived-At: List-Archive: List-Help: List-Post: List-Subscribe: List-Unsubscribe: X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1723051331841116600 Content-Type: text/plain; charset="utf-8"; x-default="true" There has been a problem for several years with libvirt's default virtual network conflicting with the host physical network connection on new installs, particularly when the "host" is actually a virtual machine that is, itself, connected to the libvirt default network on its respective host. If the two default networks use the same subnet, and if the nested host's libvirt happens to start its network before the system networking connects to the L0 host, then network connectivity to the L1 guest is just silently non-working. We've tried several things over the years to eliminate this problem, including: 1) Checking for conflicting routes/interfaces during installation of the libvirt-daemon-config-network package (the one containing the default network config file) which tries different subnets until it finds one that doesn't conflict. This helps in some cases, but fails on 2 points: a) if the installation environment is different from the environment where the system is actually run (e.g. a "live CD" image of a distro, which is built in a container by the distro maintainers, then could later run in any number of places, and b) it modifies the installed files during the rpm installation %post script, which is now discouraged because people building container images don't like dealing with that. 2) When starting a libvirt network, we now check for any route or interface that conflicts with the new network's IP's and routes. This doesn't fix the problem, but does notify the user of the problem *as long as libvirt starts its networks after the host has started its system networks*. 3) New code (in the commits immediately previous to this one) add support for an "autoaddr" attribute in each virtual network element; when autoaddr is set, the network driver goes one step beyond (2) and actually finds an unused subnet and sets the new virtual network's addresses accordingly. These are all nice in their own ways, but none of them helps in the situation where libvirt's networks are started first (before the host's own network connections are all up). This led to this patch, which does the following: 4) Using a NetworkManager facility (dispatcher.d pscripts, which are run whenever any interface is brought up or down), check for any libvirt networks that conflict with a newly started NetworkManager interface, and if a conflict is found then log a message and destroy the libvirt network. Most usefully, though, if this destroyed network has autoaddr=3D'yes' then the script will immediately restart the network, which will find a new, unused subnet. Once this is in place, the only issues are: 1) It only works with NetworkManager. But of course almost all of the cases where this problem has been an issue, networking is managed by NetworkManager. 2) If there are guests already running and connected to the network, they will be disconnected, and won't be reconnected until libvirtd/virtqemud is restarted (one of the things the QEMU driver does when rereading the status of active guests is to make sure all their interfaces are connected to their respective networks). Signed-off-by: Laine Stump --- libvirt.spec.in | 2 + src/network/meson.build | 6 + src/network/nm-dispatcher-check-nets.py | 196 ++++++++++++++++++++++++ 3 files changed, 204 insertions(+) create mode 100755 src/network/nm-dispatcher-check-nets.py diff --git a/libvirt.spec.in b/libvirt.spec.in index 29101e74fe..51cecfa598 100644 --- a/libvirt.spec.in +++ b/libvirt.spec.in @@ -603,6 +603,7 @@ Network filter configuration files for cleaning guest t= raffic Summary: Network driver plugin for the libvirtd daemon Requires: libvirt-daemon-common =3D %{version}-%{release} Requires: libvirt-libs =3D %{version}-%{release} +Requires: python3-libxml2 Requires: dnsmasq >=3D 2.41 %if %{prefer_nftables} Requires: nftables @@ -2151,6 +2152,7 @@ exit 0 %dir %attr(0755, root, root) %{_localstatedir}/lib/libvirt/dnsmasq/ %attr(0755, root, root) %{_libexecdir}/libvirt_leaseshelper %{_libdir}/libvirt/connection-driver/libvirt_driver_network.so +%{_prefix}/lib/NetworkManager/dispatcher.d/50-libvirt-check-nets %{_mandir}/man8/virtnetworkd.8* %if %{with_firewalld_zone} %{_prefix}/lib/firewalld/zones/libvirt.xml diff --git a/src/network/meson.build b/src/network/meson.build index 8faff6eb1c..f620407759 100644 --- a/src/network/meson.build +++ b/src/network/meson.build @@ -169,4 +169,10 @@ if conf.has('WITH_NETWORK') rename: [ 'libvirt-routed-in.xml' ], ) endif + + install_data( + 'nm-dispatcher-check-nets.py', + install_dir: prefix / 'lib' / 'NetworkManager' / 'dispatcher.d', + rename: [ '50-libvirt-check-nets' ], + ) endif diff --git a/src/network/nm-dispatcher-check-nets.py b/src/network/nm-dispa= tcher-check-nets.py new file mode 100755 index 0000000000..454c434c88 --- /dev/null +++ b/src/network/nm-dispatcher-check-nets.py @@ -0,0 +1,196 @@ +#!/usr/bin/env python3 +# +# Copyright (C) 2012-2019 Red Hat, Inc. +# +# 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 +# . + +import libvirt +import sys +import os +import libxml2 +from ipaddress import ip_network + +# This script should be installed in +# /usr/lib/NetworkManager/dispatcher.d/50-libvirt-check-nets. It will be +# called by NetworkManager every time a network interface is taken up +# or down. When a new network comes up, it checks the libvirt virtual +# networks to see if their IP address(es) (including any static +# routes) are in conflict with the IP address(es) (or static routes) +# of the newly added interface. If so, the libvirt network is +# disabled. It is assumed that the user will notice that their guests +# no longer have network connectvity (and/or the message logged by +# this script), see that the network has been disabled, and then +# realize the conflict when they try to restart it. +# +# set checkDefaultOnly=3DFalse to check *all* active libvirt networks +# for conflicts with the new interface. Set to True to check only the +# libvirt default network (since most networks other than the default +# network are added post-install at a time when all of the hosts other +# networks are already active, it may be overkill to check all of the +# libvirt networks for conflict here (and instead just add more +# needless overheard to bringing up a new host interface). +# +checkDefaultOnly =3D False + +# NB: since this file is installed in /usr/lib, it really shouldn't be +# modified by the user, but instead should be copied to +# /etc/NetworkManager/dispatcher.d, where it will override the copy in +# /usr/lib. Even that isn't a proper solution though - if we're going +# to actually have this config knob, perhaps we should check for it in +# the environment, and if someone wants to modify it they can put a +# short script in /etc that exports and environment variable and then +# calls this script? Just thinking out loud here. + + +def checkconflict(conn, netname, hostnets, hostif): + + # ignore if the network has been brought down or removed since we + # got the list + try: + net =3D conn.networkLookupByName(netname) + except libvirt.libvirtError: + return + + if not net.isActive(): + return + + xml =3D net.XMLDesc() + doc =3D libxml2.parseDoc(xml) + ctx =3D doc.xpathNewContext() + + # see if NetworkManager is informing us that this libvirt network + # itself is coming online + bridge =3D ctx.xpathEval("/network/bridge/@name") + if bridge and bridge[0].content =3D=3D hostif: + return + + # check *all* the addresses of this network + addrs =3D ctx.xpathEval("/network/*[@address]") + for ip in addrs: + ctx.setContextNode(ip) + address =3D ctx.xpathEval("@address") + prefix =3D ctx.xpathEval("@prefix") + netmask =3D ctx.xpathEval("@netmask") + autoaddr =3D ctx.xpathEval("@autoaddr") + + isAutoaddr =3D False + if autoaddr and len(autoaddr[0].content): + isAutoaddr =3D (autoaddr[0].content =3D=3D "yes") + + if not (address and len(address[0].content)): + continue + + addrstr =3D address[0].content + if not (prefix and len(prefix[0].content)): + # check for a netmask + if not (netmask and len(netmask[0].content)): + # this element has address, but no prefix or netmask + # probably it is so we can ignore it + continue + # convert netmask to prefix + prefixstr =3D str(ip_network("0.0.0.0/%s" % netmask[0].content= ).prefixlen) + else: + prefixstr =3D prefix[0].content + + virtnetaddress =3D ip_network("%s/%s" % (addrstr, prefixstr), stri= ct=3DFalse) + + for hostnet in hostnets: + if virtnetaddress =3D=3D hostnet: + # There is a conflict with this libvirt network and the sp= ecified + # net, so we need to disable the libvirt network + print("Stopping libvirt network '%s' because its subnet %s= conflicts with newly started interface '%s'')" + % (netname, str(hostnet), hostif)) + try: + net.destroy() + except libvirt.libvirtError: + print("Failed to destroy network %s" % netname) + return + + if isAutoaddr: + print("Restarting autoaddr libvirt network '%s'with ne= w subnet" % (netname)) + try: + net.create() + except libvirt.libvirtError: + print("Failed to restart network '%s'" % netname) + return + return + + +def addHostNets(hostnets, countenv, addrenv): + + count =3D os.getenv(countenv) + if not count or count =3D=3D 0: + return + + for num in range(int(count)): + addrstr =3D os.getenv("%s_%d" % (addrenv, num)) + if not addrstr or addrstr =3D=3D "": + continue + + net =3D ip_network(addrstr.split()[0], strict=3DFalse) + if net: + hostnets.append(net) + return + + +############################################################ + +if sys.argv[2] !=3D "up": + sys.exit(0) + +hostif =3D sys.argv[1] + +try: + conn =3D libvirt.open(None) +except libvirt.libvirtError: + print('Failed to open connection to the hypervisor') + sys.exit(0) + +if checkDefaultOnly: + nets =3D [] + net =3D conn.networkLookupByName("default") + if not (net and net.isActive()): + sys.exit(0) + nets.append(net) +else: + nets =3D conn.listAllNetworks(libvirt.VIR_CONNECT_LIST_NETWORKS_ACTIVE) + if not nets: + sys.exit(0) + +# We have at least one active network. Build a list of all network +# routes added by the new interface, and compare that list to the list +# of all networks used by each active libvirt network. If any are an +# exact match, then we have a conflict and need to shut down the +# libvirt network to avoid killing host networking. + +# When NetworkManager calls scripts in /etc/NetworkManager/dispatcher.d +# it will have all IP addresses and routes associated with the interface +# that is going up or down in the following environment variables: +# +# IP4_NUM_ADDRESSES - number of IPv4 addresses +# IP4_ADDRESS_N - one variable for each address, starting at _0 +# IP4_NUM_ROUTES - number of IPv5 routes +# IP4_ROUTE_N - one for each route, starting at _0 +# (replace "IP4" with "IP6" and repeat) +# +hostnets =3D [] +addHostNets(hostnets, "IP4_NUM_ADDRESSES", "IP4_ADDRESS") +addHostNets(hostnets, "IP4_NUM_ROUTES", "IP4_ROUTE") +addHostNets(hostnets, "IP6_NUM_ADDRESSES", "IP6_ADDRESS") +addHostNets(hostnets, "IP6_NUM_ROUTES", "IP6_ROUTE") + +for net in nets: + + checkconflict(conn, net.name(), hostnets, hostif) --=20 2.45.2 From nobody Sat Nov 23 15:37:54 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) client-ip=8.43.85.245; envelope-from=devel-bounces@lists.libvirt.org; helo=lists.libvirt.org; Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) smtp.mailfrom=devel-bounces@lists.libvirt.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.libvirt.org (lists.libvirt.org [8.43.85.245]) by mx.zohomail.com with SMTPS id 172305128777456.571287019948954; Wed, 7 Aug 2024 10:21:27 -0700 (PDT) Received: by lists.libvirt.org (Postfix, from userid 996) id B48AEE76; Wed, 7 Aug 2024 13:21:26 -0400 (EDT) Received: from lists.libvirt.org (localhost [IPv6:::1]) by lists.libvirt.org (Postfix) with ESMTP id A6E4E1316; Wed, 7 Aug 2024 13:16:22 -0400 (EDT) Received: by lists.libvirt.org (Postfix, from userid 996) id A7B6DCA7; Wed, 7 Aug 2024 13:16:11 -0400 (EDT) Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.133.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by lists.libvirt.org (Postfix) with ESMTPS id 450B5C2F for ; Wed, 7 Aug 2024 13:16:11 -0400 (EDT) Received: from mx-prod-mc-01.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-502-gLEMPPITPGWE3zOAcMBoLg-1; Wed, 07 Aug 2024 13:16:09 -0400 Received: from mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.17]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-01.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id BC2A519560A2 for ; Wed, 7 Aug 2024 17:16:08 +0000 (UTC) Received: from vhost3.router.laine.org (unknown [10.22.32.31]) by mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id 542F119560A3 for ; Wed, 7 Aug 2024 17:16:08 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on lists.libvirt.org X-Spam-Level: X-Spam-Status: No, score=-0.8 required=5.0 tests=DKIM_INVALID,DKIM_SIGNED, HEADER_FROM_DIFFERENT_DOMAINS,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE, RCVD_IN_MSPIKE_H4,RCVD_IN_MSPIKE_WL,SPF_HELO_NONE autolearn=unavailable autolearn_force=no version=3.4.4 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1723050971; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=Df/hqBTPR9i1W9CbI+SQUxBs7T5cXmjGSTOeQ3R/yns=; b=HOBMnWjtW3gOsz3jgW0SzxbA74UhYz+aAhCNTuno1Bc7ilqxAguPHRDGp3kv02DsVXgpg8 0KzW2qsnNq1wHXVuU3wUj4lyc/g69Y0IinEjNxn9h7hlbduoSwGWPLRi26L+QEy6oKvNcF Vx8S1+ShyEMVyTxg1CS09efIImxLUW0= X-MC-Unique: gLEMPPITPGWE3zOAcMBoLg-1 From: Laine Stump To: devel@lists.libvirt.org Subject: [PATCH 6/7] network: turn on autoaddr in default network Date: Wed, 7 Aug 2024 13:16:02 -0400 Message-ID: <20240807171603.218784-7-laine@redhat.com> In-Reply-To: <20240807171603.218784-1-laine@redhat.com> References: <20240807171603.218784-1-laine@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.0 on 10.30.177.17 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: quoted-printable Message-ID-Hash: DVUPQ3NTTR5LRMZ46CNK7WP24Y3SCISL X-Message-ID-Hash: DVUPQ3NTTR5LRMZ46CNK7WP24Y3SCISL X-MailFrom: laine@redhat.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; emergency; loop; banned-address; member-moderation; header-match-config-1; header-match-config-2; header-match-config-3; header-match-devel.lists.libvirt.org-0; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; suspicious-header X-Mailman-Version: 3.2.2 Precedence: list List-Id: Development discussions about the libvirt library & tools Archived-At: List-Archive: List-Help: List-Post: List-Subscribe: List-Unsubscribe: X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1723051289615116600 Content-Type: text/plain; charset="utf-8"; x-default="true" With autoaddr enabled, the subnet to be used for the default network will be verified/changed at the time the network starts. Signed-off-by: Laine Stump --- src/network/default.xml.in | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/network/default.xml.in b/src/network/default.xml.in index 08a3632eb6..a01c6d30ae 100644 --- a/src/network/default.xml.in +++ b/src/network/default.xml.in @@ -2,7 +2,7 @@ default - + --=20 2.45.2 From nobody Sat Nov 23 15:37:54 2024 Delivered-To: importer@patchew.org Received-SPF: pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) client-ip=8.43.85.245; envelope-from=devel-bounces@lists.libvirt.org; helo=lists.libvirt.org; Authentication-Results: mx.zohomail.com; dkim=fail; spf=pass (zohomail.com: domain of lists.libvirt.org designates 8.43.85.245 as permitted sender) smtp.mailfrom=devel-bounces@lists.libvirt.org; dmarc=fail(p=none dis=none) header.from=redhat.com Return-Path: Received: from lists.libvirt.org (lists.libvirt.org [8.43.85.245]) by mx.zohomail.com with SMTPS id 172305135533297.25844099352548; Wed, 7 Aug 2024 10:22:35 -0700 (PDT) Received: by lists.libvirt.org (Postfix, from userid 996) id 5519F12B5; Wed, 7 Aug 2024 13:22:34 -0400 (EDT) Received: from lists.libvirt.org (localhost [IPv6:::1]) by lists.libvirt.org (Postfix) with ESMTP id 66E5F134A; Wed, 7 Aug 2024 13:16:25 -0400 (EDT) Received: by lists.libvirt.org (Postfix, from userid 996) id 1A0E81172; Wed, 7 Aug 2024 13:16:13 -0400 (EDT) Received: from us-smtp-delivery-124.mimecast.com (us-smtp-delivery-124.mimecast.com [170.10.129.124]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by lists.libvirt.org (Postfix) with ESMTPS id 0985BCA8 for ; Wed, 7 Aug 2024 13:16:11 -0400 (EDT) Received: from mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (ec2-54-186-198-63.us-west-2.compute.amazonaws.com [54.186.198.63]) by relay.mimecast.com with ESMTP with STARTTLS (version=TLSv1.3, cipher=TLS_AES_256_GCM_SHA384) id us-mta-359--k17OFcDMP2nZ6-lTEGgZw-1; Wed, 07 Aug 2024 13:16:10 -0400 Received: from mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com [10.30.177.17]) (using TLSv1.3 with cipher TLS_AES_256_GCM_SHA384 (256/256 bits) key-exchange X25519 server-signature RSA-PSS (2048 bits) server-digest SHA256) (No client certificate requested) by mx-prod-mc-03.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTPS id 6B25B19560B6 for ; Wed, 7 Aug 2024 17:16:09 +0000 (UTC) Received: from vhost3.router.laine.org (unknown [10.22.32.31]) by mx-prod-int-05.mail-002.prod.us-west-2.aws.redhat.com (Postfix) with ESMTP id EED9419560A3 for ; Wed, 7 Aug 2024 17:16:08 +0000 (UTC) X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on lists.libvirt.org X-Spam-Level: X-Spam-Status: No, score=-0.8 required=5.0 tests=DKIM_INVALID,DKIM_SIGNED, HEADER_FROM_DIFFERENT_DOMAINS,MAILING_LIST_MULTI,RCVD_IN_DNSWL_NONE, RCVD_IN_MSPIKE_H3,RCVD_IN_MSPIKE_WL,SPF_HELO_NONE autolearn=unavailable autolearn_force=no version=3.4.4 DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed; d=redhat.com; s=mimecast20190719; t=1723050971; h=from:from:reply-to:subject:subject:date:date:message-id:message-id: to:to:cc:mime-version:mime-version:content-type:content-type: content-transfer-encoding:content-transfer-encoding: in-reply-to:in-reply-to:references:references; bh=wNJSHIN4VOVC7HgIFvttXItKf+2BmZdn6ZFy6Lzuq0k=; b=Aa1ifhMrB2LSPlxwOJhCiov4P1ZABk5tBwYfmoTLM/deSu5wmwfhtHaXjnChvO7NDAmhZ3 MF1GNrVUdr2KBJS0gtSqxbwAO7b3fEbUzdLV8fbNmOA0VtYLiUmno7DIczzEC9n3YlEa9y NCSefrVK1ZYwPyw8Cfcn1cM8IFjYm0o= X-MC-Unique: -k17OFcDMP2nZ6-lTEGgZw-1 From: Laine Stump To: devel@lists.libvirt.org Subject: [PATCH 7/7] spec: stop trying to find unused network during deamon-network-config %post Date: Wed, 7 Aug 2024 13:16:03 -0400 Message-ID: <20240807171603.218784-8-laine@redhat.com> In-Reply-To: <20240807171603.218784-1-laine@redhat.com> References: <20240807171603.218784-1-laine@redhat.com> MIME-Version: 1.0 X-Scanned-By: MIMEDefang 3.0 on 10.30.177.17 X-Mimecast-Spam-Score: 0 X-Mimecast-Originator: redhat.com Content-Transfer-Encoding: quoted-printable Message-ID-Hash: VM6Q43VA6YQX724HFPMCFMN7NGV6QU2G X-Message-ID-Hash: VM6Q43VA6YQX724HFPMCFMN7NGV6QU2G X-MailFrom: laine@redhat.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; emergency; loop; banned-address; member-moderation; header-match-config-1; header-match-config-2; header-match-config-3; header-match-devel.lists.libvirt.org-0; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; suspicious-header X-Mailman-Version: 3.2.2 Precedence: list List-Id: Development discussions about the libvirt library & tools Archived-At: List-Archive: List-Help: List-Post: List-Subscribe: List-Unsubscribe: X-ZohoMail-DKIM: fail (Header signature does not verify) X-ZM-MESSAGEID: 1723051355861116600 Content-Type: text/plain; charset="utf-8"; x-default="true" Since the default network now has autoaddr=3D'yes', there is no need to waste time during %post install looking for an unused network and modifying the config of the default virtual network. (It would be even simpler to just install the files directly to /etc rather than installing to the examples and then copying to /etc, but if we did that then someone who had manually net-undefined the default network would keep getting it reinstalled every time there was an update to libvirt-daemon-config-network. Of course these days someone who wants to do that can simply dnf rm daemon-config-network if they didn't want the stock default network config, but nobody will be expecting that they have to do that, leading to hundreds of bug reports about "I deleted the default network and it comes back every time I update my packages!") Signed-off-by: Laine Stump --- libvirt.spec.in | 36 +++++------------------------------- 1 file changed, 5 insertions(+), 31 deletions(-) diff --git a/libvirt.spec.in b/libvirt.spec.in index 51cecfa598..cb62e0dcdb 100644 --- a/libvirt.spec.in +++ b/libvirt.spec.in @@ -1949,38 +1949,12 @@ exit 0 %libvirt_systemd_config_pre virtnetworkd =20 %post daemon-config-network +# Installing during %post via cp rather than directly as a part of the pac= kage manifest +# prevents us from reinstalling on update in cases where the user has net-= undefined +# the default network (and so doesn't *want* it to be reinstalled) if test $1 -eq 1 && test ! -f %{_sysconfdir}/libvirt/qemu/networks/default= .xml ; then - # see if the network used by default network creates a conflict, - # and try to resolve it - # NB: 192.168.122.0/24 is used in the default.xml template file; - # do not modify any of those values here without also modifying - # them in the template. - orig_sub=3D122 - sub=3D${orig_sub} - nl=3D' -' - routes=3D"${nl}$(ip route show | cut -d' ' -f1)${nl}" - case ${routes} in - *"${nl}192.168.${orig_sub}.0/24${nl}"*) - # there was a match, so we need to look for an unused subnet - for new_sub in $(seq 124 254); do - case ${routes} in - *"${nl}192.168.${new_sub}.0/24${nl}"*) - ;; - *) - sub=3D$new_sub - break; - ;; - esac - done - ;; - *) - ;; - esac - - sed -e "s/${orig_sub}/${sub}/g" \ - < %{_datadir}/libvirt/networks/default.xml \ - > %{_sysconfdir}/libvirt/qemu/networks/default.xml + cp %{_datadir}/libvirt/networks/default.xml \ + %{_sysconfdir}/libvirt/qemu/networks/default.xml ln -s ../default.xml %{_sysconfdir}/libvirt/qemu/networks/autostart/de= fault.xml # libvirt saves this file with mode 0600 chmod 0600 %{_sysconfdir}/libvirt/qemu/networks/default.xml --=20 2.45.2