nplan-0.32~16.04.7~mtrudel1/0000775000000000000000000000000013534237274012260 5ustar nplan-0.32~16.04.7~mtrudel1/COPYING0000664000000000000000000010451313272657646013327 0ustar GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 3 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, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . nplan-0.32~16.04.7~mtrudel1/Makefile0000664000000000000000000000566413534237266013734 0ustar PREFIX ?= /usr SBINDIR ?= $(PREFIX)/sbin LIBEXECDIR ?= $(PREFIX)/lib BUILDFLAGS = \ -std=c99 \ -D_XOPEN_SOURCE=500 \ -DSBINDIR=\"$(SBINDIR)\" \ -Wall \ -Werror=incompatible-pointer-types \ -Werror=implicit-function-declaration \ -Werror=format \ $(NULL) SYSTEMD_GENERATOR_DIR=$(shell pkg-config --variable=systemdsystemgeneratordir systemd) PYCODE = src/netplan $(wildcard src/*.py) $(wildcard tests/*.py) $(wildcard tests/dbus/*.py) default: generate doc/netplan.5 doc/netplan.html netplan-dbus dbus/io.netplan.Netplan.service generate: src/generate.[hc] src/parse.[hc] src/util.[hc] src/networkd.[hc] src/nm.[hc] $(CC) $(BUILDFLAGS) $(CFLAGS) -o $@ $(filter %.c, $^) `pkg-config --cflags --libs glib-2.0 yaml-0.1 uuid` netplan-dbus: src/dbus.c $(CC) $(BUILDFLAGS) $(CFLAGS) -o $@ $^ `pkg-config --cflags --libs libsystemd glib-2.0` clean: rm -f netplan-dbus dbus/*.service rm -f generate doc/*.html doc/*.[1-9] rm -rf test-coverage .coverage check: default tests/generate.py tests/cli.py $(shell which pyflakes3 || echo true) $(PYCODE) $(shell which pycodestyle || which pep8 || echo true) --max-line-length=130 $(PYCODE) coverage: rm -f .coverage $(MAKE) CFLAGS="-g -O0 --coverage" clean check lcov --directory . --capture -o generate.info lcov --remove generate.info "/usr*" -o generate.info genhtml -o test-coverage -t "generate test coverage" generate.info @rm *.gcda *.gcno generate.info generate @echo "generated report: file://$(CURDIR)/test-coverage/index.html" @if grep headerCovTableEntryHi test-coverage/index.html | grep -qv '100.*%'; then \ echo "FAIL: Test coverage not 100%!" >&2; exit 1; \ fi python3-coverage report --include=src/netplan --show-missing --fail-under=100 install: default mkdir -p $(DESTDIR)/usr/sbin $(DESTDIR)/lib/netplan $(DESTDIR)/$(SYSTEMD_GENERATOR_DIR) mkdir -p $(DESTDIR)/usr/share/man/man5 $(DESTDIR)/usr/share/doc/netplan install -m 755 generate $(DESTDIR)/lib/netplan/ install -m 755 src/netplan $(DESTDIR)/usr/sbin/ ln -s /lib/netplan/generate $(DESTDIR)/$(SYSTEMD_GENERATOR_DIR)/netplan install -m 644 doc/*.html $(DESTDIR)/usr/share/doc/netplan/ install -m 644 doc/*.5 $(DESTDIR)/usr/share/man/man5/ install -D -m 644 src/netplan-wpa@.service $(DESTDIR)/`pkg-config --variable=systemdsystemunitdir systemd`/netplan-wpa@.service # dbus mkdir -p $(DESTDIR)/usr/share/dbus-1/system.d $(DESTDIR)/usr/share/dbus-1/system-services install -m 755 netplan-dbus $(DESTDIR)/lib/netplan/ install -m 644 dbus/io.netplan.Netplan.conf $(DESTDIR)/usr/share/dbus-1/system.d/ install -m 644 dbus/io.netplan.Netplan.service $(DESTDIR)/usr/share/dbus-1/system-services/ %.service: %.service.in sed -e "s#@ROOTLIBEXECDIR@#/lib#" $< > $@ %.html: %.md pandoc -s --toc -o $@ $< doc/netplan.5: doc/netplan.md pandoc -s -o $@ $< # add NAME section (looks ugly in HTML, thus only do it here) sed -i '/^.TH/ a\.SH NAME\nnetplan \\- YAML network configuration abstraction for various backends' $@ .PHONY: clean nplan-0.32~16.04.7~mtrudel1/dbus/0000775000000000000000000000000013534225677013221 5ustar nplan-0.32~16.04.7~mtrudel1/dbus/io.netplan.Netplan.conf0000664000000000000000000000076613533506646017545 0ustar nplan-0.32~16.04.7~mtrudel1/dbus/io.netplan.Netplan.service.in0000664000000000000000000000017513534006517020650 0ustar [D-BUS Service] Name=io.netplan.Netplan Exec=@ROOTLIBEXECDIR@/netplan/netplan-dbus User=root AssumedAppArmorLabel=unconfined nplan-0.32~16.04.7~mtrudel1/debian/0000775000000000000000000000000013534237274013502 5ustar nplan-0.32~16.04.7~mtrudel1/debian/changelog0000664000000000000000000004460213534237274015362 0ustar nplan (0.32~16.04.7) xenial; urgency=medium * Backport DBus support to 16.04. (LP: #1842511) * debian/control: add libsystemd-dev to Build-Depends, required for this new DBus support. -- Mathieu Trudel-Lapierre Thu, 05 Sep 2019 12:58:36 -0400 nplan (0.32~16.04.6) xenial; urgency=medium [ Mathieu Trudel-Lapierre ] * tests/integration.py: Fix autopkgtests involving bonds/bridges to do proper cleanup every time, so later tests don't unnecessarily wait for an interface not configured to be up. (LP: #1775097) [ Daniel Axtens ] * Generate udev rules files to rename devices (LP: #1770082) Due to a systemd issue[1], using link files to rename interfaces doesn't work as expected. Link files will not rename an interface if it was already renamed, and interfaces are renamed in initrd, so set-name will often not work as expected when rebooting. However, rules files will cause a renaming, even if the interface has been renamed in initrd. -- Mathieu Trudel-Lapierre Tue, 03 Jul 2018 12:55:11 -0400 nplan (0.32~16.04.5) xenial; urgency=medium * bond/bridge: Support suffixes for time-based values so things like "mii-monitor-interval" can support milliseconds. (LP: #1745597) * Do not attempt to rebind driver 'qeth'. (LP: #1756322) * Allow setting ClientIdentifier=mac for networkd-renderered devices (LP: #1738998) * IPv6: accept-ra should default to being unset, so that the kernel default can be used. (LP: #1732002) * doc/netplan.md: Clarify the behavior for time-based values for bonds and bridges. (LP: #1756587) * critical: provide a way to set "CriticalConnection=true" on a networkd connection, especially for remote-fs scenarios. (LP: #1769682) * networkd: don't wipe out /run/netplan on generate: we do want to keep any YAML configurations in that directory, we just need to remove generated wpasupplicant configs. (LP: #1764869) -- Mathieu Trudel-Lapierre Tue, 08 May 2018 10:36:24 -0400 nplan (0.32~16.04.4) xenial; urgency=medium [ Oliver Grawert ] * Prevent unbinding ath6kl_sdio, driver does not support it correctly. (LP: #1741910) [ Mathieu Trudel-Lapierre ] * Re-add snap support patch. (LP: #1747714) * Fix syntax for IPv6 addresses in doc. (LP: #1735317) * doc: routes are not top-level but per-interface. (LP: #1726695) * Implement bridge port-priority parameter. (LP: #1735821) * Implement "optional: true" to correctly write systemd network definitions with "RequiredForOnline=false", such that these networks do not block boot. (LP: #1664844) * Various documentation fixes. (LP: #1751814) -- Mathieu Trudel-Lapierre Fri, 02 Mar 2018 17:02:03 -0500 nplan (0.32~16.04.3) xenial; urgency=medium * tests/integration.py: Really fix skipping test_routes_v6 for the NM backend. -- Mathieu Trudel-Lapierre Mon, 04 Dec 2017 10:57:34 -0500 nplan (0.32~16.04.2) xenial; urgency=medium * tests/integration.py: Fix test_routes_v6 that I clobbered when I re-applied the skip rules for 16.04 after merging in 0.32. -- Mathieu Trudel-Lapierre Tue, 28 Nov 2017 11:53:55 -0500 nplan (0.32~16.04.1) xenial; urgency=medium * Backport netplan 0.32 to 16.04. (LP: #1713142) * debian/control: Depend on systemd (>= 229-4ubuntu20) for the PrimarySlave feature backported in that revision. * tests/integration.py: Skip tests that are still not yet supported in xenial -- Mathieu Trudel-Lapierre Thu, 16 Nov 2017 10:13:28 -0500 nplan (0.32) bionic; urgency=medium * src/nm.c: better handle the UUID generation; the order of iterating through interaces may affect things here. Also make sure the tests catch a null UUID. -- Mathieu Trudel-Lapierre Tue, 14 Nov 2017 08:53:51 -0500 nplan (0.31) bionic; urgency=medium [ Mathieu Trudel-Lapierre ] * src/nm.c: generate a UUID for a connection only as needed; when we're dealing with NM VLANs. (LP: #1712921) * debian/tests/autostart: Make the autostart test more verbose and avoid failing right from the start when systemd-networkd is disabled. (LP: #1699371) * tests/integration.py: bump the NetworkManager timeout for settling to 120 seconds, autopkgtest infrastructure tends to be a little slow for the network device configuration to be applied and noticed by NM. (LP: #1699371) [ Dimitri John Ledkov ] * Reload udevd to invalidate configuration cache of .rules/.link files as generate step may have changed them. LP: #1669564 [ Dan Streetman ] * Add another interface driver exception to netplan replug to prevent unbind of the Xen VIF interfaces. (LP: #1729573) -- Mathieu Trudel-Lapierre Wed, 08 Nov 2017 14:02:39 -0500 nplan (0.30) artful; urgency=medium * Add an "optional" syntax node for now to all devices. This is unimplemented for now, but intended to allow users to mark some devices as optional: to make sure they do not delay boot when configured. (LP: #1664844) -- Mathieu Trudel-Lapierre Wed, 11 Oct 2017 21:26:48 -0400 nplan (0.29) artful; urgency=medium * Fix autopkgtests in a world where /run/NetworkManager/conf.d already exists. nplan is enabled by default, so it might well have the directory already created on the filesystem. -- Mathieu Trudel-Lapierre Tue, 19 Sep 2017 15:24:17 -0400 nplan (0.28) artful; urgency=medium * Revert 56cd3eec which disabled IPv6 Router Advertisements by default. It broke default network config in LXD and was contrary to the defaults used by the kernel. Reopens LP: 1655440. (LP: #1717404) * Add "accept-ra:" key for all device types; this will default to OFF but allow users to disable processing Router Advertisements when required by their network setup. (LP: #1655440) -- Mathieu Trudel-Lapierre Mon, 18 Sep 2017 16:11:45 -0700 nplan (0.27) artful; urgency=medium [ Mathieu Trudel-Lapierre ] * Fix crash in systemd generator if called by an user on the command-line * coverage: fix exclusions to properly not cover our "never reached defaults" [ Dimitri John Ledkov ] * tests/integration.py: In teardown, stop systemd-networkd.socket. * src/networkd.c: Set UseMTU=true by default, whenever DHCP is in use. (LP: #1717471) * tests/integration.py: fix resolved detection. -- Dimitri John Ledkov Fri, 15 Sep 2017 14:25:22 +0100 nplan (0.26) artful; urgency=medium * Bonding: - Add support for specifying a primary slave. (LP: #1709135) * Rebind: - Fix brcmfmac harder. Treat any 'brcmfmac' driver as not supporting rebind. (LP: #1712224) * Autopkgtests: - Add allow-stderr. Systemd now bleats about a the networkd socket still being around and enabled when we restart the service; but we don't need to care since we're /restarting/ the service to load the new config. - Fix the autostart package to be more sensible: we don't really care if networkd autostarts or not, but we need to make sure that our generator will run at boot, so instead check the state, but only assert it once we've added a config file and before checking the state of our dummy device. - Do a bit more to make sure "mix" tests which stack virtual devices are as reliable as possible; by setting saner defaults. -- Mathieu Trudel-Lapierre Wed, 23 Aug 2017 19:32:33 -0400 nplan (0.25) artful; urgency=medium * tests/generate.py: add a test to validate that correct blacklist entries are added when creating virtual devices. * tests/integration.py: clean up after br0 in networkd's test_bridge_mac; as the remaining interface and udev configuration can confuse NetworkManager now that it seems to manage random devices it did not create again. (LP: #1699371) * src/nm.c: set the MTU even though we also specify it in systemd-networkd for consumption by udev. NetworkManager will try to set it and might otherwise default to the wrong value. * src/networkd.c: Set IPv6AcceptRA=no anytime we don't do DHCPv6 (or by the same config, SLAAC), and don't have static addresses set. This should fix the cases where unconfigured devices still get an IPv6 address. (LP: #1655440) * src/nm.c: Explicitly set IPv6 method=ignore when IPv6 is otherwise not configured; this follows the same logic as setting IPv6AcceptRA=no in networkd, with the exception that NM does not currently disable RAs. When it does, an unconfigured device for IPv6 will truly be left with no config. -- Mathieu Trudel-Lapierre Thu, 13 Jul 2017 16:22:18 -0400 nplan (0.24) artful; urgency=medium * debian/control: set Priority to important to make sure we can get into minimal. -- Mathieu Trudel-Lapierre Thu, 15 Jun 2017 21:37:51 -0400 nplan (0.23) artful; urgency=medium * Do not unbind brcmfmac, interface will be gone. (LP: #1696162) -- Mathieu Trudel-Lapierre Tue, 06 Jun 2017 12:25:22 -0400 nplan (0.22) artful; urgency=medium * Add support for setting a custom MAC address on all device types. (LP: #1690388) * Improved MAC/vlan integration tests; thanks for Dimitri John Ledkov for the changes. -- Mathieu Trudel-Lapierre Mon, 22 May 2017 11:57:39 -0400 nplan (0.21) artful; urgency=medium [ Ryan Harper ] * Add support for setting MTU on a device. (LP: #1668693) [ Mathieu Trudel-Lapierre ] * Don't rebind Atheros AR9271; it would confuse the driver. (LP: #1672740) * debian/control: Add Conflicts: against netplan; the network 'plan' daemon. Both ship the same /usr/sbin/netplan. (LP: #1665842) -- Mathieu Trudel-Lapierre Tue, 02 May 2017 09:37:57 -0400 nplan (0.20) zesty; urgency=medium * tests/integration.py: increase timeout for integration tests (networkd and NetworkManager "wait-online" checks) to account for longer bring-up times when dealing with stacked virtual devices. -- Mathieu Trudel-Lapierre Tue, 04 Apr 2017 21:26:01 -0400 nplan (0.19) zesty; urgency=medium * Add support for unordered definition of network devices: you can now specify a virtual devices before their member devices. (LP: #1670495) * Allow setting up the STP state for a bridge. (LP: #1665088) * Document bond/bridge parameters support. (LP: #1664702) -- Mathieu Trudel-Lapierre Thu, 09 Mar 2017 11:04:50 -0500 nplan (0.18) zesty; urgency=medium * debian/tests/integration.py: in some cases 'iw reg get' may qualify the reg domain results with 'global'; we must not let that trip up tests when they are run on Ubuntu infrastructure vs. local tests. -- Mathieu Trudel-Lapierre Tue, 07 Feb 2017 11:12:37 -0500 nplan (0.17) zesty; urgency=medium * New release: - Add support for configuring bonds. - Add support for configuring bridges. -- Mathieu Trudel-Lapierre Wed, 01 Feb 2017 18:35:45 -0500 nplan (0.16) zesty; urgency=medium [ Martin Pitt ] * doc/example-config: Adjust "routes:" example. It does not make sense to make "routes:" a global thing, they should be tied to an interface so that the route is only set when the corresponding interface exists and is up, and the config is not split in two parts. * doc/netplan.md: Point out that NM does not support globbing (LP: #1631018) [ Mathieu Trudel-Lapierre ] * Fix coverage for src/netplan to be 100%, and fail if coverage falls below that mark again. * Add support for specifying routes. -- Mathieu Trudel-Lapierre Fri, 23 Dec 2016 12:33:34 -0500 nplan (0.15) zesty; urgency=medium * tests/generate.py: Fix PEP-8 error (newly detected by -proposed pycodestyle). -- Martin Pitt Wed, 09 Nov 2016 17:12:54 +0100 nplan (0.14) zesty; urgency=medium * tests/generate.py: Introduce macros for commonly expected networkd output * networkd: Use NetworkManager compatible DHCP route metrics (LP: #1639754) * doc/netplan.md: Fix wrong wifi reference in "br0" example * doc/netplan.md: Clarify introduction * tests/integration.py: Fix race condition with waiting for networkd -- Martin Pitt Wed, 09 Nov 2016 16:57:49 +0100 nplan (0.13) zesty; urgency=medium [ Jonathan Cave ] * Blacklist mwifiex_pcie from rebinds (work around LP: #1630285) [ Martin Pitt ] * Add support for nameservers (LP: #1626617) -- Martin Pitt Thu, 20 Oct 2016 16:23:58 +0200 nplan (0.12) yakkety; urgency=medium * netplan apply: Ignore Non-symlinks in /sys/class/net * tests/integration.py: Stop upping client veth interfaces * Add support for bonds -- Martin Pitt Tue, 30 Aug 2016 10:32:17 +0200 nplan (0.11.1) yakkety; urgency=medium * tests/integration.py: Clean up wpa_supplicant in between tests -- Martin Pitt Tue, 30 Aug 2016 07:21:02 +0200 nplan (0.11) yakkety; urgency=medium * Support /lib/netplan/*.yaml files. This is useful for configuration snippets shipped by packages. * Add networkd support for wifi (LP: #1616928) networkd cannot handle wifi natively, so generate a wpa_supplicant configuration and unit that does the WLAN part and leave the IP part to networkd. This supports open and WPA2, and infrastructure and adhoc mode. "match:" is not supported as the netplan-wpa@.service helper unit is bound to the named network interface device unit. * As networkd can now handle wifi devices, use networkd consistently as a default renderer. * tests/integration.py: Kill leftover NetworkManager processes between tests. NetworkManager.service has KillMode=process and leaks dhclient processes. * Fix package description for updated yaml paths -- Martin Pitt Mon, 29 Aug 2016 17:25:33 +0200 nplan (0.10) yakkety; urgency=medium * Add "netplan ifupdown-migrate" command. This supports converting "loopback" (no-op) and "dhcp" interfaces (without options) for now. * Add "dhcp6:" option * Add "gateway[46]:" options * Ship empty /etc/netplan in the package * NM: Explicitly disable implied DHCP default when DHCP is not enabled. (LP: #1617051) * tests/integration.py: Quiesce systemd-networkd-wait-online. * Add support for VLAN. -- Martin Pitt Sun, 28 Aug 2016 21:25:45 +0200 nplan (0.9) yakkety; urgency=medium * tests/integration.py: Improve debug messages on failure * netplan apply: disconnect devices from NetworkManager before restarting. Merely restarting NetworkManager does not suffice to apply a changed configuration, so disconnect managed devices first. Add autopkgtest to reproduce the problem and confirm the fix. * Fix configuration path in package description * networkd: Change generated config file prefix to "10-netplan" Just "netplan-*" sorts after /lib/systemd/network/99-default.link. * netplan apply: Force-replug network devices which are down to apply renames. Unbind/rebind network devices from their driver to simulate a hotplug, so that device renames get applied. Don't do this for devices which are up (or "unknown") though, to avoid disrupting existing network connections. * tests/integration.py: Add workaround for NM "unmanaged-devices=" mishandling (LP #1615044) -- Martin Pitt Fri, 19 Aug 2016 19:10:33 +0200 nplan (0.8) yakkety; urgency=medium * tests/cli.py: Test "generate" more precisely * Let "make coverage" fail if coverage is < 100% * Support /run/netplan/*.yaml files. This is useful if you want to try out a new network config before "committing" it to /etc: if your remote server is still reachable after "apply", you copy the files to /etc; otherwise rebooting will go back to the known-good state. * If global renderer is set to NM, allow NM to manage all devices. By default, NetworkManager only manages wifi and wwan devices (via /usr/lib/NetworkManager/conf.d/10-globally-managed-devices.conf). If global renderer is set to NetworkManager, disable that file in /run so that NM will once again manage all devices. This should be configured on desktop systems. * netplan apply: Asynchronously restart networkd/NM. This avoids deadlocks when calling "apply" during the boot sequence. (LP: #1614061) -- Martin Pitt Wed, 17 Aug 2016 16:03:33 +0200 nplan (0.7) yakkety; urgency=medium * tests/cli.py: Fix TestGenerate to not depend on installed netplan -- Martin Pitt Tue, 16 Aug 2016 16:39:11 +0200 nplan (0.6) yakkety; urgency=medium * Enable systemd-networkd-wait-online when starting networkd (LP: #1613548) * networkd: Prefix generated files with "netplan-" * generate: Clean up obsolete generated configs (LP: #1608223) * Prefer pycodestyle over pep8 * Add initial "netplan" CLI. This implements commands "generate" and "apply" (partially) for now. * tests/integration.py: Use systemd-networkd-wait-online instead of polling * netplan.5: Add missing NAME section -- Martin Pitt Tue, 16 Aug 2016 16:23:02 +0200 nplan (0.5) yakkety; urgency=medium * Recognize booean values as per YAML spec (LP: #1606839) * Add explicit systemd test dependency * networkd: Disable LinkLocalAddressing and RA for bridge components * Move "generate" from a systemd unit to a systemd generator * Automatically start networkd iff there is any networkd configuration (LP: #1607693) -- Martin Pitt Mon, 01 Aug 2016 17:27:54 +0200 nplan (0.4) yakkety; urgency=medium * tests/integration.py: Avoid stderr output on reset-failed * Document configuration (man, html) -- Martin Pitt Fri, 29 Jul 2016 10:45:33 +0200 nplan (0.3) yakkety; urgency=medium * Properly terminate wifi_access_point_handlers list -- Martin Pitt Tue, 26 Jul 2016 21:57:26 +0200 nplan (0.2) yakkety; urgency=medium * Fix unstable TestConfigArgs.test_file_args() test * Add license/copyright headers to all source files -- Martin Pitt Tue, 26 Jul 2016 16:29:26 +0200 nplan (0.1) yakkety; urgency=medium * Initial release. -- Martin Pitt Tue, 26 Jul 2016 16:14:37 +0200 nplan-0.32~16.04.7~mtrudel1/debian/compat0000664000000000000000000000000213315465032014670 0ustar 9 nplan-0.32~16.04.7~mtrudel1/debian/control0000664000000000000000000000223613533545444015110 0ustar Source: nplan Maintainer: Ubuntu Developers Section: net Priority: important Standards-Version: 3.9.8 Build-Depends: debhelper (>= 9), pkg-config, libyaml-dev, libglib2.0-dev, uuid-dev, python3 (>= 3.1), python3-coverage, python3-yaml, libsystemd-dev, systemd, pyflakes3, pycodestyle | pep8, pandoc, Vcs-Git: https://git.launchpad.net/~netplan-developers/netplan Vcs-Browser: https://git.launchpad.net/~netplan-developers/netplan Package: nplan Architecture: any Multi-Arch: foreign Depends: ${shlibs:Depends}, ${misc:Depends}, systemd (>= 229-4ubuntu20), python3, python3-yaml, Suggests: network-manager | wpasupplicant Breaks: network-manager (<< 1.2.2-0ubuntu4~) Conflicts: netplan Description: YAML network configuration abstraction for various backends netplan reads YAML network configuration files which are written by administrators, installers, cloud image instantiations, or other OS deployments. During early boot it then generates backend specific configuration files in /run to hand off control of devices to a particular networking daemon. . Currently supported backends are networkd and NetworkManager. nplan-0.32~16.04.7~mtrudel1/debian/copyright0000664000000000000000000000042213315465032015423 0ustar Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Files: * Copyright: 2016 Canonical Ltd. License: GPL-3.0 On Debian systems, the complete text of the GNU Lesser General Public License version 3 can be found in "/usr/share/common-licenses/GPL-3". nplan-0.32~16.04.7~mtrudel1/debian/dirs0000664000000000000000000000003013272657635014365 0ustar etc/netplan lib/netplan nplan-0.32~16.04.7~mtrudel1/debian/rules0000775000000000000000000000003613272657635014567 0ustar #!/usr/bin/make -f %: dh $@ nplan-0.32~16.04.7~mtrudel1/debian/tests/0000775000000000000000000000000013272657635014652 5ustar nplan-0.32~16.04.7~mtrudel1/debian/tests/autostart0000775000000000000000000000425413272657635016633 0ustar #!/bin/sh # # Check that netplan and systemd/networkd will properly cooperate and run # out generator at boot. # set -eu if [ ! -x /tmp/autopkgtest-reboot ]; then echo "SKIP: Testbed does not support reboot" exit 0 fi trap 'rm -f /etc/netplan/00test.yaml' EXIT INT QUIT PIPE TERM # parameters: service expect_running assert_is_running() { if [ "$2" = 1 ] && ! systemctl --quiet is-active "$1"; then echo "ERROR: expected $1 to have started, but it was not" >&2 systemctl --no-pager status "$1" exit 1 elif [ "$2" = 0 ] && systemctl --quiet is-active "$1"; then echo "ERROR: expected $1 to not have started, but it was" >&2 systemctl --no-pager status "$1" exit 1 else systemctl --no-pager status "$1" || true fi } case "${AUTOPKGTEST_REBOOT_MARK:-}" in '') echo "INFO: Doing initial check that there is no existing netplan config." if [ -n "$(ls /etc/netplan 2>/dev/null || true)" ]; then echo "SKIP: Testbed already has netplan config" exit 0 fi # right after installation systemd-networkd may or may not be started assert_is_running systemd-networkd.service status echo "INFO: systemd-networkd is fine, rebooting..." /tmp/autopkgtest-reboot noconfig ;; noconfig) echo "INFO: Verifying that the test bridge is not up and writing config." if ip a show dev brtest00 2>/dev/null; then echo "ERROR: brtest00 bridge unexpectedly exists" >&2 exit 1 fi mkdir -p /etc/netplan cat < /etc/netplan/00test.yaml network: version: 2 bridges: brtest00: addresses: [10.42.1.1/24] EOF echo "INFO: Configuration written, rebooting..." /tmp/autopkgtest-reboot config ;; config) echo "INFO: Validate that systemd-networkd is running and our test bridge exists..." assert_is_running systemd-networkd.service 1 ip a show dev brtest00 echo "OK: Test bridge is configured." ;; *) echo "INTERNAL ERROR: autopkgtest marker $AUTOPKGTEST_REBOOT_MARK unexpected" >&2 exit 1 ;; esac nplan-0.32~16.04.7~mtrudel1/debian/tests/control0000664000000000000000000000037213272657635016257 0ustar Tests: integration.py Tests-Directory: tests Depends: @, systemd, network-manager, hostapd, dnsmasq-base, Restrictions: allow-stderr, needs-root, isolation-machine Tests: autostart Restrictions: allow-stderr, needs-root, isolation-container nplan-0.32~16.04.7~mtrudel1/doc/0000775000000000000000000000000013315466247013026 5ustar nplan-0.32~16.04.7~mtrudel1/doc/example-config0000664000000000000000000000346313272657635015662 0ustar network: version: 2 # if specified, can only realistically have that value, as networkd cannot # render wifi/3G. This would be shipped as a separate snippet by desktop images. #renderer: NetworkManager ethernets: # opaque ID for physical interfaces, only referred to by other stanzas id0: match: macaddress: 00:11:22:33:44:55 wakeonlan: true dhcp4: true addresses: - 192.168.14.2/24 - "2001:1::1/64" gateway4: 192.168.14.1 gateway6: "2001:1::2" routes: - to: 11.22.0.0/16 via: 192.168.14.3 metric: 100 nameservers: search: [foo.local, bar.local] addresses: [8.8.8.8] lom: match: driver: ixgbe # you are responsible for setting tight enough match rules # that only match one device if you use set-name set-name: lom1 dhcp6: true switchports: # all cards on second PCI bus; unconfigured by themselves, will be added # to br0 below (note: globbing is not supported by NetworkManager) match: name: enp2* mtu: 1280 wifis: all-wlans: # useful on a system where you know there is only ever going to be one device match: {} access-points: "Joe's home": # mode defaults to "managed" (client) password: "s3kr1t" # this creates an AP on wlp1s0 using hostapd; no match rules, thus ID is # the interface name wlp1s0: access-points: "guest": mode: ap # no WPA config implies default of open bridges: # the key name is the name for virtual (created) interfaces; no match: and # set-name: allowed br0: # IDs of the components; switchports expands into multiple interfaces interfaces: [wlp1s0, switchports] dhcp4: true nplan-0.32~16.04.7~mtrudel1/doc/netplan.md0000664000000000000000000005445213315465032015012 0ustar --- title: netplan section: 5 author: - Mathieu Trudel-Lapierre () - Martin Pitt () ... Introduction ============ Distribution installers, cloud instantiation, image builds for particular devices, or any other way to deploy an operating system put its desired network configuration into YAML configuration file(s). During early boot, the netplan "network renderer" runs which reads ``/{lib,etc,run}/netplan/*.yaml`` and writes configuration to ``/run`` to hand off control of devices to the specified networking daemon. - Configured devices get handled by systemd-networkd by default, unless explicitly marked as managed by a specific renderer (NetworkManager) - Devices not covered by the network config do not get touched at all. - Usable in initramfs (few dependencies and fast) - No persistent generated config, only original YAML config - Parser supports multiple config files to allow applications like libvirt or lxd to package up expected network config (``virbr0``, ``lxdbr0``), or to change the global default policy to use NetworkManager for everything. - Retains the flexibility to change backends/policy later or adjust to removing NetworkManager, as generated configuration is ephemeral. General structure ================= netplan's configuration files use the [YAML]() format. All ``/{lib,etc,run}/netplan/*.yaml`` are considered. Lexicographically later files (regardless of in which directory they are) amend (new mapping keys) or override (same mapping keys) previous ones. A file in ``/run/netplan`` completely shadows a file with same name in ``/etc/netplan``, and a file in either of those directories shadows a file with the same name in ``/lib/netplan``. The top-level node in a netplan configuration file is a ``network:`` mapping that contains ``version: 2`` (the YAML currently being used by curtin, MaaS, etc. is version 1), and then device definitions grouped by their type, such as ``ethernets:``, ``wifis:``, or ``bridges:``. These are the types that our renderer can understand and are supported by our backends. Each type block contains device definitions as a map where the keys (called "configuration IDs") are defined as below. Device configuration IDs ======================== The key names below the per-device-type definition maps (like ``ethernets:``) are called "ID"s. They must be unique throughout the entire set of configuration files. Their primary purpose is to serve as anchor names for composite devices, for example to enumerate the members of a bridge that is currently being defined. There are two physically/structurally different classes of device definitions, and the ID field has a different interpretation for each: Physical devices : (Examples: ethernet, wifi) These can dynamically come and go between reboots and even during runtime (hotplugging). In the generic case, they can be selected by ``match:`` rules on desired properties, such as name/name pattern, MAC address, driver, or device paths. In general these will match any number of devices (unless they refer to properties which are unique such as the full path or MAC address), so without further knowledge about the hardware these will always be considered as a group. It is valid to specify no match rules at all, in which case the ID field is simply the interface name to be matched. This is mostly useful if you want to keep simple cases simple, and it's how network device configuration has been done for a long time. If there are ``match``: rules, then the ID field is a purely opaque name which is only being used for references from definitions of compound devices in the config. Virtual devices : (Examples: veth, bridge, bond) These are fully under the control of the config file(s) and the network stack. I. e. these devices are being created instead of matched. Thus ``match:`` and ``set-name:`` are not applicable for these, and the ID field is the name of the created virtual device. Common properties for physical device types =========================================== ``match`` (mapping) : This selects a subset of available physical devices by various hardware properties. The following configuration will then apply to all matching devices, as soon as they appear. *All* specified properties must match. ``name`` (scalar) : Current interface name. Globs are supported, and the primary use case for matching on names, as selecting one fixed name can be more easily achieved with having no ``match:`` at all and just using the ID (see above). Note that currently only networkd supports globbing, NetworkManager does not. ``macaddress`` (scalar) : Device's MAC address in the form "XX:XX:XX:XX:XX:XX". Globs are not allowed. ``driver`` (scalar) : Kernel driver name, corresponding to the ``DRIVER`` udev property. Globs are supported. Matching on driver is *only* supported with networkd. Examples: - all cards on second PCI bus: match: name: enp2* - fixed MAC address: match: macaddress: 11:22:33:AA:BB:FF - first card of driver ``ixgbe``: match: driver: ixgbe name: en*s0 ``set-name`` (scalar) : When matching on unique properties such as path or MAC, or with additional assumptions such as "there will only ever be one wifi device", match rules can be written so that they only match one device. Then this property can be used to give that device a more specific/desirable/nicer name than the default from udev’s ifnames. Any additional device that satisfies the match rules will then fail to get renamed and keep the original kernel name (and dmesg will show an error). ``wakeonlan`` (bool) : Enable wake on LAN. Off by default. Common properties for all device types ====================================== ``renderer`` (scalar) : Use the given networking backend for this definition. Currently supported are ``networkd`` and ``NetworkManager``. This property can be specified globally in ``networks:``, for a device type (in e. g. ``ethernets:``) or for a particular device definition. Default is ``networkd``. ``dhcp4`` (bool) : Enable DHCP for IPv4. Off by default. ``dhcp6`` (bool) : Enable DHCP for IPv6. Off by default. ``dhcp-identifier`` (scalar) : When set to 'mac'; pass that setting over to systemd-networkd to use the device's MAC address as a unique identifier rather than a RFC4361-compliant Client ID. This has no effect when NetworkManager is used as a renderer. ``critical`` (bool) : (networkd backend only) Designate the connection as "critical to the system", meaning that special care will be taken by systemd-networkd to not release the IP from DHCP when it the daemon is restarted. ``accept-ra`` (bool) : Accept Router Advertisement that would have the kernel configure IPv6 by itself. When enabled, accept Router Advertisements. When disabled, do not respond to Router Advertisements. If unset use the host kernel default setting. ``addresses`` (sequence of scalars) : Add static addresses to the interface in addition to the ones received through DHCP or RA. Each sequence entry is in CIDR notation, i. e. of the form ``addr/prefixlen``. ``addr`` is an IPv4 or IPv6 address as recognized by **``inet_pton``**(3) and ``prefixlen`` the number of bits of the subnet. Example: ``addresses: [192.168.14.2/24, "2001:1::1/64"]`` ``gateway4``, ``gateway6`` (scalar) : Set default gateway for IPv4/6, for manual address configuration. This requires setting ``addresses`` too. Gateway IPs must be in a form recognized by **``inet_pton``**(3). Example for IPv4: ``gateway4: 172.16.0.1`` Example for IPv6: ``gateway6: "2001:4::1"`` ``nameservers`` (mapping) : Set DNS servers and search domains, for manual address configuration. There are two supported fields: ``addresses:`` is a list of IPv4 or IPv6 addresses similar to ``gateway*``, and ``search:`` is a list of search domains. Example: ethernets: id0: [...] nameservers: search: [lab, home] addresses: [8.8.8.8, "FEDC::1"] ``macaddress`` (scalar) : Set the device's MAC address. The MAC address must be in the form "XX:XX:XX:XX:XX:XX". Example: ethernets: id0: [...] macaddress: 52:54:00:6b:3c:59 ``optional`` (boolean) : An optional device is not required for booting. Normally, networkd will wait some time for device to become configured before proceeding with booting. However, if a device is marked as optional, networkd will not wait for it. This is *only* supported by networkd, and the default is false. Example: ethernets: eth7: # this is plugged into a test network that is often # down - don't wait for it to come up during boot. dhcp4: true optional: true Properties for device type ``ethernets:`` ========================================= Ethernet device definitions do not support any specific properties beyond the common ones described above. Properties for device type ``wifis:`` ===================================== Note that ``systemd-networkd`` does not natively support wifi, so you need wpasupplicant installed if you let the ``networkd`` renderer handle wifi. ``access-points`` (mapping) : This provides pre-configured connections to NetworkManager. Note that users can of course select other access points/SSIDs. The keys of the mapping are the SSIDs, and the values are mappings with the following supported properties: ``password`` (scalar) : Enable WPA2 authentication and set the passphrase for it. If not given, the network is assumed to be open. Other authentication modes are not currently supported. ``mode`` (scalar) : Possible access point modes are ``infrastructure`` (the default), ``ap`` (create an access point to which other devices can connect), and ``adhoc`` (peer to peer networks without a central access point). ``ap`` is only supported with NetworkManager. Properties for device type ``bridges:`` ======================================= ``interfaces`` (sequence of scalars) : All devices matching this ID list will be added to the bridge. Example: ethernets: switchports: match: {name: "enp2*"} [...] bridges: br0: interfaces: [switchports] ``parameters`` (mapping) : Customization parameters for special bridging options. Unless otherwise specified, parameter values for time intervals should be expressed in milliseconds, but can also be expressed in seconds using a time suffix (such as "s" for seconds, "ms" for milliseconds). ``ageing-time`` (scalar) : Set the period of time (in seconds) to keep a MAC address in the forwarding database after a packet is received. This maps to the AgeingTimeSec= property when the networkd renderer is used. ``priority`` (scalar) : Set the priority value for the bridge. This value should be a number between ``0`` and ``65535``. Lower values mean higher priority. The bridge with the higher priority will be elected as the root bridge. ``port-priority`` (scalar) : Set the port priority to . The priority value is a number between ``0`` and ``63``. This metric is used in the designated port and root port selection algorithms. ``forward-delay`` (scalar) : Specify the period of time (in seconds) the bridge will remain in Listening and Learning states before getting to the Forwarding state. This field maps to the ForwardDelaySec= property for the networkd renderer. ``hello-time`` (scalar) : Specify the interval (in seconds) between two hello packets being sent out from the root and designated bridges. Hello packets communicate information about the network topology. When the networkd renderer is used, this maps to the HelloTimeSec= property. ``max-age`` (scalar) : Set the maximum age (in seconds) of a hello packet. If the last hello packet is older than that value, the bridge will attempt to become the root bridge. This maps to the MaxAgeSec= property when the networkd renderer is used. ``path-cost`` (scalar) : Set the cost of a path on the bridge. Faster interfaces should have a lower cost. This allows a finer control on the network topology so that the fastest paths are available whenever possible. ``stp`` (bool) : Define whether the bridge should use Spanning Tree Protocol. The default value is "true", which means that Spanning Tree should be used. Properties for device type ``bonds:`` ======================================= ``interfaces`` (sequence of scalars) : All devices matching this ID list will be added to the bond. Example: ethernets: switchports: match: {name: "enp2*"} [...] bonds: bond0: interfaces: [switchports] ``parameters`` (mapping) : Customization parameters for special bonding options. Unless otherwise specified, parameter values for time intervals should be expressed in milliseconds, but can also be expressed in seconds using a time suffix (such as "s" for seconds, "ms" for milliseconds). ``mode`` (scalar) : Set the bonding mode used for the interfaces. The default is ``balance-rr`` (round robin). Possible values are ``balance-rr``, ``active-backup``, ``balance-xor``, ``broadcast``, ``802.3ad``, ``balance-tlb``, and ``balance-alb``. ``lacp-rate`` (scalar) : Set the rate at which LACPDUs are transmitted. This is only useful in 802.3ad mode. Possible values are ``slow`` (30 seconds, default), and ``fast`` (every second). ``mii-monitor-interval`` (scalar) : Specifies the interval for MII monitoring (verifying if an interface of the bond has carrier). The default is ``0``; which disables MII monitoring. This is equivalent to the MIIMonitorSec= field for the networkd backend. ``min-links`` (scalar) : The minimum number of links up in a bond to consider the bond interface to be up. ``transmit-hash-policy`` (scalar) : Specifies the transmit hash policy for the selection of slaves. This is only useful in balance-xor, 802.3ad and balance-tlb modes. Possible values are ``layer2``, ``layer3+4``, ``layer2+3``, ``encap2+3``, and ``encap3+4``. ``ad-select`` (scalar) : Set the aggregation selection mode. Possible values are ``stable``, ``bandwidth``, and ``count``. This option is only used in 802.3ad mode. ``all-slaves-active`` (bool) : If the bond should drop duplicate frames received on inactive ports, set this option to ``false``. If they should be delivered, set this option to ``true``. The default value is false, and is the desirable behavior in most situations. ``arp-interval`` (scalar) : Set the interval value for how frequently ARP link monitoring should happen. The default value is ``0``, which disables ARP monitoring. For the networkd backend, this maps to the ARPIntervalSec= property. ``arp-ip-targets`` (sequence of scalars) : IPs of other hosts on the link which should be sent ARP requests in order to validate that a slave is up. This option is only used when ``arp-interval`` is set to a value other than ``0``. At least one IP address must be given for ARP link monitoring to function. Only IPv4 addresses are supported. You can specify up to 16 IP addresses. The default value is an empty list. ``arp-validate`` (scalar) : Configure how ARP replies are to be validated when using ARP link monitoring. Possible values are ``none``, ``active``, ``backup``, and ``all``. ``arp-all-targets`` (scalar) : Specify whether to use any ARP IP target being up as sufficient for a slave to be considered up; or if all the targets must be up. This is only used for ``active-backup`` mode when ``arp-validate`` is enabled. Possible values are ``any`` and ``all``. ``up-delay`` (scalar) : Specify the delay before enabling a link once the link is physically up. The default value is ``0``. This maps to the UpDelaySec= property for the networkd renderer. ``down-delay`` (scalar) : Specify the delay before disabling a link once the link has been lost. The default value is ``0``. This maps to the DownDelaySec= property for the networkd renderer. ``fail-over-mac-policy`` (scalar) : Set whether to set all slaves to the same MAC address when adding them to the bond, or how else the system should handle MAC addresses. The possible values are ``none``, ``active``, and ``follow``. ``gratuitious-arp`` (scalar) : Specify how many ARP packets to send after failover. Once a link is up on a new slave, a notification is sent and possibly repeated if this value is set to a number greater than ``1``. The default value is ``1`` and valid values are between ``1`` and ``255``. This only affects ``active-backup`` mode. ``packets-per-slave`` (scalar) : In ``balance-rr`` mode, specifies the number of packets to transmit on a slave before switching to the next. When this value is set to ``0``, slaves are chosen at random. Allowable values are between ``0`` and ``65535``. The default value is ``1``. This setting is only used in ``balance-rr`` mode. ``primary-reselect-policy`` (scalar) : Set the reselection policy for the primary slave. On failure of the active slave, the system will use this policy to decide how the new active slave will be chosen and how recovery will be handled. The possible values are ``always``, ``better``, and ``failure``. ``resend-igmp`` (scalar) : In modes ``balance-rr``, ``active-backup``, ``balance-tlb`` and ``balance-alb``, a failover can switch IGMP traffic from one slave to another. This parameter specifies how many IGMP membership reports are issued on a failover event. Values range from 0 to 255. 0 disables sending membership reports. Otherwise, the first membership report is sent on failover and subsequent reports are sent at 200ms intervals. ``learn-packet-interval`` (scalar) : Specify the interval (seconds) between sending learning packets to each slave. The value range is between ``1`` and ``0x7fffffff``. The default value is ``1``. This option only affects ``balance-tlb`` and ``balance-alb`` modes. Using the networkd renderer, this field maps to the LearnPacketIntervalSec= property. ``primary`` (scalar) : Specify a device to be used as a primary slave, or preferred device to use as a slave for the bond (ie. the preferred device to send data through), whenever it is available. This only affects ``active-backup``, ``balance-alb``, and ``balance-tlb`` modes. Properties for device type ``vlans:`` ======================================= ``id`` (scalar) : VLAN ID, a number between 0 and 4094. ``link`` (scalar) : netplan ID of the underlying device definition on which this VLAN gets created. Example: ethernets: eno1: {...} vlans: en-intra: id: 1 link: eno1 dhcp4: yes en-vpn: id: 2 link: eno1 address: ... Examples ======== Configure an ethernet device with networkd, identified by its name, and enable DHCP: network: version: 2 ethernets: eno1: dhcp4: true This is a complex example which shows most available features: network: version: 2 # if specified, can only realistically have that value, as networkd cannot # render wifi/3G. renderer: NetworkManager ethernets: # opaque ID for physical interfaces, only referred to by other stanzas id0: match: macaddress: 00:11:22:33:44:55 wakeonlan: true dhcp4: true addresses: - 192.168.14.2/24 - "2001:1::1/64" gateway4: 192.168.14.1 gateway6: "2001:1::2" nameservers: search: [foo.local, bar.local] addresses: [8.8.8.8] routes: - to: 0.0.0.0/0 via: 11.0.0.1 metric: 3 lom: match: driver: ixgbe # you are responsible for setting tight enough match rules # that only match one device if you use set-name set-name: lom1 dhcp6: true switchports: # all cards on second PCI bus; unconfigured by themselves, will be added # to br0 below (note: globbing is not supported by NetworkManager) match: name: enp2* mtu: 1280 wifis: all-wlans: # useful on a system where you know there is only ever going to be one device match: {} access-points: "Joe's home": # mode defaults to "infrastructure" (client) password: "s3kr1t" # this creates an AP on wlp1s0 using hostapd; no match rules, thus ID is # the interface name wlp1s0: access-points: "guest": mode: ap # no WPA config implies default of open bridges: # the key name is the name for virtual (created) interfaces; no match: and # set-name: allowed br0: # IDs of the components; switchports expands into multiple interfaces interfaces: [wlp1s0, switchports] dhcp4: true nplan-0.32~16.04.7~mtrudel1/src/0000775000000000000000000000000013534225717013046 5ustar nplan-0.32~16.04.7~mtrudel1/src/dbus.c0000664000000000000000000000536013533506646014155 0ustar #include #include #include #include #include #include #include #include #include static int method_apply(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) { g_autoptr(GError) err = NULL; g_autofree gchar *stdout = NULL; g_autofree gchar *stderr = NULL; gint exit_status = 0; gchar *argv[] = {SBINDIR "/" "netplan", "apply", NULL}; // for tests only: allow changing what netplan to run if (getuid() != 0 && getenv("DBUS_TEST_NETPLAN_CMD") != 0) { argv[0] = getenv("DBUS_TEST_NETPLAN_CMD"); } g_spawn_sync("/", argv, NULL, 0, NULL, NULL, &stdout, &stderr, &exit_status, &err); if (err != NULL) { return sd_bus_error_setf(ret_error, SD_BUS_ERROR_FAILED, "cannot run netplan apply: %s", err->message); } g_spawn_check_exit_status(exit_status, &err); if (err != NULL) { return sd_bus_error_setf(ret_error, SD_BUS_ERROR_FAILED, "netplan apply failed: %s\nstdout: '%s'\nstderr: '%s'", err->message, stdout, stderr); } return sd_bus_reply_method_return(m, "b", true); } static const sd_bus_vtable netplan_vtable[] = { SD_BUS_VTABLE_START(0), SD_BUS_METHOD("Apply", "", "b", method_apply, 0), SD_BUS_VTABLE_END }; int main(int argc, char *argv[]) { sd_bus_slot *slot = NULL; sd_bus *bus = NULL; int r; r = sd_bus_open_system(&bus); if (r < 0) { fprintf(stderr, "Failed to connect to system bus: %s\n", strerror(-r)); goto finish; } r = sd_bus_add_object_vtable(bus, &slot, "/io/netplan/Netplan", /* object path */ "io.netplan.Netplan", /* interface name */ netplan_vtable, NULL); if (r < 0) { fprintf(stderr, "Failed to issue method call: %s\n", strerror(-r)); goto finish; } r = sd_bus_request_name(bus, "io.netplan.Netplan", 0); if (r < 0) { fprintf(stderr, "Failed to acquire service name: %s\n", strerror(-r)); goto finish; } for (;;) { r = sd_bus_process(bus, NULL); if (r < 0) { fprintf(stderr, "Failed to process bus: %s\n", strerror(-r)); goto finish; } if (r > 0) continue; /* Wait for the next request to process */ r = sd_bus_wait(bus, (uint64_t) -1); if (r < 0) { fprintf(stderr, "Failed to wait on bus: %s\n", strerror(-r)); goto finish; } } finish: sd_bus_slot_unref(slot); sd_bus_unref(bus); return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS; } nplan-0.32~16.04.7~mtrudel1/src/generate.c0000664000000000000000000001673313315465032015007 0ustar /* * Copyright (C) 2016 Canonical, Ltd. * Author: Martin Pitt * * 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; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include #include #include "util.h" #include "parse.h" #include "networkd.h" #include "nm.h" static gchar* rootdir; static gchar** files; static gboolean any_networkd; static GOptionEntry options[] = { {"root-dir", 'r', 0, G_OPTION_ARG_FILENAME, &rootdir, "Search for and generate configuration files in this root directory instead of /"}, {G_OPTION_REMAINING, 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &files, "Read configuration from this/these file(s) instead of /etc/netplan/*.yaml", "[config file ..]"}, {NULL} }; static void reload_udevd(void) { const gchar *argv[] = { "/sbin/udevadm", "control", "--reload", NULL }; g_spawn_sync(NULL, (gchar**)argv, NULL, G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, NULL, NULL, NULL, NULL); }; static void nd_iterator(gpointer key, gpointer value, gpointer user_data) { if (write_networkd_conf((net_definition*) value, (const char*) user_data)) any_networkd = TRUE; write_nm_conf((net_definition*) value, (const char*) user_data); } static void process_input_file(const char* f) { GError* error = NULL; g_debug("Processing input file %s..", f); if (!parse_yaml(f, &error)) { g_fprintf(stderr, "%s\n", error->message); exit(1); } } int main(int argc, char** argv) { GError* error = NULL; GOptionContext* opt_context; /* are we being called as systemd generator? */ gboolean called_as_generator = (strstr(argv[0], "systemd/system-generators/") != NULL); g_autofree char* generator_run_stamp = NULL; /* Parse CLI options */ opt_context = g_option_context_new(NULL); if (called_as_generator) g_option_context_set_help_enabled(opt_context, FALSE); g_option_context_set_summary(opt_context, "Generate backend network configuration from netplan YAML definition."); g_option_context_set_description(opt_context, "This program reads the specified netplan YAML definition file(s)\n" "or, if none are given, /etc/netplan/*.yaml.\n" "It then generates the corresponding systemd-networkd, NetworkManager,\n" "and udev configuration files in /run."); g_option_context_add_main_entries(opt_context, options, NULL); if (!g_option_context_parse(opt_context, &argc, &argv, &error)) { g_fprintf(stderr, "failed to parse options: %s\n", error->message); return 1; } if (called_as_generator) { if (files == NULL || g_strv_length(files) != 3 || files[0] == NULL) { g_fprintf(stderr, "%s can not be called directly, use 'netplan generate'.", argv[0]); return 1; } generator_run_stamp = g_build_path(G_DIR_SEPARATOR_S, files[0], "netplan.stamp", NULL); if (g_access(generator_run_stamp, F_OK) == 0) { g_fprintf(stderr, "netplan generate already ran, remove %s to force re-run\n", generator_run_stamp); return 0; } } /* Read all input files */ if (files && !called_as_generator) { for (gchar** f = files; f && *f; ++f) process_input_file(*f); } else { /* Files with asciibetically higher names override/append settings from * earlier ones (in all config dirs); files in /run/netplan/ * shadow files in /etc/netplan/ which shadow files in /lib/netplan/. * To do that, we put all found files in a hash table, then sort it by * file name, and add the entries from /run after the ones from /etc * and those after the ones from /lib. */ g_autofree char* glob_etc = g_strjoin(NULL, rootdir ?: "", G_DIR_SEPARATOR_S, "/etc/netplan/*.yaml", NULL); g_autofree char* glob_run = g_strjoin(NULL, rootdir ?: "", G_DIR_SEPARATOR_S, "/run/netplan/*.yaml", NULL); g_autofree char* glob_lib = g_strjoin(NULL, rootdir ?: "", G_DIR_SEPARATOR_S, "/lib/netplan/*.yaml", NULL); glob_t gl; int rc; /* keys are strdup()ed, free them; values point into the glob_t, don't free them */ g_autoptr(GHashTable) configs = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL); g_autoptr(GList) config_keys = NULL; rc = glob(glob_lib, 0, NULL, &gl); if (rc != 0 && rc != GLOB_NOMATCH) { g_fprintf(stderr, "failed to glob for %s: %m\n", glob_lib); /* LCOV_EXCL_LINE */ return 1; /* LCOV_EXCL_LINE */ } rc = glob(glob_etc, GLOB_APPEND, NULL, &gl); if (rc != 0 && rc != GLOB_NOMATCH) { g_fprintf(stderr, "failed to glob for %s: %m\n", glob_etc); /* LCOV_EXCL_LINE */ return 1; /* LCOV_EXCL_LINE */ } rc = glob(glob_run, GLOB_APPEND, NULL, &gl); if (rc != 0 && rc != GLOB_NOMATCH) { g_fprintf(stderr, "failed to glob for %s: %m\n", glob_run); /* LCOV_EXCL_LINE */ return 1; /* LCOV_EXCL_LINE */ } for (size_t i = 0; i < gl.gl_pathc; ++i) g_hash_table_insert(configs, g_path_get_basename(gl.gl_pathv[i]), gl.gl_pathv[i]); config_keys = g_list_sort(g_hash_table_get_keys(configs), (GCompareFunc) strcmp); for (GList* i = config_keys; i != NULL; i = i->next) process_input_file(g_hash_table_lookup(configs, i->data)); } g_assert(finish_parse(&error)); /* Clean up generated config from previous runs */ cleanup_networkd_conf(rootdir); cleanup_nm_conf(rootdir); /* Generate backend specific configuration files from merged data. */ if (netdefs) { g_debug("Generating output files.."); g_hash_table_foreach(netdefs, nd_iterator, rootdir); write_nm_conf_finish(rootdir); /* We may have written .rules & .link files, thus we must * invalidate udevd cache of its config as by default it only * invalidates cache at most every 3 seconds. Not sure if this * should live in `generate' or `apply', but it is confusing * when udevd ignores just-in-time created rules files. */ reload_udevd(); } /* Disable /usr/lib/NetworkManager/conf.d/10-globally-managed-devices.conf * (which restricts NM to wifi and wwan) if global renderer is NM */ if (get_global_backend() == BACKEND_NM) g_string_free_to_file(g_string_new(NULL), rootdir, "/run/NetworkManager/conf.d/10-globally-managed-devices.conf", NULL); if (called_as_generator) { /* Ensure networkd starts if we have any configuration for it */ if (any_networkd) enable_networkd(files[0]); /* Leave a stamp file so that we don't regenerate the configuration * multiple times and userspace can wait for it to finish */ FILE* f = fopen(generator_run_stamp, "w"); g_assert(f != NULL); fclose(f); } return 0; } nplan-0.32~16.04.7~mtrudel1/src/netplan0000775000000000000000000004370413534004427014436 0ustar #!/usr/bin/python3 # # Copyright (C) 2016 Canonical, Ltd. # Author: Martin Pitt # # 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; version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . '''netplan command line''' import argparse import logging import os import sys import re import shutil import subprocess from glob import glob import yaml path_generate = os.environ.get('NETPLAN_GENERATE_PATH', '/lib/netplan/generate') NM_SERVICE_NAME = 'NetworkManager.service' NM_SNAP_SERVICE_NAME = 'snap.network-manager.networkmanager.service' # # helper functions # def parse_args(): parser = argparse.ArgumentParser(description='netplan commands') parser.add_argument('--debug', action='store_true', help='Enable debug messages') subparsers = parser.add_subparsers(title='Available commands (see "netplan --help")', metavar='', dest='command') # command: generate p_generate = subparsers.add_parser('generate', help='Generate backend specific configuration files from /etc/netplan/*.yaml.') p_generate.add_argument('--root-dir', help='Search for and generate configuration files in this root directory instead of /') # command: apply p_generate = subparsers.add_parser('apply', help='Apply current netplan config to running system (use with care!)') # command: ifupdown-migrate p_ifupdown = subparsers.add_parser('ifupdown-migrate', help='Try to convert /etc/network/interfaces to netplan. ' 'If successful, disable /etc/network/interfaces.') p_ifupdown.add_argument('--root-dir', help='Search for and generate configuration files in this root directory instead of /') p_ifupdown.add_argument('--dry-run', action='store_true', help='Print converted netplan configuration to stdout instead of writing/changing files') args = parser.parse_args() if not args.command: parser.error('You need to specify a command') return args def is_nm_snap_enabled(): # pragma: nocover (covered in autopkgtest) return subprocess.call(['systemctl', '--quiet', 'is-enabled', NM_SNAP_SERVICE_NAME], stderr=subprocess.DEVNULL) == 0 def nmcli(args): # pragma: nocover (covered in autopkgtest) binary_name = 'nmcli' if is_nm_snap_enabled(): binary_name = 'network-manager.nmcli' subprocess.check_call([binary_name] + args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) def nm_running(): # pragma: nocover (covered in autopkgtest) '''Check if NetworkManager is running''' try: nmcli(['general']) return True except (OSError, subprocess.SubprocessError): return False def systemctl_network_manager(action): # pragma: nocover (covered in autopkgtest) service_name = NM_SERVICE_NAME # If the network-manager snap is installed use its service # name rather than the one of the deb packaged NetworkManager if is_nm_snap_enabled(): service_name = NM_SNAP_SERVICE_NAME subprocess.check_call(['systemctl', action, '--no-block', service_name]) def replug(device): # pragma: nocover (covered in autopkgtest) '''Unbind and rebind device if it is down''' devdir = os.path.join('/sys/class/net', device) try: with open(os.path.join(devdir, 'operstate')) as f: state = f.read().strip() if state != 'down': logging.debug('device %s operstate is %s, not replugging', device, state) return False except IOError as e: logging.error('Cannot determine operstate of %s: %s', device, str(e)) return False # /sys/class/net/ens3/device -> ../../../virtio0 # /sys/class/net/ens3/device/driver -> ../../../../bus/virtio/drivers/virtio_net try: devname = os.path.basename(os.readlink(os.path.join(devdir, 'device'))) except IOError as e: logging.debug('Cannot replug %s: cannot read link %s/device: %s', device, devdir, str(e)) return False try: # we must resolve symlinks here as the device dir will be gone after unbind subsystem = os.path.realpath(os.path.join(devdir, 'device', 'subsystem')) subsystem_name = os.path.basename(subsystem) driver = os.path.realpath(os.path.join(devdir, 'device', 'driver')) driver_name = os.path.basename(driver) if driver_name == 'mac80211_hwsim': logging.debug('replug %s: mac80211_hwsim does not support rebinding, ignoring', device) return False # workaround for https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1630285 if driver_name == 'mwifiex_pcie': logging.debug('replug %s: mwifiex_pcie crashes on rebinding, ignoring', device) return False # workaround for https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1729573 if subsystem_name == 'xen' and driver_name == 'vif': logging.debug('replug %s: xen:vif fails on rebinding, ignoring', device) return False # workaround for problem with ath9k_htc module: this driver is async and does not support # sequential unbind / rebind, one soon after the other if driver_name == 'ath9k_htc': logging.debug('replug %s: ath9k_htc does not support rebinding, ignoring', device) return False # workaround for brcmfmac, interface will be gone after unbind if 'brcmfmac' in driver_name: logging.debug('replug %s: brcmfmac drivers do not support rebinding, ignoring', device) return False # workaround for ath6kl_sdio, interface does not work after unbinding if 'ath6kl_sdio' in driver_name: logging.debug('replug %s: ath6kl_sdio driver does not support rebinding, ignoring', device) return False # workaround for qeth: driver does not recognize unbind command # https://bugs.launchpad.net/ubuntu/+source/netplan.io/+bug/1756322 if driver_name == 'qeth': logging.debug('replug %s: qeth driver do not support rebinding, ignoring (LP: #1756322)', device) return False logging.debug('replug %s: unbinding %s from %s', device, devname, driver) with open(os.path.join(driver, 'unbind'), 'w') as f: f.write(devname) logging.debug('replug %s: rebinding %s to %s', device, devname, driver) with open(os.path.join(driver, 'bind'), 'w') as f: f.write(devname) except IOError as e: logging.error('Cannot replug %s: %s', device, str(e)) return False return True def _ifupdown_lines_from_file(rootdir, path): '''Return normalized lines from ifupdown config This resolves "source" and "source-directory" includes. ''' def expand_source_arg(rootdir, curdir, line): arg = line.split()[1] if arg.startswith('/'): return rootdir + arg else: return curdir + '/' + arg lines = [] rootdir_len = len(rootdir) + 1 try: with open(rootdir + '/' + path) as f: logging.debug('reading %s', f.name) for line in f: # normalize, strip empty lines and comments line = line.strip() if not line or line.startswith('#'): continue if line.startswith('source-directory '): valid_re = re.compile('^[a-zA-Z0-9_-]+$') d = expand_source_arg(rootdir, os.path.dirname(f.name), line) for f in os.listdir(d): if valid_re.match(f): lines += _ifupdown_lines_from_file(rootdir, os.path.join(d[rootdir_len:], f)) elif line.startswith('source '): for f in glob(expand_source_arg(rootdir, os.path.dirname(f.name), line)): lines += _ifupdown_lines_from_file(rootdir, f[rootdir_len:]) else: lines.append(line) except FileNotFoundError: logging.debug('%s/%s does not exist, ignoring', rootdir, path) return lines def parse_ifupdown(rootdir='/'): '''Parse ifupdown configuration. Return (iface_name → family → {method, options}, auto_ifaces: set) tuple on successful parsing, or a ValueError when encountering an invalid file or ifupdown features which are not supported (such as "mapping"). options is itself a dictionary option_name → value. ''' # expected number of fields for every possible keyword, excluding the keyword itself fieldlen = {'auto': 1, 'allow-auto': 1, 'allow-hotplug': 1, 'mapping': 1, 'no-scripts': 1, 'iface': 3} # read and normalize all lines from config, with resolving includes lines = _ifupdown_lines_from_file(rootdir, '/etc/network/interfaces') ifaces = {} auto = set() in_options = None # interface name if parsing options lines after iface stanza in_family = None # we now have resolved all includes and normalized lines for line in lines: fields = line.split() try: # does the line start with a known stanza field? exp_len = fieldlen[fields[0]] logging.debug('line fields %s (expected length: %i)', fields, exp_len) in_options = None # stop option line parsing of iface stanza in_family = None except KeyError: # no known stanza field, are we in an iface stanza and parsing options? if in_options: logging.debug('in_options %s, parsing as option: %s', in_options, line) ifaces[in_options][in_family]['options'][fields[0]] = line.split(maxsplit=1)[1] continue else: raise ValueError('Unknown stanza type %s' % fields[0]) # do we have the expected #parameters? if len(fields) != exp_len + 1: raise ValueError('Expected %i fields for stanza type %s but got %i' % (exp_len, fields[0], len(fields) - 1)) # we have a valid stanza line now, handle them if fields[0] in ('auto', 'allow-auto', 'allow-hotplug'): auto.add(fields[1]) elif fields[0] == 'mapping': raise ValueError('mapping stanza is not supported') elif fields[0] == 'no-scripts': pass # ignore these elif fields[0] == 'iface': if fields[2] not in ('inet', 'inet6'): raise ValueError('Unknown address family %s' % fields[2]) if fields[3] not in ('loopback', 'static', 'dhcp'): raise ValueError('Unsupported method %s' % fields[3]) in_options = fields[1] in_family = fields[2] ifaces.setdefault(fields[1], {})[in_family] = {'method': fields[3], 'options': {}} else: raise NotImplementedError('stanza type %s is not implemented' % fields[0]) # pragma nocover logging.debug('final parsed interfaces: %s; auto ifaces: %s', ifaces, auto) return (ifaces, auto) # # implementation of the top-level commands # def command_generate(): argv = [path_generate] if args.root_dir: argv += ['--root-dir', args.root_dir] logging.debug('command generate: running %s', argv) # FIXME: os.execv(argv[0], argv) would be better but fails coverage sys.exit(subprocess.call(argv)) def command_apply(): # pragma: nocover (covered in autopkgtest) # if we are inside a snap, then call dbus to run netplan apply instead if "SNAP" in os.environ: # TODO: maybe check if we are inside a classic snap and don't do # this if we are in a classic snap? busctl = shutil.which("busctl") if busctl is None: raise RuntimeError("missing busctl utility") res = subprocess.call([busctl, "call", "--quiet", "--system", "io.netplan.Netplan", # the service "/io/netplan/Netplan", # the object "io.netplan.Netplan", # the interface "Apply", # the method ]) if res != 0: if res == 130: raise PermissionError( "failed to communicate with dbus service") elif res == 1: raise RuntimeError( "failed to communicate with dbus service") sys.exit(res) else: return if subprocess.call([path_generate]) != 0: sys.exit(1) devices = os.listdir('/sys/class/net') restart_networkd = bool(glob('/run/systemd/network/*netplan-*')) restart_nm = bool(glob('/run/NetworkManager/system-connections/netplan-*')) # stop backends if restart_networkd: logging.debug('netplan generated networkd configuration exists, restarting networkd') subprocess.check_call(['systemctl', 'stop', '--no-block', 'systemd-networkd.service', 'netplan-wpa@*.service']) else: logging.debug('no netplan generated networkd configuration exists') if restart_nm: logging.debug('netplan generated NM configuration exists, restarting NM') if nm_running(): # restarting NM does not cause new config to be applied, need to shut down devices first for device in devices: # ignore failures here -- some/many devices might not be managed by NM try: nmcli(['device', 'disconnect', device]) except subprocess.CalledProcessError: pass systemctl_network_manager('stop') else: logging.debug('no netplan generated NM configuration exists') # force-hotplug all "down" network interfaces to apply renames any_replug = False for device in devices: if not os.path.islink('/sys/class/net/' + device): continue if replug(device): any_replug = True else: # if the interface is up, we can still apply .link file changes logging.debug('netplan triggering .link rules for %s', device) with open(os.devnull, 'w') as fd: subprocess.check_call(['udevadm', 'test-builtin', 'net_setup_link', '/sys/class/net/' + device], stdout=fd, stderr=fd) if any_replug: subprocess.check_call(['udevadm', 'settle']) # (re)start backends if restart_networkd: subprocess.check_call(['systemctl', 'start', '--no-block', 'systemd-networkd.service'] + [os.path.basename(f) for f in glob('/run/systemd/system/*.wants/netplan-wpa@*.service')]) if restart_nm: systemctl_network_manager('start') def command_ifupdown_migrate(): netplan_config = {} try: ifaces, auto_ifaces = parse_ifupdown(args.root_dir or '') except ValueError as e: logging.error(str(e)) sys.exit(2) for iface, family_config in ifaces.items(): for family, config in family_config.items(): logging.debug('Converting %s family %s %s', iface, family, config) if iface not in auto_ifaces: logging.error('%s: non-automatic interfaces are not supported', iface) sys.exit(2) if config['method'] == 'loopback': # both systemd and modern ifupdown set up lo automatically logging.debug('Ignoring loopback interface %s', iface) elif config['method'] == 'dhcp': if config['options']: logging.error('%s: options are not supported for dhcp method', iface) sys.exit(2) c = netplan_config.setdefault('network', {}).setdefault('ethernets', {}).setdefault(iface, {}) if family == 'inet': c['dhcp4'] = True else: assert family == 'inet6' c['dhcp6'] = True else: logging.error('%s: method %s is not supported', iface, config['method']) sys.exit(2) if_config = os.path.join(args.root_dir or '/', 'etc/network/interfaces') if netplan_config: netplan_config['network']['version'] = 2 netplan_yaml = yaml.dump(netplan_config) if args.dry_run: print(netplan_yaml) else: dest = os.path.join(args.root_dir or '/', 'etc/netplan/10-ifupdown.yaml') try: os.makedirs(os.path.dirname(dest)) except FileExistsError: pass try: with open(dest, 'x') as f: f.write(netplan_yaml) except FileExistsError: logging.error('%s already exists; remove it if you want to run the migration again', dest) sys.exit(3) logging.info('migration complete, wrote %s', dest) else: logging.info('ifupdown does not configure any interfaces, nothing to migrate') if not args.dry_run: logging.info('renaming %s to %s.netplan-converted', if_config, if_config) os.rename(if_config, if_config + '.netplan-converted') # # main # args = parse_args() if args.debug: logging.basicConfig(level=logging.DEBUG, format='%(levelname)s:%(message)s') os.environ['G_MESSAGES_DEBUG'] = 'all' else: logging.basicConfig(level=logging.INFO, format='%(message)s') eval('command_' + args.command.replace('-', '_'))() nplan-0.32~16.04.7~mtrudel1/src/netplan-wpa@.service0000664000000000000000000000041213272657646016764 0ustar [Unit] Description=WPA supplicant for netplan %I Requires=sys-subsystem-net-devices-%i.device After=sys-subsystem-net-devices-%i.device Before=network.target Wants=network.target [Service] Type=simple ExecStart=/sbin/wpa_supplicant -c /run/netplan/wpa-%I.conf -i%I nplan-0.32~16.04.7~mtrudel1/src/networkd.c0000664000000000000000000004672513315465504015062 0ustar /* * Copyright (C) 2016 Canonical, Ltd. * Author: Martin Pitt * * 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; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include #include "networkd.h" #include "parse.h" #include "util.h" /** * Append [Match] section of @def to @s. */ static void append_match_section(net_definition* def, GString* s, gboolean match_rename) { /* Note: an empty [Match] section is interpreted as matching all devices, * which is what we want for the simple case that you only have one device * (of the given type) */ g_string_append(s, "[Match]\n"); if (def->match.driver) g_string_append_printf(s, "Driver=%s\n", def->match.driver); if (def->match.mac) g_string_append_printf(s, "MACAddress=%s\n", def->match.mac); /* name matching is special: if the .link renames the interface, the * .network has to use the renamed one, otherwise the original one */ if (!match_rename && def->match.original_name) g_string_append_printf(s, "OriginalName=%s\n", def->match.original_name); if (match_rename) { if (def->type >= ND_VIRTUAL) g_string_append_printf(s, "Name=%s\n", def->id); else if (def->set_name) g_string_append_printf(s, "Name=%s\n", def->set_name); else if (def->match.original_name) g_string_append_printf(s, "Name=%s\n", def->match.original_name); } } static void write_bridge_params(GString* s, net_definition* def) { GString *params = NULL; if (def->custom_bridging) { params = g_string_sized_new(200); if (def->bridge_params.ageing_time) g_string_append_printf(params, "AgeingTimeSec=%s\n", def->bridge_params.ageing_time); if (def->bridge_params.priority) g_string_append_printf(params, "Priority=%u\n", def->bridge_params.priority); if (def->bridge_params.forward_delay) g_string_append_printf(params, "ForwardDelaySec=%s\n", def->bridge_params.forward_delay); if (def->bridge_params.hello_time) g_string_append_printf(params, "HelloTimeSec=%s\n", def->bridge_params.hello_time); if (def->bridge_params.max_age) g_string_append_printf(params, "MaxAgeSec=%s\n", def->bridge_params.max_age); g_string_append_printf(params, "STP=%s\n", def->bridge_params.stp ? "true" : "false"); g_string_append_printf(s, "\n[Bridge]\n%s", params->str); g_string_free(params, TRUE); } } static void write_link_file(net_definition* def, const char* rootdir, const char* path) { GString* s = NULL; /* Don't write .link files for virtual devices; they use .netdev instead */ if (def->type >= ND_VIRTUAL) return; /* do we need to write a .link file? */ if (!def->set_name && !def->wake_on_lan && !def->mtubytes && !def->set_mac) return; /* build file contents */ s = g_string_sized_new(200); append_match_section(def, s, FALSE); g_string_append(s, "\n[Link]\n"); if (def->set_name) g_string_append_printf(s, "Name=%s\n", def->set_name); /* FIXME: Should this be turned from bool to str and support multiple values? */ g_string_append_printf(s, "WakeOnLan=%s\n", def->wake_on_lan ? "magic" : "off"); if (def->mtubytes) g_string_append_printf(s, "MTUBytes=%u\n", def->mtubytes); if (def->set_mac) g_string_append_printf(s, "MACAddress=%s\n", def->set_mac); g_string_free_to_file(s, rootdir, path, ".link"); } static gboolean interval_has_suffix(const char* param) { gchar* endptr; g_ascii_strtoull(param, &endptr, 10); if (*endptr == '\0') return FALSE; return TRUE; } static void write_bond_parameters(net_definition* def, GString* s) { GString* params = NULL; params = g_string_sized_new(200); if (def->bond_params.mode) g_string_append_printf(params, "\nMode=%s", def->bond_params.mode); if (def->bond_params.lacp_rate) g_string_append_printf(params, "\nLACPTransmitRate=%s", def->bond_params.lacp_rate); if (def->bond_params.monitor_interval) { g_string_append(params, "\nMIIMonitorSec="); if (interval_has_suffix(def->bond_params.monitor_interval)) g_string_append(params, def->bond_params.monitor_interval); else g_string_append_printf(params, "%sms", def->bond_params.monitor_interval); } if (def->bond_params.min_links) g_string_append_printf(params, "\nMinLinks=%d", def->bond_params.min_links); if (def->bond_params.transmit_hash_policy) g_string_append_printf(params, "\nTransmitHashPolicy=%s", def->bond_params.transmit_hash_policy); if (def->bond_params.selection_logic) g_string_append_printf(params, "\nAdSelect=%s", def->bond_params.selection_logic); if (def->bond_params.all_slaves_active) g_string_append_printf(params, "\nAllSlavesActive=%d", def->bond_params.all_slaves_active); if (def->bond_params.arp_interval) { g_string_append(params, "\nARPIntervalSec="); if (interval_has_suffix(def->bond_params.arp_interval)) g_string_append(params, def->bond_params.arp_interval); else g_string_append_printf(params, "%sms", def->bond_params.arp_interval); } if (def->bond_params.arp_ip_targets && def->bond_params.arp_ip_targets->len > 0) { g_string_append_printf(params, "\nARPIPTargets="); for (unsigned i = 0; i < def->bond_params.arp_ip_targets->len; ++i) { if (i > 0) g_string_append_printf(params, ","); g_string_append_printf(params, "%s", g_array_index(def->bond_params.arp_ip_targets, char*, i)); } } if (def->bond_params.arp_validate) g_string_append_printf(params, "\nARPValidate=%s", def->bond_params.arp_validate); if (def->bond_params.arp_all_targets) g_string_append_printf(params, "\nARPAllTargets=%s", def->bond_params.arp_all_targets); if (def->bond_params.up_delay) { g_string_append(params, "\nUpDelaySec="); if (interval_has_suffix(def->bond_params.up_delay)) g_string_append(params, def->bond_params.up_delay); else g_string_append_printf(params, "%sms", def->bond_params.up_delay); } if (def->bond_params.down_delay) { g_string_append(params, "\nDownDelaySec="); if (interval_has_suffix(def->bond_params.down_delay)) g_string_append(params, def->bond_params.down_delay); else g_string_append_printf(params, "%sms", def->bond_params.down_delay); } if (def->bond_params.fail_over_mac_policy) g_string_append_printf(params, "\nFailOverMACPolicy=%s", def->bond_params.fail_over_mac_policy); if (def->bond_params.gratuitious_arp) g_string_append_printf(params, "\nGratuitiousARP=%d", def->bond_params.gratuitious_arp); /* TODO: add unsolicited_na, not documented as supported by NM. */ if (def->bond_params.packets_per_slave) g_string_append_printf(params, "\nPacketsPerSlave=%d", def->bond_params.packets_per_slave); if (def->bond_params.primary_reselect_policy) g_string_append_printf(params, "\nPrimaryReselectPolicy=%s", def->bond_params.primary_reselect_policy); if (def->bond_params.resend_igmp) g_string_append_printf(params, "\nResendIGMP=%d", def->bond_params.resend_igmp); if (def->bond_params.learn_interval) g_string_append_printf(params, "\nLearnPacketIntervalSec=%s", def->bond_params.learn_interval); if (params->len) g_string_append_printf(s, "\n[Bond]%s\n", params->str); g_string_free(params, TRUE); } static void write_netdev_file(net_definition* def, const char* rootdir, const char* path) { GString* s = NULL; g_assert(def->type >= ND_VIRTUAL); /* build file contents */ s = g_string_sized_new(200); g_string_append_printf(s, "[NetDev]\nName=%s\n", def->id); if (def->set_mac) g_string_append_printf(s, "MACAddress=%s\n", def->set_mac); if (def->mtubytes) g_string_append_printf(s, "MTUBytes=%u\n", def->mtubytes); switch (def->type) { case ND_BRIDGE: g_string_append(s, "Kind=bridge\n"); write_bridge_params(s, def); break; case ND_BOND: g_string_append(s, "Kind=bond\n"); write_bond_parameters(def, s); break; case ND_VLAN: g_string_append_printf(s, "Kind=vlan\n\n[VLAN]\nId=%u\n", def->vlan_id); break; /* LCOV_EXCL_START */ default: g_assert_not_reached(); /* LCOV_EXCL_STOP */ } g_string_free_to_file(s, rootdir, path, ".netdev"); } static void write_network_file(net_definition* def, const char* rootdir, const char* path) { GString* s = NULL; /* do we need to write a .network file? */ if (!def->dhcp4 && !def->dhcp6 && !def->bridge && !def->bond && !def->ip4_addresses && !def->ip6_addresses && !def->gateway4 && !def->gateway6 && !def->ip4_nameservers && !def->ip6_nameservers && !def->has_vlans) return; /* build file contents */ s = g_string_sized_new(200); append_match_section(def, s, TRUE); if (def->optional) g_string_append(s, "\n[Link]\nRequiredForOnline=no\n"); g_string_append(s, "\n[Network]\n"); if (def->dhcp4 && def->dhcp6) g_string_append(s, "DHCP=yes\n"); else if (def->dhcp4) g_string_append(s, "DHCP=ipv4\n"); else if (def->dhcp6) g_string_append(s, "DHCP=ipv6\n"); if (def->ip4_addresses) for (unsigned i = 0; i < def->ip4_addresses->len; ++i) g_string_append_printf(s, "Address=%s\n", g_array_index(def->ip4_addresses, char*, i)); if (def->ip6_addresses) for (unsigned i = 0; i < def->ip6_addresses->len; ++i) g_string_append_printf(s, "Address=%s\n", g_array_index(def->ip6_addresses, char*, i)); if (def->accept_ra == ACCEPT_RA_ENABLED) g_string_append_printf(s, "IPv6AcceptRA=yes\n"); else if (def->accept_ra == ACCEPT_RA_DISABLED) g_string_append_printf(s, "IPv6AcceptRA=no\n"); if (def->gateway4) g_string_append_printf(s, "Gateway=%s\n", def->gateway4); if (def->gateway6) g_string_append_printf(s, "Gateway=%s\n", def->gateway6); if (def->ip4_nameservers) for (unsigned i = 0; i < def->ip4_nameservers->len; ++i) g_string_append_printf(s, "DNS=%s\n", g_array_index(def->ip4_nameservers, char*, i)); if (def->ip6_nameservers) for (unsigned i = 0; i < def->ip6_nameservers->len; ++i) g_string_append_printf(s, "DNS=%s\n", g_array_index(def->ip6_nameservers, char*, i)); if (def->search_domains) { g_string_append_printf(s, "Domains=%s", g_array_index(def->search_domains, char*, 0)); for (unsigned i = 1; i < def->search_domains->len; ++i) g_string_append_printf(s, " %s", g_array_index(def->search_domains, char*, i)); g_string_append(s, "\n"); } if (def->bridge) { g_string_append_printf(s, "Bridge=%s\nLinkLocalAddressing=no\n", def->bridge); if (def->bridge_params.path_cost || def->bridge_params.port_priority) g_string_append_printf(s, "\n[Bridge]\n"); if (def->bridge_params.path_cost) g_string_append_printf(s, "Cost=%u\n", def->bridge_params.path_cost); if (def->bridge_params.port_priority) g_string_append_printf(s, "Priority=%u\n", def->bridge_params.port_priority); } if (def->bond) { g_string_append_printf(s, "Bond=%s\nLinkLocalAddressing=no\n", def->bond); if (def->bond_params.primary_slave) g_string_append_printf(s, "PrimarySlave=true\n"); } if (def->has_vlans) { /* iterate over all netdefs to find VLANs attached to us */ GHashTableIter i; net_definition* nd; g_hash_table_iter_init(&i, netdefs); while (g_hash_table_iter_next (&i, NULL, (gpointer*) &nd)) if (nd->vlan_link == def) g_string_append_printf(s, "VLAN=%s\n", nd->id); } if (def->routes != NULL) { for (unsigned i = 0; i < def->routes->len; ++i) { ip_route* cur_route = g_array_index (def->routes, ip_route*, i); g_string_append_printf(s, "\n[Route]\nDestination=%s\nGateway=%s\n", cur_route->to, cur_route->via); if (cur_route->metric != METRIC_UNSPEC) g_string_append_printf(s, "Metric=%d\n", cur_route->metric); } } if (def->dhcp4 || def->dhcp6) { /* isc-dhcp dhclient compatible UseMTU, networkd default is to * not accept MTU, which breaks clouds */ g_string_append_printf(s, "\n[DHCP]\nUseMTU=true\n"); /* NetworkManager compatible route metrics */ g_string_append_printf(s, "RouteMetric=%i\n", (def->type == ND_WIFI ? 600 : 100)); if (g_strcmp0(def->dhcp_identifier, "duid") != 0) g_string_append_printf(s, "ClientIdentifier=%s\n", def->dhcp_identifier); if (def->critical) g_string_append_printf(s, "CriticalConnection=true\n"); } g_string_free_to_file(s, rootdir, path, ".network"); } static void write_rules_file(net_definition* def, const char* rootdir) { GString* s = NULL; g_autofree char* path = g_strjoin(NULL, "run/udev/rules.d/99-netplan-", def->id, ".rules", NULL); /* do we need to write a .rules file? * It's only required for reliably setting the name of a physical device * until systemd issue #9006 is resolved. */ if (def->type >= ND_VIRTUAL) return; /* Matching by name does not work. * * As far as I can tell, if you match by the name coming out of * initrd, systemd complains that a link file is matching on a * renamed name. If you match by the unstable kernel name, the * device no longer has that name when udevd reads the file, so * the rule doesn't fire. So only support mac and driver. */ if (!def->set_name || (!def->match.mac && !def->match.driver)) return; /* build file contents */ s = g_string_sized_new(200); g_string_append(s, "SUBSYSTEM==\"net\", ACTION==\"add\", "); if (def->match.driver) { g_string_append_printf(s,"DRIVERS==\"%s\", ", def->match.driver); } else { g_string_append(s, "DRIVERS==\"?*\", "); } if (def->match.mac) g_string_append_printf(s, "ATTR{address}==\"%s\", ", def->match.mac); g_string_append_printf(s, "NAME=\"%s\"\n", def->set_name); g_string_free_to_file(s, rootdir, path, NULL); } static void write_wpa_conf(net_definition* def, const char* rootdir) { GHashTableIter iter; wifi_access_point* ap; GString* s = g_string_new("ctrl_interface=/run/wpa_supplicant\n\n"); g_autofree char* path = g_strjoin(NULL, "run/netplan/wpa-", def->id, ".conf", NULL); mode_t orig_umask; g_debug("%s: Creating wpa_supplicant configuration file %s", def->id, path); g_hash_table_iter_init(&iter, def->access_points); while (g_hash_table_iter_next(&iter, NULL, (gpointer) &ap)) { g_string_append_printf(s, "network={\n ssid=\"%s\"\n", ap->ssid); if (ap->password) g_string_append_printf(s, " psk=\"%s\"\n", ap->password); else g_string_append(s, " key_mgmt=NONE\n"); switch (ap->mode) { case WIFI_MODE_INFRASTRUCTURE: /* default in wpasupplicant */ break; case WIFI_MODE_ADHOC: g_string_append(s, " mode=1\n"); break; case WIFI_MODE_AP: g_fprintf(stderr, "ERROR: %s: networkd does not support wifi in access point mode\n", def->id); exit(1); } g_string_append(s, "}\n"); } /* use tight permissions as this contains secrets */ orig_umask = umask(077); g_string_free_to_file(s, rootdir, path, NULL); umask(orig_umask); } /** * Generate networkd configuration in @rootdir/run/systemd/network/ from the * parsed #netdefs. * @rootdir: If not %NULL, generate configuration in this root directory * (useful for testing). * Returns: TRUE if @def applies to networkd, FALSE otherwise. */ gboolean write_networkd_conf(net_definition* def, const char* rootdir) { g_autofree char* path_base = g_strjoin(NULL, "run/systemd/network/10-netplan-", def->id, NULL); /* We want this for all backends when renaming, as *.link and *.rules files are * evaluated by udev, not networkd itself or NetworkManager. */ write_link_file(def, rootdir, path_base); write_rules_file(def, rootdir); if (def->backend != BACKEND_NETWORKD) { g_debug("networkd: definition %s is not for us (backend %i)", def->id, def->backend); return FALSE; } if (def->type == ND_WIFI) { g_autofree char* link = g_strjoin(NULL, rootdir ?: "", "/run/systemd/system/multi-user.target.wants/netplan-wpa@", def->id, ".service", NULL); if (def->has_match) { g_fprintf(stderr, "ERROR: %s: networkd backend does not support wifi with match:, only by interface name\n", def->id); exit(1); } write_wpa_conf(def, rootdir); g_debug("Creating wpa_supplicant service enablement link %s", link); safe_mkdir_p_dir(link); if (symlink("/lib/systemd/system/netplan-wpa@.service", link) < 0 && errno != EEXIST) { g_fprintf(stderr, "failed to create enablement symlink: %m\n"); /* LCOV_EXCL_LINE */ exit(1); /* LCOV_EXCL_LINE */ } } if (def->type >= ND_VIRTUAL) write_netdev_file(def, rootdir, path_base); write_network_file(def, rootdir, path_base); return TRUE; } /** * Clean up all generated configurations in @rootdir from previous runs. */ void cleanup_networkd_conf(const char* rootdir) { unlink_glob(rootdir, "/run/systemd/network/10-netplan-*"); unlink_glob(rootdir, "/run/netplan/wpa-*.conf"); unlink_glob(rootdir, "/run/systemd/system/multi-user.target.wants/netplan-wpa@*.service"); unlink_glob(rootdir, "/run/udev/rules.d/99-netplan-*"); } /** * Create enablement symlink for systemd-networkd.service. */ void enable_networkd(const char* generator_dir) { g_autofree char* link = g_build_path(G_DIR_SEPARATOR_S, generator_dir, "multi-user.target.wants", "systemd-networkd.service", NULL); g_debug("We created networkd configuration, adding %s enablement symlink", link); safe_mkdir_p_dir(link); if (symlink("../systemd-networkd.service", link) < 0 && errno != EEXIST) { g_fprintf(stderr, "failed to create enablement symlink: %m\n"); /* LCOV_EXCL_LINE */ exit(1); /* LCOV_EXCL_LINE */ } g_autofree char* link2 = g_build_path(G_DIR_SEPARATOR_S, generator_dir, "network-online.target.wants", "systemd-networkd-wait-online.service", NULL); safe_mkdir_p_dir(link2); if (symlink("/lib/systemd/system/systemd-networkd-wait-online.service", link2) < 0 && errno != EEXIST) { g_fprintf(stderr, "failed to create enablement symlink: %m\n"); /* LCOV_EXCL_LINE */ exit(1); /* LCOV_EXCL_LINE */ } } nplan-0.32~16.04.7~mtrudel1/src/networkd.h0000664000000000000000000000156313272657646015072 0ustar /* * Copyright (C) 2016 Canonical, Ltd. * Author: Martin Pitt * * 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; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #pragma once #include "parse.h" gboolean write_networkd_conf(net_definition* def, const char* rootdir); void cleanup_networkd_conf(const char* rootdir); void enable_networkd(const char* generator_dir); nplan-0.32~16.04.7~mtrudel1/src/nm.c0000664000000000000000000004745413315465032013633 0ustar /* * Copyright (C) 2016 Canonical, Ltd. * Author: Martin Pitt * * 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; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include #include #include #include "nm.h" #include "parse.h" #include "util.h" GString* udev_rules; /** * Append NM device specifier of @def to @s. */ static void g_string_append_netdef_match(GString* s, const net_definition* def) { g_assert(!def->match.driver || def->set_name); if (def->match.mac) { g_string_append_printf(s, "mac:%s", def->match.mac); } else if (def->match.original_name || def->set_name || def->type >= ND_VIRTUAL) { /* we always have the renamed name here */ g_string_append_printf(s, "interface-name:%s", (def->type >= ND_VIRTUAL) ? def->id : (def->set_name ?: def->match.original_name)); } else { /* no matches → match all devices of that type */ switch (def->type) { case ND_ETHERNET: g_string_append(s, "type:ethernet"); break; /* This cannot be reached with just NM and networkd backends, as * networkd does not support wifi and thus we'll never blacklist a * wifi device from NM. This would become relevant with another * wifi-supporting backend, but until then this just spoils 100% * code coverage. case ND_WIFI: g_string_append(s, "type:wifi"); break; */ /* LCOV_EXCL_START */ default: g_assert_not_reached(); /* LCOV_EXCL_STOP */ } } } /** * Return NM "type=" string. */ static const char* type_str(netdef_type type) { switch (type) { case ND_ETHERNET: return "ethernet"; case ND_WIFI: return "wifi"; case ND_BRIDGE: return "bridge"; case ND_BOND: return "bond"; case ND_VLAN: return "vlan"; /* LCOV_EXCL_START */ default: g_assert_not_reached(); /* LCOV_EXCL_STOP */ } } /** * Return NM wifi "mode=" string. */ static const char* wifi_mode_str(wifi_mode mode) { switch (mode) { case WIFI_MODE_INFRASTRUCTURE: return "infrastructure"; case WIFI_MODE_ADHOC: return "adhoc"; case WIFI_MODE_AP: return "ap"; /* LCOV_EXCL_START */ default: g_assert_not_reached(); /* LCOV_EXCL_STOP */ } } static void write_search_domains(const net_definition* def, GString *s) { if (def->search_domains) { g_string_append(s, "dns-search="); for (unsigned i = 0; i < def->search_domains->len; ++i) g_string_append_printf(s, "%s;", g_array_index(def->search_domains, char*, i)); g_string_append(s, "\n"); } } static void write_routes(const net_definition* def, GString *s, int family) { if (def->routes != NULL) { for (unsigned i = 0, j = 1; i < def->routes->len; ++i) { ip_route *cur_route = g_array_index(def->routes, ip_route*, i); if (cur_route->family != family) continue; g_string_append_printf(s, "route%d=%s,%s", j, cur_route->to, cur_route->via); if (cur_route->metric != METRIC_UNSPEC) g_string_append_printf(s, ",%d", cur_route->metric); g_string_append(s, "\n"); j++; } } } static void write_bond_parameters(const net_definition* def, GString *s) { GString* params = NULL; params = g_string_sized_new(200); if (def->bond_params.mode) g_string_append_printf(params, "\nmode=%s", def->bond_params.mode); if (def->bond_params.lacp_rate) g_string_append_printf(params, "\nlacp_rate=%s", def->bond_params.lacp_rate); if (def->bond_params.monitor_interval) g_string_append_printf(params, "\nmiimon=%s", def->bond_params.monitor_interval); if (def->bond_params.min_links) g_string_append_printf(params, "\nmin_links=%d", def->bond_params.min_links); if (def->bond_params.transmit_hash_policy) g_string_append_printf(params, "\nxmit_hash_policy=%s", def->bond_params.transmit_hash_policy); if (def->bond_params.selection_logic) g_string_append_printf(params, "\nad_select=%s", def->bond_params.selection_logic); if (def->bond_params.all_slaves_active) g_string_append_printf(params, "\nall_slaves_active=%d", def->bond_params.all_slaves_active); if (def->bond_params.arp_interval) g_string_append_printf(params, "\narp_interval=%s", def->bond_params.arp_interval); if (def->bond_params.arp_ip_targets) { g_string_append_printf(params, "\narp_ip_target="); for (unsigned i = 0; i < def->bond_params.arp_ip_targets->len; ++i) { if (i > 0) g_string_append_printf(params, ","); g_string_append_printf(params, "%s", g_array_index(def->bond_params.arp_ip_targets, char*, i)); } } if (def->bond_params.arp_validate) g_string_append_printf(params, "\narp_validate=%s", def->bond_params.arp_validate); if (def->bond_params.arp_all_targets) g_string_append_printf(params, "\narp_all_targets=%s", def->bond_params.arp_all_targets); if (def->bond_params.up_delay) g_string_append_printf(params, "\nupdelay=%s", def->bond_params.up_delay); if (def->bond_params.down_delay) g_string_append_printf(params, "\ndowndelay=%s", def->bond_params.down_delay); if (def->bond_params.fail_over_mac_policy) g_string_append_printf(params, "\nfail_over_mac=%s", def->bond_params.fail_over_mac_policy); if (def->bond_params.gratuitious_arp) g_string_append_printf(params, "\nnum_grat_arp=%d", def->bond_params.gratuitious_arp); /* TODO: add unsolicited_na, not documented as supported by NM. */ if (def->bond_params.packets_per_slave) g_string_append_printf(params, "\npackets_per_slave=%d", def->bond_params.packets_per_slave); if (def->bond_params.primary_reselect_policy) g_string_append_printf(params, "\nprimary_reselect=%s", def->bond_params.primary_reselect_policy); if (def->bond_params.resend_igmp) g_string_append_printf(params, "\nresend_igmp=%d", def->bond_params.resend_igmp); if (def->bond_params.learn_interval) g_string_append_printf(params, "\nlp_interval=%s", def->bond_params.learn_interval); if (def->bond_params.primary_slave) g_string_append_printf(params, "\nprimary=%s", def->bond_params.primary_slave); if (params->len > 0) g_string_append_printf(s, "\n[bond]%s\n", params->str); g_string_free(params, TRUE); } static void write_bridge_params(const net_definition* def, GString *s) { GString* params = NULL; if (def->custom_bridging) { params = g_string_sized_new(200); if (def->bridge_params.ageing_time) g_string_append_printf(params, "ageing-time=%s\n", def->bridge_params.ageing_time); if (def->bridge_params.priority) g_string_append_printf(params, "priority=%u\n", def->bridge_params.priority); if (def->bridge_params.forward_delay) g_string_append_printf(params, "forward-delay=%s\n", def->bridge_params.forward_delay); if (def->bridge_params.hello_time) g_string_append_printf(params, "hello-time=%s\n", def->bridge_params.hello_time); if (def->bridge_params.max_age) g_string_append_printf(params, "max-age=%s\n", def->bridge_params.max_age); g_string_append_printf(params, "stp=%s\n", def->bridge_params.stp ? "true" : "false"); g_string_append_printf(s, "\n[bridge]\n%s", params->str); g_string_free(params, TRUE); } } static void maybe_generate_uuid(net_definition* def) { if (uuid_is_null(def->uuid)) uuid_generate(def->uuid); } /** * Generate NetworkManager configuration in @rootdir/run/NetworkManager/ for a * particular net_definition and wifi_access_point, as NM requires a separate * connection file for each SSID. * @def: The net_definition for which to create a connection * @rootdir: If not %NULL, generate configuration in this root directory * (useful for testing). * @ap: The access point for which to create a connection. Must be %NULL for * non-wifi types. */ static void write_nm_conf_access_point(net_definition* def, const char* rootdir, const wifi_access_point* ap) { GString *s = NULL; g_autofree char* conf_path = NULL; mode_t orig_umask; char uuidstr[37]; if (def->type == ND_WIFI) g_assert(ap); else g_assert(ap == NULL); s = g_string_new(NULL); g_string_append_printf(s, "[connection]\nid=netplan-%s", def->id); if (ap) g_string_append_printf(s, "-%s", ap->ssid); g_string_append_printf(s, "\ntype=%s\n", type_str(def->type)); /* VLAN devices refer to us as their parent; if our ID is not a name but we * have matches, parent= must be the connection UUID, so put it into the * connection */ if (def->has_vlans && def->has_match) { maybe_generate_uuid(def); uuid_unparse(def->uuid, uuidstr); g_string_append_printf(s, "uuid=%s\n", uuidstr); } if (def->type < ND_VIRTUAL) { /* physical (existing) devices use matching; driver matching is not * supported, MAC matching is done below (different keyfile section), * so only match names here */ if (def->set_name) g_string_append_printf(s, "interface-name=%s\n", def->set_name); else if (!def->has_match) g_string_append_printf(s, "interface-name=%s\n", def->id); else if (def->match.original_name) { /* NM does not support interface name globbing */ if (strpbrk(def->match.original_name, "*[]?")) { g_fprintf(stderr, "ERROR: %s: NetworkManager definitions do not support name globbing\n", def->id); exit(1); } g_string_append_printf(s, "interface-name=%s\n", def->match.original_name); } /* else matches on something other than the name, do not restrict interface-name */ } else { /* virtual (created) devices set a name */ g_string_append_printf(s, "interface-name=%s\n", def->id); if (def->type == ND_BRIDGE) write_bridge_params(def, s); } if (def->bridge) { g_string_append_printf(s, "slave-type=bridge\nmaster=%s\n", def->bridge); if (def->bridge_params.path_cost || def->bridge_params.port_priority) g_string_append_printf(s, "\n[bridge-port]\n"); if (def->bridge_params.path_cost) g_string_append_printf(s, "path-cost=%u\n", def->bridge_params.path_cost); if (def->bridge_params.port_priority) g_string_append_printf(s, "priority=%u\n", def->bridge_params.port_priority); } if (def->bond) g_string_append_printf(s, "slave-type=bond\nmaster=%s\n", def->bond); if (def->type < ND_VIRTUAL) { GString *link_str = NULL; link_str = g_string_new(NULL); g_string_append_printf(s, "\n[ethernet]\nwake-on-lan=%i\n", def->wake_on_lan ? 1 : 0); if (!def->set_name && def->match.mac) { g_string_append_printf(link_str, "mac-address=%s\n", def->match.mac); } if (def->set_mac) { g_string_append_printf(link_str, "cloned-mac-address=%s\n", def->set_mac); } if (def->mtubytes) { g_string_append_printf(link_str, "mtu=%d\n", def->mtubytes); } if (link_str->len > 0) { switch (def->type) { case ND_WIFI: g_string_append_printf(s, "\n[802-11-wireless]\n%s", link_str->str); break; default: g_string_append_printf(s, "\n[802-3-ethernet]\n%s", link_str->str); break; } } g_string_free(link_str, TRUE); } else { GString *link_str = NULL; link_str = g_string_new(NULL); if (def->set_mac) { g_string_append_printf(link_str, "cloned-mac-address=%s\n", def->set_mac); } if (def->mtubytes) { g_string_append_printf(link_str, "mtu=%d\n", def->mtubytes); } if (link_str->len > 0) { g_string_append_printf(s, "\n[802-3-ethernet]\n%s", link_str->str); } g_string_free(link_str, TRUE); } if (def->type == ND_VLAN) { g_assert(def->vlan_id < G_MAXUINT); g_assert(def->vlan_link != NULL); g_string_append_printf(s, "\n[vlan]\nid=%u\nparent=", def->vlan_id); if (def->vlan_link->has_match) { /* we need to refer to the parent's UUID as we don't have an * interface name with match: */ maybe_generate_uuid(def->vlan_link); uuid_unparse(def->vlan_link->uuid, uuidstr); g_string_append_printf(s, "%s\n", uuidstr); } else { /* if we have an interface name, use that as parent */ g_string_append_printf(s, "%s\n", def->vlan_link->id); } } if (def->type == ND_BOND) write_bond_parameters(def, s); g_string_append(s, "\n[ipv4]\n"); if (ap && ap->mode == WIFI_MODE_AP) g_string_append(s, "method=shared\n"); else if (def->dhcp4) g_string_append(s, "method=auto\n"); else if (def->ip4_addresses) /* This requires adding at least one address (done below) */ g_string_append(s, "method=manual\n"); else /* Without any address, this is the only available mode */ g_string_append(s, "method=link-local\n"); if (def->ip4_addresses) for (unsigned i = 0; i < def->ip4_addresses->len; ++i) g_string_append_printf(s, "address%i=%s\n", i+1, g_array_index(def->ip4_addresses, char*, i)); if (def->gateway4) g_string_append_printf(s, "gateway=%s\n", def->gateway4); if (def->ip4_nameservers) { g_string_append(s, "dns="); for (unsigned i = 0; i < def->ip4_nameservers->len; ++i) g_string_append_printf(s, "%s;", g_array_index(def->ip4_nameservers, char*, i)); g_string_append(s, "\n"); } write_search_domains(def, s); write_routes(def, s, AF_INET); if (def->dhcp6 || def->ip6_addresses || def->gateway6 || def->ip6_nameservers) { g_string_append(s, "\n[ipv6]\n"); g_string_append(s, def->dhcp6 ? "method=auto\n" : "method=manual\n"); if (def->ip6_addresses) for (unsigned i = 0; i < def->ip6_addresses->len; ++i) g_string_append_printf(s, "address%i=%s\n", i+1, g_array_index(def->ip6_addresses, char*, i)); if (def->gateway6) g_string_append_printf(s, "gateway=%s\n", def->gateway6); if (def->ip6_nameservers) { g_string_append(s, "dns="); for (unsigned i = 0; i < def->ip6_nameservers->len; ++i) g_string_append_printf(s, "%s;", g_array_index(def->ip6_nameservers, char*, i)); g_string_append(s, "\n"); } /* nm-settings(5) specifies search-domain for both [ipv4] and [ipv6] -- * do we really need to repeat it here? */ write_search_domains(def, s); /* We can only write valid routes if there is a DHCPv6 or static IPv6 address */ write_routes(def, s, AF_INET6); } else { g_string_append(s, "\n[ipv6]\nmethod=ignore\n"); } conf_path = g_strjoin(NULL, "run/NetworkManager/system-connections/netplan-", def->id, NULL); if (ap) { g_autofree char* escaped_ssid = g_uri_escape_string(ap->ssid, NULL, TRUE); conf_path = g_strjoin(NULL, "run/NetworkManager/system-connections/netplan-", def->id, "-", escaped_ssid, NULL); g_string_append_printf(s, "\n[wifi]\nssid=%s\nmode=%s\n", ap->ssid, wifi_mode_str(ap->mode)); if (ap->password) g_string_append_printf(s, "\n[wifi-security]\nkey-mgmt=wpa-psk\npsk=%s\n", ap->password); } else { conf_path = g_strjoin(NULL, "run/NetworkManager/system-connections/netplan-", def->id, NULL); } /* NM connection files might contain secrets, and NM insists on tight permissions */ orig_umask = umask(077); g_string_free_to_file(s, rootdir, conf_path, NULL); umask(orig_umask); } /** * Generate NetworkManager configuration in @rootdir/run/NetworkManager/ for a * particular net_definition. * @rootdir: If not %NULL, generate configuration in this root directory * (useful for testing). */ void write_nm_conf(net_definition* def, const char* rootdir) { if (def->backend != BACKEND_NM) { g_debug("NetworkManager: definition %s is not for us (backend %i)", def->id, def->backend); return; } if (def->match.driver && !def->set_name) { g_fprintf(stderr, "ERROR: %s: NetworkManager definitions do not support matching by driver\n", def->id); exit(1); } /* for wifi we need to create a separate connection file for every SSID */ if (def->type == ND_WIFI) { GHashTableIter iter; gpointer key; wifi_access_point* ap; g_assert(def->access_points); g_hash_table_iter_init(&iter, def->access_points); while (g_hash_table_iter_next(&iter, &key, (gpointer) &ap)) write_nm_conf_access_point(def, rootdir, ap); } else { g_assert(def->access_points == NULL); write_nm_conf_access_point(def, rootdir, NULL); } } static void nd_append_non_nm_ids(gpointer key, gpointer value, gpointer str) { net_definition* nd = value; if (nd->backend != BACKEND_NM) { if (nd->match.driver) { /* NM cannot match on drivers, so ignore these via udev rules */ if (!udev_rules) udev_rules = g_string_new(NULL); g_string_append_printf(udev_rules, "ACTION==\"add|change\", SUBSYSTEM==\"net\", ENV{ID_NET_DRIVER}==\"%s\", ENV{NM_UNMANAGED}=\"1\"\n", nd->match.driver); } else { g_string_append_netdef_match((GString*) str, nd); g_string_append((GString*) str, ","); } } } void write_nm_conf_finish(const char* rootdir) { GString *s = NULL; gsize len; if (g_hash_table_size(netdefs) == 0) return; /* Set all devices not managed by us to unmanaged, so that NM does not * auto-connect and interferes */ s = g_string_new("[keyfile]\n# devices managed by networkd\nunmanaged-devices+="); len = s->len; g_hash_table_foreach(netdefs, nd_append_non_nm_ids, s); if (s->len > len) g_string_free_to_file(s, rootdir, "run/NetworkManager/conf.d/netplan.conf", NULL); else g_string_free(s, TRUE); /* write generated udev rules */ if (udev_rules) g_string_free_to_file(udev_rules, rootdir, "run/udev/rules.d/90-netplan.rules", NULL); } /** * Clean up all generated configurations in @rootdir from previous runs. */ void cleanup_nm_conf(const char* rootdir) { g_autofree char* confpath = g_strjoin(NULL, rootdir ?: "", "/run/NetworkManager/conf.d/netplan.conf", NULL); g_autofree char* global_manage_path = g_strjoin(NULL, rootdir ?: "", "/run/NetworkManager/conf.d/10-globally-managed-devices.conf", NULL); unlink(confpath); unlink(global_manage_path); unlink_glob(rootdir, "/run/NetworkManager/system-connections/netplan-*"); } nplan-0.32~16.04.7~mtrudel1/src/nm.h0000664000000000000000000000154213272657646013644 0ustar /* * Copyright (C) 2016 Canonical, Ltd. * Author: Martin Pitt * * 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; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #pragma once #include "parse.h" void write_nm_conf(net_definition* def, const char* rootdir); void write_nm_conf_finish(const char* rootdir); void cleanup_nm_conf(const char* rootdir); nplan-0.32~16.04.7~mtrudel1/src/parse.c0000664000000000000000000014277113315465032014331 0ustar /* * Copyright (C) 2016 Canonical, Ltd. * Author: Martin Pitt * * 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; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include #include #include "parse.h" /* convenience macro to put the offset of a net_definition field into "void* data" */ #define netdef_offset(field) GUINT_TO_POINTER(offsetof(net_definition, field)) #define route_offset(field) GUINT_TO_POINTER(offsetof(ip_route, field)) /* file that is currently being processed, for useful error messages */ const char* current_file; /* net_definition that is currently being processed */ net_definition* cur_netdef; /* wifi AP that is currently being processed */ wifi_access_point* cur_access_point; ip_route* cur_route; netdef_backend backend_global, backend_cur_type; /* Global ID → net_definition* map for all parsed config files */ GHashTable* netdefs; /* Set of IDs in currently parsed YAML file, for being able to detect * "duplicate ID within one file" vs. allowing a drop-in to override/amend an * existing definition */ GHashTable* ids_in_file; /* List of "seen" ids not found in netdefs yet by the parser. * These are removed when it exists in this list and we reach the point of * creating a netdef for that id; so by the time we're done parsing the yaml * document it should be empty. */ GHashTable *missing_id; int missing_ids_found; /**************************************************** * Loading and error handling ****************************************************/ /** * Load YAML file name into a yaml_document_t. * * Returns: TRUE on success, FALSE if the document is malformed; @error gets set then. */ static gboolean load_yaml(const char* yaml, yaml_document_t* doc, GError** error) { FILE* fyaml = NULL; yaml_parser_t parser; gboolean ret = TRUE; current_file = yaml; fyaml = g_fopen(yaml, "r"); if (!fyaml) { g_set_error(error, G_FILE_ERROR, errno, "Cannot open %s: %s", yaml, g_strerror(errno)); return FALSE; } yaml_parser_initialize(&parser); yaml_parser_set_input_file(&parser, fyaml); if (!yaml_parser_load(&parser, doc)) { g_set_error(error, G_MARKUP_ERROR, G_MARKUP_ERROR_PARSE, "Invalid YAML at %s line %zu column %zu: %s", yaml, parser.problem_mark.line, parser.problem_mark.column, parser.problem); ret = FALSE; } fclose(fyaml); return ret; } /** * Put a YAML specific error message for @node into @error. */ static gboolean yaml_error(yaml_node_t* node, GError** error, const char* msg, ...) { va_list argp; gchar* s; va_start(argp, msg); g_vasprintf(&s, msg, argp); g_set_error(error, G_MARKUP_ERROR, G_MARKUP_ERROR_PARSE, "Error in network definition %s line %zu column %zu: %s", current_file, node->start_mark.line, node->start_mark.column, s); g_free(s); va_end(argp); return FALSE; } /** * Raise a GError about a type mismatch and return FALSE. */ static gboolean assert_type_fn(yaml_node_t* node, yaml_node_type_t expected_type, GError** error) { if (node->type == expected_type) return TRUE; switch (expected_type) { case YAML_SCALAR_NODE: yaml_error(node, error, "expected scalar"); break; case YAML_SEQUENCE_NODE: yaml_error(node, error, "expected sequence"); break; case YAML_MAPPING_NODE: yaml_error(node, error, "expected mapping"); break; /* LCOV_EXCL_START */ default: g_assert_not_reached(); /* LCOV_EXCL_STOP */ } return FALSE; } static inline const char* scalar(const yaml_node_t* node) { return (const char*) node->data.scalar.value; } static void add_missing_node(const yaml_node_t* node) { missing_node* missing; /* Let's capture the current netdef we were playing with along with the * actual yaml_node_t that errors (that is an identifier not previously * seen by the compiler). We can use it later to write an sensible error * message and point the user in the right direction. */ missing = g_new0(missing_node, 1); missing->netdef_id = cur_netdef->id; missing->node = node; g_debug("recording missing yaml_node_t %s", scalar(node)); g_hash_table_insert(missing_id, (gpointer)scalar(node), missing); } /** * Check that node contains a valid ID/interface name. Raise GError if not. */ static gboolean assert_valid_id(yaml_node_t* node, GError** error) { static regex_t re; static gboolean re_inited = FALSE; g_assert(node->type == YAML_SCALAR_NODE); if (!re_inited) { g_assert(regcomp(&re, "^[[:alnum:][:punct:]]+$", REG_EXTENDED|REG_NOSUB) == 0); re_inited = TRUE; } if (regexec(&re, scalar(node), 0, NULL, 0) != 0) return yaml_error(node, error, "Invalid name '%s'", scalar(node)); return TRUE; } #define assert_type(n,t) { if (!assert_type_fn(n,t,error)) return FALSE; } /**************************************************** * Data types and functions for interpreting YAML nodes ****************************************************/ typedef gboolean (*node_handler) (yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error); typedef struct mapping_entry_handler_s { /* mapping key (must be scalar) */ const char* key; /* expected type of the mapped value */ yaml_node_type_t type; /* handler for the value of this key */ node_handler handler; /* if type == YAML_MAPPING_NODE and handler is NULL, use process_mapping() * on this handler map as handler */ const struct mapping_entry_handler_s* map_handlers; /* user_data */ const void* data; } mapping_entry_handler; /** * Return the #mapping_entry_handler that matches @key, or NULL if not found. */ static const mapping_entry_handler* get_handler(const mapping_entry_handler* handlers, const char* key) { for (unsigned i = 0; handlers[i].key != NULL; ++i) { if (g_strcmp0(handlers[i].key, key) == 0) return &handlers[i]; } return NULL; } /** * Call handlers for all entries in a YAML mapping. * @doc: The yaml_document_t * @node: The yaml_node_t to process, must be a #YAML_MAPPING_NODE * @handlers: Array of mapping_entry_handler with allowed keys * @error: Gets set on data type errors or unknown keys * * Returns: TRUE on success, FALSE on error (@error gets set then). */ static gboolean process_mapping(yaml_document_t* doc, yaml_node_t* node, const mapping_entry_handler* handlers, GError** error) { yaml_node_pair_t* entry; assert_type(node, YAML_MAPPING_NODE); for (entry = node->data.mapping.pairs.start; entry < node->data.mapping.pairs.top; entry++) { yaml_node_t* key, *value; const mapping_entry_handler* h; key = yaml_document_get_node(doc, entry->key); value = yaml_document_get_node(doc, entry->value); assert_type(key, YAML_SCALAR_NODE); h = get_handler(handlers, scalar(key)); if (!h) return yaml_error(node, error, "unknown key %s", scalar(key)); assert_type(value, h->type); if (h->map_handlers) { g_assert(h->handler == NULL); g_assert(h->type == YAML_MAPPING_NODE); if (!process_mapping(doc, value, h->map_handlers, error)) return FALSE; } else { if (!h->handler(doc, value, h->data, error)) return FALSE; } } return TRUE; } /** * Generic handler for setting a cur_netdef string field from a scalar node * @data: offset into net_definition where the const char* field to write is * located */ static gboolean handle_netdef_str(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { guint offset = GPOINTER_TO_UINT(data); char** dest = (char**) ((void*) cur_netdef + offset); g_free(*dest); *dest = g_strdup(scalar(node)); return TRUE; } /** * Generic handler for setting a cur_netdef ID/iface name field from a scalar node * @data: offset into net_definition where the const char* field to write is * located */ static gboolean handle_netdef_id(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { if (!assert_valid_id(node, error)) return FALSE; return handle_netdef_str(doc, node, data, error); } /** * Generic handler for setting a cur_netdef ID/iface name field refering to an * existing ID from a scalar node * @data: offset into net_definition where the net_definition* field to write is * located */ static gboolean handle_netdef_id_ref(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { guint offset = GPOINTER_TO_UINT(data); net_definition* ref = NULL; ref = g_hash_table_lookup(netdefs, scalar(node)); if (!ref) { add_missing_node(node); } else { *((net_definition**) ((void*) cur_netdef + offset)) = ref; } return TRUE; } /** * Generic handler for setting a cur_netdef MAC address field from a scalar node * @data: offset into net_definition where the const char* field to write is * located */ static gboolean handle_netdef_mac(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { static regex_t re; static gboolean re_inited = FALSE; g_assert(node->type == YAML_SCALAR_NODE); if (!re_inited) { g_assert(regcomp(&re, "^[[:xdigit:]][[:xdigit:]]:[[:xdigit:]][[:xdigit:]]:[[:xdigit:]][[:xdigit:]]:[[:xdigit:]][[:xdigit:]]:[[:xdigit:]][[:xdigit:]]:[[:xdigit:]][[:xdigit:]]$", REG_EXTENDED|REG_NOSUB) == 0); re_inited = TRUE; } if (regexec(&re, scalar(node), 0, NULL, 0) != 0) return yaml_error(node, error, "Invalid MAC address '%s', must be XX:XX:XX:XX:XX:XX", scalar(node)); return handle_netdef_str(doc, node, data, error); } /** * Generic handler for setting a cur_netdef gboolean field from a scalar node * @data: offset into net_definition where the gboolean field to write is located */ static gboolean handle_netdef_bool(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { guint offset = GPOINTER_TO_UINT(data); gboolean v; if (g_ascii_strcasecmp(scalar(node), "true") == 0 || g_ascii_strcasecmp(scalar(node), "on") == 0 || g_ascii_strcasecmp(scalar(node), "yes") == 0 || g_ascii_strcasecmp(scalar(node), "y") == 0) v = TRUE; else if (g_ascii_strcasecmp(scalar(node), "false") == 0 || g_ascii_strcasecmp(scalar(node), "off") == 0 || g_ascii_strcasecmp(scalar(node), "no") == 0 || g_ascii_strcasecmp(scalar(node), "n") == 0) v = FALSE; else return yaml_error(node, error, "invalid boolean value %s", scalar(node)); *((gboolean*) ((void*) cur_netdef + offset)) = v; return TRUE; } /** * Generic handler for setting a cur_netdef guint field from a scalar node * @data: offset into net_definition where the guint field to write is located */ static gboolean handle_netdef_guint(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { guint offset = GPOINTER_TO_UINT(data); guint64 v; gchar* endptr; v = g_ascii_strtoull(scalar(node), &endptr, 10); if (*endptr != '\0' || v > G_MAXUINT) return yaml_error(node, error, "invalid unsigned int value %s", scalar(node)); *((guint*) ((void*) cur_netdef + offset)) = (guint) v; return TRUE; } /**************************************************** * Grammar and handlers for network config "match" entry ****************************************************/ const mapping_entry_handler match_handlers[] = { {"driver", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(match.driver)}, {"macaddress", YAML_SCALAR_NODE, handle_netdef_mac, NULL, netdef_offset(match.mac)}, {"name", YAML_SCALAR_NODE, handle_netdef_id, NULL, netdef_offset(match.original_name)}, {NULL} }; /**************************************************** * Grammar and handlers for network device definition ****************************************************/ static netdef_backend get_default_backend_for_type(netdef_type type) { if (backend_global != BACKEND_NONE) return backend_global; /* networkd can handle all device types at the moment, so nothing * type-specific */ return BACKEND_NETWORKD; } static gboolean handle_access_point_password(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { g_assert(cur_access_point); cur_access_point->password = g_strdup(scalar(node)); return TRUE; } static gboolean handle_access_point_mode(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { g_assert(cur_access_point); if (strcmp(scalar(node), "infrastructure") == 0) cur_access_point->mode = WIFI_MODE_INFRASTRUCTURE; else if (strcmp(scalar(node), "adhoc") == 0) cur_access_point->mode = WIFI_MODE_ADHOC; else if (strcmp(scalar(node), "ap") == 0) cur_access_point->mode = WIFI_MODE_AP; else return yaml_error(node, error, "unknown wifi mode '%s'", scalar(node)); return TRUE; } const mapping_entry_handler wifi_access_point_handlers[] = { {"mode", YAML_SCALAR_NODE, handle_access_point_mode}, {"password", YAML_SCALAR_NODE, handle_access_point_password}, {NULL} }; /** * Parse scalar node's string into a netdef_backend. */ static gboolean parse_renderer(yaml_node_t* node, netdef_backend* backend, GError** error) { if (strcmp(scalar(node), "networkd") == 0) *backend = BACKEND_NETWORKD; else if (strcmp(scalar(node), "NetworkManager") == 0) *backend = BACKEND_NM; else return yaml_error(node, error, "unknown renderer '%s'", scalar(node)); return TRUE; } static gboolean handle_netdef_renderer(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { return parse_renderer(node, &cur_netdef->backend, error); } static gboolean handle_accept_ra(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { if (g_ascii_strcasecmp(scalar(node), "true") == 0 || g_ascii_strcasecmp(scalar(node), "on") == 0 || g_ascii_strcasecmp(scalar(node), "yes") == 0 || g_ascii_strcasecmp(scalar(node), "y") == 0) cur_netdef->accept_ra = ACCEPT_RA_ENABLED; else if (g_ascii_strcasecmp(scalar(node), "false") == 0 || g_ascii_strcasecmp(scalar(node), "off") == 0 || g_ascii_strcasecmp(scalar(node), "no") == 0 || g_ascii_strcasecmp(scalar(node), "n") == 0) cur_netdef->accept_ra = ACCEPT_RA_DISABLED; else return yaml_error(node, error, "invalid boolean value %s", scalar(node)); return TRUE; } static gboolean handle_match(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { cur_netdef->has_match = TRUE; return process_mapping(doc, node, match_handlers, error); } static gboolean handle_addresses(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { for (yaml_node_item_t *i = node->data.sequence.items.start; i < node->data.sequence.items.top; i++) { struct in_addr a4; struct in6_addr a6; int ret; g_autofree char* addr = NULL; char* prefix_len; guint64 prefix_len_num; yaml_node_t *entry = yaml_document_get_node(doc, *i); assert_type(entry, YAML_SCALAR_NODE); /* split off /prefix_len */ addr = g_strdup(scalar(entry)); prefix_len = strrchr(addr, '/'); if (!prefix_len) return yaml_error(node, error, "address '%s' is missing /prefixlength", scalar(entry)); *prefix_len = '\0'; prefix_len++; /* skip former '/' into first char of prefix */ prefix_len_num = g_ascii_strtoull(prefix_len, NULL, 10); /* is it an IPv4 address? */ ret = inet_pton(AF_INET, addr, &a4); g_assert(ret >= 0); if (ret > 0) { if (prefix_len_num == 0 || prefix_len_num > 32) return yaml_error(node, error, "invalid prefix length in address '%s'", scalar(entry)); if (!cur_netdef->ip4_addresses) cur_netdef->ip4_addresses = g_array_new(FALSE, FALSE, sizeof(char*)); char* s = g_strdup(scalar(entry)); g_array_append_val(cur_netdef->ip4_addresses, s); continue; } /* is it an IPv6 address? */ ret = inet_pton(AF_INET6, addr, &a6); g_assert(ret >= 0); if (ret > 0) { if (prefix_len_num == 0 || prefix_len_num > 128) return yaml_error(node, error, "invalid prefix length in address '%s'", scalar(entry)); if (!cur_netdef->ip6_addresses) cur_netdef->ip6_addresses = g_array_new(FALSE, FALSE, sizeof(char*)); char* s = g_strdup(scalar(entry)); g_array_append_val(cur_netdef->ip6_addresses, s); continue; } return yaml_error(node, error, "malformed address '%s', must be X.X.X.X/NN or X:X:X:X:X:X:X:X/NN", scalar(entry)); } return TRUE; } static gboolean handle_gateway4(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { struct in_addr a4; int ret = inet_pton(AF_INET, scalar(node), &a4); g_assert(ret >= 0); if (ret == 0) return yaml_error(node, error, "invalid IPv4 address '%s'", scalar(node)); cur_netdef->gateway4 = g_strdup(scalar(node)); return TRUE; } static gboolean handle_gateway6(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { struct in6_addr a6; int ret = inet_pton(AF_INET6, scalar(node), &a6); g_assert(ret >= 0); if (ret == 0) return yaml_error(node, error, "invalid IPv6 address '%s'", scalar(node)); cur_netdef->gateway6 = g_strdup(scalar(node)); return TRUE; } static gboolean handle_wifi_access_points(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { for (yaml_node_pair_t* entry = node->data.mapping.pairs.start; entry < node->data.mapping.pairs.top; entry++) { yaml_node_t* key, *value; key = yaml_document_get_node(doc, entry->key); assert_type(key, YAML_SCALAR_NODE); value = yaml_document_get_node(doc, entry->value); assert_type(value, YAML_MAPPING_NODE); g_assert(cur_access_point == NULL); cur_access_point = g_new0(wifi_access_point, 1); cur_access_point->ssid = g_strdup(scalar(key)); g_debug("%s: adding wifi AP '%s'", cur_netdef->id, cur_access_point->ssid); if (!cur_netdef->access_points) cur_netdef->access_points = g_hash_table_new(g_str_hash, g_str_equal); if (!g_hash_table_insert(cur_netdef->access_points, cur_access_point->ssid, cur_access_point)) return yaml_error(key, error, "%s: Duplicate access point SSID '%s'", cur_netdef->id, cur_access_point->ssid); if (!process_mapping(doc, value, wifi_access_point_handlers, error)) return FALSE; cur_access_point = NULL; } return TRUE; } /** * Handler for "interfaces:" list. We don't store that list in cur_netdef, but * set cur_netdef's ID in all listed interfaces' "bond" or "bridge" field. * @data: offset into net_definition where the const char* ID reference field * to write is located */ static gboolean handle_interfaces(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { /* all entries must refer to already defined IDs */ for (yaml_node_item_t *i = node->data.sequence.items.start; i < node->data.sequence.items.top; i++) { yaml_node_t *entry = yaml_document_get_node(doc, *i); net_definition *component; char** component_ref_ptr; assert_type(entry, YAML_SCALAR_NODE); component = g_hash_table_lookup(netdefs, scalar(entry)); if (!component) { add_missing_node(entry); } else { component_ref_ptr = ((char**) ((void*) component + GPOINTER_TO_UINT(data))); if (*component_ref_ptr && *component_ref_ptr != cur_netdef->id) return yaml_error(node, error, "%s: interface %s is already assigned to %s", cur_netdef->id, scalar(entry), *component_ref_ptr); *component_ref_ptr = cur_netdef->id; } } return TRUE; } static gboolean handle_nameservers_search(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { for (yaml_node_item_t *i = node->data.sequence.items.start; i < node->data.sequence.items.top; i++) { yaml_node_t *entry = yaml_document_get_node(doc, *i); assert_type(entry, YAML_SCALAR_NODE); if (!cur_netdef->search_domains) cur_netdef->search_domains = g_array_new(FALSE, FALSE, sizeof(char*)); char* s = g_strdup(scalar(entry)); g_array_append_val(cur_netdef->search_domains, s); } return TRUE; } static gboolean handle_nameservers_addresses(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { for (yaml_node_item_t *i = node->data.sequence.items.start; i < node->data.sequence.items.top; i++) { struct in_addr a4; struct in6_addr a6; int ret; yaml_node_t *entry = yaml_document_get_node(doc, *i); assert_type(entry, YAML_SCALAR_NODE); /* is it an IPv4 address? */ ret = inet_pton(AF_INET, scalar(entry), &a4); g_assert(ret >= 0); if (ret > 0) { if (!cur_netdef->ip4_nameservers) cur_netdef->ip4_nameservers = g_array_new(FALSE, FALSE, sizeof(char*)); char* s = g_strdup(scalar(entry)); g_array_append_val(cur_netdef->ip4_nameservers, s); continue; } /* is it an IPv6 address? */ ret = inet_pton(AF_INET6, scalar(entry), &a6); g_assert(ret >= 0); if (ret > 0) { if (!cur_netdef->ip6_nameservers) cur_netdef->ip6_nameservers = g_array_new(FALSE, FALSE, sizeof(char*)); char* s = g_strdup(scalar(entry)); g_array_append_val(cur_netdef->ip6_nameservers, s); continue; } return yaml_error(node, error, "malformed address '%s', must be X.X.X.X or X:X:X:X:X:X:X:X", scalar(entry)); } return TRUE; } static int get_ip_family(const char* address) { struct in_addr a4; struct in6_addr a6; g_autofree char *ip_str; char *prefix_len; int ret = -1; ip_str = g_strdup(address); prefix_len = strrchr(ip_str, '/'); if (prefix_len) *prefix_len = '\0'; ret = inet_pton(AF_INET, ip_str, &a4); g_assert(ret >= 0); if (ret > 0) return AF_INET; ret = inet_pton(AF_INET6, ip_str, &a6); g_assert(ret >= 0); if (ret > 0) return AF_INET6; return -1; } static gboolean check_and_set_family(int family) { if (cur_route->family != -1 && cur_route->family != family) return FALSE; cur_route->family = family; return TRUE; } static gboolean handle_routes_ip(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { guint offset = GPOINTER_TO_UINT(data); int family = get_ip_family(scalar(node)); char** dest = (char**) ((void*) cur_route + offset); g_free(*dest); if (family < 0) return yaml_error(node, error, "invalid IP family %d", family); if (!check_and_set_family(family)) return yaml_error(node, error, "IP family mismatch in route to %s", scalar(node)); *dest = g_strdup(scalar(node)); return TRUE; } static gboolean handle_routes_metric(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { guint64 v; gchar* endptr; v = g_ascii_strtoull(scalar(node), &endptr, 10); if (*endptr != '\0' || v > G_MAXUINT) return yaml_error(node, error, "invalid unsigned int value %s", scalar(node)); cur_route->metric = (guint) v; return TRUE; } /**************************************************** * Grammar and handlers for network config "bridge_params" entry ****************************************************/ static gboolean handle_bridge_path_cost(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { for (yaml_node_pair_t* entry = node->data.mapping.pairs.start; entry < node->data.mapping.pairs.top; entry++) { yaml_node_t* key, *value; guint v; gchar* endptr; net_definition *component; guint* ref_ptr; key = yaml_document_get_node(doc, entry->key); assert_type(key, YAML_SCALAR_NODE); value = yaml_document_get_node(doc, entry->value); assert_type(value, YAML_SCALAR_NODE); component = g_hash_table_lookup(netdefs, scalar(key)); if (!component) { add_missing_node(key); } else { ref_ptr = ((guint*) ((void*) component + GPOINTER_TO_UINT(data))); if (*ref_ptr) return yaml_error(node, error, "%s: interface %s already has a path cost of %u", cur_netdef->id, scalar(key), *ref_ptr); v = g_ascii_strtoull(scalar(value), &endptr, 10); if (*endptr != '\0' || v > G_MAXUINT) return yaml_error(node, error, "invalid unsigned int value %s", scalar(value)); g_debug("%s: adding path '%s' of cost: %d", cur_netdef->id, scalar(key), v); *ref_ptr = v; } } return TRUE; } static gboolean handle_bridge_port_priority(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { for (yaml_node_pair_t* entry = node->data.mapping.pairs.start; entry < node->data.mapping.pairs.top; entry++) { yaml_node_t* key, *value; guint v; gchar* endptr; net_definition *component; guint* ref_ptr; key = yaml_document_get_node(doc, entry->key); assert_type(key, YAML_SCALAR_NODE); value = yaml_document_get_node(doc, entry->value); assert_type(value, YAML_SCALAR_NODE); component = g_hash_table_lookup(netdefs, scalar(key)); if (!component) { add_missing_node(key); } else { ref_ptr = ((guint*) ((void*) component + GPOINTER_TO_UINT(data))); if (*ref_ptr) return yaml_error(node, error, "%s: interface %s already has a port priority of %u", cur_netdef->id, scalar(key), *ref_ptr); v = g_ascii_strtoull(scalar(value), &endptr, 10); if (*endptr != '\0' || v > 63) return yaml_error(node, error, "invalid port priority value (must be between 0 and 63): %s", scalar(value)); g_debug("%s: adding port '%s' of priority: %d", cur_netdef->id, scalar(key), v); *ref_ptr = v; } } return TRUE; } const mapping_entry_handler bridge_params_handlers[] = { {"ageing-time", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bridge_params.ageing_time)}, {"forward-delay", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bridge_params.forward_delay)}, {"hello-time", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bridge_params.hello_time)}, {"max-age", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bridge_params.max_age)}, {"path-cost", YAML_MAPPING_NODE, handle_bridge_path_cost, NULL, netdef_offset(bridge_params.path_cost)}, {"port-priority", YAML_MAPPING_NODE, handle_bridge_port_priority, NULL, netdef_offset(bridge_params.port_priority)}, {"priority", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(bridge_params.priority)}, {"stp", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(bridge_params.stp)}, {NULL} }; static gboolean handle_bridge(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { cur_netdef->custom_bridging = TRUE; cur_netdef->bridge_params.stp = TRUE; return process_mapping(doc, node, bridge_params_handlers, error); } /**************************************************** * Grammar and handlers for network config "routes" entry ****************************************************/ const mapping_entry_handler routes_handlers[] = { {"to", YAML_SCALAR_NODE, handle_routes_ip, NULL, route_offset(to)}, {"via", YAML_SCALAR_NODE, handle_routes_ip, NULL, route_offset(via)}, {"metric", YAML_SCALAR_NODE, handle_routes_metric}, {NULL} }; static gboolean handle_routes(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { for (yaml_node_item_t *i = node->data.sequence.items.start; i < node->data.sequence.items.top; i++) { yaml_node_t *entry = yaml_document_get_node(doc, *i); cur_route = g_new0(ip_route, 1); cur_route->family = G_MAXUINT; /* 0 is a valid family ID */ cur_route->metric = G_MAXUINT; /* 0 is a valid metric */ if (process_mapping(doc, entry, routes_handlers, error)) { if (!cur_netdef->routes) { cur_netdef->routes = g_array_new(FALSE, FALSE, sizeof(ip_route*)); } g_array_append_val(cur_netdef->routes, cur_route); } if (!cur_route->to || !cur_route->via) return yaml_error(node, error, "route must include both a 'to' and 'via' IP"); cur_route = NULL; if (error && *error) return FALSE; } return TRUE; } /**************************************************** * Grammar and handlers for bond parameters ****************************************************/ static gboolean handle_arp_ip_targets(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { for (yaml_node_item_t *i = node->data.sequence.items.start; i < node->data.sequence.items.top; i++) { struct in_addr a4; int ret; g_autofree char* addr = NULL; yaml_node_t *entry = yaml_document_get_node(doc, *i); assert_type(entry, YAML_SCALAR_NODE); addr = g_strdup(scalar(entry)); /* is it an IPv4 address? */ ret = inet_pton(AF_INET, addr, &a4); g_assert(ret >= 0); if (ret > 0) { if (!cur_netdef->bond_params.arp_ip_targets) cur_netdef->bond_params.arp_ip_targets = g_array_new(FALSE, FALSE, sizeof(char*)); char* s = g_strdup(scalar(entry)); g_array_append_val(cur_netdef->bond_params.arp_ip_targets, s); continue; } return yaml_error(node, error, "malformed address '%s', must be X.X.X.X or X:X:X:X:X:X:X:X", scalar(entry)); } return TRUE; } static gboolean handle_bond_primary_slave(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { net_definition *component; char** ref_ptr; component = g_hash_table_lookup(netdefs, scalar(node)); if (!component) { add_missing_node(node); } else { if (cur_netdef->bond_params.primary_slave) return yaml_error(node, error, "%s: bond already has a primary slave: %s", cur_netdef->id, cur_netdef->bond_params.primary_slave); ref_ptr = ((char**) ((void*) component + GPOINTER_TO_UINT(data))); *ref_ptr = g_strdup(scalar(node)); cur_netdef->bond_params.primary_slave = g_strdup(scalar(node)); } return TRUE; } const mapping_entry_handler bond_params_handlers[] = { {"mode", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.mode)}, {"lacp-rate", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.lacp_rate)}, {"mii-monitor-interval", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.monitor_interval)}, {"min-links", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(bond_params.min_links)}, {"transmit-hash-policy", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.transmit_hash_policy)}, {"ad-select", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.selection_logic)}, {"all-slaves-active", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(bond_params.all_slaves_active)}, {"arp-interval", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.arp_interval)}, /* TODO: arp_ip_targets */ {"arp-ip-targets", YAML_SEQUENCE_NODE, handle_arp_ip_targets}, {"arp-validate", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.arp_validate)}, {"arp-all-targets", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.arp_all_targets)}, {"up-delay", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.up_delay)}, {"down-delay", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.down_delay)}, {"fail-over-mac-policy", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.fail_over_mac_policy)}, {"gratuitious-arp", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(bond_params.gratuitious_arp)}, /* TODO: unsolicited_na */ {"packets-per-slave", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(bond_params.packets_per_slave)}, {"primary-reselect-policy", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.primary_reselect_policy)}, {"resend-igmp", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(bond_params.resend_igmp)}, {"learn-packet-interval", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(bond_params.learn_interval)}, {"primary", YAML_SCALAR_NODE, handle_bond_primary_slave, NULL, netdef_offset(bond_params.primary_slave)}, {NULL} }; static gboolean handle_bonding(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { return process_mapping(doc, node, bond_params_handlers, error); } static gboolean handle_dhcp_identifier(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { if (cur_netdef->dhcp_identifier) g_free(cur_netdef->dhcp_identifier); cur_netdef->dhcp_identifier = g_strdup(scalar(node)); if (g_ascii_strcasecmp(cur_netdef->dhcp_identifier, "duid") == 0 || g_ascii_strcasecmp(cur_netdef->dhcp_identifier, "mac") == 0) return TRUE; return yaml_error(node, error, "invalid DHCP client identifier type '%s'", cur_netdef->dhcp_identifier); } /**************************************************** * Grammar and handlers for network devices ****************************************************/ const mapping_entry_handler nameservers_handlers[] = { {"search", YAML_SEQUENCE_NODE, handle_nameservers_search}, {"addresses", YAML_SEQUENCE_NODE, handle_nameservers_addresses}, {NULL} }; const mapping_entry_handler ethernet_def_handlers[] = { {"accept-ra", YAML_SCALAR_NODE, handle_accept_ra}, {"addresses", YAML_SEQUENCE_NODE, handle_addresses}, {"critical", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(critical)}, {"dhcp4", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp4)}, {"dhcp6", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp6)}, {"dhcp-identifier", YAML_SCALAR_NODE, handle_dhcp_identifier}, {"gateway4", YAML_SCALAR_NODE, handle_gateway4}, {"gateway6", YAML_SCALAR_NODE, handle_gateway6}, {"macaddress", YAML_SCALAR_NODE, handle_netdef_mac, NULL, netdef_offset(set_mac)}, {"match", YAML_MAPPING_NODE, handle_match}, {"mtu", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(mtubytes)}, {"nameservers", YAML_MAPPING_NODE, NULL, nameservers_handlers}, {"renderer", YAML_SCALAR_NODE, handle_netdef_renderer}, {"routes", YAML_SEQUENCE_NODE, handle_routes}, {"set-name", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(set_name)}, {"wakeonlan", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(wake_on_lan)}, {"optional", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(optional)}, {NULL} }; const mapping_entry_handler wifi_def_handlers[] = { {"accept-ra", YAML_SCALAR_NODE, handle_accept_ra}, {"access-points", YAML_MAPPING_NODE, handle_wifi_access_points}, {"addresses", YAML_SEQUENCE_NODE, handle_addresses}, {"critical", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(critical)}, {"dhcp4", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp4)}, {"dhcp6", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp6)}, {"dhcp-identifier", YAML_SCALAR_NODE, handle_dhcp_identifier}, {"gateway4", YAML_SCALAR_NODE, handle_gateway4}, {"gateway6", YAML_SCALAR_NODE, handle_gateway6}, {"macaddress", YAML_SCALAR_NODE, handle_netdef_mac, NULL, netdef_offset(set_mac)}, {"match", YAML_MAPPING_NODE, handle_match}, {"mtu", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(mtubytes)}, {"nameservers", YAML_MAPPING_NODE, NULL, nameservers_handlers}, {"renderer", YAML_SCALAR_NODE, handle_netdef_renderer}, {"routes", YAML_SEQUENCE_NODE, handle_routes}, {"set-name", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(set_name)}, {"wakeonlan", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(wake_on_lan)}, {"optional", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(optional)}, {NULL} }; const mapping_entry_handler bridge_def_handlers[] = { {"accept-ra", YAML_SCALAR_NODE, handle_accept_ra}, {"addresses", YAML_SEQUENCE_NODE, handle_addresses}, {"critical", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(critical)}, {"dhcp4", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp4)}, {"dhcp6", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp6)}, {"dhcp-identifier", YAML_SCALAR_NODE, handle_dhcp_identifier}, {"gateway4", YAML_SCALAR_NODE, handle_gateway4}, {"gateway6", YAML_SCALAR_NODE, handle_gateway6}, {"interfaces", YAML_SEQUENCE_NODE, handle_interfaces, NULL, netdef_offset(bridge)}, {"macaddress", YAML_SCALAR_NODE, handle_netdef_mac, NULL, netdef_offset(set_mac)}, {"mtu", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(mtubytes)}, {"nameservers", YAML_MAPPING_NODE, NULL, nameservers_handlers}, {"parameters", YAML_MAPPING_NODE, handle_bridge}, {"renderer", YAML_SCALAR_NODE, handle_netdef_renderer}, {"routes", YAML_SEQUENCE_NODE, handle_routes}, {"optional", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(optional)}, {NULL} }; const mapping_entry_handler bond_def_handlers[] = { {"accept-ra", YAML_SCALAR_NODE, handle_accept_ra}, {"addresses", YAML_SEQUENCE_NODE, handle_addresses}, {"critical", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(critical)}, {"dhcp4", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp4)}, {"dhcp6", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp6)}, {"dhcp-identifier", YAML_SCALAR_NODE, handle_dhcp_identifier}, {"gateway4", YAML_SCALAR_NODE, handle_gateway4}, {"gateway6", YAML_SCALAR_NODE, handle_gateway6}, {"interfaces", YAML_SEQUENCE_NODE, handle_interfaces, NULL, netdef_offset(bond)}, {"macaddress", YAML_SCALAR_NODE, handle_netdef_mac, NULL, netdef_offset(set_mac)}, {"mtu", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(mtubytes)}, {"nameservers", YAML_MAPPING_NODE, NULL, nameservers_handlers}, {"parameters", YAML_MAPPING_NODE, handle_bonding}, {"renderer", YAML_SCALAR_NODE, handle_netdef_renderer}, {"routes", YAML_SEQUENCE_NODE, handle_routes}, {"optional", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(optional)}, {NULL} }; const mapping_entry_handler vlan_def_handlers[] = { {"accept-ra", YAML_SCALAR_NODE, handle_accept_ra}, {"addresses", YAML_SEQUENCE_NODE, handle_addresses}, {"critical", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(critical)}, {"dhcp4", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp4)}, {"dhcp6", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(dhcp6)}, {"dhcp-identifier", YAML_SCALAR_NODE, handle_dhcp_identifier}, {"gateway4", YAML_SCALAR_NODE, handle_gateway4}, {"gateway6", YAML_SCALAR_NODE, handle_gateway6}, {"id", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(vlan_id)}, {"link", YAML_SCALAR_NODE, handle_netdef_id_ref, NULL, netdef_offset(vlan_link)}, {"nameservers", YAML_MAPPING_NODE, NULL, nameservers_handlers}, {"macaddress", YAML_SCALAR_NODE, handle_netdef_mac, NULL, netdef_offset(set_mac)}, {"mtu", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(mtubytes)}, {"renderer", YAML_SCALAR_NODE, handle_netdef_renderer}, {"routes", YAML_SEQUENCE_NODE, handle_routes}, {"optional", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(optional)}, {NULL} }; /**************************************************** * Grammar and handlers for network node ****************************************************/ static gboolean handle_network_version(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { if (strcmp(scalar(node), "2") != 0) return yaml_error(node, error, "Only version 2 is supported"); return TRUE; } static gboolean handle_network_renderer(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error) { return parse_renderer(node, &backend_global, error); } static gboolean validate_netdef(net_definition* nd, yaml_node_t* node, GError** error) { int missing_id_count = g_hash_table_size(missing_id); g_assert(nd->type != ND_NONE); /* Skip all validation if we're missing some definition IDs (devices). * The ones we have yet to see may be necessary for validation to succeed, * we can complete it on the next parser pass. */ if (missing_id_count > 0) return TRUE; /* set-name: requires match: */ if (nd->set_name && !nd->has_match) return yaml_error(node, error, "%s: set-name: requires match: properties", nd->id); if (nd->type == ND_WIFI && nd->access_points == NULL) return yaml_error(node, error, "%s: No access points defined", nd->id); if (nd->type == ND_VLAN) { if (!nd->vlan_link) return yaml_error(node, error, "%s: missing link property", nd->id); nd->vlan_link->has_vlans = TRUE; if (nd->vlan_id == G_MAXUINT) return yaml_error(node, error, "%s: missing id property", nd->id); if (nd->vlan_id > 4094) return yaml_error(node, error, "%s: invalid id %u (allowed values are 0 to 4094)", nd->id, nd->vlan_id); } return TRUE; } /** * Callback for a net device type entry like "ethernets:" in "networks:" * @data: netdef_type (as pointer) */ static gboolean handle_network_type(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error) { for (yaml_node_pair_t* entry = node->data.mapping.pairs.start; entry < node->data.mapping.pairs.top; entry++) { yaml_node_t* key, *value; const mapping_entry_handler* handlers; key = yaml_document_get_node(doc, entry->key); if (!assert_valid_id(key, error)) return FALSE; /* globbing is not allowed for IDs */ if (strpbrk(scalar(key), "*[]?")) return yaml_error(key, error, "Definition ID '%s' must not use globbing", scalar(key)); value = yaml_document_get_node(doc, entry->value); /* special-case "renderer:" key to set the per-type backend */ if (strcmp(scalar(key), "renderer") == 0) { if (!parse_renderer(value, &backend_cur_type, error)) return FALSE; continue; } assert_type(value, YAML_MAPPING_NODE); /* At this point we've seen a new starting definition, if it has been * already mentioned in another netdef, removing it from our "missing" * list. */ if(g_hash_table_remove(missing_id, scalar(key))) missing_ids_found++; cur_netdef = g_hash_table_lookup(netdefs, scalar(key)); if (cur_netdef) { /* already exists, overriding/amending previous definition */ if (cur_netdef->type != GPOINTER_TO_UINT(data)) return yaml_error(key, error, "Updated definition '%s' changes device type", scalar(key)); } else { /* create new network definition */ cur_netdef = g_new0(net_definition, 1); cur_netdef->type = GPOINTER_TO_UINT(data); cur_netdef->backend = backend_cur_type ?: BACKEND_NONE; cur_netdef->id = g_strdup(scalar(key)); cur_netdef->vlan_id = G_MAXUINT; /* 0 is a valid ID */ cur_netdef->dhcp_identifier = g_strdup("duid"); /* keep networkd's default */ g_hash_table_insert(netdefs, cur_netdef->id, cur_netdef); } // XXX: breaks multi-pass parsing. //if (!g_hash_table_add(ids_in_file, cur_netdef->id)) // return yaml_error(key, error, "Duplicate net definition ID '%s'", cur_netdef->id); /* and fill it with definitions */ switch (cur_netdef->type) { case ND_ETHERNET: handlers = ethernet_def_handlers; break; case ND_WIFI: handlers = wifi_def_handlers; break; case ND_BRIDGE: handlers = bridge_def_handlers; break; case ND_BOND: handlers = bond_def_handlers; break; case ND_VLAN: handlers = vlan_def_handlers; break; default: g_assert_not_reached(); /* LCOV_EXCL_LINE */ } if (!process_mapping(doc, value, handlers, error)) return FALSE; /* validate definition-level conditions */ if (!validate_netdef(cur_netdef, value, error)) return FALSE; /* convenience shortcut: physical device without match: means match * name on ID */ if (cur_netdef->type < ND_VIRTUAL && !cur_netdef->has_match) cur_netdef->match.original_name = cur_netdef->id; } backend_cur_type = BACKEND_NONE; return TRUE; } const mapping_entry_handler network_handlers[] = { {"version", YAML_SCALAR_NODE, handle_network_version}, {"renderer", YAML_SCALAR_NODE, handle_network_renderer}, {"ethernets", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(ND_ETHERNET)}, {"wifis", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(ND_WIFI)}, {"bridges", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(ND_BRIDGE)}, {"bonds", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(ND_BOND)}, {"vlans", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(ND_VLAN)}, {NULL} }; /**************************************************** * Grammar and handlers for root node ****************************************************/ const mapping_entry_handler root_handlers[] = { {"network", YAML_MAPPING_NODE, NULL, network_handlers}, {NULL} }; /** * Handle multiple-pass parsing of the yaml document. */ static gboolean process_document(yaml_document_t* doc, GError** error) { gboolean ret; int previously_found; int still_missing; g_assert(missing_id == NULL); missing_id = g_hash_table_new_full(g_str_hash, g_str_equal, NULL, g_free); do { g_debug("starting new processing pass"); previously_found = missing_ids_found; missing_ids_found = 0; ret = process_mapping(doc, yaml_document_get_root_node(doc), root_handlers, error); still_missing = g_hash_table_size(missing_id); if (still_missing > 0 && missing_ids_found == previously_found) break; } while (still_missing > 0 || missing_ids_found > 0); if (g_hash_table_size(missing_id) > 0) { GHashTableIter iter; gpointer key, value; missing_node *missing; g_clear_error(error); /* Get the first missing identifier we can get from our list, to * approximate early failure and give the user a meaningful error. */ g_hash_table_iter_init (&iter, missing_id); g_hash_table_iter_next (&iter, &key, &value); missing = (missing_node*) value; return yaml_error(missing->node, error, "%s: interface %s is not defined", missing->netdef_id, key); } g_hash_table_destroy(missing_id); missing_id = NULL; return ret; } /** * Parse given YAML file and create/update global "netdefs" list. */ gboolean parse_yaml(const char* filename, GError** error) { yaml_document_t doc; gboolean ret; if (!load_yaml(filename, &doc, error)) return FALSE; /* empty file? */ if (yaml_document_get_root_node(&doc) == NULL) return TRUE; if (!netdefs) netdefs = g_hash_table_new(g_str_hash, g_str_equal); g_assert(ids_in_file == NULL); ids_in_file = g_hash_table_new(g_str_hash, NULL); ret = process_document(&doc, error); cur_netdef = NULL; yaml_document_delete(&doc); g_hash_table_destroy(ids_in_file); ids_in_file = NULL; return ret; } static void finish_iterator(gpointer key, gpointer value, gpointer user_data) { net_definition* nd = value; if (nd->backend == BACKEND_NONE) { nd->backend = get_default_backend_for_type(nd->type); g_debug("%s: setting default backend to %i", nd->id, nd->backend); } } /** * Post-processing after parsing all config files */ gboolean finish_parse(GError** error) { if (netdefs) g_hash_table_foreach(netdefs, finish_iterator, NULL); return TRUE; } /** * Return current global backend. */ netdef_backend get_global_backend() { return backend_global; } nplan-0.32~16.04.7~mtrudel1/src/parse.h0000664000000000000000000001036613315465032014330 0ustar /* * Copyright (C) 2016 Canonical, Ltd. * Author: Martin Pitt * * 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; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #pragma once #include #include /**************************************************** * Parsed definitions ****************************************************/ typedef enum { ND_NONE, /* physical devices */ ND_ETHERNET, ND_WIFI, /* virtual devices */ ND_VIRTUAL, ND_BRIDGE = ND_VIRTUAL, ND_BOND, ND_VLAN, } netdef_type; typedef enum { BACKEND_NONE, BACKEND_NETWORKD, BACKEND_NM, } netdef_backend; typedef enum { ACCEPT_RA_KERNEL, ACCEPT_RA_ENABLED, ACCEPT_RA_DISABLED, } ra_mode; typedef struct missing_node { char* netdef_id; yaml_node_t* node; } missing_node; /** * Represent a configuration stanza */ typedef struct net_definition { netdef_type type; netdef_backend backend; char* id; /* only necessary for NetworkManager connection UUIDs in some cases */ uuid_t uuid; /* status options */ gboolean optional; gboolean critical; /* addresses */ gboolean dhcp4; gboolean dhcp6; char* dhcp_identifier; ra_mode accept_ra; GArray* ip4_addresses; GArray* ip6_addresses; char* gateway4; char* gateway6; GArray* ip4_nameservers; GArray* ip6_nameservers; GArray* search_domains; GArray* routes; /* master ID for slave devices */ char* bridge; char* bond; /* vlan */ guint vlan_id; struct net_definition* vlan_link; gboolean has_vlans; /* Configured custom MAC address */ char* set_mac; /* interface mtu */ guint mtubytes; /* these properties are only valid for physical interfaces (type < ND_VIRTUAL) */ char* set_name; struct { char* driver; char* mac; char* original_name; } match; gboolean has_match; gboolean wake_on_lan; /* these properties are only valid for ND_WIFI */ GHashTable* access_points; /* SSID → wifi_access_point* */ struct { char* mode; char* lacp_rate; char* monitor_interval; guint min_links; char* transmit_hash_policy; char* selection_logic; gboolean all_slaves_active; char* arp_interval; GArray* arp_ip_targets; char* arp_validate; char* arp_all_targets; char* up_delay; char* down_delay; char* fail_over_mac_policy; guint gratuitious_arp; /* TODO: unsolicited_na */ guint packets_per_slave; char* primary_reselect_policy; guint resend_igmp; char* learn_interval; char* primary_slave; } bond_params; struct { char* ageing_time; guint priority; guint port_priority; char* forward_delay; char* hello_time; char* max_age; guint path_cost; gboolean stp; } bridge_params; gboolean custom_bridging; } net_definition; typedef enum { WIFI_MODE_INFRASTRUCTURE, WIFI_MODE_ADHOC, WIFI_MODE_AP } wifi_mode; typedef struct { wifi_mode mode; char* ssid; char* password; } wifi_access_point; #define METRIC_UNSPEC G_MAXUINT typedef struct { guint family; char* to; char* via; /* valid metrics are valid positive integers. * invalid metrics are represented by METRIC_UNSPEC */ guint metric; } ip_route; /* Written/updated by parse_yaml(): char* id → net_definition */ extern GHashTable* netdefs; /**************************************************** * Functions ****************************************************/ gboolean parse_yaml(const char* filename, GError** error); gboolean finish_parse(GError** error); netdef_backend get_global_backend(); nplan-0.32~16.04.7~mtrudel1/src/toto0000664000000000000000000000000013533506261013737 0ustar nplan-0.32~16.04.7~mtrudel1/src/util.c0000664000000000000000000000527113315465032014165 0ustar /* * Copyright (C) 2016 Canonical, Ltd. * Author: Martin Pitt * * 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; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include #include #include "util.h" /** * Create the parent directories of given file path. Exit program on failure. */ void safe_mkdir_p_dir(const char* file_path) { g_autofree char* dir = g_path_get_dirname(file_path); if (g_mkdir_with_parents(dir, 0755) < 0) { g_fprintf(stderr, "ERROR: cannot create directory %s: %m\n", dir); exit(1); } } /** * Write a GString to a file and free it. Create necessary parent directories * and exit with error message on error. * @s: #GString whose contents to write. Will be fully freed afterwards. * @rootdir: optional rootdir (@NULL means "/") * @path: path of file to write (@rootdir will be prepended) * @suffix: optional suffix to append to path */ void g_string_free_to_file(GString* s, const char* rootdir, const char* path, const char* suffix) { g_autofree char* full_path = NULL; g_autofree char* contents = g_string_free(s, FALSE); GError* error = NULL; full_path = g_strjoin(NULL, rootdir ?: "", G_DIR_SEPARATOR_S, path, suffix, NULL); safe_mkdir_p_dir(full_path); if (!g_file_set_contents(full_path, contents, -1, &error)) { /* LCOV_EXCL_START -- the mkdir() just succeeded, there is no sensible * method to test this without root privileges, bind mounts, and * simulating ENOSPC */ g_fprintf(stderr, "ERROR: cannot create file %s: %s\n", path, error->message); exit(1); /* LCOV_EXCL_END */ } } /** * Remove all files matching given glob. */ void unlink_glob(const char* rootdir, const char* _glob) { glob_t gl; int rc; g_autofree char* rglob = g_strjoin(NULL, rootdir ?: "", G_DIR_SEPARATOR_S, _glob, NULL); rc = glob(rglob, 0, NULL, &gl); if (rc != 0 && rc != GLOB_NOMATCH) { g_fprintf(stderr, "failed to glob for %s: %m\n", rglob); /* LCOV_EXCL_LINE */ return; /* LCOV_EXCL_LINE */ } for (size_t i = 0; i < gl.gl_pathc; ++i) unlink(gl.gl_pathv[i]); } nplan-0.32~16.04.7~mtrudel1/src/util.h0000664000000000000000000000160013272657646014202 0ustar /* * Copyright (C) 2016 Canonical, Ltd. * Author: Martin Pitt * * 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; version 3. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #pragma once void safe_mkdir_p_dir(const char* file_path); void g_string_free_to_file(GString* s, const char* rootdir, const char* path, const char* suffix); void unlink_glob(const char* rootdir, const char* _glob); nplan-0.32~16.04.7~mtrudel1/tests/0000775000000000000000000000000013534004174013411 5ustar nplan-0.32~16.04.7~mtrudel1/tests/cli.py0000775000000000000000000003044313315465032014542 0ustar #!/usr/bin/python3 # Blackbox tests of netplan CLI. These are run during "make check" and don't # touch the system configuration at all. # # Copyright (C) 2016 Canonical, Ltd. # Author: Martin Pitt # # 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; version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os import sys import subprocess import unittest import tempfile import shutil import yaml rootdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) exe_cli = [os.path.join(rootdir, 'src', 'netplan')] if shutil.which('python3-coverage'): exe_cli = ['python3-coverage', 'run', '--append', '--'] + exe_cli class TestArgs(unittest.TestCase): '''Generic argument parsing tests''' def test_global_help(self): out = subprocess.check_output(exe_cli + ['--help']) self.assertIn(b'Available commands', out) self.assertIn(b'generate', out) self.assertIn(b'--debug', out) def test_command_help(self): out = subprocess.check_output(exe_cli + ['generate', '--help']) self.assertIn(b'--root-dir', out) def test_no_command(self): os.environ['NETPLAN_GENERATE_PATH'] = os.path.join(rootdir, 'generate') p = subprocess.Popen(exe_cli, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() self.assertEqual(out, b'') self.assertIn(b'need to specify a command', err) self.assertNotEqual(p.returncode, 0) class TestGenerate(unittest.TestCase): def setUp(self): self.workdir = tempfile.TemporaryDirectory() def test_no_config(self): out = subprocess.check_output(exe_cli + ['generate', '--root-dir', self.workdir.name]) self.assertEqual(out, b'') self.assertEqual(os.listdir(self.workdir.name), []) def test_with_config(self): c = os.path.join(self.workdir.name, 'etc', 'netplan') os.makedirs(c) with open(os.path.join(c, 'a.yaml'), 'w') as f: f.write('''network: version: 2 ethernets: enlol: {dhcp4: yes}''') out = subprocess.check_output(exe_cli + ['generate', '--root-dir', self.workdir.name]) self.assertEqual(out, b'') self.assertEqual(os.listdir(os.path.join(self.workdir.name, 'run', 'systemd', 'network')), ['10-netplan-enlol.network']) class TestIfupdownMigrate(unittest.TestCase): def setUp(self): self.workdir = tempfile.TemporaryDirectory() self.ifaces_path = os.path.join(self.workdir.name, 'etc/network/interfaces') self.converted_path = os.path.join(self.workdir.name, 'etc/netplan/10-ifupdown.yaml') def test_system(self): rc = subprocess.call(exe_cli + ['ifupdown-migrate', '--dry-run'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) # may succeed or fail, but should not crash self.assertIn(rc, [0, 2]) def do_test(self, iface_file, expect_success=True, dry_run=True, dropins=None): if iface_file is not None: os.makedirs(os.path.dirname(self.ifaces_path)) with open(self.ifaces_path, 'w') as f: f.write(iface_file) if dropins: for fname, contents in dropins.items(): path = os.path.join(os.path.dirname(self.ifaces_path), fname) os.makedirs(os.path.dirname(path), exist_ok=True) with open(path, 'w') as f: f.write(contents) argv = exe_cli + ['--debug', 'ifupdown-migrate', '--root-dir', self.workdir.name] if dry_run: argv.append('--dry-run') p = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (out, err) = p.communicate() if expect_success: self.assertEqual(p.returncode, 0, err.decode()) else: self.assertIn(p.returncode, [2, 3], err.decode()) return (out, err) # # configs which can be converted # def test_no_config(self): (out, err) = self.do_test(None) self.assertEqual(out, b'') self.assertEqual(os.listdir(self.workdir.name), []) def test_only_empty_include(self): out = self.do_test('''# default interfaces file source-directory /etc/network/interfaces.d''')[0] self.assertFalse(os.path.exists(self.converted_path)) self.assertEqual(out, b'') def test_loopback_only(self): (out, err) = self.do_test('auto lo\n#ignore me\niface lo inet loopback') self.assertEqual(out, b'') self.assertIn(b'nothing to migrate\n', err) def test_dhcp4(self): out = self.do_test('auto en1\niface en1 inet dhcp')[0] self.assertEqual(yaml.load(out), {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp4': True}}}}, out.decode()) def test_dhcp6(self): out = self.do_test('auto en1\niface en1 inet6 dhcp')[0] self.assertEqual(yaml.load(out), {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp6': True}}}}, out.decode()) def test_dhcp4_and_6(self): out = self.do_test('auto lo\niface lo inet loopback\n\n' 'auto en1\niface en1 inet dhcp\niface en1 inet6 dhcp')[0] self.assertEqual(yaml.load(out), {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp4': True, 'dhcp6': True}}}}, out.decode()) def test_includedir_rel(self): out = self.do_test('iface lo inet loopback\nauto lo\nsource-directory interfaces.d', dropins={'interfaces.d/std': 'auto en1\niface en1 inet dhcp', 'interfaces.d/std.bak': 'some_bogus dontreadme'})[0] self.assertEqual(yaml.load(out), {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp4': True}}}}, out.decode()) def test_includedir_abs(self): out = self.do_test('iface lo inet loopback\nauto lo\nsource-directory /etc/network/defs/my', dropins={'defs/my/std': 'auto en1\niface en1 inet dhcp', 'defs/my/std.bak': 'some_bogus dontreadme'})[0] self.assertEqual(yaml.load(out), {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp4': True}}}}, out.decode()) def test_include_rel(self): out = self.do_test('iface lo inet loopback\nauto lo\nsource interfaces.d/*.cfg', dropins={'interfaces.d/std.cfg': 'auto en1\niface en1 inet dhcp', 'interfaces.d/std.cfgold': 'some_bogus dontreadme'})[0] self.assertEqual(yaml.load(out), {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp4': True}}}}, out.decode()) def test_include_abs(self): out = self.do_test('iface lo inet loopback\nauto lo\nsource /etc/network/*.cfg', dropins={'std.cfg': 'auto en1\niface en1 inet dhcp', 'std.cfgold': 'some_bogus dontreadme'})[0] self.assertEqual(yaml.load(out), {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp4': True}}}}, out.decode()) def test_allow(self): out = self.do_test('allow-hotplug en1\niface en1 inet dhcp\n' 'allow-auto en2\niface en2 inet dhcp')[0] self.assertEqual(yaml.load(out), {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp4': True}, 'en2': {'dhcp4': True}}}}, out.decode()) def test_no_scripts(self): out = self.do_test('auto en1\niface en1 inet dhcp\nno-scripts en1')[0] self.assertEqual(yaml.load(out), {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp4': True}}}}, out.decode()) def test_write_file_noconfig(self): (out, err) = self.do_test('auto lo\niface lo inet loopback', dry_run=False) self.assertFalse(os.path.exists(self.converted_path)) # should disable original ifupdown config self.assertFalse(os.path.exists(self.ifaces_path)) self.assertTrue(os.path.exists(self.ifaces_path + '.netplan-converted')) def test_write_file_haveconfig(self): (out, err) = self.do_test('auto en1\niface en1 inet dhcp', dry_run=False) with open(self.converted_path) as f: config = yaml.load(f) self.assertEqual(config, {'network': { 'version': 2, 'ethernets': {'en1': {'dhcp4': True}}}}) # should disable original ifupdown config self.assertFalse(os.path.exists(self.ifaces_path)) self.assertTrue(os.path.exists(self.ifaces_path + '.netplan-converted')) def test_write_file_prev_run(self): os.makedirs(os.path.dirname(self.converted_path)) with open(self.converted_path, 'w') as f: f.write('canary') (out, err) = self.do_test('auto en1\niface en1 inet dhcp', dry_run=False, expect_success=False) with open(self.converted_path) as f: self.assertEqual(f.read(), 'canary') # should not disable original ifupdown config self.assertTrue(os.path.exists(self.ifaces_path)) # # configs which are not supported # def test_noauto(self): (out, err) = self.do_test('iface en1 inet dhcp', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'non-automatic interfaces are not supported', err) def test_dhcp_options(self): (out, err) = self.do_test('auto en1\niface en1 inet dhcp\nup myhook', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'options are not supported for dhcp method', err) def test_static(self): (out, err) = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'method static is not supported', err) def test_mapping(self): (out, err) = self.do_test('mapping en*\n script /some/path/mapscheme\nmap HOME en1-home\n\n' 'auto map1\niface map1 inet dhcp', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'mapping stanza is not supported', err) def test_unknown_allow(self): (out, err) = self.do_test('allow-foo en1\niface en1 inet dhcp', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'Unknown stanza type allow-foo', err) def test_unknown_stanza(self): (out, err) = self.do_test('foo en1\niface en1 inet dhcp', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'Unknown stanza type foo', err) def test_unknown_family(self): (out, err) = self.do_test('auto en1\niface en1 inet7 dhcp', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'Unknown address family inet7', err) def test_unknown_method(self): (out, err) = self.do_test('auto en1\niface en1 inet mangle', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'Unsupported method mangle', err) def test_too_few_fields(self): (out, err) = self.do_test('auto en1\niface en1 inet', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'Expected 3 fields for stanza type iface but got 2', err) def test_too_many_fields(self): (out, err) = self.do_test('auto en1\niface en1 inet dhcp foo', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'Expected 3 fields for stanza type iface but got 4', err) def test_write_file_notsupported(self): (out, err) = self.do_test('iface en1 inet dhcp', expect_success=False) self.assertEqual(out, b'') self.assertIn(b'non-automatic interfaces are not supported', err) # should keep original ifupdown config self.assertTrue(os.path.exists(self.ifaces_path)) unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) nplan-0.32~16.04.7~mtrudel1/tests/dbus/0000775000000000000000000000000013533506646014360 5ustar nplan-0.32~16.04.7~mtrudel1/tests/dbus/test_dbus.py0000664000000000000000000001404413533506646016731 0ustar # # Copyright (C) 2019 Canonical, Ltd. # # 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; version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os import shutil import subprocess import tempfile import unittest rootdir = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) exe_cli = [os.path.join(rootdir, 'src', 'netplan.script')] if shutil.which('python3-coverage'): exe_cli = ['python3-coverage', 'run', '--append', '--'] + exe_cli # Make sure we can import our development netplan. os.environ.update({'PYTHONPATH': '.'}) class MockCmd: """MockCmd will mock a given command name and capture all calls to it""" def __init__(self, name): self._tmp = tempfile.TemporaryDirectory() self.name = name self.path = os.path.join(self._tmp.name, name) self.call_log = os.path.join(self._tmp.name, "call.log") with open(self.path, "w") as fp: fp.write("""#!/bin/bash printf "%%s" "$(basename "$0")" >> %(log)s printf '\\0' >> %(log)s for arg in "$@"; do printf "%%s" "$arg" >> %(log)s printf '\\0' >> %(log)s done printf '\\0' >> %(log)s """ % {'log': self.call_log}) os.chmod(self.path, 0o755) def calls(self): """ calls() returns the calls to the given mock command in the form of [ ["cmd", "call1-arg1"], ["cmd", "call2-arg1"], ... ] """ with open(self.call_log) as fp: b = fp.read() calls = [] for raw_call in b.rstrip("\0\0").split("\0\0"): call = raw_call.rstrip("\0") calls.append(call.split("\0")) return calls class TestNetplanDBus(unittest.TestCase): def setUp(self): self.tmp = tempfile.mkdtemp() self.addCleanup(shutil.rmtree, self.tmp) self.mock_netplan_cmd = MockCmd("netplan") self._create_mock_system_bus() self._run_netplan_dbus_on_mock_bus() self._mock_snap_env() self.mock_busctl_cmd = MockCmd("busctl") def _mock_snap_env(self): os.environ["SNAP"] = "test-netplan-apply-snapd" def _create_mock_system_bus(self): env = {} output = subprocess.check_output(["dbus-launch"], env={}) for s in output.decode("utf-8").split("\n"): if s == "": continue k, v = s.split("=", 1) env[k] = v # override system bus with the fake one os.environ["DBUS_SYSTEM_BUS_ADDRESS"] = env["DBUS_SESSION_BUS_ADDRESS"] self.addCleanup(os.kill, int(env["DBUS_SESSION_BUS_PID"]), 15) def _run_netplan_dbus_on_mock_bus(self): # run netplan-dbus in a fake system bus os.environ["DBUS_TEST_NETPLAN_CMD"] = self.mock_netplan_cmd.path p = subprocess.Popen( os.path.join(os.path.dirname(__file__), "..", "..", "netplan-dbus"), stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.addCleanup(self._cleanup_netplan_dbus, p) def _cleanup_netplan_dbus(self, p): p.terminate() p.wait() # netplan-dbus does not produce output self.assertEqual(p.stdout.read(), b"") self.assertEqual(p.stderr.read(), b"") def test_netplan_apply_in_snap_uses_dbus(self): p = subprocess.Popen( exe_cli + ["apply"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) self.assertEqual(p.stdout.read(), b"") self.assertEqual(p.stderr.read(), b"") self.assertEquals(self.mock_netplan_cmd.calls(), [ ["netplan", "apply"], ]) def test_netplan_apply_in_snap_calls_busctl(self): newenv = os.environ.copy() busctlDir = os.path.dirname(self.mock_busctl_cmd.path) newenv["PATH"] = busctlDir+":"+os.environ["PATH"] p = subprocess.Popen( exe_cli + ["apply"], stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=newenv) self.assertEqual(p.stdout.read(), b"") self.assertEqual(p.stderr.read(), b"") self.assertEquals(self.mock_busctl_cmd.calls(), [ ["busctl", "call", "--quiet", "--system", "io.netplan.Netplan", # the service "/io/netplan/Netplan", # the object "io.netplan.Netplan", # the interface "Apply", # the method ], ]) def test_netplan_dbus_happy(self): BUSCTL_NETPLAN_APPLY = [ "busctl", "call", "--system", "io.netplan.Netplan", "/io/netplan/Netplan", "io.netplan.Netplan", "Apply", ] output = subprocess.check_output(BUSCTL_NETPLAN_APPLY) self.assertEqual(output.decode("utf-8"), "b true\n") # one call to netplan apply in total self.assertEquals(self.mock_netplan_cmd.calls(), [ ["netplan", "apply"], ]) # and again! output = subprocess.check_output(BUSCTL_NETPLAN_APPLY) self.assertEqual(output.decode("utf-8"), "b true\n") # and another call to netplan apply self.assertEquals(self.mock_netplan_cmd.calls(), [ ["netplan", "apply"], ["netplan", "apply"], ]) def test_netplan_dbus_no_such_command(self): p = subprocess.Popen( ["busctl", "call", "io.netplan.Netplan", "/io/netplan/Netplan", "io.netplan.Netplan", "NoSuchCommand"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) p.wait() self.assertEqual(p.returncode, 1) self.assertEqual(p.stdout.read().decode("utf-8"), "") self.assertIn("Unknown method", p.stderr.read().decode("utf-8")) nplan-0.32~16.04.7~mtrudel1/tests/generate.py0000775000000000000000000030123013315465504015564 0ustar #!/usr/bin/python3 # Blackbox tests of netplan generate that verify that the generated # configuration files look as expected. These are run during "make check" and # don't touch the system configuration at all. # # Copyright (C) 2016 Canonical, Ltd. # Author: Martin Pitt # # 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; version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os import re import sys import stat import tempfile import textwrap import subprocess import unittest exe_generate = os.path.join(os.path.dirname(os.path.dirname( os.path.abspath(__file__))), 'generate') # make sure we fail on criticals os.environ['G_DEBUG'] = 'fatal-criticals' # common patterns for expected output ND_DHCP4 = '[Match]\nName=%s\n\n[Network]\nDHCP=ipv4\n\n[DHCP]\nUseMTU=true\nRouteMetric=100\n' ND_WIFI_DHCP4 = '[Match]\nName=%s\n\n[Network]\nDHCP=ipv4\n\n[DHCP]\nUseMTU=true\nRouteMetric=600\n' ND_DHCP6 = '[Match]\nName=%s\n\n[Network]\nDHCP=ipv6\n\n[DHCP]\nUseMTU=true\nRouteMetric=100\n' ND_DHCPYES = '[Match]\nName=%s\n\n[Network]\nDHCP=yes\n\n[DHCP]\nUseMTU=true\nRouteMetric=100\n' UDEV_MAC_RULE = 'SUBSYSTEM=="net", ACTION=="add", DRIVERS=="%s", ATTR{address}=="%s", NAME="%s"\n' UDEV_NO_MAC_RULE = 'SUBSYSTEM=="net", ACTION=="add", DRIVERS=="%s", NAME="%s"\n' class TestBase(unittest.TestCase): def setUp(self): self.workdir = tempfile.TemporaryDirectory() self.confdir = os.path.join(self.workdir.name, 'etc', 'netplan') self.nm_enable_all_conf = os.path.join( self.workdir.name, 'run', 'NetworkManager', 'conf.d', '10-globally-managed-devices.conf') def generate(self, yaml, expect_fail=False, extra_args=[], confs=None): '''Call generate with given YAML string as configuration Return stderr output. ''' conf = os.path.join(self.confdir, 'a.yaml') os.makedirs(os.path.dirname(conf), exist_ok=True) if yaml is not None: with open(conf, 'w') as f: f.write(yaml) if confs: for f, contents in confs.items(): with open(os.path.join(self.confdir, f + '.yaml'), 'w') as f: f.write(contents) argv = [exe_generate, '--root-dir', self.workdir.name] + extra_args if 'TEST_SHELL' in os.environ: print('Test is about to run:\n%s' % ' '.join(argv)) subprocess.call(['bash', '-i'], cwd=self.workdir.name) p = subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) (out, err) = p.communicate() if expect_fail: self.assertGreater(p.returncode, 0) else: self.assertEqual(p.returncode, 0, err) self.assertEqual(out, '') return err def assert_networkd(self, file_contents_map): networkd_dir = os.path.join(self.workdir.name, 'run', 'systemd', 'network') if not file_contents_map: self.assertFalse(os.path.exists(networkd_dir)) return self.assertEqual(set(os.listdir(self.workdir.name)) - {'lib'}, {'etc', 'run'}) self.assertEqual(set(os.listdir(networkd_dir)), {'10-netplan-' + f for f in file_contents_map}) for fname, contents in file_contents_map.items(): with open(os.path.join(networkd_dir, '10-netplan-' + fname)) as f: self.assertEqual(f.read(), contents) def assert_networkd_udev(self, file_contents_map): udev_dir = os.path.join(self.workdir.name, 'run', 'udev', 'rules.d') if not file_contents_map: # it can either not exist, or can only contain 90-netplan.rules self.assertTrue((not os.path.exists(udev_dir)) or (os.listdir(udev_dir) == ['90-netplan.rules'])) return self.assertEqual(set(os.listdir(udev_dir)) - set(['90-netplan.rules']), {'99-netplan-' + f for f in file_contents_map}) for fname, contents in file_contents_map.items(): with open(os.path.join(udev_dir, '99-netplan-' + fname)) as f: self.assertEqual(f.read(), contents) def assert_nm(self, connections_map=None, conf=None): # check config conf_path = os.path.join(self.workdir.name, 'run', 'NetworkManager', 'conf.d', 'netplan.conf') if conf: with open(conf_path) as f: self.assertEqual(f.read(), conf) else: if os.path.exists(conf_path): with open(conf_path) as f: self.fail('unexpected %s:\n%s' % (conf_path, f.read())) # check connections con_dir = os.path.join(self.workdir.name, 'run', 'NetworkManager', 'system-connections') if connections_map: self.assertEqual(set(os.listdir(con_dir)), set(['netplan-' + n for n in connections_map])) for fname, contents in connections_map.items(): with open(os.path.join(con_dir, 'netplan-' + fname)) as f: self.assertEqual(f.read(), contents) # NM connection files might contain secrets self.assertEqual(stat.S_IMODE(os.fstat(f.fileno()).st_mode), 0o600) else: if os.path.exists(con_dir): self.assertEqual(os.listdir(con_dir), []) def assert_nm_udev(self, contents): rule_path = os.path.join(self.workdir.name, 'run/udev/rules.d/90-netplan.rules') if contents is None: self.assertFalse(os.path.exists(rule_path)) return with open(rule_path) as f: self.assertEqual(f.read(), contents) class TestConfigArgs(TestBase): '''Config file argument handling''' def test_no_files(self): subprocess.check_call([exe_generate, '--root-dir', self.workdir.name]) self.assertEqual(os.listdir(self.workdir.name), []) self.assert_nm_udev(None) def test_no_configs(self): self.generate('network:\n version: 2') # should not write any files self.assertEqual(os.listdir(self.workdir.name), ['etc']) self.assert_nm_udev(None) def test_empty_config(self): self.generate('') # should not write any files self.assertEqual(os.listdir(self.workdir.name), ['etc']) self.assert_nm_udev(None) def test_file_args(self): conf = os.path.join(self.workdir.name, 'config') with open(conf, 'w') as f: f.write('network: {}') # when specifying custom files, it should ignore the global config self.generate('''network: version: 2 ethernets: eth0: dhcp4: true''', extra_args=[conf]) self.assertEqual(set(os.listdir(self.workdir.name)), {'config', 'etc'}) def test_file_args_notfound(self): err = self.generate('''network: version: 2 ethernets: eth0: dhcp4: true''', expect_fail=True, extra_args=['/non/existing/config']) self.assertEqual(err, 'Cannot open /non/existing/config: No such file or directory\n') self.assertEqual(os.listdir(self.workdir.name), ['etc']) def test_help(self): conf = os.path.join(self.workdir.name, 'etc', 'netplan', 'a.yaml') os.makedirs(os.path.dirname(conf)) with open(conf, 'w') as f: f.write('''network: version: 2 ethernets: eth0: dhcp4: true''') p = subprocess.Popen([exe_generate, '--root-dir', self.workdir.name, '--help'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) (out, err) = p.communicate() self.assertEqual(err, '') self.assertEqual(p.returncode, 0) self.assertIn('Usage:', out) self.assertEqual(os.listdir(self.workdir.name), ['etc']) def test_unknown_cli_args(self): p = subprocess.Popen([exe_generate, '--foo'], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) (out, err) = p.communicate() self.assertIn('nknown option --foo', err) self.assertNotEqual(p.returncode, 0) def test_output_mkdir_error(self): conf = os.path.join(self.workdir.name, 'config') with open(conf, 'w') as f: f.write('''network: version: 2 ethernets: eth0: dhcp4: true''') err = self.generate('', extra_args=['--root-dir', '/proc/foo', conf], expect_fail=True) self.assertIn('cannot create directory /proc/foo/run/systemd/network', err) def test_systemd_generator(self): conf = os.path.join(self.confdir, 'a.yaml') os.makedirs(os.path.dirname(conf)) with open(conf, 'w') as f: f.write('''network: version: 2 ethernets: eth0: dhcp4: true''') outdir = os.path.join(self.workdir.name, 'out') os.mkdir(outdir) generator = os.path.join(self.workdir.name, 'systemd', 'system-generators', 'netplan') os.makedirs(os.path.dirname(generator)) os.symlink(exe_generate, generator) subprocess.check_call([generator, '--root-dir', self.workdir.name, outdir, outdir, outdir]) self.assertEqual(set(os.listdir(outdir)), {'netplan.stamp', 'multi-user.target.wants', 'network-online.target.wants'}) n = os.path.join(self.workdir.name, 'run', 'systemd', 'network', '10-netplan-eth0.network') self.assertTrue(os.path.exists(n)) os.unlink(n) # should auto-enable networkd and -wait-online self.assertTrue(os.path.islink(os.path.join( outdir, 'multi-user.target.wants', 'systemd-networkd.service'))) self.assertTrue(os.path.islink(os.path.join( outdir, 'network-online.target.wants', 'systemd-networkd-wait-online.service'))) # should be a no-op the second time while the stamp exists out = subprocess.check_output([generator, '--root-dir', self.workdir.name, outdir, outdir, outdir], stderr=subprocess.STDOUT) self.assertFalse(os.path.exists(n)) self.assertIn(b'netplan generate already ran', out) # after removing the stamp it generates again, and not trip over the # existing enablement symlink os.unlink(os.path.join(outdir, 'netplan.stamp')) subprocess.check_output([generator, '--root-dir', self.workdir.name, outdir, outdir, outdir]) self.assertTrue(os.path.exists(n)) def test_systemd_generator_noconf(self): outdir = os.path.join(self.workdir.name, 'out') os.mkdir(outdir) generator = os.path.join(self.workdir.name, 'systemd', 'system-generators', 'netplan') os.makedirs(os.path.dirname(generator)) os.symlink(exe_generate, generator) subprocess.check_call([generator, '--root-dir', self.workdir.name, outdir, outdir, outdir]) # no enablement symlink here self.assertEqual(os.listdir(outdir), ['netplan.stamp']) def test_systemd_generator_badcall(self): outdir = os.path.join(self.workdir.name, 'out') os.mkdir(outdir) generator = os.path.join(self.workdir.name, 'systemd', 'system-generators', 'netplan') os.makedirs(os.path.dirname(generator)) os.symlink(exe_generate, generator) try: subprocess.check_output([generator, '--root-dir', self.workdir.name], stderr=subprocess.STDOUT) self.fail("direct systemd generator call is expected to fail, but succeeded.") except subprocess.CalledProcessError as e: self.assertEqual(e.returncode, 1) self.assertIn(b'can not be called directly', e.output) class TestNetworkd(TestBase): '''networkd output''' def test_eth_optional(self): self.generate('''network: version: 2 ethernets: eth0: dhcp6: true optional: true''') self.assert_networkd({'eth0.network': '''[Match] Name=eth0 [Link] RequiredForOnline=no [Network] DHCP=ipv6 [DHCP] UseMTU=true RouteMetric=100 '''}) self.assert_networkd_udev(None) def test_eth_wol(self): self.generate('''network: version: 2 ethernets: eth0: wakeonlan: true dhcp4: n''') self.assert_networkd({'eth0.link': '[Match]\nOriginalName=eth0\n\n[Link]\nWakeOnLan=magic\n'}) self.assert_networkd_udev(None) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:eth0,''') self.assert_nm_udev(None) # should not allow NM to manage everything self.assertFalse(os.path.exists(self.nm_enable_all_conf)) def test_eth_mtu(self): self.generate('''network: version: 2 ethernets: eth1: mtu: 1280 dhcp4: n''') self.assert_networkd({'eth1.link': '[Match]\nOriginalName=eth1\n\n[Link]\nWakeOnLan=off\nMTUBytes=1280\n'}) self.assert_networkd_udev(None) def test_mtu_all(self): self.generate(textwrap.dedent(""" network: version: 2 ethernets: eth1: mtu: 1280 dhcp4: n bonds: bond0: interfaces: - eth1 mtu: 9000 vlans: bond0.108: link: bond0 id: 108""")) self.assert_networkd({ 'bond0.108.netdev': '[NetDev]\nName=bond0.108\nKind=vlan\n\n[VLAN]\nId=108\n', 'bond0.netdev': '[NetDev]\nName=bond0\nMTUBytes=9000\nKind=bond\n', 'bond0.network': '[Match]\nName=bond0\n\n[Network]\nVLAN=bond0.108\n', 'eth1.link': '[Match]\nOriginalName=eth1\n\n[Link]\nWakeOnLan=off\nMTUBytes=1280\n', 'eth1.network': '[Match]\nName=eth1\n\n[Network]\nBond=bond0\nLinkLocalAddressing=no\n' }) self.assert_networkd_udev(None) def test_eth_match_by_driver_rename(self): self.generate('''network: version: 2 ethernets: def1: match: driver: ixgbe set-name: lom1''') self.assert_networkd({'def1.link': '[Match]\nDriver=ixgbe\n\n[Link]\nName=lom1\nWakeOnLan=off\n'}) self.assert_networkd_udev({'def1.rules': (UDEV_NO_MAC_RULE % ('ixgbe', 'lom1'))}) # NM cannot match by driver, so blacklisting needs to happen via udev self.assert_nm(None, None) self.assert_nm_udev('ACTION=="add|change", SUBSYSTEM=="net", ENV{ID_NET_DRIVER}=="ixgbe", ENV{NM_UNMANAGED}="1"\n') def test_eth_match_by_mac_rename(self): self.generate('''network: version: 2 ethernets: def1: match: macaddress: 11:22:33:44:55:66 set-name: lom1''') self.assert_networkd({'def1.link': '[Match]\nMACAddress=11:22:33:44:55:66\n\n[Link]\nName=lom1\nWakeOnLan=off\n'}) self.assert_networkd_udev({'def1.rules': (UDEV_MAC_RULE % ('?*', '11:22:33:44:55:66', 'lom1'))}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=mac:11:22:33:44:55:66,''') self.assert_nm_udev(None) def test_eth_implicit_name_match_dhcp4(self): self.generate('''network: version: 2 ethernets: engreen: dhcp4: y''') self.assert_networkd({'engreen.network': ND_DHCP4 % 'engreen'}) self.assert_networkd_udev(None) def test_eth_match_dhcp4(self): self.generate('''network: version: 2 ethernets: def1: match: driver: ixgbe dhcp4: true''') self.assert_networkd({'def1.network': '''[Match] Driver=ixgbe [Network] DHCP=ipv4 [DHCP] UseMTU=true RouteMetric=100 '''}) self.assert_networkd_udev(None) self.assert_nm_udev('ACTION=="add|change", SUBSYSTEM=="net", ENV{ID_NET_DRIVER}=="ixgbe", ENV{NM_UNMANAGED}="1"\n') def test_eth_match_name(self): self.generate('''network: version: 2 ethernets: def1: match: name: green dhcp4: true''') self.assert_networkd({'def1.network': ND_DHCP4 % 'green'}) self.assert_networkd_udev(None) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:green,''') self.assert_nm_udev(None) def test_eth_set_mac(self): self.generate('''network: version: 2 ethernets: def1: match: name: green macaddress: 00:01:02:03:04:05 dhcp4: true''') self.assert_networkd({'def1.network': ND_DHCP4 % 'green', 'def1.link': '[Match]\nOriginalName=green\n\n[Link]\nWakeOnLan=off\nMACAddress=00:01:02:03:04:05\n' }) self.assert_networkd_udev(None) def test_eth_match_name_rename(self): self.generate('''network: version: 2 ethernets: def1: match: name: green set-name: blue dhcp4: true''') # the .network needs to match on the renamed name self.assert_networkd({'def1.link': '[Match]\nOriginalName=green\n\n[Link]\nName=blue\nWakeOnLan=off\n', 'def1.network': ND_DHCP4 % 'blue'}) # The udev rules engine does support renaming by name self.assert_networkd_udev(None) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:blue,''') def test_eth_match_all_names(self): self.generate('''network: version: 2 ethernets: def1: match: {name: "*"} dhcp4: true''') self.assert_networkd({'def1.network': ND_DHCP4 % '*'}) self.assert_networkd_udev(None) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:*,''') self.assert_nm_udev(None) def test_eth_match_all(self): self.generate('''network: version: 2 ethernets: def1: match: {} dhcp4: true''') self.assert_networkd({'def1.network': '[Match]\n\n[Network]\nDHCP=ipv4\n\n' '[DHCP]\nUseMTU=true\nRouteMetric=100\n'}) self.assert_networkd_udev(None) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=type:ethernet,''') self.assert_nm_udev(None) def test_match_multiple(self): self.generate('''network: version: 2 ethernets: def1: match: name: en1s* macaddress: 00:11:22:33:44:55 dhcp4: on''') self.assert_networkd({'def1.network': '''[Match] MACAddress=00:11:22:33:44:55 Name=en1s* [Network] DHCP=ipv4 [DHCP] UseMTU=true RouteMetric=100 '''}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=mac:00:11:22:33:44:55,''') def test_eth_global_renderer(self): self.generate('''network: version: 2 renderer: networkd ethernets: eth0: dhcp4: true''') self.assert_networkd({'eth0.network': ND_DHCP4 % 'eth0'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:eth0,''') self.assert_nm_udev(None) # should not allow NM to manage everything self.assertFalse(os.path.exists(self.nm_enable_all_conf)) def test_eth_type_renderer(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: renderer: networkd eth0: dhcp4: true''') self.assert_networkd({'eth0.network': ND_DHCP4 % 'eth0'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:eth0,''') # should allow NM to manage everything else self.assertTrue(os.path.exists(self.nm_enable_all_conf)) self.assert_nm_udev(None) def test_bridge_set_mac(self): self.generate('''network: version: 2 bridges: br0: macaddress: 00:01:02:03:04:05 dhcp4: true''') self.assert_networkd({'br0.network': ND_DHCP4 % 'br0', 'br0.netdev': '[NetDev]\nName=br0\nMACAddress=00:01:02:03:04:05\nKind=bridge\n'}) def test_eth_def_renderer(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: renderer: NetworkManager eth0: renderer: networkd dhcp4: true''') self.assert_networkd({'eth0.network': ND_DHCP4 % 'eth0'}) self.assert_networkd_udev(None) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:eth0,''') self.assert_nm_udev(None) def test_eth_dhcp6(self): self.generate('''network: version: 2 ethernets: eth0: {dhcp6: true}''') self.assert_networkd({'eth0.network': ND_DHCP6 % 'eth0'}) def test_eth_dhcp6_no_accept_ra(self): self.generate('''network: version: 2 ethernets: eth0: dhcp6: true accept-ra: n''') self.assert_networkd({'eth0.network': '''[Match] Name=eth0 [Network] DHCP=ipv6 IPv6AcceptRA=no [DHCP] UseMTU=true RouteMetric=100 '''}) def test_bridge_dhcp6_no_accept_ra(self): self.generate('''network: version: 2 ethernets: engreen: dhcp4: no dhcp6: no accept-ra: no bridges: br0: interfaces: [engreen] dhcp6: true accept-ra: no''') self.assert_networkd({'br0.network': '''[Match] Name=br0 [Network] DHCP=ipv6 IPv6AcceptRA=no [DHCP] UseMTU=true RouteMetric=100 ''', 'br0.netdev': '''[NetDev] Name=br0 Kind=bridge ''', 'engreen.network': '''[Match] Name=engreen [Network] IPv6AcceptRA=no Bridge=br0 LinkLocalAddressing=no '''}) def test_bond_dhcp6_no_accept_ra(self): self.generate('''network: version: 2 ethernets: engreen: dhcp6: no accept-ra: no bonds: bond0: interfaces: [engreen] dhcp6: true accept-ra: yes''') self.assert_networkd({'bond0.network': '''[Match] Name=bond0 [Network] DHCP=ipv6 IPv6AcceptRA=yes [DHCP] UseMTU=true RouteMetric=100 ''', 'bond0.netdev': '''[NetDev] Name=bond0 Kind=bond ''', 'engreen.network': '''[Match] Name=engreen [Network] IPv6AcceptRA=no Bond=bond0 LinkLocalAddressing=no '''}) def test_eth_dhcp6_accept_ra(self): self.generate('''network: version: 2 ethernets: eth0: dhcp6: true accept-ra: yes''') self.assert_networkd({'eth0.network': '''[Match] Name=eth0 [Network] DHCP=ipv6 IPv6AcceptRA=yes [DHCP] UseMTU=true RouteMetric=100 '''}) def test_eth_dhcp6_accept_ra_unset(self): self.generate('''network: version: 2 ethernets: eth0: dhcp6: true''') self.assert_networkd({'eth0.network': '''[Match] Name=eth0 [Network] DHCP=ipv6 [DHCP] UseMTU=true RouteMetric=100 '''}) def test_eth_dhcp4_and_6(self): self.generate('''network: version: 2 ethernets: eth0: {dhcp4: true, dhcp6: true}''') self.assert_networkd({'eth0.network': ND_DHCPYES % 'eth0'}) def test_eth_manual_addresses(self): self.generate('''network: version: 2 ethernets: engreen: addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''') self.assert_networkd({'engreen.network': '''[Match] Name=engreen [Network] Address=192.168.14.2/24 Address=2001:FFfe::1/64 '''}) def test_eth_manual_addresses_dhcp(self): self.generate('''network: version: 2 ethernets: engreen: dhcp4: yes addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''') self.assert_networkd({'engreen.network': '''[Match] Name=engreen [Network] DHCP=ipv4 Address=192.168.14.2/24 Address=2001:FFfe::1/64 [DHCP] UseMTU=true RouteMetric=100 '''}) def test_dhcp_critical_true(self): self.generate('''network: version: 2 ethernets: engreen: dhcp4: yes critical: yes ''') self.assert_networkd({'engreen.network': '''[Match] Name=engreen [Network] DHCP=ipv4 [DHCP] UseMTU=true RouteMetric=100 CriticalConnection=true '''}) def test_dhcp_identifier_mac(self): self.generate('''network: version: 2 ethernets: engreen: dhcp4: yes dhcp-identifier: mac ''') self.assert_networkd({'engreen.network': '''[Match] Name=engreen [Network] DHCP=ipv4 [DHCP] UseMTU=true RouteMetric=100 ClientIdentifier=mac '''}) def test_dhcp_identifier_duid(self): # This option should be silently ignored, since it's the default self.generate('''network: version: 2 ethernets: engreen: dhcp4: yes dhcp-identifier: duid ''') self.assert_networkd({'engreen.network': '''[Match] Name=engreen [Network] DHCP=ipv4 [DHCP] UseMTU=true RouteMetric=100 '''}) def test_route_v4_single(self): self.generate('''network: version: 2 ethernets: engreen: addresses: ["192.168.14.2/24"] routes: - to: 10.10.10.0/24 via: 192.168.14.20 metric: 100 ''') self.assert_networkd({'engreen.network': '''[Match] Name=engreen [Network] Address=192.168.14.2/24 [Route] Destination=10.10.10.0/24 Gateway=192.168.14.20 Metric=100 '''}) def test_route_v4_multiple(self): self.generate('''network: version: 2 ethernets: engreen: addresses: ["192.168.14.2/24"] routes: - to: 8.8.0.0/16 via: 192.168.1.1 - to: 10.10.10.8 via: 192.168.1.2 metric: 5000 - to: 11.11.11.0/24 via: 192.168.1.3 metric: 9999 ''') self.assert_networkd({'engreen.network': '''[Match] Name=engreen [Network] Address=192.168.14.2/24 [Route] Destination=8.8.0.0/16 Gateway=192.168.1.1 [Route] Destination=10.10.10.8 Gateway=192.168.1.2 Metric=5000 [Route] Destination=11.11.11.0/24 Gateway=192.168.1.3 Metric=9999 '''}) def test_route_v6_single(self): self.generate('''network: version: 2 ethernets: enblue: addresses: ["192.168.1.3/24"] routes: - to: 2001:dead:beef::2/64 via: 2001:beef:beef::1''') self.assert_networkd({'enblue.network': '''[Match] Name=enblue [Network] Address=192.168.1.3/24 [Route] Destination=2001:dead:beef::2/64 Gateway=2001:beef:beef::1 '''}) def test_route_v6_multiple(self): self.generate('''network: version: 2 ethernets: enblue: addresses: ["192.168.1.3/24"] routes: - to: 2001:dead:beef::2/64 via: 2001:beef:beef::1 - to: 2001:f00f:f00f::fe/64 via: 2001:beef:feed::1 metric: 1024''') self.assert_networkd({'enblue.network': '''[Match] Name=enblue [Network] Address=192.168.1.3/24 [Route] Destination=2001:dead:beef::2/64 Gateway=2001:beef:beef::1 [Route] Destination=2001:f00f:f00f::fe/64 Gateway=2001:beef:feed::1 Metric=1024 '''}) def test_wifi(self): self.generate('''network: version: 2 wifis: wl0: access-points: "Joe's Home": password: "s3kr1t" workplace: password: "c0mpany" peer2peer: mode: adhoc dhcp4: yes''') self.assert_networkd({'wl0.network': ND_WIFI_DHCP4 % 'wl0'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:wl0,''') self.assert_nm_udev(None) # generates wpa config and enables wpasupplicant unit with open(os.path.join(self.workdir.name, 'run/netplan/wpa-wl0.conf')) as f: self.assertEqual(f.read(), '''ctrl_interface=/run/wpa_supplicant network={ ssid="Joe's Home" psk="s3kr1t" } network={ ssid="workplace" psk="c0mpany" } network={ ssid="peer2peer" key_mgmt=NONE mode=1 } ''') self.assertEqual(stat.S_IMODE(os.fstat(f.fileno()).st_mode), 0o600) self.assertTrue(os.path.islink(os.path.join( self.workdir.name, 'run/systemd/system/multi-user.target.wants/netplan-wpa@wl0.service'))) def test_wifi_route(self): self.generate('''network: version: 2 wifis: wl0: access-points: workplace: password: "c0mpany" dhcp4: yes routes: - to: 10.10.10.0/24 via: 8.8.8.8''') self.assert_networkd({'wl0.network': '''[Match] Name=wl0 [Network] DHCP=ipv4 [Route] Destination=10.10.10.0/24 Gateway=8.8.8.8 [DHCP] UseMTU=true RouteMetric=600 '''}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:wl0,''') self.assert_nm_udev(None) def test_wifi_match(self): err = self.generate('''network: version: 2 wifis: somewifi: match: driver: foo access-points: workplace: password: "c0mpany" dhcp4: yes''', expect_fail=True) self.assertIn('networkd backend does not support wifi with match:', err) def test_wifi_ap(self): err = self.generate('''network: version: 2 wifis: wl0: access-points: workplace: password: "c0mpany" mode: ap dhcp4: yes''', expect_fail=True) self.assertIn('networkd does not support wifi in access point mode', err) def test_bridge_empty(self): self.generate('''network: version: 2 bridges: br0: dhcp4: true''') self.assert_networkd({'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n', 'br0.network': ND_DHCP4 % 'br0'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:br0,''') self.assert_nm_udev(None) def test_bridge_type_renderer(self): self.generate('''network: version: 2 renderer: NetworkManager bridges: renderer: networkd br0: dhcp4: true''') self.assert_networkd({'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n', 'br0.network': ND_DHCP4 % 'br0'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:br0,''') self.assert_nm_udev(None) def test_bridge_def_renderer(self): self.generate('''network: version: 2 renderer: NetworkManager bridges: renderer: NetworkManager br0: renderer: networkd addresses: [1.2.3.4/12] dhcp4: true''') self.assert_networkd({'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n', 'br0.network': '''[Match] Name=br0 [Network] DHCP=ipv4 Address=1.2.3.4/12 [DHCP] UseMTU=true RouteMetric=100 '''}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:br0,''') self.assert_nm_udev(None) def test_bridge_forward_declaration(self): self.generate('''network: version: 2 bridges: br0: interfaces: [eno1, switchports] dhcp4: true ethernets: eno1: {} switchports: match: driver: yayroute ''') self.assert_networkd({'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n', 'br0.network': ND_DHCP4 % 'br0', 'eno1.network': '[Match]\nName=eno1\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n', 'switchports.network': '[Match]\nDriver=yayroute\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n'}) def test_eth_bridge_nm_blacklist(self): self.generate('''network: renderer: networkd ethernets: eth42: dhcp4: yes ethbr: match: {name: eth43} bridges: mybr: interfaces: [ethbr] dhcp4: yes''') self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:eth42,interface-name:eth43,interface-name:mybr,''') def test_bridge_components(self): self.generate('''network: version: 2 ethernets: eno1: {} switchports: match: driver: yayroute bridges: br0: interfaces: [eno1, switchports] dhcp4: true''') self.assert_networkd({'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n', 'br0.network': ND_DHCP4 % 'br0', 'eno1.network': '[Match]\nName=eno1\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n', 'switchports.network': '[Match]\nDriver=yayroute\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n'}) def test_bridge_params(self): self.generate('''network: version: 2 ethernets: eno1: {} switchports: match: driver: yayroute bridges: br0: interfaces: [eno1, switchports] parameters: ageing-time: 50 forward-delay: 12 hello-time: 6 max-age: 24 stp: true path-cost: eno1: 70 port-priority: eno1: 14 dhcp4: true''') self.assert_networkd({'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n\n' '[Bridge]\nAgeingTimeSec=50\n' 'ForwardDelaySec=12\n' 'HelloTimeSec=6\n' 'MaxAgeSec=24\n' 'STP=true\n', 'br0.network': ND_DHCP4 % 'br0', 'eno1.network': '[Match]\nName=eno1\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n\n' '[Bridge]\nCost=70\nPriority=14\n', 'switchports.network': '[Match]\nDriver=yayroute\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n'}) def test_bond_empty(self): self.generate('''network: version: 2 bonds: bn0: dhcp4: true''') self.assert_networkd({'bn0.netdev': '[NetDev]\nName=bn0\nKind=bond\n', 'bn0.network': ND_DHCP4 % 'bn0'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:bn0,''') self.assert_nm_udev(None) def test_bond_components(self): self.generate('''network: version: 2 ethernets: eno1: {} switchports: match: driver: yayroute bonds: bn0: interfaces: [eno1, switchports] dhcp4: true''') self.assert_networkd({'bn0.netdev': '[NetDev]\nName=bn0\nKind=bond\n', 'bn0.network': ND_DHCP4 % 'bn0', 'eno1.network': '[Match]\nName=eno1\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\n', 'switchports.network': '[Match]\nDriver=yayroute\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\n'}) def test_bond_empty_parameters(self): self.generate('''network: version: 2 ethernets: eno1: {} switchports: match: driver: yayroute bonds: bn0: parameters: {} interfaces: [eno1, switchports] dhcp4: true''') self.assert_networkd({'bn0.netdev': '[NetDev]\nName=bn0\nKind=bond\n', 'bn0.network': ND_DHCP4 % 'bn0', 'eno1.network': '[Match]\nName=eno1\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\n', 'switchports.network': '[Match]\nDriver=yayroute\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\n'}) def test_bond_with_parameters(self): self.generate('''network: version: 2 ethernets: eno1: {} switchports: match: driver: yayroute bonds: bn0: parameters: mode: 802.1ad lacp-rate: 10 mii-monitor-interval: 10 min-links: 10 up-delay: 20 down-delay: 30 all-slaves-active: true transmit-hash-policy: none ad-select: none arp-interval: 15 arp-validate: all arp-all-targets: all fail-over-mac-policy: none gratuitious-arp: 10 packets-per-slave: 10 primary-reselect-policy: none resend-igmp: 10 learn-packet-interval: 10 arp-ip-targets: - 10.10.10.10 - 20.20.20.20 interfaces: [eno1, switchports] dhcp4: true''') self.assert_networkd({'bn0.netdev': '[NetDev]\nName=bn0\nKind=bond\n\n' '[Bond]\n' 'Mode=802.1ad\n' 'LACPTransmitRate=10\n' 'MIIMonitorSec=10ms\n' 'MinLinks=10\n' 'TransmitHashPolicy=none\n' 'AdSelect=none\n' 'AllSlavesActive=1\n' 'ARPIntervalSec=15ms\n' 'ARPIPTargets=10.10.10.10,20.20.20.20\n' 'ARPValidate=all\n' 'ARPAllTargets=all\n' 'UpDelaySec=20ms\n' 'DownDelaySec=30ms\n' 'FailOverMACPolicy=none\n' 'GratuitiousARP=10\n' 'PacketsPerSlave=10\n' 'PrimaryReselectPolicy=none\n' 'ResendIGMP=10\n' 'LearnPacketIntervalSec=10\n', 'bn0.network': ND_DHCP4 % 'bn0', 'eno1.network': '[Match]\nName=eno1\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\n', 'switchports.network': '[Match]\nDriver=yayroute\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\n'}) def test_bond_with_parameters_all_suffix(self): self.generate('''network: version: 2 ethernets: eno1: {} switchports: match: driver: yayroute bonds: bn0: parameters: mode: 802.1ad mii-monitor-interval: 10ms up-delay: 20ms down-delay: 30s arp-interval: 15m interfaces: [eno1, switchports] dhcp4: true''') self.assert_networkd({'bn0.netdev': '[NetDev]\nName=bn0\nKind=bond\n\n' '[Bond]\n' 'Mode=802.1ad\n' 'MIIMonitorSec=10ms\n' 'ARPIntervalSec=15m\n' 'UpDelaySec=20ms\n' 'DownDelaySec=30s\n', 'bn0.network': ND_DHCP4 % 'bn0', 'eno1.network': '[Match]\nName=eno1\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\n', 'switchports.network': '[Match]\nDriver=yayroute\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\n'}) def test_bond_primary_slave(self): self.generate('''network: version: 2 ethernets: eno1: {} switchports: match: driver: yayroute bonds: bn0: parameters: mode: active-backup primary: eno1 interfaces: [eno1, switchports] dhcp4: true''') self.assert_networkd({'bn0.netdev': '[NetDev]\nName=bn0\nKind=bond\n\n' '[Bond]\n' 'Mode=active-backup\n', 'bn0.network': ND_DHCP4 % 'bn0', 'eno1.network': '[Match]\nName=eno1\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\nPrimarySlave=true\n', 'switchports.network': '[Match]\nDriver=yayroute\n\n' '[Network]\nBond=bn0\nLinkLocalAddressing=no\n'}) def test_gateway(self): self.generate('''network: version: 2 ethernets: engreen: addresses: ["192.168.14.2/24", "2001:FFfe::1/64"] gateway4: 192.168.14.1 gateway6: 2001:FFfe::2''') self.assert_networkd({'engreen.network': '''[Match] Name=engreen [Network] Address=192.168.14.2/24 Address=2001:FFfe::1/64 Gateway=192.168.14.1 Gateway=2001:FFfe::2 '''}) def test_nameserver(self): self.generate('''network: version: 2 ethernets: engreen: addresses: ["192.168.14.2/24"] nameservers: addresses: [1.2.3.4, "1234::FFFF"] enblue: addresses: ["192.168.1.3/24"] nameservers: search: [lab, kitchen] addresses: [8.8.8.8]''') self.assert_networkd({'engreen.network': '''[Match] Name=engreen [Network] Address=192.168.14.2/24 DNS=1.2.3.4 DNS=1234::FFFF ''', 'enblue.network': '''[Match] Name=enblue [Network] Address=192.168.1.3/24 DNS=8.8.8.8 Domains=lab kitchen '''}) def test_vlan(self): self.generate('''network: version: 2 ethernets: en1: {} vlans: enblue: id: 1 link: en1 addresses: [1.2.3.4/24] enred: id: 3 link: en1 macaddress: aa:bb:cc:dd:ee:11 engreen: {id: 2, link: en1, dhcp6: true}''') self.assert_networkd({'en1.network': '[Match]\nName=en1\n\n[Network]\nVLAN=engreen\nVLAN=enblue\nVLAN=enred\n', 'enblue.netdev': '[NetDev]\nName=enblue\nKind=vlan\n\n[VLAN]\nId=1\n', 'engreen.netdev': '[NetDev]\nName=engreen\nKind=vlan\n\n[VLAN]\nId=2\n', 'enred.netdev': '[NetDev]\nName=enred\nMACAddress=aa:bb:cc:dd:ee:11\nKind=vlan\n\n[VLAN]\nId=3\n', 'enblue.network': '[Match]\nName=enblue\n\n[Network]\nAddress=1.2.3.4/24\n', 'engreen.network': ND_DHCP6 % 'engreen'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:engreen,interface-name:en1,interface-name:enblue,interface-name:enred,''') self.assert_nm_udev(None) class TestNetworkManager(TestBase): def test_eth_wol(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eth0: wakeonlan: true''') self.assert_nm({'eth0': '''[connection] id=netplan-eth0 type=ethernet interface-name=eth0 [ethernet] wake-on-lan=1 [ipv4] method=link-local [ipv6] method=ignore '''}) # should allow NM to manage everything else self.assertTrue(os.path.exists(self.nm_enable_all_conf)) self.assert_networkd({'eth0.link': '[Match]\nOriginalName=eth0\n\n[Link]\nWakeOnLan=magic\n'}) self.assert_nm_udev(None) def test_eth_mtu(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eth1: mtu: 1280 dhcp4: n''') self.assert_networkd({'eth1.link': '[Match]\nOriginalName=eth1\n\n[Link]\nWakeOnLan=off\nMTUBytes=1280\n'}) self.assert_nm({'eth1': '''[connection] id=netplan-eth1 type=ethernet interface-name=eth1 [ethernet] wake-on-lan=0 [802-3-ethernet] mtu=1280 [ipv4] method=link-local [ipv6] method=ignore '''}) def test_mtu_all(self): self.generate(textwrap.dedent(""" network: version: 2 renderer: NetworkManager ethernets: eth1: mtu: 1280 dhcp4: n bonds: bond0: interfaces: - eth1 mtu: 9000 vlans: bond0.108: link: bond0 id: 108""")) self.assert_nm({ 'bond0.108': '''[connection] id=netplan-bond0.108 type=vlan interface-name=bond0.108 [vlan] id=108 parent=bond0 [ipv4] method=link-local [ipv6] method=ignore ''', 'bond0': '''[connection] id=netplan-bond0 type=bond interface-name=bond0 [802-3-ethernet] mtu=9000 [ipv4] method=link-local [ipv6] method=ignore ''', 'eth1': '''[connection] id=netplan-eth1 type=ethernet interface-name=eth1 slave-type=bond master=bond0 [ethernet] wake-on-lan=0 [802-3-ethernet] mtu=1280 [ipv4] method=link-local [ipv6] method=ignore ''', }) def test_eth_set_mac(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eth0: macaddress: 00:01:02:03:04:05 dhcp4: true''') self.assert_networkd({'eth0.link': '''[Match] OriginalName=eth0 [Link] WakeOnLan=off MACAddress=00:01:02:03:04:05 '''}) self.assert_nm({'eth0': '''[connection] id=netplan-eth0 type=ethernet interface-name=eth0 [ethernet] wake-on-lan=0 [802-3-ethernet] cloned-mac-address=00:01:02:03:04:05 [ipv4] method=auto [ipv6] method=ignore '''}) def test_eth_match_by_driver(self): err = self.generate('''network: version: 2 renderer: NetworkManager ethernets: def1: match: driver: ixgbe''', expect_fail=True) self.assertIn('NetworkManager definitions do not support matching by driver', err) def test_eth_match_by_driver_rename(self): # in this case udev will rename the device so that NM can use the name self.generate('''network: version: 2 renderer: NetworkManager ethernets: def1: match: driver: ixgbe set-name: lom1''') self.assert_networkd({'def1.link': '[Match]\nDriver=ixgbe\n\n[Link]\nName=lom1\nWakeOnLan=off\n'}) self.assert_networkd_udev({'def1.rules': (UDEV_NO_MAC_RULE % ('ixgbe', 'lom1'))}) self.assert_nm({'def1': '''[connection] id=netplan-def1 type=ethernet interface-name=lom1 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore '''}) self.assert_nm_udev(None) def test_eth_match_by_mac_rename(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: def1: match: macaddress: 11:22:33:44:55:66 set-name: lom1''') self.assert_networkd({'def1.link': '[Match]\nMACAddress=11:22:33:44:55:66\n\n[Link]\nName=lom1\nWakeOnLan=off\n'}) self.assert_networkd_udev({'def1.rules': (UDEV_MAC_RULE % ('?*', '11:22:33:44:55:66', 'lom1'))}) self.assert_nm({'def1': '''[connection] id=netplan-def1 type=ethernet interface-name=lom1 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore '''}) self.assert_nm_udev(None) def test_eth_implicit_name_match_dhcp4(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: engreen: dhcp4: true''') self.assert_nm({'engreen': '''[connection] id=netplan-engreen type=ethernet interface-name=engreen [ethernet] wake-on-lan=0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) def test_eth_match_mac_dhcp4(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: def1: match: macaddress: 11:22:33:44:55:66 dhcp4: true''') self.assert_nm({'def1': '''[connection] id=netplan-def1 type=ethernet [ethernet] wake-on-lan=0 [802-3-ethernet] mac-address=11:22:33:44:55:66 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) def test_eth_match_name(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: def1: match: name: green dhcp4: true''') self.assert_nm({'def1': '''[connection] id=netplan-def1 type=ethernet interface-name=green [ethernet] wake-on-lan=0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_eth_match_name_rename(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: def1: match: name: green set-name: blue dhcp4: true''') # The udev rules engine does support renaming by name self.assert_networkd_udev(None) # NM needs to match on the renamed name self.assert_nm({'def1': '''[connection] id=netplan-def1 type=ethernet interface-name=blue [ethernet] wake-on-lan=0 [ipv4] method=auto [ipv6] method=ignore '''}) # ... while udev renames it self.assert_networkd({'def1.link': '[Match]\nOriginalName=green\n\n[Link]\nName=blue\nWakeOnLan=off\n'}) self.assert_nm_udev(None) def test_eth_match_name_glob(self): err = self.generate('''network: version: 2 renderer: NetworkManager ethernets: def1: match: {name: "en*"} dhcp4: true''', expect_fail=True) self.assertIn('def1: NetworkManager definitions do not support name globbing', err) self.assert_nm({}) self.assert_networkd({}) def test_eth_match_all(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: def1: match: {} dhcp4: true''') self.assert_nm({'def1': '''[connection] id=netplan-def1 type=ethernet [ethernet] wake-on-lan=0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) def test_match_multiple(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: def1: match: name: engreen macaddress: 00:11:22:33:44:55 dhcp4: yes''') self.assert_nm({'def1': '''[connection] id=netplan-def1 type=ethernet interface-name=engreen [ethernet] wake-on-lan=0 [802-3-ethernet] mac-address=00:11:22:33:44:55 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_eth_global_renderer(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eth0: dhcp4: true''') self.assert_nm({'eth0': '''[connection] id=netplan-eth0 type=ethernet interface-name=eth0 [ethernet] wake-on-lan=0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_eth_type_renderer(self): self.generate('''network: version: 2 renderer: networkd ethernets: renderer: NetworkManager eth0: dhcp4: true''') self.assert_nm({'eth0': '''[connection] id=netplan-eth0 type=ethernet interface-name=eth0 [ethernet] wake-on-lan=0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_eth_def_renderer(self): self.generate('''network: version: 2 renderer: networkd ethernets: renderer: networkd eth0: renderer: NetworkManager''') self.assert_nm({'eth0': '''[connection] id=netplan-eth0 type=ethernet interface-name=eth0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_global_renderer_only(self): self.generate(None, confs={'01-default-nm.yaml': 'network: {version: 2, renderer: NetworkManager}'}) # should allow NM to manage everything else self.assertTrue(os.path.exists(self.nm_enable_all_conf)) # but not configure anything else self.assert_nm(None, None) self.assert_networkd({}) self.assert_nm_udev(None) def test_eth_dhcp6(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eth0: {dhcp6: true}''') self.assert_nm({'eth0': '''[connection] id=netplan-eth0 type=ethernet interface-name=eth0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=auto '''}) def test_eth_dhcp4_and_6(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eth0: {dhcp4: true, dhcp6: true}''') self.assert_nm({'eth0': '''[connection] id=netplan-eth0 type=ethernet interface-name=eth0 [ethernet] wake-on-lan=0 [ipv4] method=auto [ipv6] method=auto '''}) def test_eth_manual_addresses(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: engreen: addresses: - 192.168.14.2/24 - 172.16.0.4/16 - 2001:FFfe::1/64''') self.assert_nm({'engreen': '''[connection] id=netplan-engreen type=ethernet interface-name=engreen [ethernet] wake-on-lan=0 [ipv4] method=manual address1=192.168.14.2/24 address2=172.16.0.4/16 [ipv6] method=manual address1=2001:FFfe::1/64 '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_eth_manual_addresses_dhcp(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: engreen: dhcp4: yes addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''') self.assert_nm({'engreen': '''[connection] id=netplan-engreen type=ethernet interface-name=engreen [ethernet] wake-on-lan=0 [ipv4] method=auto address1=192.168.14.2/24 [ipv6] method=manual address1=2001:FFfe::1/64 '''}) def test_route_v4_single(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: engreen: addresses: ["192.168.14.2/24"] routes: - to: 10.10.10.0/24 via: 192.168.14.20 metric: 100 ''') self.assert_nm({'engreen': '''[connection] id=netplan-engreen type=ethernet interface-name=engreen [ethernet] wake-on-lan=0 [ipv4] method=manual address1=192.168.14.2/24 route1=10.10.10.0/24,192.168.14.20,100 [ipv6] method=ignore '''}) def test_route_v4_multiple(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: engreen: addresses: ["192.168.14.2/24"] routes: - to: 8.8.0.0/16 via: 192.168.1.1 metric: 5000 - to: 10.10.10.8 via: 192.168.1.2 - to: 11.11.11.0/24 via: 192.168.1.3 metric: 9999 ''') self.assert_nm({'engreen': '''[connection] id=netplan-engreen type=ethernet interface-name=engreen [ethernet] wake-on-lan=0 [ipv4] method=manual address1=192.168.14.2/24 route1=8.8.0.0/16,192.168.1.1,5000 route2=10.10.10.8,192.168.1.2 route3=11.11.11.0/24,192.168.1.3,9999 [ipv6] method=ignore '''}) def test_route_v6_single(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: enblue: addresses: ["2001:f00f:f00f::2/64"] routes: - to: 2001:dead:beef::2/64 via: 2001:beef:beef::1''') self.assert_nm({'enblue': '''[connection] id=netplan-enblue type=ethernet interface-name=enblue [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=manual address1=2001:f00f:f00f::2/64 route1=2001:dead:beef::2/64,2001:beef:beef::1 '''}) def test_route_v6_multiple(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: enblue: addresses: ["2001:f00f:f00f::2/64"] routes: - to: 2001:dead:beef::2/64 via: 2001:beef:beef::1 - to: 2001:dead:feed::2/64 via: 2001:beef:beef::2 metric: 1000''') self.assert_nm({'enblue': '''[connection] id=netplan-enblue type=ethernet interface-name=enblue [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=manual address1=2001:f00f:f00f::2/64 route1=2001:dead:beef::2/64,2001:beef:beef::1 route2=2001:dead:feed::2/64,2001:beef:beef::2,1000 '''}) def test_routes_mixed(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: engreen: addresses: ["192.168.14.2/24", "2001:f00f::2/128"] routes: - to: 2001:dead:beef::2/64 via: 2001:beef:beef::1 metric: 997 - to: 8.8.0.0/16 via: 192.168.1.1 metric: 5000 - to: 10.10.10.8 via: 192.168.1.2 - to: 11.11.11.0/24 via: 192.168.1.3 metric: 9999 - to: 2001:f00f:f00f::fe/64 via: 2001:beef:feed::1 ''') self.assert_nm({'engreen': '''[connection] id=netplan-engreen type=ethernet interface-name=engreen [ethernet] wake-on-lan=0 [ipv4] method=manual address1=192.168.14.2/24 route1=8.8.0.0/16,192.168.1.1,5000 route2=10.10.10.8,192.168.1.2 route3=11.11.11.0/24,192.168.1.3,9999 [ipv6] method=manual address1=2001:f00f::2/128 route1=2001:dead:beef::2/64,2001:beef:beef::1,997 route2=2001:f00f:f00f::fe/64,2001:beef:feed::1 '''}) def test_wifi_default(self): self.generate('''network: version: 2 renderer: NetworkManager wifis: wl0: access-points: "Joe's Home": password: "s3kr1t" workplace: password: "c0mpany" dhcp4: yes''') self.assert_nm({'wl0-Joe%27s%20Home': '''[connection] id=netplan-wl0-Joe's Home type=wifi interface-name=wl0 [ethernet] wake-on-lan=0 [ipv4] method=auto [ipv6] method=ignore [wifi] ssid=Joe's Home mode=infrastructure [wifi-security] key-mgmt=wpa-psk psk=s3kr1t ''', 'wl0-workplace': '''[connection] id=netplan-wl0-workplace type=wifi interface-name=wl0 [ethernet] wake-on-lan=0 [ipv4] method=auto [ipv6] method=ignore [wifi] ssid=workplace mode=infrastructure [wifi-security] key-mgmt=wpa-psk psk=c0mpany '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_wifi_match_mac(self): self.generate('''network: version: 2 renderer: NetworkManager wifis: all: match: macaddress: 11:22:33:44:55:66 access-points: workplace: {}''') self.assert_nm({'all-workplace': '''[connection] id=netplan-all-workplace type=wifi [ethernet] wake-on-lan=0 [802-11-wireless] mac-address=11:22:33:44:55:66 [ipv4] method=link-local [ipv6] method=ignore [wifi] ssid=workplace mode=infrastructure '''}) def test_wifi_match_all(self): self.generate('''network: version: 2 renderer: NetworkManager wifis: all: match: {} access-points: workplace: {mode: infrastructure}''') self.assert_nm({'all-workplace': '''[connection] id=netplan-all-workplace type=wifi [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore [wifi] ssid=workplace mode=infrastructure '''}) def test_wifi_ap(self): self.generate('''network: version: 2 renderer: NetworkManager wifis: wl0: access-points: homenet: mode: ap password: s3cret''') self.assert_nm({'wl0-homenet': '''[connection] id=netplan-wl0-homenet type=wifi interface-name=wl0 [ethernet] wake-on-lan=0 [ipv4] method=shared [ipv6] method=ignore [wifi] ssid=homenet mode=ap [wifi-security] key-mgmt=wpa-psk psk=s3cret '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_wifi_adhoc(self): self.generate('''network: version: 2 renderer: NetworkManager wifis: wl0: access-points: homenet: mode: adhoc''') self.assert_nm({'wl0-homenet': '''[connection] id=netplan-wl0-homenet type=wifi interface-name=wl0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore [wifi] ssid=homenet mode=adhoc '''}) def test_bridge_empty(self): self.generate('''network: version: 2 renderer: NetworkManager bridges: br0: dhcp4: true''') self.assert_nm({'br0': '''[connection] id=netplan-br0 type=bridge interface-name=br0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_bridge_type_renderer(self): self.generate('''network: version: 2 renderer: networkd bridges: renderer: NetworkManager br0: dhcp4: true''') self.assert_nm({'br0': '''[connection] id=netplan-br0 type=bridge interface-name=br0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_bridge_set_mac(self): self.generate('''network: version: 2 bridges: renderer: NetworkManager br0: macaddress: 00:01:02:03:04:05 dhcp4: true''') self.assert_nm({'br0': '''[connection] id=netplan-br0 type=bridge interface-name=br0 [802-3-ethernet] cloned-mac-address=00:01:02:03:04:05 [ipv4] method=auto [ipv6] method=ignore '''}) def test_bridge_def_renderer(self): self.generate('''network: version: 2 renderer: networkd bridges: renderer: networkd br0: renderer: NetworkManager addresses: [1.2.3.4/12] dhcp4: true''') self.assert_nm({'br0': '''[connection] id=netplan-br0 type=bridge interface-name=br0 [ipv4] method=auto address1=1.2.3.4/12 [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_bridge_forward_declaration(self): self.generate('''network: version: 2 renderer: NetworkManager bridges: br0: interfaces: [eno1, switchport] dhcp4: true ethernets: eno1: {} switchport: match: name: enp2s1 ''') self.assert_nm({'eno1': '''[connection] id=netplan-eno1 type=ethernet interface-name=eno1 slave-type=bridge master=br0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'switchport': '''[connection] id=netplan-switchport type=ethernet interface-name=enp2s1 slave-type=bridge master=br0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'br0': '''[connection] id=netplan-br0 type=bridge interface-name=br0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_bridge_components(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eno1: {} switchport: match: name: enp2s1 bridges: br0: interfaces: [eno1, switchport] dhcp4: true''') self.assert_nm({'eno1': '''[connection] id=netplan-eno1 type=ethernet interface-name=eno1 slave-type=bridge master=br0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'switchport': '''[connection] id=netplan-switchport type=ethernet interface-name=enp2s1 slave-type=bridge master=br0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'br0': '''[connection] id=netplan-br0 type=bridge interface-name=br0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_bridge_params(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eno1: {} switchport: match: name: enp2s1 bridges: br0: interfaces: [eno1, switchport] parameters: ageing-time: 50 priority: 1000 forward-delay: 12 hello-time: 6 max-age: 24 path-cost: eno1: 70 port-priority: eno1: 61 stp: true dhcp4: true''') self.assert_nm({'eno1': '''[connection] id=netplan-eno1 type=ethernet interface-name=eno1 slave-type=bridge master=br0 [bridge-port] path-cost=70 priority=61 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'switchport': '''[connection] id=netplan-switchport type=ethernet interface-name=enp2s1 slave-type=bridge master=br0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'br0': '''[connection] id=netplan-br0 type=bridge interface-name=br0 [bridge] ageing-time=50 priority=1000 forward-delay=12 hello-time=6 max-age=24 stp=true [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_bond_empty(self): self.generate('''network: version: 2 renderer: NetworkManager bonds: bn0: dhcp4: true''') self.assert_nm({'bn0': '''[connection] id=netplan-bn0 type=bond interface-name=bn0 [ipv4] method=auto [ipv6] method=ignore '''}) def test_bond_components(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eno1: {} switchport: match: name: enp2s1 bonds: bn0: interfaces: [eno1, switchport] dhcp4: true''') self.assert_nm({'eno1': '''[connection] id=netplan-eno1 type=ethernet interface-name=eno1 slave-type=bond master=bn0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'switchport': '''[connection] id=netplan-switchport type=ethernet interface-name=enp2s1 slave-type=bond master=bn0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'bn0': '''[connection] id=netplan-bn0 type=bond interface-name=bn0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_bond_empty_params(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eno1: {} switchport: match: name: enp2s1 bonds: bn0: interfaces: [eno1, switchport] parameters: {} dhcp4: true''') self.assert_nm({'eno1': '''[connection] id=netplan-eno1 type=ethernet interface-name=eno1 slave-type=bond master=bn0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'switchport': '''[connection] id=netplan-switchport type=ethernet interface-name=enp2s1 slave-type=bond master=bn0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'bn0': '''[connection] id=netplan-bn0 type=bond interface-name=bn0 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_bond_with_params(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eno1: {} switchport: match: name: enp2s1 bonds: bn0: interfaces: [eno1, switchport] parameters: mode: 802.1ad lacp-rate: 10 mii-monitor-interval: 10 min-links: 10 up-delay: 10 down-delay: 10 all-slaves-active: true transmit-hash-policy: none ad-select: none arp-interval: 10 arp-validate: all arp-all-targets: all arp-ip-targets: - 10.10.10.10 - 20.20.20.20 fail-over-mac-policy: none gratuitious-arp: 10 packets-per-slave: 10 primary-reselect-policy: none resend-igmp: 10 learn-packet-interval: 10 dhcp4: true''') self.assert_nm({'eno1': '''[connection] id=netplan-eno1 type=ethernet interface-name=eno1 slave-type=bond master=bn0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'switchport': '''[connection] id=netplan-switchport type=ethernet interface-name=enp2s1 slave-type=bond master=bn0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'bn0': '''[connection] id=netplan-bn0 type=bond interface-name=bn0 [bond] mode=802.1ad lacp_rate=10 miimon=10 min_links=10 xmit_hash_policy=none ad_select=none all_slaves_active=1 arp_interval=10 arp_ip_target=10.10.10.10,20.20.20.20 arp_validate=all arp_all_targets=all updelay=10 downdelay=10 fail_over_mac=none num_grat_arp=10 packets_per_slave=10 primary_reselect=none resend_igmp=10 lp_interval=10 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_bond_primary_slave(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: eno1: {} switchport: match: name: enp2s1 bonds: bn0: interfaces: [eno1, switchport] parameters: mode: active-backup primary: eno1 dhcp4: true''') self.assert_nm({'eno1': '''[connection] id=netplan-eno1 type=ethernet interface-name=eno1 slave-type=bond master=bn0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'switchport': '''[connection] id=netplan-switchport type=ethernet interface-name=enp2s1 slave-type=bond master=bn0 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'bn0': '''[connection] id=netplan-bn0 type=bond interface-name=bn0 [bond] mode=active-backup primary=eno1 [ipv4] method=auto [ipv6] method=ignore '''}) self.assert_networkd({}) self.assert_nm_udev(None) def test_gateway(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: engreen: addresses: ["192.168.14.2/24", "2001:FFfe::1/64"] gateway4: 192.168.14.1 gateway6: 2001:FFfe::2''') self.assert_nm({'engreen': '''[connection] id=netplan-engreen type=ethernet interface-name=engreen [ethernet] wake-on-lan=0 [ipv4] method=manual address1=192.168.14.2/24 gateway=192.168.14.1 [ipv6] method=manual address1=2001:FFfe::1/64 gateway=2001:FFfe::2 '''}) def test_nameserver(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: engreen: addresses: ["192.168.14.2/24"] nameservers: addresses: [1.2.3.4, 2.3.4.5, "1234::FFFF"] search: [lab, kitchen] enblue: addresses: ["192.168.1.3/24"] nameservers: addresses: [8.8.8.8]''') self.assert_nm({'engreen': '''[connection] id=netplan-engreen type=ethernet interface-name=engreen [ethernet] wake-on-lan=0 [ipv4] method=manual address1=192.168.14.2/24 dns=1.2.3.4;2.3.4.5; dns-search=lab;kitchen; [ipv6] method=manual dns=1234::FFFF; dns-search=lab;kitchen; ''', 'enblue': '''[connection] id=netplan-enblue type=ethernet interface-name=enblue [ethernet] wake-on-lan=0 [ipv4] method=manual address1=192.168.1.3/24 dns=8.8.8.8; [ipv6] method=ignore '''}) def test_vlan(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: en1: {} vlans: enblue: id: 1 link: en1 addresses: [1.2.3.4/24] engreen: {id: 2, link: en1, dhcp6: true}''') self.assert_networkd({}) self.assert_nm({'en1': '''[connection] id=netplan-en1 type=ethernet interface-name=en1 [ethernet] wake-on-lan=0 [ipv4] method=link-local [ipv6] method=ignore ''', 'enblue': '''[connection] id=netplan-enblue type=vlan interface-name=enblue [vlan] id=1 parent=en1 [ipv4] method=manual address1=1.2.3.4/24 [ipv6] method=ignore ''', 'engreen': '''[connection] id=netplan-engreen type=vlan interface-name=engreen [vlan] id=2 parent=en1 [ipv4] method=link-local [ipv6] method=auto '''}) self.assert_nm_udev(None) def test_vlan_parent_match(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: en-v: match: {macaddress: "11:22:33:44:55:66"} vlans: engreen: {id: 2, link: en-v, dhcp4: true}''') self.assert_networkd({}) # get assigned UUID from en-v connection with open(os.path.join(self.workdir.name, 'run/NetworkManager/system-connections/netplan-en-v')) as f: m = re.search('uuid=([0-9a-fA-F-]{36})\n', f.read()) self.assertTrue(m) uuid = m.group(1) self.assertNotEquals(uuid, "00000000-0000-0000-0000-000000000000") self.assert_nm({'en-v': '''[connection] id=netplan-en-v type=ethernet uuid=%s [ethernet] wake-on-lan=0 [802-3-ethernet] mac-address=11:22:33:44:55:66 [ipv4] method=link-local [ipv6] method=ignore ''' % uuid, 'engreen': '''[connection] id=netplan-engreen type=vlan interface-name=engreen [vlan] id=2 parent=%s [ipv4] method=auto [ipv6] method=ignore ''' % uuid}) self.assert_nm_udev(None) class TestConfigErrors(TestBase): def test_malformed_yaml(self): err = self.generate('network:\n version: 2\n foo: *', expect_fail=True) self.assertIn('Invalid YAML', err) self.assertIn('/a.yaml line 2 column 1: did not find expected key', err) def test_yaml_expected_scalar(self): err = self.generate('network:\n version: {}', expect_fail=True) self.assertIn('expected scalar', err) def test_yaml_expected_sequence(self): err = self.generate('''network: version: 2 bridges: br0: interfaces: {}''', expect_fail=True) self.assertIn('expected sequence', err) def test_yaml_expected_mapping(self): err = self.generate('network:\n version', expect_fail=True) self.assertIn('/a.yaml line 1 column 2: expected mapping', err) def test_invalid_bool(self): err = self.generate('''network: version: 2 ethernets: id0: wakeonlan: wut ''', expect_fail=True) self.assertIn('invalid boolean value wut', err) def test_invalid_version(self): err = self.generate('network:\n version: 1', expect_fail=True) self.assertIn('/a.yaml line 1 column 11: Only version 2 is supported', err) def test_id_redef_type_mismatch(self): err = self.generate('''network: version: 2 ethernets: id0: wakeonlan: true''', confs={'redef': '''network: version: 2 bridges: id0: wakeonlan: true'''}, expect_fail=True) self.assertIn("redef.yaml line 3 column 4: Updated definition 'id0' changes device type", err) def test_set_name_without_match(self): err = self.generate('''network: version: 2 ethernets: def1: set-name: lom1 ''', expect_fail=True) self.assertIn('/a.yaml line 4 column 6: def1: set-name: requires match: properties', err) def test_virtual_set_name(self): err = self.generate('''network: version: 2 bridges: br0: set_name: br1''', expect_fail=True) self.assertIn('/a.yaml line 4 column 6: unknown key set_name\n', err) def test_virtual_match(self): err = self.generate('''network: version: 2 bridges: br0: match: driver: foo''', expect_fail=True) self.assertIn('/a.yaml line 4 column 6: unknown key match\n', err) def test_virtual_wol(self): err = self.generate('''network: version: 2 bridges: br0: wakeonlan: true''', expect_fail=True) self.assertIn('/a.yaml line 4 column 6: unknown key wakeonlan\n', err) def test_bridge_unknown_iface(self): err = self.generate('''network: version: 2 bridges: br0: interfaces: ['foo']''', expect_fail=True) self.assertIn('/a.yaml line 4 column 19: br0: interface foo is not defined\n', err) def test_bridge_multiple_assignments(self): err = self.generate('''network: version: 2 ethernets: eno1: {} bridges: br0: interfaces: [eno1] br1: interfaces: [eno1]''', expect_fail=True) self.assertIn('br1: interface eno1 is already assigned to br0\n', err) def test_unknown_global_renderer(self): err = self.generate('''network: version: 2 renderer: bogus ''', expect_fail=True) self.assertIn("unknown renderer 'bogus'", err) def test_unknown_type_renderer(self): err = self.generate('''network: version: 2 ethernets: renderer: bogus ''', expect_fail=True) self.assertIn("unknown renderer 'bogus'", err) def test_invalid_id(self): err = self.generate('''network: version: 2 ethernets: "eth 0": dhcp4: true''', expect_fail=True) self.assertIn("Invalid name 'eth 0'", err) def test_invalid_name_match(self): err = self.generate('''network: version: 2 ethernets: def1: match: name: | fo o bar dhcp4: true''', expect_fail=True) self.assertIn("Invalid name 'fo o\nbar\n'", err) def test_invalid_mac_match(self): err = self.generate('''network: version: 2 ethernets: def1: match: macaddress: 00:11:ZZ dhcp4: true''', expect_fail=True) self.assertIn("Invalid MAC address '00:11:ZZ', must be XX:XX:XX:XX:XX:XX", err) def test_glob_in_id(self): err = self.generate('''network: version: 2 ethernets: en*: dhcp4: true''', expect_fail=True) self.assertIn("Definition ID 'en*' must not use globbing", err) def test_wifi_duplicate_ssid(self): err = self.generate('''network: version: 2 wifis: wl0: access-points: workplace: password: "s3kr1t" workplace: password: "c0mpany" dhcp4: yes''', expect_fail=True) self.assertIn("wl0: Duplicate access point SSID 'workplace'", err) def test_wifi_no_ap(self): err = self.generate('''network: version: 2 wifis: wl0: dhcp4: yes''', expect_fail=True) self.assertIn('wl0: No access points defined', err) def test_wifi_empty_ap(self): err = self.generate('''network: version: 2 wifis: wl0: access-points: {} dhcp4: yes''', expect_fail=True) self.assertIn('wl0: No access points defined', err) def test_wifi_ap_unknown_key(self): err = self.generate('''network: version: 2 wifis: wl0: access-points: workplace: something: false dhcp4: yes''', expect_fail=True) self.assertIn('/etc/netplan/a.yaml line 6 column 10: unknown key something', err) def test_wifi_ap_unknown_mode(self): err = self.generate('''network: version: 2 wifis: wl0: access-points: workplace: mode: bogus''', expect_fail=True) self.assertIn("unknown wifi mode 'bogus'", err) def test_invalid_ipv4_address(self): err = self.generate('''network: version: 2 ethernets: engreen: addresses: - 192.168.14/24 - 2001:FFfe::1/64''', expect_fail=True) self.assertIn("malformed address '192.168.14/24', must be X.X.X.X/NN", err) def test_missing_ipv4_prefixlen(self): err = self.generate('''network: version: 2 ethernets: engreen: addresses: - 192.168.14.1''', expect_fail=True) self.assertIn("address '192.168.14.1' is missing /prefixlength", err) def test_empty_ipv4_prefixlen(self): err = self.generate('''network: version: 2 ethernets: engreen: addresses: - 192.168.14.1/''', expect_fail=True) self.assertIn("invalid prefix length in address '192.168.14.1/'", err) def test_invalid_ipv4_prefixlen(self): err = self.generate('''network: version: 2 ethernets: engreen: addresses: - 192.168.14.1/33''', expect_fail=True) self.assertIn("invalid prefix length in address '192.168.14.1/33'", err) def test_invalid_ipv6_address(self): err = self.generate('''network: version: 2 ethernets: engreen: addresses: - 2001:G::1/64''', expect_fail=True) self.assertIn("malformed address '2001:G::1/64', must be X.X.X.X/NN", err) def test_missing_ipv6_prefixlen(self): err = self.generate('''network: version: 2 ethernets: engreen: addresses: - 2001::1''', expect_fail=True) self.assertIn("address '2001::1' is missing /prefixlength", err) def test_invalid_ipv6_prefixlen(self): err = self.generate('''network: version: 2 ethernets: engreen: addresses: - 2001::1/129''', expect_fail=True) self.assertIn("invalid prefix length in address '2001::1/129'", err) def test_empty_ipv6_prefixlen(self): err = self.generate('''network: version: 2 ethernets: engreen: addresses: - 2001::1/''', expect_fail=True) self.assertIn("invalid prefix length in address '2001::1/'", err) def test_invalid_gateway4(self): for a in ['300.400.1.1', '1.2.3', '192.168.14.1/24']: err = self.generate('''network: version: 2 ethernets: engreen: gateway4: %s''' % a, expect_fail=True) self.assertIn("invalid IPv4 address '%s'" % a, err) def test_invalid_gateway6(self): for a in ['1234', '1:::c', '1234::1/50']: err = self.generate('''network: version: 2 ethernets: engreen: gateway6: %s''' % a, expect_fail=True) self.assertIn("invalid IPv6 address '%s'" % a, err) def test_invalid_nameserver_ipv4(self): for a in ['300.400.1.1', '1.2.3', '192.168.14.1/24']: err = self.generate('''network: version: 2 ethernets: engreen: nameservers: addresses: [%s]''' % a, expect_fail=True) self.assertIn("malformed address '%s'" % a, err) def test_invalid_nameserver_ipv6(self): for a in ['1234', '1:::c', '1234::1/50']: err = self.generate('''network: version: 2 ethernets: engreen: nameservers: addresses: ["%s"]''' % a, expect_fail=True) self.assertIn("malformed address '%s'" % a, err) def test_vlan_missing_id(self): err = self.generate('''network: version: 2 ethernets: {en1: {}} vlans: ena: {link: en1}''', expect_fail=True) self.assertIn('missing id property', err) def test_vlan_invalid_id(self): err = self.generate('''network: version: 2 ethernets: {en1: {}} vlans: ena: {id: a, link: en1}''', expect_fail=True) self.assertIn('invalid unsigned int value a', err) err = self.generate('''network: version: 2 ethernets: {en1: {}} vlans: ena: {id: 4095, link: en1}''', expect_fail=True) self.assertIn('invalid id 4095', err) def test_vlan_missing_link(self): err = self.generate('''network: version: 2 vlans: ena: {id: 1}''', expect_fail=True) self.assertIn('ena: missing link property', err) def test_vlan_unknown_link(self): err = self.generate('''network: version: 2 vlans: ena: {id: 1, link: en1}''', expect_fail=True) self.assertIn('ena: interface en1 is not defined\n', err) def test_device_bad_route_to(self): self.generate('''network: version: 2 ethernets: engreen: routes: - to: badlocation via: 192.168.14.20 metric: 100 addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''', expect_fail=True) def test_device_bad_route_via(self): self.generate('''network: version: 2 ethernets: engreen: routes: - to: 10.10.0.0/16 via: badgateway metric: 100 addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''', expect_fail=True) def test_device_bad_route_metric(self): self.generate('''network: version: 2 ethernets: engreen: routes: - to: 10.10.0.0/16 via: 10.1.1.1 metric: -1 addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''', expect_fail=True) def test_device_route_family_mismatch_ipv6_to(self): self.generate('''network: version: 2 ethernets: engreen: routes: - to: 2001:dead:beef::0/16 via: 10.1.1.1 metric: 1 addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''', expect_fail=True) def test_device_route_family_mismatch_ipv4_to(self): self.generate('''network: version: 2 ethernets: engreen: routes: - via: 2001:dead:beef::2 to: 10.10.10.0/24 metric: 1 addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''', expect_fail=True) def test_device_route_missing_to(self): self.generate('''network: version: 2 ethernets: engreen: routes: - via: 2001:dead:beef::2 metric: 1 addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''', expect_fail=True) def test_device_route_missing_via(self): self.generate('''network: version: 2 ethernets: engreen: routes: - to: 2001:dead:beef::2 metric: 1 addresses: - 192.168.14.2/24 - 2001:FFfe::1/64''', expect_fail=True) def test_bridge_invalid_dev_for_path_cost(self): self.generate('''network: version: 2 ethernets: eno1: match: name: eth0 bridges: br0: interfaces: [eno1] parameters: path-cost: eth0: 50 dhcp4: true''', expect_fail=True) def test_bridge_path_cost_already_defined(self): self.generate('''network: version: 2 ethernets: eno1: match: name: eth0 bridges: br0: interfaces: [eno1] parameters: path-cost: eno1: 50 eno1: 40 dhcp4: true''', expect_fail=True) def test_bridge_invalid_path_cost(self): self.generate('''network: version: 2 ethernets: eno1: match: name: eth0 bridges: br0: interfaces: [eno1] parameters: path-cost: eno1: aa dhcp4: true''', expect_fail=True) def test_bridge_invalid_dev_for_port_prio(self): self.generate('''network: version: 2 ethernets: eno1: match: name: eth0 bridges: br0: interfaces: [eno1] parameters: port-priority: eth0: 50 dhcp4: true''', expect_fail=True) def test_bridge_port_prio_already_defined(self): self.generate('''network: version: 2 ethernets: eno1: match: name: eth0 bridges: br0: interfaces: [eno1] parameters: port-priority: eno1: 50 eno1: 40 dhcp4: true''', expect_fail=True) def test_bridge_invalid_port_prio(self): self.generate('''network: version: 2 ethernets: eno1: match: name: eth0 bridges: br0: interfaces: [eno1] parameters: port-priority: eno1: 257 dhcp4: true''', expect_fail=True) def test_bond_invalid_arp_target(self): self.generate('''network: version: 2 ethernets: eno1: match: name: eth0 bonds: bond0: interfaces: [eno1] parameters: arp-ip-targets: - 2001:dead:beef::1 dhcp4: true''', expect_fail=True) def test_bond_invalid_primary_slave(self): self.generate('''network: version: 2 ethernets: eno1: match: name: eth0 bonds: bond0: interfaces: [eno1] parameters: primary: wigglewiggle dhcp4: true''', expect_fail=True) def test_bond_duplicate_primary_slave(self): self.generate('''network: version: 2 ethernets: eno1: match: name: eth0 eno2: match: name: eth1 bonds: bond0: interfaces: [eno1, eno2] parameters: primary: eno1 primary: eno2 dhcp4: true''', expect_fail=True) def test_invalid_dhcp_identifier(self): self.generate('''network: version: 2 ethernets: engreen: dhcp4: yes dhcp-identifier: invalid''', expect_fail=True) def test_invalid_accept_ra(self): err = self.generate('''network: version: 2 bridges: br0: accept-ra: j''', expect_fail=True) self.assertIn('invalid boolean', err) class TestForwardDeclaration(TestBase): def test_fwdecl_bridge_on_bond(self): self.generate('''network: version: 2 bridges: br0: interfaces: ['bond0'] dhcp4: true bonds: bond0: interfaces: ['eth0', 'eth1'] ethernets: eth0: match: macaddress: 00:01:02:03:04:05 set-name: eth0 eth1: match: macaddress: 02:01:02:03:04:05 set-name: eth1 ''') self.assert_networkd({'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n', 'br0.network': ND_DHCP4 % 'br0', 'bond0.netdev': '[NetDev]\nName=bond0\nKind=bond\n', 'bond0.network': '[Match]\nName=bond0\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n', 'eth0.link': '[Match]\nMACAddress=00:01:02:03:04:05\n\n' '[Link]\nName=eth0\nWakeOnLan=off\n', 'eth0.network': '[Match]\nMACAddress=00:01:02:03:04:05\nName=eth0\n\n' '[Network]\nBond=bond0\nLinkLocalAddressing=no\n', 'eth1.link': '[Match]\nMACAddress=02:01:02:03:04:05\n\n' '[Link]\nName=eth1\nWakeOnLan=off\n', 'eth1.network': '[Match]\nMACAddress=02:01:02:03:04:05\nName=eth1\n\n' '[Network]\nBond=bond0\nLinkLocalAddressing=no\n'}) def test_fwdecl_feature_blend(self): self.generate('''network: version: 2 vlans: vlan1: link: 'br0' id: 1 dhcp4: true bridges: br0: interfaces: ['bond0', 'eth2'] parameters: path-cost: eth2: 1000 bond0: 8888 bonds: bond0: interfaces: ['eth0', 'br1'] ethernets: eth0: match: macaddress: 00:01:02:03:04:05 set-name: eth0 bridges: br1: interfaces: ['eth1'] ethernets: eth1: match: macaddress: 02:01:02:03:04:05 set-name: eth1 eth2: match: name: eth2 ''') self.assert_networkd({'vlan1.netdev': '[NetDev]\nName=vlan1\nKind=vlan\n\n' '[VLAN]\nId=1\n', 'vlan1.network': ND_DHCP4 % 'vlan1', 'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n\n' '[Bridge]\nSTP=true\n', 'br0.network': '[Match]\nName=br0\n\n' '[Network]\nVLAN=vlan1\n', 'bond0.netdev': '[NetDev]\nName=bond0\nKind=bond\n', 'bond0.network': '[Match]\nName=bond0\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n\n' '[Bridge]\nCost=8888\n', 'eth2.network': '[Match]\nName=eth2\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n\n' '[Bridge]\nCost=1000\n', 'br1.netdev': '[NetDev]\nName=br1\nKind=bridge\n', 'br1.network': '[Match]\nName=br1\n\n' '[Network]\nBond=bond0\nLinkLocalAddressing=no\n', 'eth0.link': '[Match]\nMACAddress=00:01:02:03:04:05\n\n' '[Link]\nName=eth0\nWakeOnLan=off\n', 'eth0.network': '[Match]\nMACAddress=00:01:02:03:04:05\nName=eth0\n\n' '[Network]\nBond=bond0\nLinkLocalAddressing=no\n', 'eth1.link': '[Match]\nMACAddress=02:01:02:03:04:05\n\n' '[Link]\nName=eth1\nWakeOnLan=off\n', 'eth1.network': '[Match]\nMACAddress=02:01:02:03:04:05\nName=eth1\n\n' '[Network]\nBridge=br1\nLinkLocalAddressing=no\n'}) class TestMerging(TestBase): '''multiple *.yaml merging''' def test_global_backend(self): self.generate('''network: version: 2 renderer: NetworkManager ethernets: engreen: dhcp4: y''', confs={'backend': 'network:\n renderer: networkd'}) self.assert_networkd({'engreen.network': ND_DHCP4 % 'engreen'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:engreen,''') self.assert_nm_udev(None) def test_add_def(self): self.generate('''network: version: 2 ethernets: engreen: dhcp4: true''', confs={'blue': '''network: version: 2 ethernets: enblue: dhcp4: true'''}) self.assert_networkd({'enblue.network': ND_DHCP4 % 'enblue', 'engreen.network': ND_DHCP4 % 'engreen'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:enblue,interface-name:engreen,''') self.assert_nm_udev(None) def test_change_def(self): self.generate('''network: version: 2 ethernets: engreen: wakeonlan: true dhcp4: false''', confs={'green-dhcp': '''network: version: 2 ethernets: engreen: dhcp4: true'''}) self.assert_networkd({'engreen.link': '[Match]\nOriginalName=engreen\n\n[Link]\nWakeOnLan=magic\n', 'engreen.network': ND_DHCP4 % 'engreen'}) def test_cleanup_old_config(self): self.generate('''network: version: 2 ethernets: engreen: {dhcp4: true} enyellow: {renderer: NetworkManager}''', confs={'blue': '''network: version: 2 ethernets: enblue: dhcp4: true'''}) os.unlink(os.path.join(self.confdir, 'blue.yaml')) self.generate('''network: version: 2 ethernets: engreen: {dhcp4: true}''') self.assert_networkd({'engreen.network': ND_DHCP4 % 'engreen'}) self.assert_nm(None, '''[keyfile] # devices managed by networkd unmanaged-devices+=interface-name:engreen,''') self.assert_nm_udev(None) def test_ref(self): self.generate('''network: version: 2 ethernets: eno1: {} switchports: match: driver: yayroute''', confs={'bridges': '''network: version: 2 bridges: br0: interfaces: [eno1, switchports] dhcp4: true'''}) self.assert_networkd({'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n', 'br0.network': ND_DHCP4 % 'br0', 'eno1.network': '[Match]\nName=eno1\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n', 'switchports.network': '[Match]\nDriver=yayroute\n\n' '[Network]\nBridge=br0\nLinkLocalAddressing=no\n'}) def test_def_in_run(self): rundir = os.path.join(self.workdir.name, 'run', 'netplan') os.makedirs(rundir) # override b.yaml definition for enred with open(os.path.join(rundir, 'b.yaml'), 'w') as f: f.write('''network: version: 2 ethernets: {enred: {dhcp4: true}}''') # append new definition for enblue with open(os.path.join(rundir, 'c.yaml'), 'w') as f: f.write('''network: version: 2 ethernets: {enblue: {dhcp4: true}}''') self.generate('''network: version: 2 ethernets: engreen: {dhcp4: true}''', confs={'b': '''network: version: 2 ethernets: {enred: {wakeonlan: true}}'''}) # b.yaml in /run/ should completely shadow b.yaml in /etc, thus no enred.link self.assert_networkd({'engreen.network': ND_DHCP4 % 'engreen', 'enred.network': ND_DHCP4 % 'enred', 'enblue.network': ND_DHCP4 % 'enblue'}) def test_def_in_lib(self): libdir = os.path.join(self.workdir.name, 'lib', 'netplan') rundir = os.path.join(self.workdir.name, 'run', 'netplan') os.makedirs(libdir) os.makedirs(rundir) # b.yaml is in /etc/netplan too which should have precedence with open(os.path.join(libdir, 'b.yaml'), 'w') as f: f.write('''network: version: 2 ethernets: {notme: {dhcp4: true}}''') # /run should trump /lib too with open(os.path.join(libdir, 'c.yaml'), 'w') as f: f.write('''network: version: 2 ethernets: {alsonot: {dhcp4: true}}''') with open(os.path.join(rundir, 'c.yaml'), 'w') as f: f.write('''network: version: 2 ethernets: {enyellow: {dhcp4: true}}''') # this should be considered with open(os.path.join(libdir, 'd.yaml'), 'w') as f: f.write('''network: version: 2 ethernets: {enblue: {dhcp4: true}}''') self.generate('''network: version: 2 ethernets: engreen: {dhcp4: true}''', confs={'b': '''network: version: 2 ethernets: {enred: {wakeonlan: true}}'''}) self.assert_networkd({'engreen.network': ND_DHCP4 % 'engreen', 'enred.link': '[Match]\nOriginalName=enred\n\n[Link]\nWakeOnLan=magic\n', 'enyellow.network': ND_DHCP4 % 'enyellow', 'enblue.network': ND_DHCP4 % 'enblue'}) unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2)) nplan-0.32~16.04.7~mtrudel1/tests/integration.py0000775000000000000000000023552713315465032016330 0ustar #!/usr/bin/python3 # System integration tests of netplan-generate. NM and networkd are # started on the generated configuration, using emulated ethernets (veth) and # Wifi (mac80211-hwsim). These need to be run in a VM and do change the system # configuration. # # Copyright (C) 2016 Canonical, Ltd. # Author: Martin Pitt # # 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; version 3. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os import sys import re import time import subprocess import tempfile import unittest import shutil for program in ['wpa_supplicant', 'hostapd', 'dnsmasq']: if subprocess.call(['which', program], stdout=subprocess.PIPE) != 0: sys.stderr.write('%s is required for this test suite, but not available. Skipping\n' % program) sys.exit(0) nm_uses_dnsmasq = b'dns=dnsmasq' in subprocess.check_output(['NetworkManager', '--print-config']) def resolved_in_use(): return os.path.isfile('/run/systemd/resolve/resolv.conf') class NetworkTestBase(unittest.TestCase): '''Common functionality for network test cases setUp() creates two test wlan devices, one for a simulated access point (self.dev_w_ap), the other for a simulated client device (self.dev_w_client), and two test ethernet devices (self.dev_e_{ap,client} and self.dev_e2_{ap,client}. Each test should call self.setup_ap() or self.setup_eth() with the desired configuration. ''' @classmethod def setUpClass(klass): # ensure we have this so that iw works subprocess.check_call(['modprobe', 'cfg80211']) # ensure NM can manage our fake eths os.makedirs('/run/udev/rules.d', exist_ok=True) with open('/run/udev/rules.d/99-nm-veth-test.rules', 'w') as f: f.write('ENV{ID_NET_DRIVER}=="veth", ENV{INTERFACE}=="eth42|eth43", ENV{NM_UNMANAGED}="0"\n') subprocess.check_call(['udevadm', 'control', '--reload']) # set regulatory domain "EU", so that we can use 80211.a 5 GHz channels out = subprocess.check_output(['iw', 'reg', 'get'], universal_newlines=True) m = re.match('^(?:global\n)?country (\S+):', out) assert m klass.orig_country = m.group(1) subprocess.check_call(['iw', 'reg', 'set', 'EU']) @classmethod def tearDownClass(klass): subprocess.check_call(['iw', 'reg', 'set', klass.orig_country]) try: os.remove('/run/NetworkManager/conf.d/test-blacklist.conf') except FileNotFoundError: pass try: os.remove('/run/udev/rules.d/99-nm-veth-test.rules') except FileNotFoundError: pass def tearDown(self): subprocess.call(['systemctl', 'stop', 'NetworkManager', 'systemd-networkd', 'netplan-wpa@*', 'systemd-networkd.socket']) # NM has KillMode=process and leaks dhclient processes subprocess.call(['systemctl', 'kill', 'NetworkManager']) subprocess.call(['systemctl', 'reset-failed', 'NetworkManager', 'systemd-networkd'], stderr=subprocess.DEVNULL) shutil.rmtree('/etc/netplan', ignore_errors=True) shutil.rmtree('/run/NetworkManager', ignore_errors=True) shutil.rmtree('/run/systemd/network', ignore_errors=True) try: os.remove('/run/systemd/generator/netplan.stamp') except FileNotFoundError: pass @classmethod def create_devices(klass): '''Create Access Point and Client devices with mac80211_hwsim and veth''' if os.path.exists('/sys/module/mac80211_hwsim'): raise SystemError('mac80211_hwsim module already loaded') if os.path.exists('/sys/class/net/eth42'): raise SystemError('eth42 interface already exists') # create virtual ethernet devs subprocess.check_call(['ip', 'link', 'add', 'name', 'eth42', 'type', 'veth', 'peer', 'name', 'veth42']) klass.dev_e_ap = 'veth42' klass.dev_e_client = 'eth42' out = subprocess.check_output(['ip', '-br', 'link', 'show', 'dev', 'eth42'], universal_newlines=True) klass.dev_e_client_mac = out.split()[2] subprocess.check_call(['ip', 'link', 'add', 'name', 'eth43', 'type', 'veth', 'peer', 'name', 'veth43']) klass.dev_e2_ap = 'veth43' klass.dev_e2_client = 'eth43' out = subprocess.check_output(['ip', '-br', 'link', 'show', 'dev', 'eth43'], universal_newlines=True) klass.dev_e2_client_mac = out.split()[2] # create virtual wlan devs before_wlan = set([c for c in os.listdir('/sys/class/net') if c.startswith('wlan')]) subprocess.check_call(['modprobe', 'mac80211_hwsim']) # wait 5 seconds for fake devices to appear timeout = 50 while timeout > 0: after_wlan = set([c for c in os.listdir('/sys/class/net') if c.startswith('wlan')]) if len(after_wlan) - len(before_wlan) >= 2: break timeout -= 1 time.sleep(0.1) else: raise SystemError('timed out waiting for fake devices to appear') devs = list(after_wlan - before_wlan) klass.dev_w_ap = devs[0] klass.dev_w_client = devs[1] # don't let NM trample over our fake AP os.makedirs('/run/NetworkManager/conf.d', exist_ok=True) with open('/run/NetworkManager/conf.d/test-blacklist.conf', 'w') as f: f.write('[main]\nplugins=keyfile\n[keyfile]\nunmanaged-devices+=nptestsrv,%s\n' % klass.dev_w_ap) # work around https://launchpad.net/bugs/1615044 with open('/run/NetworkManager/conf.d/11-globally-managed-devices.conf', 'w') as f: f.write('[keyfile]\nunmanaged-devices=') @classmethod def shutdown_devices(klass): '''Remove test wlan devices''' subprocess.check_call(['rmmod', 'mac80211_hwsim']) subprocess.check_call(['ip', 'link', 'del', 'dev', klass.dev_e_ap]) subprocess.check_call(['ip', 'link', 'del', 'dev', klass.dev_e2_ap]) subprocess.call(['ip', 'link', 'del', 'dev', 'mybr'], stderr=subprocess.PIPE) klass.dev_w_ap = None klass.dev_w_client = None klass.dev_e_ap = None klass.dev_e_client = None klass.dev_e2_ap = None klass.dev_e2_client = None def setUp(self): '''Create test devices and workdir''' self.create_devices() self.addCleanup(self.shutdown_devices) self.workdir_obj = tempfile.TemporaryDirectory() self.workdir = self.workdir_obj.name self.config = '/etc/netplan/01-main.yaml' os.makedirs('/etc/netplan', exist_ok=True) # create static entropy file to avoid draining/blocking on /dev/random self.entropy_file = os.path.join(self.workdir, 'entropy') with open(self.entropy_file, 'wb') as f: f.write(b'012345678901234567890') def setup_ap(self, hostapd_conf, ipv6_mode): '''Set up simulated access point On self.dev_w_ap, run hostapd with given configuration. Setup dnsmasq according to ipv6_mode, see start_dnsmasq(). This is torn down automatically at the end of the test. ''' # give our AP an IP subprocess.check_call(['ip', 'a', 'flush', 'dev', self.dev_w_ap]) if ipv6_mode is not None: subprocess.check_call(['ip', 'a', 'add', '2600::1/64', 'dev', self.dev_w_ap]) else: subprocess.check_call(['ip', 'a', 'add', '192.168.5.1/24', 'dev', self.dev_w_ap]) self.start_hostapd(hostapd_conf) self.start_dnsmasq(ipv6_mode, self.dev_w_ap) def setup_eth(self, ipv6_mode, start_dnsmasq=True): '''Set up simulated ethernet router On self.dev_e_ap, run dnsmasq according to ipv6_mode, see start_dnsmasq(). This is torn down automatically at the end of the test. ''' # give our router an IP subprocess.check_call(['ip', 'a', 'flush', 'dev', self.dev_e_ap]) if ipv6_mode is not None: subprocess.check_call(['ip', 'a', 'add', '2600::1/64', 'dev', self.dev_e_ap]) subprocess.check_call(['ip', 'a', 'add', '2601::1/64', 'dev', self.dev_e2_ap]) else: subprocess.check_call(['ip', 'a', 'add', '192.168.5.1/24', 'dev', self.dev_e_ap]) subprocess.check_call(['ip', 'a', 'add', '192.168.6.1/24', 'dev', self.dev_e2_ap]) subprocess.check_call(['ip', 'link', 'set', self.dev_e_ap, 'up']) subprocess.check_call(['ip', 'link', 'set', self.dev_e2_ap, 'up']) if start_dnsmasq: self.start_dnsmasq(ipv6_mode, self.dev_e_ap) # # Internal implementation details # @classmethod def poll_text(klass, logpath, string, timeout=50): '''Poll log file for a given string with a timeout. Timeout is given in deciseconds. ''' log = '' while timeout > 0: if os.path.exists(logpath): break timeout -= 1 time.sleep(0.1) assert timeout > 0, 'Timed out waiting for file %s to appear' % logpath with open(logpath) as f: while timeout > 0: line = f.readline() if line: log += line if string in line: break continue timeout -= 1 time.sleep(0.1) assert timeout > 0, 'Timed out waiting for "%s":\n------------\n%s\n-------\n' % (string, log) def start_hostapd(self, conf): hostapd_conf = os.path.join(self.workdir, 'hostapd.conf') with open(hostapd_conf, 'w') as f: f.write('interface=%s\ndriver=nl80211\n' % self.dev_w_ap) f.write(conf) log = os.path.join(self.workdir, 'hostapd.log') p = subprocess.Popen(['hostapd', '-e', self.entropy_file, '-f', log, hostapd_conf], stdout=subprocess.PIPE) self.addCleanup(p.wait) self.addCleanup(p.terminate) self.poll_text(log, '' + self.dev_w_ap + ': AP-ENABLED') def start_dnsmasq(self, ipv6_mode, iface): '''Start dnsmasq. If ipv6_mode is None, IPv4 is set up with DHCP. If it is not None, it must be a valid dnsmasq mode, i. e. a combination of "ra-only", "slaac", "ra-stateless", and "ra-names". See dnsmasq(8). ''' if ipv6_mode is None: if iface == self.dev_e2_ap: dhcp_range = '192.168.6.10,192.168.6.200' else: dhcp_range = '192.168.5.10,192.168.5.200' else: if iface == self.dev_e2_ap: dhcp_range = '2601::10,2601::20' else: dhcp_range = '2600::10,2600::20' if ipv6_mode: dhcp_range += ',' + ipv6_mode self.dnsmasq_log = os.path.join(self.workdir, 'dnsmasq-%s.log' % iface) lease_file = os.path.join(self.workdir, 'dnsmasq-%s.leases' % iface) p = subprocess.Popen(['dnsmasq', '--keep-in-foreground', '--log-queries', '--log-facility=' + self.dnsmasq_log, '--conf-file=/dev/null', '--dhcp-leasefile=' + lease_file, '--bind-interfaces', '--interface=' + iface, '--except-interface=lo', '--enable-ra', '--dhcp-range=' + dhcp_range]) self.addCleanup(p.wait) self.addCleanup(p.terminate) if ipv6_mode is not None: self.poll_text(self.dnsmasq_log, 'IPv6 router advertisement enabled') else: self.poll_text(self.dnsmasq_log, 'DHCP, IP range') def assert_iface_up(self, iface, expected_ip_a=None, unexpected_ip_a=None): '''Assert that client interface is up''' out = subprocess.check_output(['ip', 'a', 'show', 'dev', iface], universal_newlines=True) if 'bond' not in iface: self.assertIn('state UP', out) if expected_ip_a: for r in expected_ip_a: self.assertRegex(out, r, out) if unexpected_ip_a: for r in unexpected_ip_a: self.assertNotRegex(out, r, out) if iface == self.dev_w_client: out = subprocess.check_output(['iw', 'dev', iface, 'link'], universal_newlines=True) # self.assertIn('Connected to ' + self.mac_w_ap, out) self.assertIn('SSID: fake net', out) def generate_and_settle(self): '''Generate config, launch and settle NM and networkd''' # regenerate netplan config subprocess.check_call(['netplan', 'apply']) # start NM so that we can verify that it does not manage anything subprocess.check_call(['systemctl', 'start', '--no-block', 'NetworkManager.service']) # wait until networkd is done if self.is_active('systemd-networkd.service'): if subprocess.call(['/lib/systemd/systemd-networkd-wait-online', '--quiet', '--timeout=50']) != 0: subprocess.call(['journalctl', '-b', '--no-pager', '-t', 'systemd-networkd']) st = subprocess.check_output(['networkctl'], stderr=subprocess.PIPE, universal_newlines=True) st_e = subprocess.check_output(['networkctl', 'status', self.dev_e_client], stderr=subprocess.PIPE, universal_newlines=True) st_e2 = subprocess.check_output(['networkctl', 'status', self.dev_e2_client], stderr=subprocess.PIPE, universal_newlines=True) self.fail('timed out waiting for networkd to settle down:\n%s\n%s\n%s' % (st, st_e, st_e2)) if subprocess.call(['nm-online', '--quiet', '--timeout=120', '--wait-for-startup']) != 0: self.fail('timed out waiting for NetworkManager to settle down') def nm_wait_connected(self, iface, timeout): for t in range(timeout): try: out = subprocess.check_output(['nmcli', 'dev', 'show', iface]) except subprocess.CalledProcessError: out = b'' if b'(connected' in out: break time.sleep(1) else: self.fail('timed out waiting for %s to get connected by NM:\n%s' % (iface, out.decode())) @classmethod def is_active(klass, unit): '''Check if given unit is active or activating''' p = subprocess.Popen(['systemctl', 'is-active', unit], stdout=subprocess.PIPE) out = p.communicate()[0] return p.returncode == 0 or out.startswith(b'activating') class _CommonTests: def test_eth_and_bridge(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: %(ec)s: dhcp4: yes accept-ra: no ethbr: match: {name: %(e2c)s} accept-ra: no bridges: mybr: interfaces: [ethbr] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) # ensure that they do not get managed by NM for foreign backends expected_state = (self.backend == 'NetworkManager') and 'connected' or 'unmanaged' out = subprocess.check_output(['nmcli', 'dev'], universal_newlines=True) for i in [self.dev_e_client, self.dev_e2_client, 'mybr']: self.assertRegex(out, '%s\s+(ethernet|bridge)\s+%s' % (i, expected_state)) def test_eth_mtu(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: %(ec)s: dhcp4: yes enmtus: match: {name: %(e2c)s} mtu: 1492 dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['inet 192.168.6.[0-9]+/24']) out = subprocess.check_output(['ip', 'a', 'show', self.dev_e2_client], universal_newlines=True) self.assertTrue('mtu 1492' in out, "checking MTU, should be 1492") def test_eth_mac(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: %(ec)s: dhcp4: yes enmac: match: {name: %(e2c)s} macaddress: 00:01:02:03:04:05 dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e2_client, ['inet 192.168.6.[0-9]+/24', '00:01:02:03:04:05'], ['master']) out = subprocess.check_output(['ip', 'link', 'show', self.dev_e2_client], universal_newlines=True) self.assertTrue('ether 00:01:02:03:04:05' in out) subprocess.check_call(['ip', 'link', 'set', self.dev_e2_client, 'address', self.dev_e2_client_mac]) def test_bridge_path_cost(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: {name: %(e2c)s} accept-ra: no bridges: mybr: interfaces: [ethbr] parameters: path-cost: ethbr: 50 stp: false dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) with open('/sys/class/net/mybr/brif/%s/path_cost' % self.dev_e2_client) as f: self.assertEqual(f.read().strip(), '50') def test_bridge_ageing_time(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: {name: %(e2c)s} accept-ra: no bridges: mybr: interfaces: [ethbr] parameters: ageing-time: 21 stp: false dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) with open('/sys/class/net/mybr/bridge/ageing_time') as f: self.assertEqual(f.read().strip(), '2100') def test_bridge_max_age(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: {name: %(e2c)s} accept-ra: no bridges: mybr: interfaces: [ethbr] parameters: max-age: 12 stp: false dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) with open('/sys/class/net/mybr/bridge/max_age') as f: self.assertEqual(f.read().strip(), '1200') def test_bridge_hello_time(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: {name: %(e2c)s} accept-ra: no bridges: mybr: interfaces: [ethbr] parameters: hello-time: 1 stp: false dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) with open('/sys/class/net/mybr/bridge/hello_time') as f: self.assertEqual(f.read().strip(), '100') def test_bridge_priority(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: {name: %(e2c)s} accept-ra: no bridges: mybr: interfaces: [ethbr] parameters: priority: 16384 stp: false dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) with open('/sys/class/net/mybr/bridge/priority') as f: self.assertEqual(f.read().strip(), '16384') def test_bridge_forward_delay(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: {name: %(e2c)s} accept-ra: no bridges: mybr: interfaces: [ethbr] parameters: forward-delay: 10 stp: false dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) with open('/sys/class/net/mybr/bridge/forward_delay') as f: self.assertEqual(f.read().strip(), '1000') def test_bridge_stp_false(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: {name: %(e2c)s} accept-ra: no bridges: mybr: interfaces: [ethbr] parameters: hello-time: 100000 max-age: 100000 stp: false dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) with open('/sys/class/net/mybr/bridge/stp_state') as f: self.assertEqual(f.read().strip(), '0') def test_bond_base(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: interfaces: [ethbn] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) def test_bond_primary_slave(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: %(ec)s: accept-ra: no %(e2c)s: accept-ra: no bonds: mybond: interfaces: [%(ec)s, %(e2c)s] parameters: mode: active-backup primary: %(ec)s addresses: [ '10.10.10.1/24' ]''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 10.10.10.1/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: result = f.read().strip() self.assertIn(self.dev_e_client, result) self.assertIn(self.dev_e2_client, result) with open('/sys/class/net/mybond/bonding/primary') as f: self.assertEqual(f.read().strip(), '%(ec)s' % {'ec': self.dev_e_client}) def test_bond_all_slaves_active(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: accept-ra: no bonds: mybond: interfaces: [ethbn] parameters: all-slaves-active: true dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/all_slaves_active') as f: self.assertEqual(f.read().strip(), '1') def test_bond_mode_8023ad(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: accept-ra: no bonds: mybond: parameters: mode: 802.3ad interfaces: [ethbn] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/mode') as f: self.assertEqual(f.read().strip(), '802.3ad 4') def test_bond_mode_8023ad_adselect(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: accept-ra: no bonds: mybond: parameters: mode: 802.3ad ad-select: bandwidth interfaces: [ethbn] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/ad_select') as f: self.assertEqual(f.read().strip(), 'bandwidth 1') def test_bond_mode_8023ad_lacp_rate(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: parameters: mode: 802.3ad lacp-rate: fast interfaces: [ethbn] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/lacp_rate') as f: self.assertEqual(f.read().strip(), 'fast 1') def test_bond_mode_activebackup_failover_mac(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: parameters: mode: active-backup fail-over-mac-policy: follow interfaces: [ethbn] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/mode') as f: self.assertEqual(f.read().strip(), 'active-backup 1') with open('/sys/class/net/mybond/bonding/fail_over_mac') as f: self.assertEqual(f.read().strip(), 'follow 2') def test_bond_mode_balance_xor(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: parameters: mode: balance-xor interfaces: [ethbn] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/mode') as f: self.assertEqual(f.read().strip(), 'balance-xor 2') def test_bond_mode_balance_rr(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: parameters: mode: balance-rr interfaces: [ethbn] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/mode') as f: self.assertEqual(f.read().strip(), 'balance-rr 0') def test_bond_mode_balance_rr_pps(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: parameters: mode: balance-rr packets-per-slave: 15 interfaces: [ethbn] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/mode') as f: self.assertEqual(f.read().strip(), 'balance-rr 0') with open('/sys/class/net/mybond/bonding/packets_per_slave') as f: self.assertEqual(f.read().strip(), '15') def test_bond_resend_igmp(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no ethb2: match: {name: %(e2c)s} accept-ra: no bonds: mybond: interfaces: [ethbn, ethb2] parameters: mode: balance-rr resend-igmp: 100 dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: result = f.read().strip() self.assertIn(self.dev_e_client, result) self.assertIn(self.dev_e2_client, result) with open('/sys/class/net/mybond/bonding/resend_igmp') as f: self.assertEqual(f.read().strip(), '100') @unittest.skip("fails due to networkd bug setting routes with dhcp") def test_routes_v4_with_dhcp(self): self.setup_eth(None) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: %(ec)s: dhcp4: yes routes: - to: 10.10.10.0/24 via: 192.168.5.254 metric: 99''' % {'r': self.backend, 'ec': self.dev_e_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24']) # from DHCP self.assertIn(b'default via 192.168.5.1', # from DHCP subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'10.10.10.0/24 via 192.168.5.254', # from static route subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'metric 99', # check metric from static route subprocess.check_output(['ip', 'route', 'show', '10.10.10.0/24'])) def test_routes_v4(self): self.setup_eth(None) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: %(ec)s: addresses: - 192.168.5.99/24 gateway4: 192.168.5.1 routes: - to: 10.10.10.0/24 via: 192.168.5.254 metric: 99''' % {'r': self.backend, 'ec': self.dev_e_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24']) # from DHCP self.assertIn(b'default via 192.168.5.1', # from DHCP subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'10.10.10.0/24 via 192.168.5.254', # from DHCP subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'metric 99', # check metric from static route subprocess.check_output(['ip', 'route', 'show', '10.10.10.0/24'])) def test_manual_addresses(self): self.setup_eth(None) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: %(ec)s: addresses: ["172.16.42.99/18", "1234:FFFF::42/64"] dhcp4: yes %(e2c)s: addresses: ["172.16.1.2/24"] gateway4: "172.16.1.1" nameservers: addresses: [172.1.2.3] search: ["fakesuffix"] ''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 172.16.42.99/18', 'inet6 1234:ffff::42/64', 'inet 192.168.5.[0-9]+/24']) # from DHCP self.assert_iface_up(self.dev_e2_client, ['inet 172.16.1.2/24']) self.assertIn(b'default via 192.168.5.1', # from DHCP subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e_client])) self.assertNotIn(b'default', subprocess.check_output(['ip', '-6', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'default via 172.16.1.1', subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e2_client])) self.assertNotIn(b'default', subprocess.check_output(['ip', '-6', 'route', 'show', 'dev', self.dev_e2_client])) # ensure that they do not get managed by NM for foreign backends expected_state = (self.backend == 'NetworkManager') and 'connected' or 'unmanaged' out = subprocess.check_output(['nmcli', 'dev'], universal_newlines=True) for i in [self.dev_e_client, self.dev_e2_client]: self.assertRegex(out, '%s\s+(ethernet|bridge)\s+%s' % (i, expected_state)) with open('/etc/resolv.conf') as f: resolv_conf = f.read() if self.backend == 'NetworkManager' and nm_uses_dnsmasq: sys.stdout.write('[NM with dnsmasq] ') sys.stdout.flush() self.assertRegex(resolv_conf, 'search.*fakesuffix') # not easy to peek dnsmasq's brain, so check its logging out = subprocess.check_output(['journalctl', '--quiet', '-tdnsmasq', '-ocat', '--since=-30s'], universal_newlines=True) self.assertIn('nameserver 172.1.2.3', out) elif resolved_in_use(): sys.stdout.write('[resolved] ') sys.stdout.flush() out = subprocess.check_output(['systemd-resolve', '--status'], universal_newlines=True) self.assertIn('DNS Servers: 172.1.2.3', out) self.assertIn('DNS Domain: fakesuffix', out) else: sys.stdout.write('[/etc/resolv.conf] ') sys.stdout.flush() self.assertRegex(resolv_conf, 'search.*fakesuffix') # /etc/resolve.conf often already has three nameserver entries if 'nameserver 172.1.2.3' not in resolv_conf: self.assertGreaterEqual(resolv_conf.count('nameserver'), 3) # change the addresses, make sure that "apply" does not leave leftovers with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: %(ec)s: addresses: ["172.16.5.3/20", "9876:BBBB::11/70"] gateway6: "9876:BBBB::1" %(e2c)s: addresses: ["172.16.7.2/30", "4321:AAAA::99/80"] dhcp4: yes ''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.start_dnsmasq(None, self.dev_e2_ap) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 172.16.5.3/20'], ['inet 192.168.5', # old DHCP 'inet 172.16.42', # old static IPv4 'inet6 1234']) # old static IPv6 self.assert_iface_up(self.dev_e2_client, ['inet 172.16.7.2/30', 'inet6 4321:aaaa::99/80', 'inet 192.168.6.[0-9]+/24'], # from DHCP ['inet 172.16.1']) # old static IPv4 self.assertNotIn(b'default', subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'default via 9876:bbbb::1', subprocess.check_output(['ip', '-6', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'default via 192.168.6.1', # from DHCP subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e2_client])) self.assertNotIn(b'default', subprocess.check_output(['ip', '-6', 'route', 'show', 'dev', self.dev_e2_client])) def test_dhcp6(self): self.setup_eth('slaac') with open(self.config, 'w') as f: f.write('''network: version: 2 renderer: %(r)s ethernets: %(ec)s: {dhcp6: yes} %(e2c)s: {}''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet6 2600:'], ['inet 192.168']) def test_vlan(self): # we create two VLANs on e2c, and run dnsmasq on ID 2002 to test DHCP via VLAN self.setup_eth(None, start_dnsmasq=False) self.start_dnsmasq(None, self.dev_e2_ap) subprocess.check_call(['ip', 'link', 'add', 'link', self.dev_e2_ap, 'name', 'nptestsrv', 'type', 'vlan', 'id', '2002']) subprocess.check_call(['ip', 'a', 'add', '192.168.5.1/24', 'dev', 'nptestsrv']) subprocess.check_call(['ip', 'link', 'set', 'nptestsrv', 'up']) self.start_dnsmasq(None, 'nptestsrv') with open(self.config, 'w') as f: f.write('''network: version: 2 renderer: %(r)s ethernets: %(ec)s: {} myether: match: {name: %(e2c)s} dhcp4: yes vlans: nptestone: id: 1001 link: myether addresses: [10.9.8.7/24] nptesttwo: id: 2002 link: myether dhcp4: true ''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up('nptestone', ['nptestone@' + self.dev_e2_client, 'inet 10.9.8.7/24']) self.assert_iface_up('nptesttwo', ['nptesttwo@' + self.dev_e2_client, 'inet 192.168.5']) self.assertNotIn(b'default', subprocess.check_output(['ip', 'route', 'show', 'dev', 'nptestone'])) self.assertIn(b'default via 192.168.5.1', # from DHCP subprocess.check_output(['ip', 'route', 'show', 'dev', 'nptesttwo'])) def test_vlan_mac_address(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'myvlan'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} %(e2c)s: {} vlans: myvlan: id: 101 link: ethbn macaddress: aa:bb:cc:dd:ee:22 ''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up('myvlan', ['myvlan@' + self.dev_e_client]) with open('/sys/class/net/myvlan/address') as f: self.assertEqual(f.read().strip(), 'aa:bb:cc:dd:ee:22') def test_wifi_ipv4_open(self): self.setup_ap('hw_mode=b\nchannel=1\nssid=fake net', None) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s wifis: %(wc)s: dhcp4: yes access-points: "fake net": {} decoy: {}''' % {'r': self.backend, 'wc': self.dev_w_client}) self.generate_and_settle() # nm-online doesn't wait for wifis, argh if self.backend == 'NetworkManager': self.nm_wait_connected(self.dev_w_client, 60) self.assert_iface_up(self.dev_w_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assertIn(b'default via 192.168.5.1', # from DHCP subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_w_client])) if self.backend == 'NetworkManager': out = subprocess.check_output(['nmcli', 'dev', 'show', self.dev_w_client], universal_newlines=True) self.assertRegex(out, 'GENERAL.CONNECTION.*netplan-%s-fake net' % self.dev_w_client) self.assertRegex(out, 'IP4.DNS.*192.168.5.1') else: out = subprocess.check_output(['networkctl', 'status', self.dev_w_client], universal_newlines=True) self.assertRegex(out, 'DNS.*192.168.5.1') def test_wifi_ipv4_wpa2(self): self.setup_ap('''hw_mode=g channel=1 ssid=fake net wpa=1 wpa_key_mgmt=WPA-PSK wpa_pairwise=TKIP wpa_passphrase=12345678 ''', None) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s wifis: %(wc)s: dhcp4: yes access-points: "fake net": password: 12345678 decoy: {}''' % {'r': self.backend, 'wc': self.dev_w_client}) self.generate_and_settle() # nm-online doesn't wait for wifis, argh if self.backend == 'NetworkManager': self.nm_wait_connected(self.dev_w_client, 60) self.assert_iface_up(self.dev_w_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assertIn(b'default via 192.168.5.1', # from DHCP subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_w_client])) if self.backend == 'NetworkManager': out = subprocess.check_output(['nmcli', 'dev', 'show', self.dev_w_client], universal_newlines=True) self.assertRegex(out, 'GENERAL.CONNECTION.*netplan-%s-fake net' % self.dev_w_client) self.assertRegex(out, 'IP4.DNS.*192.168.5.1') else: out = subprocess.check_output(['networkctl', 'status', self.dev_w_client], universal_newlines=True) self.assertRegex(out, 'DNS.*192.168.5.1') def test_mix_bridge_on_bond(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'bond0'], stderr=subprocess.DEVNULL) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'br0'], stderr=subprocess.DEVNULL) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'br1'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s bridges: br0: interfaces: [bond0] addresses: ['192.168.0.2/24'] bonds: bond0: interfaces: [ethbn, ethb2] accept-ra: no parameters: mode: balance-rr ethernets: ethbn: match: {name: %(ec)s} accept-ra: no ethb2: match: {name: %(e2c)s} accept-ra: no ''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master bond0'], ['inet ']) self.assert_iface_up(self.dev_e2_client, ['master bond0'], ['inet ']) self.assert_iface_up('bond0', ['master br0']) ipaddr = subprocess.check_output(['ip', 'a', 'show', 'dev', 'br0'], universal_newlines=True) self.assertIn('inet 192.168', ipaddr) with open('/sys/class/net/bond0/bonding/slaves') as f: result = f.read().strip() self.assertIn(self.dev_e_client, result) self.assertIn(self.dev_e2_client, result) def test_mix_vlan_on_bridge_on_bond(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'bond0'], stderr=subprocess.DEVNULL) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'br0'], stderr=subprocess.DEVNULL) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'br1'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s version: 2 vlans: vlan1: link: 'br0' id: 1 addresses: [ '10.10.10.1/24' ] bridges: br0: interfaces: ['bond0', 'vlan2'] accept-ra: no parameters: stp: false path-cost: bond0: 1000 vlan2: 2000 bonds: bond0: interfaces: ['br1'] accept-ra: no parameters: mode: balance-rr bridges: br1: interfaces: ['ethb2'] accept-ra: no vlans: vlan2: link: ethbn id: 2 accept-ra: no ethernets: ethbn: match: {name: %(ec)s} accept-ra: no ethb2: match: {name: %(e2c)s} accept-ra: no ''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up('vlan1', ['vlan1@br0']) self.assert_iface_up('vlan2', ['vlan2@' + self.dev_e_client, 'master br0']) self.assert_iface_up(self.dev_e2_client, ['master br1'], ['inet ']) self.assert_iface_up('bond0', ['master br0']) class TestNetworkd(NetworkTestBase, _CommonTests): backend = 'networkd' @unittest.skip("networkd in xenial will block waiting for SLAAC") def test_eth_dhcp6_off(self): self.setup_eth('slaac') with open(self.config, 'w') as f: f.write('''network: version: 2 renderer: %(r)s ethernets: %(ec)s: dhcp6: no addresses: [ '192.168.1.100/24' ] %(e2c)s: {}''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet6 2600:'], []) def test_eth_dhcp6_off_no_accept_ra(self): self.setup_eth('slaac') with open(self.config, 'w') as f: f.write('''network: version: 2 renderer: %(r)s ethernets: %(ec)s: dhcp6: no accept-ra: no addresses: [ '192.168.1.100/24' ] %(e2c)s: {}''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, [], ['inet6 2600:']) def test_bond_mac(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: name: %(ec)s macaddress: %(ec_mac)s accept-ra: no bonds: mybond: interfaces: [ethbn] macaddress: 00:01:02:03:04:05 dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client, 'ec_mac': self.dev_e_client_mac}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24', '00:01:02:03:04:05']) def test_bridge_mac(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'br0'], stderr=subprocess.DEVNULL) self.start_dnsmasq(None, self.dev_e2_ap) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: name: %(ec)s macaddress: %(ec_mac)s accept-ra: no bridges: br0: interfaces: [ethbr] macaddress: 00:01:02:03:04:05 dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client, 'ec_mac': self.dev_e_client_mac}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master br0'], ['inet']) self.assert_iface_up('br0', ['inet 192.168.5.[0-9]+/24', '00:01:02:03:04:05']) def test_bond_down_delay(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: accept-ra: no bonds: mybond: interfaces: [ethbn] parameters: mode: active-backup mii-monitor-interval: 5s down-delay: 10s accept-ra: no dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/downdelay') as f: self.assertEqual(f.read().strip(), '10000') def test_bond_up_delay(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: active-backup mii-monitor-interval: 50ms up-delay: 50ms accept-ra: no dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/updelay') as f: self.assertEqual(f.read().strip(), '50') def test_bond_arp_interval(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: balance-xor arp-ip-targets: [ 192.168.5.1 ] arp-interval: 50s dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/arp_interval') as f: self.assertEqual(f.read().strip(), '50000') def test_bond_arp_targets(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: balance-xor arp-interval: 50s arp-ip-targets: [ 192.168.5.1 ] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/arp_ip_target') as f: self.assertEqual(f.read().strip(), '192.168.5.1') def test_bond_arp_all_targets(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: balance-xor arp-ip-targets: [192.168.5.1] arp-interval: 50s arp-all-targets: all arp-validate: all dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/arp_all_targets') as f: self.assertEqual(f.read().strip(), 'all 1') def test_bond_arp_validate(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} accept-ra: no %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: balance-xor arp-ip-targets: [192.168.5.1] arp-interval: 50s arp-validate: all dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/arp_validate') as f: self.assertEqual(f.read().strip(), 'all 3') def test_routes_v6(self): self.setup_eth(None) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: %(ec)s: addresses: ["9876:BBBB::11/70"] gateway6: "9876:BBBB::1" routes: - to: 2001:f00f:f00f::1/64 via: 9876:BBBB::5 metric: 799''' % {'r': self.backend, 'ec': self.dev_e_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet6 9876:bbbb::11/70']) self.assertNotIn(b'default', subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'default via 9876:bbbb::1', subprocess.check_output(['ip', '-6', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'2001:f00f:f00f::/64 via 9876:bbbb::5', subprocess.check_output(['ip', '-6', 'route', 'show', 'dev', self.dev_e_client])) self.assertIn(b'metric 799', subprocess.check_output(['ip', '-6', 'route', 'show', '2001:f00f:f00f::/64'])) def test_bridge_port_priority(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: {name: %(e2c)s} accept-ra: no bridges: mybr: interfaces: [ethbr] parameters: port-priority: ethbr: 42 stp: false dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) with open('/sys/class/net/mybr/brif/%s/priority' % self.dev_e2_client) as f: self.assertEqual(f.read().strip(), '42') class TestNetworkManager(NetworkTestBase, _CommonTests): backend = 'NetworkManager' @unittest.skip("SKIP 16.04: broken on 16.04 versions of linux/NetworkManager") def test_routes_v6(self): pass @unittest.skip("NetworkManager does not disable accept_ra: bug LP: #1704210") def test_eth_dhcp6_off(self): self.setup_eth('slaac') with open(self.config, 'w') as f: f.write('''network: version: 2 renderer: %(r)s ethernets: %(ec)s: dhcp6: no addresses: [ '192.168.1.100/24' ] %(e2c)s: {}''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, [], ['inet6 2600:']) @unittest.skip("NetworkManager does not support setting MAC for a bond") def test_bond_mac(self): pass @unittest.skip("NetworkManager does not support setting MAC for a bridge") def test_bridge_mac(self): pass def test_wifi_ap_open(self): # we use dev_w_client and dev_w_ap in switched roles here, to keep the # existing device blacklisting in NM; i. e. dev_w_client is the # NM-managed AP, and dev_w_ap the manually managed client with open(self.config, 'w') as f: f.write('''network: wifis: renderer: NetworkManager %(wc)s: dhcp4: yes access-points: "fake net": mode: ap''' % {'wc': self.dev_w_client}) self.generate_and_settle() # nm-online doesn't wait for wifis, argh self.nm_wait_connected(self.dev_w_client, 60) out = subprocess.check_output(['iw', 'dev', self.dev_w_client, 'info'], universal_newlines=True) self.assertIn('type AP', out) self.assertIn('ssid fake net', out) # connect the other end subprocess.check_call(['ip', 'link', 'set', self.dev_w_ap, 'up']) subprocess.check_call(['iw', 'dev', self.dev_w_ap, 'connect', 'fake net']) out = subprocess.check_output(['dhclient', '-1', '-v', self.dev_w_ap], stderr=subprocess.STDOUT, universal_newlines=True) self.assertIn('DHCPACK', out) out = subprocess.check_output(['iw', 'dev', self.dev_w_ap, 'info'], universal_newlines=True) self.assertIn('type managed', out) self.assertIn('ssid fake net', out) out = subprocess.check_output(['ip', 'a', 'show', self.dev_w_ap], universal_newlines=True) self.assertIn('state UP', out) self.assertIn('inet 10.', out) def test_bond_down_delay(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: active-backup mii-monitor-interval: 5000 down-delay: 10000 dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/downdelay') as f: self.assertEqual(f.read().strip(), '10000') def test_bond_up_delay(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: active-backup mii-monitor-interval: 5000 up-delay: 10000 dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/updelay') as f: self.assertEqual(f.read().strip(), '10000') def test_bond_arp_interval(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: balance-xor arp-ip-targets: [ 192.168.5.1 ] arp-interval: 50000 dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/arp_interval') as f: self.assertEqual(f.read().strip(), '50000') def test_bond_arp_targets(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: balance-xor arp-interval: 50000 arp-ip-targets: [ 192.168.5.1 ] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/arp_ip_target') as f: self.assertEqual(f.read().strip(), '192.168.5.1') @unittest.skip("SKIP 16.04: broken on 16.04 versions of linux/NetworkManager") def test_bond_arp_all_targets(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} %(e2c)s: {} bonds: mybond: interfaces: [ethbn] parameters: mode: balance-xor arp-ip-targets: [192.168.5.1] arp-interval: 50000 arp-all-targets: all arp-validate: all dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/arp_all_targets') as f: self.assertEqual(f.read().strip(), 'all 1') def test_bond_mode_balance_tlb_learn_interval(self): self.setup_eth(None) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybond'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbn: match: {name: %(ec)s} %(e2c)s: {} bonds: mybond: parameters: mode: balance-tlb mii-monitor-interval: 5000 learn-packet-interval: 15 interfaces: [ethbn] dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['master mybond'], ['inet ']) self.assert_iface_up('mybond', ['inet 192.168.5.[0-9]+/24']) with open('/sys/class/net/mybond/bonding/slaves') as f: self.assertEqual(f.read().strip(), self.dev_e_client) with open('/sys/class/net/mybond/bonding/mode') as f: self.assertEqual(f.read().strip(), 'balance-tlb 5') with open('/sys/class/net/mybond/bonding/lp_interval') as f: self.assertEqual(f.read().strip(), '15') def test_bridge_port_priority(self): self.setup_eth(None) self.start_dnsmasq(None, self.dev_e2_ap) self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], stderr=subprocess.DEVNULL) with open(self.config, 'w') as f: f.write('''network: renderer: %(r)s ethernets: ethbr: match: {name: %(e2c)s} bridges: mybr: interfaces: [ethbr] parameters: port-priority: ethbr: 42 stp: false dhcp4: yes''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client}) self.generate_and_settle() self.assert_iface_up(self.dev_e_client, ['inet 192.168.5.[0-9]+/24'], ['master']) self.assert_iface_up(self.dev_e2_client, ['master mybr'], ['inet ']) self.assert_iface_up('mybr', ['inet 192.168.6.[0-9]+/24']) lines = subprocess.check_output(['bridge', 'link', 'show', 'mybr'], universal_newlines=True).splitlines() self.assertEqual(len(lines), 1, lines) self.assertIn(self.dev_e2_client, lines[0]) with open('/sys/class/net/mybr/brif/%s/priority' % self.dev_e2_client) as f: self.assertEqual(f.read().strip(), '42') unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))