pax_global_header 0000666 0000000 0000000 00000000064 13646002212 0014506 g ustar 00root root 0000000 0000000 52 comment=522b156823facb499e5af38cc499eb5d9ad31d23
netplan.io-0.99/ 0000775 0000000 0000000 00000000000 13646002212 0013516 5 ustar 00root root 0000000 0000000 netplan.io-0.99/.github/ 0000775 0000000 0000000 00000000000 13646002212 0015056 5 ustar 00root root 0000000 0000000 netplan.io-0.99/.github/pull_request_template.md 0000664 0000000 0000000 00000000353 13646002212 0022020 0 ustar 00root root 0000000 0000000
## Description
## Checklist
- [ ] Runs `make check` successfully.
- [ ] Retains 100% code coverage (`make check-coverage`).
- [ ] New/changed keys in YAML format are documented.
- [ ] \(Optional\) Closes an open bug in Launchpad.
netplan.io-0.99/.gitignore 0000664 0000000 0000000 00000000244 13646002212 0015506 0 ustar 00root root 0000000 0000000 generate
netplan-dbus
test-coverage
doc/*.html
doc/*.[1-9]
__pycache__
*.pyc
.coverage
.vscode
src/_features.h
netplan/_features.py
dbus/io.netplan.Netplan.service
netplan.io-0.99/CONTRIBUTING 0000664 0000000 0000000 00000004747 13646002212 0015364 0 ustar 00root root 0000000 0000000 # Contributing to netplan.io
Thanks for taking the time to contribute to netplan!
Here are the guidelines for contributing to the development of netplan. These
are guidelines, not hard and fast rules; but please exercise judgement. Feel
free to propose changes to this document.
#### Table Of Contents
[Code of Conduct](#code-of-conduct)
[What should I know before I get started](#what-should-i-know-before-i-get-started)
* [Did you find a bug?](#did-you-find-a-bug)
* [Code Quality](#code-quality)
* [Conventions](#conventions)
## Code of Conduct
This project and everyone participating in it is governed by the
[Ubuntu Code of Conduct](https://www.ubuntu.com/community/code-of-conduct).
By participating, you are expected to uphold this code. Please report
unacceptable behavior to
[netplan-developers@lists.launchpad.net](mailto:netplan-developers@lists.launchpad.net).
## What should I know before I get started?
### Did you find a bug?
If you've found a bug, please make sure to report it on Launchpad against the
[netplan](http://bugs.launchpad.net/netplan) project. We do use these bug reports
to make it easier to backport features to supported releases of Ubuntu: having
an existing bug report, with people who understand well how the bug appears
helps immensely in making sure the feature or bug fix is well tested when it is
being released to supported Ubuntu releases.
### Code quality
We want to maintain the quality of the code in netplan to the highest possible
degree. As such, we do insist on keeping a code coverage with unit tests to 100%
coverage if it is possible. If not, please make sure to explain why when submitting
a pull request, and expect reviewers to challenge you on that decision and suggest
a course of action.
### Conventions
The netplan project mixes C and python code. Generator code is generally all
written in C, while the UI / command-line interface is written in python. Please
look at the surrounding code, and make a best effort to follow the general style
used in the code. We do insist on proper indentation (4 spaces), but we will
not block good features and bug fixes on purely style issues. Please exercise
your best judgement: if it looks odd or too clever to you, chances are it will
look odd or too clever to code reviewers. In that case, you may be asked for
some styles changes in a pull request. Similary, if you see code that you
find hard to understand, we do encourage that you submit pull requests that
help make the code easier to understand and maintain.
netplan.io-0.99/COPYING 0000664 0000000 0000000 00000104513 13646002212 0014555 0 ustar 00root root 0000000 0000000 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
.
netplan.io-0.99/Makefile 0000664 0000000 0000000 00000013115 13646002212 0015157 0 ustar 00root root 0000000 0000000 NETPLAN_SOVER=0.0
BUILDFLAGS = \
-g \
-fPIC \
-std=c99 \
-D_XOPEN_SOURCE=500 \
-DSBINDIR=\"$(SBINDIR)\" \
-Wall \
-Werror \
$(NULL)
SYSTEMD_GENERATOR_DIR=$(shell pkg-config --variable=systemdsystemgeneratordir systemd)
SYSTEMD_UNIT_DIR=$(shell pkg-config --variable=systemdsystemunitdir systemd)
BASH_COMPLETIONS_DIR=$(shell pkg-config --variable=completionsdir bash-completion || echo "/etc/bash_completion.d")
GCOV ?= gcov
ROOTPREFIX ?=
PREFIX ?= /usr
LIBDIR ?= $(PREFIX)/lib
ROOTLIBEXECDIR ?= $(ROOTPREFIX)/lib
LIBEXECDIR ?= $(PREFIX)/lib
SBINDIR ?= $(PREFIX)/sbin
DATADIR ?= $(PREFIX)/share
DOCDIR ?= $(DATADIR)/doc
MANDIR ?= $(DATADIR)/man
INCLUDEDIR ?= $(PREFIX)/include
PYCODE = netplan/ $(wildcard src/*.py) $(wildcard tests/*.py) $(wildcard tests/generator/*.py) $(wildcard tests/dbus/*.py)
# Order: Fedora/Mageia/openSUSE || Debian/Ubuntu || null
PYFLAKES3 ?= $(shell which pyflakes-3 || which pyflakes3 || echo true)
PYCODESTYLE3 ?= $(shell which pycodestyle-3 || which pycodestyle || which pep8 || echo true)
NOSETESTS3 ?= $(shell which nosetests-3 || which nosetests3 || echo true)
default: netplan/_features.py generate netplan-dbus dbus/io.netplan.Netplan.service doc/netplan.html doc/netplan.5 doc/netplan-generate.8 doc/netplan-apply.8 doc/netplan-try.8
%.o: src/%.c
$(CC) $(BUILDFLAGS) $(CFLAGS) $(LDFLAGS) -c $^ `pkg-config --cflags --libs glib-2.0 gio-2.0 yaml-0.1 uuid`
libnetplan.so.$(NETPLAN_SOVER): parse.o util.o validation.o error.o
$(CC) -shared -Wl,-soname,libnetplan.so.$(NETPLAN_SOVER) $(BUILDFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $^ `pkg-config --libs yaml-0.1`
ln -snf libnetplan.so.$(NETPLAN_SOVER) libnetplan.so
#generate: src/generate.[hc] src/parse.[hc] src/util.[hc] src/networkd.[hc] src/nm.[hc] src/validation.[hc] src/error.[hc]
generate: libnetplan.so.$(NETPLAN_SOVER) nm.o networkd.o generate.o
$(CC) $(BUILDFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $^ -L. -lnetplan `pkg-config --cflags --libs glib-2.0 gio-2.0 yaml-0.1 uuid`
netplan-dbus: src/dbus.c src/_features.h
$(CC) $(BUILDFLAGS) $(CFLAGS) $(LDFLAGS) -o $@ $^ `pkg-config --cflags --libs libsystemd glib-2.0`
src/_features.h: src/[^_]*.[hc]
printf "#include \nstatic const char *feature_flags[] __attribute__((__unused__)) = {\n" > $@
awk 'match ($$0, /netplan-feature:.*/ ) { $$0=substr($$0, RSTART, RLENGTH); print "\""$$2"\"," }' $^ >> $@
echo "NULL, };" >> $@
netplan/_features.py: src/[^_]*.[hc]
echo "# Generated file" > $@
echo "NETPLAN_FEATURE_FLAGS = [" >> $@
awk 'match ($$0, /netplan-feature:.*/ ) { $$0=substr($$0, RSTART, RLENGTH); print " \""$$2"\"," }' $^ >> $@
echo "]" >> $@
clean:
rm -f netplan/_features.py src/_features.h
rm -f generate doc/*.html doc/*.[1-9]
rm -f *.o *.so*
rm -f netplan-dbus dbus/*.service
rm -f *.gcda *.gcno generate.info
rm -rf test-coverage .coverage
check: default linting
tests/cli.py
$(NOSETESTS3) -v --with-coverage
tests/validate_docs.sh
linting:
$(PYFLAKES3) $(PYCODE)
$(PYCODESTYLE3) --max-line-length=130 $(PYCODE)
coverage: | pre-coverage c-coverage python-coverage
pre-coverage:
rm -f .coverage
$(MAKE) CFLAGS="-g -O0 --coverage" clean check
mkdir -p test-coverage/C test-coverage/python
check-coverage: coverage
@if grep headerCovTableEntryHi test-coverage/C/index.html | grep -qv '100.*%'; then \
echo "FAIL: Test coverage not 100%!" >&2; exit 1; \
fi
python3-coverage report --omit=/usr* --show-missing --fail-under=100
c-coverage:
lcov --directory . --capture --gcov-tool=$(GCOV) -o generate.info
lcov --remove generate.info "/usr*" -o generate.info
genhtml -o test-coverage/C/ -t "generate test coverage" generate.info
python-coverage:
python3-coverage html -d test-coverage/python --omit=/usr* || true
python3-coverage xml --omit=/usr* || true
install: default
mkdir -p $(DESTDIR)/$(SBINDIR) $(DESTDIR)/$(ROOTLIBEXECDIR)/netplan $(DESTDIR)/$(SYSTEMD_GENERATOR_DIR) $(DESTDIR)/$(LIBDIR)
mkdir -p $(DESTDIR)/$(MANDIR)/man5 $(DESTDIR)/$(MANDIR)/man8
mkdir -p $(DESTDIR)/$(DOCDIR)/netplan/examples
mkdir -p $(DESTDIR)/$(DATADIR)/netplan/netplan
mkdir -p $(DESTDIR)/$(INCLUDEDIR)/netplan
install -m 755 generate $(DESTDIR)/$(ROOTLIBEXECDIR)/netplan/
find netplan/ -name '*.py' -exec install -Dm 644 "{}" "$(DESTDIR)/$(DATADIR)/netplan/{}" \;
install -m 755 src/netplan.script $(DESTDIR)/$(DATADIR)/netplan/
ln -srf $(DESTDIR)/$(DATADIR)/netplan/netplan.script $(DESTDIR)/$(SBINDIR)/netplan
ln -srf $(DESTDIR)/$(ROOTLIBEXECDIR)/netplan/generate $(DESTDIR)/$(SYSTEMD_GENERATOR_DIR)/netplan
# lib
install -m 644 *.so.* $(DESTDIR)/$(LIBDIR)/
ln -snf libnetplan.so.$(NETPLAN_SOVER) $(DESTDIR)/$(LIBDIR)/libnetplan.so
# headers, dev data
install -m 644 src/*.h $(DESTDIR)/$(INCLUDEDIR)/netplan/
# TODO: install pkg-config once available
# docs, data
install -m 644 doc/*.html $(DESTDIR)/$(DOCDIR)/netplan/
install -m 644 examples/*.yaml $(DESTDIR)/$(DOCDIR)/netplan/examples/
install -m 644 doc/*.5 $(DESTDIR)/$(MANDIR)/man5/
install -m 644 doc/*.8 $(DESTDIR)/$(MANDIR)/man8/
install -T -D -m 644 netplan.completions $(DESTDIR)/$(BASH_COMPLETIONS_DIR)/netplan
# dbus
mkdir -p $(DESTDIR)/$(DATADIR)/dbus-1/system.d $(DESTDIR)/$(DATADIR)/dbus-1/system-services
install -m 755 netplan-dbus $(DESTDIR)/$(ROOTLIBEXECDIR)/netplan/
install -m 644 dbus/io.netplan.Netplan.conf $(DESTDIR)/$(DATADIR)/dbus-1/system.d/
install -m 644 dbus/io.netplan.Netplan.service $(DESTDIR)/$(DATADIR)/dbus-1/system-services/
%.service: %.service.in
sed -e "s#@ROOTLIBEXECDIR@#$(ROOTLIBEXECDIR)#" $< > $@
%.html: %.md
pandoc -s --toc -o $@ $<
doc/netplan.5: doc/manpage-header.md doc/netplan.md doc/manpage-footer.md
pandoc -s -o $@ $^
%.8: %.md
pandoc -s -o $@ $^
.PHONY: clean
netplan.io-0.99/README.md 0000664 0000000 0000000 00000001701 13646002212 0014774 0 ustar 00root root 0000000 0000000 # netplan - Backend-agnostic network configuration in YAML
[](https://semaphoreci.com/cyphermox/netplan)
[](https://codecov.io/gh/CanonicalLtd/netplan)
[](https://build.snapcraft.io/user/CanonicalLtd/netplan)
# Website
http://netplan.io
# Documentation
The full documentation for netplan is available in the [doc/netplan.md file](../master/doc/netplan.md)
# Bug reports
Please file bug reports in [Launchpad](https://bugs.launchpad.net/netplan/+filebug).
# Contact us
Please join us on IRC on Freenode, in #netplan.
Our mailing list is [here](https://lists.launchpad.net/netplan-developers/).
Email the list at [netplan-developers@lists.launchpad.net](mailto:netplan-developers@lists.launchpad.net).
netplan.io-0.99/TODO 0000664 0000000 0000000 00000002362 13646002212 0014211 0 ustar 00root root 0000000 0000000 - improve IPv6 RA handling
- support tunnel device types
- support ethtool/sysctl knobs (TSO, LRO, txqueuelen)
- inspecting current network config via "netplan show $interface" for a
collated view of each interface's yaml.
- debugging config generation via "netplan diff [backend|system]":
- netplan diff system: compare generated config with current ip addr output
- netplan diff backend: compare generated config with current config for backend
- support other devices types from networkd/NetworkManager:
- infiniband
- veth
- better handle VLAN Q-in-Q (mostly generation tweaks + patching backends)
- support device aliases (eth0 + eth0.1; add eth0 to multiple bridges)
- workaround for two bridges is to use eth0 and vlan1
- make errors translatable
- "netplan save" to capture kernel state into netplan YAML.
- better parsing/validation for time-based values (ie. bond, bridge params)
- openvswitch integration
- wpa enterprise support
- better parsing/validation for all schema
- improve exit codes / behavior on error
- integrate 'netplan try' in tmux/screen
- replace nose for python tests with something else, preserving coverage reports
- add automated integration tests for WPA Enterprise / 802.1x that can run self-contained
netplan.io-0.99/dbus/ 0000775 0000000 0000000 00000000000 13646002212 0014453 5 ustar 00root root 0000000 0000000 netplan.io-0.99/dbus/io.netplan.Netplan.conf 0000664 0000000 0000000 00000000766 13646002212 0021002 0 ustar 00root root 0000000 0000000
netplan.io-0.99/dbus/io.netplan.Netplan.service.in 0000664 0000000 0000000 00000000175 13646002212 0022114 0 ustar 00root root 0000000 0000000 [D-BUS Service]
Name=io.netplan.Netplan
Exec=@ROOTLIBEXECDIR@/netplan/netplan-dbus
User=root
AssumedAppArmorLabel=unconfined
netplan.io-0.99/doc/ 0000775 0000000 0000000 00000000000 13646002212 0014263 5 ustar 00root root 0000000 0000000 netplan.io-0.99/doc/example-config 0000664 0000000 0000000 00000003463 13646002212 0017112 0 ustar 00root root 0000000 0000000 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
netplan.io-0.99/doc/manpage-footer.md 0000664 0000000 0000000 00000000200 13646002212 0017501 0 ustar 00root root 0000000 0000000 # SEE ALSO
**netplan-generate**(8), **netplan-apply**(8), **netplan-try**(8), **systemd-networkd**(8), **NetworkManager**(8)
netplan.io-0.99/doc/manpage-header.md 0000664 0000000 0000000 00000000545 13646002212 0017447 0 ustar 00root root 0000000 0000000 ---
title: netplan
section: 5
author:
- Mathieu Trudel-Lapierre ()
- Martin Pitt ()
...
# NAME
netplan - YAML network configuration abstraction for various backends
# SYNOPSIS
**netplan** [ *COMMAND* | help ]
# COMMANDS
See **netplan help** for a list of available commands on this system.
# DESCRIPTION
netplan.io-0.99/doc/netplan-apply.md 0000664 0000000 0000000 00000003171 13646002212 0017373 0 ustar 00root root 0000000 0000000 ---
title: netplan-apply
section: 8
author:
- Daniel Axtens ()
...
# NAME
netplan-apply - apply configuration from netplan YAML files to a running system
# SYNOPSIS
**netplan** [--debug] **apply** -h | --help
**netplan** [--debug] **apply**
# DESCRIPTION
**netplan apply** applies the current netplan configuration to a running system.
The process works as follows:
1. The backend configuration is generated from netplan YAML files.
2. The appropriate backends (**systemd-networkd**(8) or
**NetworkManager**(8)) are invoked to bring up configured interfaces.
3. **netplan apply** iterates through interfaces that are still down, unbinding
them from their drivers, and rebinding them. This gives **udev**(7) renaming
rules the opportunity to run.
4. If any devices have been rebound, the appropriate backends are re-invoked in
case more matches can be done.
For information about the generation step, see
**netplan-generate**(8). For details of the configuration file format,
see **netplan**(5).
# OPTIONS
-h, --help
: Print basic help.
--debug
: Print debugging output during the process.
# KNOWN ISSUES
**netplan apply** will not remove virtual devices such as bridges
and bonds that have been created, even if they are no longer described
in the netplan configuration.
This can be resolved by manually removing the virtual device (for
example ``ip link delete dev bond0``) and then running **netplan
apply**, or by rebooting.
# SEE ALSO
**netplan**(5), **netplan-generate**(8), **netplan-try**(8), **udev**(7),
**systemd-networkd.service**(8), **NetworkManager**(8)
netplan.io-0.99/doc/netplan-generate.md 0000664 0000000 0000000 00000004630 13646002212 0020041 0 ustar 00root root 0000000 0000000 ---
title: netplan-generate
section: 8
author:
- Daniel Axtens ()
...
# NAME
netplan-generate - generate backend configuration from netplan YAML files
# SYNOPSIS
**netplan** [--debug] **generate** -h | --help
**netplan** [--debug] **generate** [--root-dir _ROOT_DIR_] [--mapping _MAPPING_]
# DESCRIPTION
netplan generate converts netplan YAML into configuration files
understood by the backends (**systemd-networkd**(8) or
**NetworkManager**(8)). It *does not* apply the generated
configuration.
You will not normally need to run this directly as it is run by
**netplan apply**, **netplan try**, or at boot.
For details of the configuration file format, see **netplan**(5).
# OPTIONS
-h, --help
: Print basic help.
--debug
: Print debugging output during the process.
--root-dir _ROOT_DIR_
: Instead of looking in /{lib,etc,run}/netplan, look in
/_ROOT_DIR_/{lib,etc,run}/netplan
--mapping _MAPPING_
: Instead of generating output files, parse the configuration files
and print some internal information about the device specified in
_MAPPING_.
# HANDLING MULTIPLE FILES
There are 3 locations that netplan generate considers:
* /lib/netplan/*.yaml
* /etc/netplan/*.yaml
* /run/netplan/*.yaml
If there are multiple files with exactly the same name, then only one
will be read. A file in /run/netplan will shadow - completely replace
- a file with the same name in /etc/netplan. A file in /etc/netplan
will itself shadow a file in /lib/netplan.
Or in other words, /run/netplan is top priority, then /etc/netplan,
with /lib/netplan having the lowest priority.
If there are files with different names, then they are considered in
lexicographical order - regardless of the directory they are in. Later
files add to or override earlier files. For example,
/run/netplan/10-foo.yaml would be updated by /lib/netplan/20-abc.yaml.
If you have two files with the same key/setting, the following rules
apply:
* If the values are YAML boolean or scalar values (numbers and
strings) the old value is overwritten by the new value.
* If the values are sequences, the sequences are concatenated - the
new values are appended to the old list.
* If the values are mappings, netplan will examine the elements
of the mappings in turn using these rules.
# SEE ALSO
**netplan**(5), **netplan-apply**(8), **netplan-try**(8),
**systemd-networkd**(8), **NetworkManager**(8)
netplan.io-0.99/doc/netplan-try.md 0000664 0000000 0000000 00000003135 13646002212 0017064 0 ustar 00root root 0000000 0000000 ---
title: netplan-try
section: 8
author:
- Daniel Axtens ()
...
# NAME
netplan-try - try a configuration, optionally rolling it back
# SYNOPSIS
**netplan** [--debug] **try** -h | --help
**netplan** [--debug] **try** [--config-file _CONFIG_FILE_] [--timeout _TIMEOUT_]
# DESCRIPTION
**netplan try** takes a **netplan**(5) configuration, applies it, and
automatically rolls it back if the user does not confirm the
configuration within a time limit.
This may be especially useful on remote systems, to prevent an
administrator being permanently locked out of systems in the case of a
network configuration error.
# OPTIONS
-h, --help
: Print basic help.
--debug
: Print debugging output during the process.
--config-file _CONFIG_FILE_
: In addition to the usual configuration, apply _CONFIG_FILE_. It must
be a YAML file in the **netplan**(5) format.
--timeout _TIMEOUT_
: Wait for _TIMEOUT_ seconds before reverting. Defaults to 120
seconds. Note that some network configurations (such as STP) may take
over a minute to settle.
# KNOWN ISSUES
**netplan try** uses similar procedures to **netplan apply**, so some
of the same caveats apply around virtual devices.
There are also some known bugs: if **netplan try** times out or is
cancelled, make sure to verify if the network configuration has in
fact been reverted.
As with **netplan apply**, a reboot should fix any issues. However, be
sure to verify that the config on disk is in the state you expect
before rebooting!
# SEE ALSO
**netplan**(5), **netplan-generate**(8), **netplan-apply**(8)
netplan.io-0.99/doc/netplan.md 0000664 0000000 0000000 00000131050 13646002212 0016246 0 ustar 00root root 0000000 0000000 ## 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:``, ``modems:``, ``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.
If an interface is defined with an ID in a configuration file; it will be
brought up by the applicable renderer. To not have netplan touch an interface
at all, it should be completely omitted from the netplan configuration files.
There are two physically/structurally different classes of device definitions,
and the ID field has a different interpretation for each:
Physical devices
: (Examples: ethernet, modem, 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.
``emit-lldp`` (bool)
: (networkd backend only) Whether to emit LLDP packets. 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``.
The ``renderer`` property has one additional acceptable value for vlan objects
(i. e. defined in ``vlans:``): ``sriov``. If a vlan is defined with the ``sriov``
renderer for an SR-IOV Virtual Function interface, this causes netplan to set
up a hardware VLAN filter for it. There can be only one defined per VF.
``dhcp4`` (bool)
: Enable DHCP for IPv4. Off by default.
``dhcp6`` (bool)
: Enable DHCP for IPv6. Off by default. This covers both stateless DHCP -
where the DHCP server supplies information like DNS nameservers but not the
IP address - and stateful DHCP, where the server provides both the address
and the other information.
If you are in an IPv6-only environment with completely stateless
autoconfiguration (SLAAC with RDNSS), this option can be set to cause the
interface to be brought up. (Setting accept-ra alone is not sufficient.)
Autoconfiguration will still honour the contents of the router advertisement
and only use DHCP if requested in the RA.
Note that **``rdnssd``**(8) is required to use RDNSS with networkd. No extra
software is required for NetworkManager.
``ipv6-mtu`` (scalar)
: Set the IPv6 MTU (only supported with `networkd` backend). Note
that needing to set this is an unusual requirement.
**Requires feature: ipv6-mtu**
``ipv6-privacy`` (bool)
: Enable IPv6 Privacy Extensions (RFC 4941) for the specified interface, and
prefer temporary addresses. Defaults to false - no privacy extensions. There
is currently no way to have a private address but prefer the public address.
``link-local`` (sequence of scalars)
: Configure the link-local addresses to bring up. Valid options are 'ipv4'
and 'ipv6', which respectively allow enabling IPv4 and IPv6 link local
addressing. If this field is not defined, the default is to enable only
IPv6 link-local addresses. If the field is defined but configured as an
empty set, IPv6 link-local addresses are disabled as well as IPv4 link-
local addresses.
This feature enables or disables link-local addresses for a protocol, but
the actual implementation differs per backend. On networkd, this directly
changes the behavior and may add an extra address on an interface. When
using the NetworkManager backend, enabling link-local has no effect if the
interface also has DHCP enabled.
Example to enable only IPv4 link-local: ``link-local: [ ipv4 ]``
Example to enable all link-local addresses: ``link-local: [ ipv4, ipv6 ]``
Example to disable all link-local addresses: ``link-local: [ ]``
``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 assigned IP when the daemon is restarted.
``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.
``dhcp4-overrides`` (mapping)
: (networkd backend only) Overrides default DHCP behavior; see the
``DHCP Overrides`` section below.
``dhcp6-overrides`` (mapping)
: (networkd backend only) Overrides default DHCP behavior; see the
``DHCP Overrides`` section below.
``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.
For virtual devices (bridges, bonds, vlan) if there is no address
configured and DHCP is disabled, the interface may still be brought online,
but will not be addressable from the network.
Example: ``addresses: [192.168.14.2/24, "2001:1::1/64"]``
``ipv6-address-generation`` (scalar)
: Configure method for creating the address for use with RFC4862 IPv6
Stateless Address Autoconfiguration. Possible values are ``eui64``
or ``stable-privacy``.
``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".
**Note:** This will not work reliably for devices matched by name
only and rendered by networkd, due to interactions with device
renaming in udev. Match devices by MAC when setting MAC addresses.
Example:
ethernets:
id0:
match:
macaddress: 52:54:00:6b:3c:58
[...]
macaddress: 52:54:00:6b:3c:59
``mtu`` (scalar)
: Set the Maximum Transmission Unit for the interface. The default is 1500.
Valid values depend on your network interface.
**Note:** This will not work reliably for devices matched by name
only and rendered by networkd, due to interactions with device
renaming in udev. Match devices by MAC when setting MTU.
``optional`` (bool)
: 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
``optional-addresses`` (sequence of scalars)
: Specify types of addresses that are not required for a device to be
considered online. This changes the behavior of backends at boot time to
avoid waiting for addresses that are marked optional, and thus consider
the interface as "usable" sooner. This does not disable these addresses,
which will be brought up anyway.
Example:
ethernets:
eth7:
dhcp4: true
dhcp6: true
optional-addresses: [ ipv4-ll, dhcp6 ]
``routes`` (mapping)
: Configure static routing for the device; see the ``Routing`` section below.
``routing-policy`` (mapping)
: Configure policy routing for the device; see the ``Routing`` section below.
## DHCP Overrides
Several DHCP behavior overrides are available. Most currently only have any
effect when using the ``networkd`` backend, with the exception of ``use-routes``
and ``route-metric``.
Overrides only have an effect if the corresponding ``dhcp4`` or ``dhcp6`` is
set to ``true``.
If both ``dhcp4`` and ``dhcp6`` are ``true``, the ``networkd`` backend requires
that ``dhcp4-overrides`` and ``dhcp6-overrides`` contain the same keys and
values. If the values do not match, an error will be shown and the network
configuration will not be applied.
When using the NetworkManager backend, different values may be specified for
``dhcp4-overrides`` and ``dhcp6-overrides``, and will be applied to the DHCP
client processes as specified in the netplan YAML.
: The ``dhcp4-overrides`` and ``dhcp6-overrides`` mappings override the
default DHCP behavior.
``use-dns`` (bool)
: Default: ``true``. When ``true``, the DNS servers received from the
DHCP server will be used and take precedence over any statically
configured ones. Currently only has an effect on the ``networkd``
backend.
``use-ntp`` (bool)
: Default: ``true``. When ``true``, the NTP servers received from the
DHCP server will be used by systemd-timesyncd and take precedence
over any statically configured ones. Currently only has an effect on
the ``networkd`` backend.
``send-hostname`` (bool)
: Default: ``true``. When ``true``, the machine's hostname will be sent
to the DHCP server. Currently only has an effect on the ``networkd``
backend.
``use-hostname`` (bool)
: Default: ``true``. When ``true``, the hostname received from the DHCP
server will be set as the transient hostname of the system. Currently
only has an effect on the ``networkd`` backend.
``use-mtu`` (bool)
: Default: ``true``. When ``true``, the MTU received from the DHCP
server will be set as the MTU of the network interface. When ``false``,
the MTU advertised by the DHCP server will be ignored. Currently only
has an effect on the ``networkd`` backend.
``hostname`` (scalar)
: Use this value for the hostname which is sent to the DHCP server,
instead of machine's hostname. Currently only has an effect on the
``networkd`` backend.
``use-routes`` (bool)
: Default: ``true``. When ``true``, the routes received from the DHCP
server will be installed in the routing table normally. When set to
``false``, routes from the DHCP server will be ignored: in this case,
the user is responsible for adding static routes if necessary for
correct network operation. This allows users to avoid installing a
default gateway for interfaces configured via DHCP. Available for
both the ``networkd`` and ``NetworkManager`` backends.
``route-metric`` (scalar)
: Use this value for default metric for automatically-added routes.
Use this to prioritize routes for devices by setting a higher metric
on a preferred interface. Available for both the ``networkd`` and
``NetworkManager`` backends.
``use-domains`` (scalar)
: Takes a boolean, or the special value "route". When true, the domain
name received from the DHCP server will be used as DNS search domain
over this link, similar to the effect of the Domains= setting. If set
to "route", the domain name received from the DHCP server will be
used for routing DNS queries only, but not for searching, similar to
the effect of the Domains= setting when the argument is prefixed with
"~".
**Requires feature: dhcp-use-domains**
## Routing
Complex routing is possible with netplan. Standard static routes as well
as policy routing using routing tables are supported via the ``networkd``
backend.
These options are available for all types of interfaces.
``routes`` (mapping)
: The ``routes`` block defines standard static routes for an interface.
At least ``to`` and ``via`` must be specified.
For ``from``, ``to``, and ``via``, both IPv4 and IPv6 addresses are
recognized, and must be in the form ``addr/prefixlen`` or ``addr``.
``from`` (scalar)
: Set a source IP address for traffic going through the route.
``to`` (scalar)
: Destination address for the route.
``via`` (scalar)
: Address to the gateway to use for this route.
``on-link`` (bool)
: When set to "true", specifies that the route is directly connected
to the interface.
``metric`` (scalar)
: The relative priority of the route. Must be a positive integer value.
``type`` (scalar)
: The type of route. Valid options are "unicast" (default),
"unreachable", "blackhole" or "prohibit".
``scope`` (scalar)
: The route scope, how wide-ranging it is to the network. Possible
values are "global", "link", or "host".
``table`` (scalar)
: The table number to use for the route. In some scenarios, it may be
useful to set routes in a separate routing table. It may also be used
to refer to routing policy rules which also accept a ``table``
parameter. Allowed values are positive integers starting from 1.
Some values are already in use to refer to specific routing tables:
see ``/etc/iproute2/rt_tables``.
``routing-policy`` (mapping)
: The ``routing-policy`` block defines extra routing policy for a network,
where traffic may be handled specially based on the source IP, firewall
marking, etc.
For ``from``, ``to``, both IPv4 and IPv6 addresses are recognized, and
must be in the form ``addr/prefixlen`` or ``addr``.
``from`` (scalar)
: Set a source IP address to match traffic for this policy rule.
``to`` (scalar)
: Match on traffic going to the specified destination.
``table`` (scalar)
: The table number to match for the route. In some scenarios, it may be
useful to set routes in a separate routing table. It may also be used
to refer to routes which also accept a ``table`` parameter.
Allowed values are positive integers starting from 1.
Some values are already in use to refer to specific routing tables:
see ``/etc/iproute2/rt_tables``.
``priority`` (scalar)
: Specify a priority for the routing policy rule, to influence the order
in which routing rules are processed. A higher number means lower
priority: rules are processed in order by increasing priority number.
``mark`` (scalar)
: Have this routing policy rule match on traffic that has been marked
by the iptables firewall with this value. Allowed values are positive
integers starting from 1.
``type-of-service`` (scalar)
: Match this policy rule based on the type of service number applied to
the traffic.
## Authentication
Netplan supports advanced authentication settings for ethernet and wifi
interfaces, as well as individual wifi networks, by means of the ``auth`` block.
``auth`` (mapping)
: Specifies authentication settings for a device of type ``ethernets:``, or
an ``access-points:`` entry on a ``wifis:`` device.
The ``auth`` block supports the following properties:
``key-management`` (scalar)
: The supported key management modes are ``none`` (no key management);
``psk`` (WPA with pre-shared key, common for home wifi); ``eap`` (WPA
with EAP, common for enterprise wifi); and ``802.1x`` (used primarily
for wired Ethernet connections).
``password`` (scalar)
: The password string for EAP, or the pre-shared key for WPA-PSK.
The following properties can be used if ``key-management`` is ``eap``
or ``802.1x``:
``method`` (scalar)
: The EAP method to use. The supported EAP methods are ``tls`` (TLS),
``peap`` (Protected EAP), and ``ttls`` (Tunneled TLS).
``identity`` (scalar)
: The identity to use for EAP.
``anonymous-identity`` (scalar)
: The identity to pass over the unencrypted channel if the chosen EAP
method supports passing a different tunnelled identity.
``ca-certificate`` (scalar)
: Path to a file with one or more trusted certificate authority (CA)
certificates.
``client-certificate`` (scalar)
: Path to a file containing the certificate to be used by the client
during authentication.
``client-key`` (scalar)
: Path to a file containing the private key corresponding to
``client-certificate``.
``client-key-password`` (scalar)
: Password to use to decrypt the private key specified in
``client-key`` if it is encrypted.
``phase2-auth`` (scalar)
: Phase 2 authentication mechanism.
## Properties for device type ``ethernets:``
Ethernet device definitions, beyond common ones described above, also support
some additional properties that can be used for SR-IOV devices.
``link`` (scalar)
: (SR-IOV devices only) The ``link`` property declares the device as a
Virtual Function of the selected Physical Function device, as identified
by the given netplan id.
Example:
ethernets:
enp1: {...}
enp1s16f1:
link: enp1
``virtual-function-count`` (scalar)
: (SR-IOV devices only) In certain special cases VFs might need to be
configured outside of netplan. For such configurations ``virtual-function-count``
can be optionally used to set an explicit number of Virtual Functions for
the given Physical Function. If unset, the default is to create only as many
VFs as are defined in the netplan configuration. This should be used for special
cases only.
## Properties for device type ``modems:``
GSM/CDMA modem configuration is only supported for the ``NetworkManager`` backend. ``systemd-networkd`` does
not support modems.
``apn`` (scalar)
: Set the carrier APN (Access Point Name). This can be omitted if ``auto-config`` is enabled.
``auto-config`` (bool)
: Specify whether to try and autoconfigure the modem by doing a lookup of the carrier
against the Mobile Broadband Provider database. This may not work for all carriers.
``device-id`` (scalar)
: Specify the device ID (as given by the WWAN management service) of the modem to match.
This can be found using ``mmcli``.
``network-id`` (scalar)
: Specify the Network ID (GSM LAI format). If this is specified, the device will not roam networks.
``number`` (scalar)
: The number to dial to establish the connection to the mobile broadband network. (Deprecated for GSM)
``password`` (scalar)
: Specify the password used to authenticate with the carrier network. This can be omitted
if ``auto-config`` is enabled.
``pin`` (scalar)
: Specify the SIM PIN to allow it to operate if a PIN is set.
``sim-id`` (scalar)
: Specify the SIM unique identifier (as given by the WWAN management service) which this
connection applies to. If given, the connection will apply to any device also allowed by
``device-id`` which contains a SIM card matching the given identifier.
``sim-operator-id`` (scalar)
: Specify the MCC/MNC string (such as "310260" or "21601") which identifies the carrier that
this connection should apply to. If given, the connection will apply to any device also
allowed by ``device-id`` and ``sim-id`` which contains a SIM card provisioned by the given operator.
``username`` (scalar)
: Specify the username used to authentiate with the carrier network. This can be omitted if
``auto-config`` is enabled.
## 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 neither
this nor an ``auth`` block are given, the network is assumed to be
open. The setting
password: "S3kr1t"
is equivalent to
auth:
key-management: psk
password: "S3kr1t"
``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.
``bssid`` (scalar)
: If specified, directs the device to only associate with the given
access point.
``band`` (scalar)
: Possible bands are ``5GHz`` (for 5GHz 802.11a) and ``2.4GHz``
(for 2.4GHz 802.11), do not restrict the 802.11 frequency band of the
network if unset (the default).
``channel`` (scalar)
: Wireless channel to use for the Wi-Fi connection. Because channel
numbers overlap between bands, this property takes effect only if
the ``band`` property is also set.
``wakeonwlan`` (sequence of scalars)
: This enables WakeOnWLan on supported devices. Not all drivers support all
options. May be any combination of ``any``, ``disconnect``, ``magic_pkt``,
``gtk_rekey_failure``, ``eap_identity_req``, ``four_way_handshake``,
``rfkill_release`` or ``tcp`` (NetworkManager only). Or the exclusive
``default`` flag (the default).
## Properties for device type ``bridges:``
``interfaces`` (sequence of scalars)
: All devices matching this ID list will be added to the bridge. This may
be an empty list, in which case the bridge will be brought online with
no member interfaces.
Example:
ethernets:
switchports:
match: {name: "enp2*"}
[...]
bridges:
br0:
interfaces: [switchports]
``parameters`` (mapping)
: Customization parameters for special bridging options. Time intervals
may need to be expressed as a number of seconds or milliseconds: the
default value type is specified below. If necessary, time intervals can
be qualified using a time suffix (such as "s" for seconds, "ms" for
milliseconds) to allow for more control over its behavior.
``ageing-time`` (scalar)
: Set the period of time 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. If no time suffix is
specified, the value will be interpreted as seconds.
``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 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.
If no time suffix is specified, the value will be interpreted as
seconds.
``hello-time`` (scalar)
: Specify the interval 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. If no time suffix
is specified, the value will be interpreted as seconds.
``max-age`` (scalar)
: Set the maximum age 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. If no time suffix is specified, the value will be
interpreted as seconds.
``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. Time intervals
may need to be expressed as a number of seconds or milliseconds: the
default value type is specified below. If necessary, time intervals can
be qualified using a time suffix (such as "s" for seconds, "ms" for
milliseconds) to allow for more control over its behavior.
``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. If no time suffix is specified, the value will be
interpreted as milliseconds.
``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.
If no time suffix is specified, the value will be interpreted as
milliseconds.
``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. This option is only valid for the miimon
link monitor. If no time suffix is specified, the value will be
interpreted as milliseconds.
``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. This option is only valid for the
miimon link monitor. If no time suffix is specified, the value will
be interpreted as milliseconds.
``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``.
``gratuitous-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.
For historical reasons, the misspelling ``gratuitious-arp`` is also
accepted and has the same function.
``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 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. If no time suffix is
specified, the value will be interpreted as seconds.
``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 ``tunnels:``
Tunnels allow traffic to pass as if it was between systems on the same local
network, although systems may be far from each other but reachable via the
Internet. They may be used to support IPv6 traffic on a network where the ISP
does not provide the service, or to extend and "connect" separate local
networks. Please see https://en.wikipedia.org/wiki/Tunneling_protocol for
more general information about tunnels.
``mode`` (scalar)
: Defines the tunnel mode. Valid options are ``sit``, ``gre``, ``ip6gre``,
``ipip``, ``ipip6``, ``ip6ip6``, ``vti``, and ``vti6``. Additionally,
the ``networkd`` backend also supports ``gretap`` and ``ip6gretap`` modes.
In addition, the ``NetworkManager`` backend supports ``isatap`` tunnels.
``local`` (scalar)
: Defines the address of the local endpoint of the tunnel.
``remote`` (scalar)
: Defines the address of the remote endpoint of the tunnel.
``key`` (scalar or mapping)
: Define keys to use for the tunnel. The key can be a number or a dotted
quad (an IPv4 address). It is used for identification of IP transforms.
This is only required for ``vti`` and ``vti6`` when using the networkd
backend, and for ``gre`` or ``ip6gre`` tunnels when using the
NetworkManager backend.
This field may be used as a scalar (meaning that a single key is
specified and to be used for both input and output key), or as a mapping,
where you can then further specify ``input`` and ``output``.
``input`` (scalar)
: The input key for the tunnel
``output`` (scalar)
: The output key for the tunnel
Examples:
tunnels:
tun0:
mode: gre
local: ...
remote: ...
keys:
input: 1234
output: 5678
tunnels:
tun0:
mode: vti6
local: ...
remote: ...
key: 59568549
``keys`` (scalar or mapping)
: Alternate name for the ``key`` field. See above.
## 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
addresses: ...
## Backend-specific configuration parameters
In addition to the other fields available to configure interfaces, some
backends may require to record some of their own parameters in netplan,
especially if the netplan definitions are generated automatically by the
consumer of that backend. Currently, this is only used with ``NetworkManager``.
``networkmanager`` (mapping)
: Keeps the NetworkManager-specific configuration parameters used by the
daemon to recognize connections.
``name`` (scalar)
: Set the display name for the connection.
``uuid`` (scalar)
: Defines the UUID (unique identifier) for this connection, as
generated by NetworkManager itself.
``stable-id`` (scalar)
: Defines the stable ID (a different form of a connection name) used
by NetworkManager in case the name of the connection might otherwise
change, such as when sharing connections between users.
``device`` (scalar)
: Defines the interface name for which this connection applies.
## Examples
Configure an ethernet device with networkd, identified by its name, and enable
DHCP:
network:
version: 2
ethernets:
eno1:
dhcp4: true
This is an example of a static-configured interface with multiple IPv4 addresses
and multiple gateways with networkd, with equal route metric levels, and static
DNS nameservers (Google DNS for this example):
network:
version: 2
renderer: networkd
ethernets:
eno1:
addresses:
- 10.0.0.10/24
- 11.0.0.11/24
nameservers:
addresses:
- 8.8.8.8
- 8.8.4.4
routes:
- to: 0.0.0.0/0
via: 10.0.0.1
metric: 100
- to: 0.0.0.0/0
via: 11.0.0.1
metric: 100
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
- 192.168.14.3/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
table: 70
on-link: true
metric: 3
routing-policy:
- to: 10.0.0.0/8
from: 192.168.14.2/24
table: 70
priority: 100
- to: 20.0.0.0/8
from: 192.168.14.3/24
table: 70
priority: 50
# only networkd can render on-link routes and routing policies
renderer: networkd
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 the 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
netplan.io-0.99/examples/ 0000775 0000000 0000000 00000000000 13646002212 0015334 5 ustar 00root root 0000000 0000000 netplan.io-0.99/examples/bonding.yaml 0000664 0000000 0000000 00000000312 13646002212 0017634 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
bonds:
bond0:
dhcp4: yes
interfaces:
- enp3s0
- enp4s0
parameters:
mode: active-backup
primary: enp3s0
netplan.io-0.99/examples/bonding_router.yaml 0000664 0000000 0000000 00000001652 13646002212 0021244 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
enp1s0:
dhcp4: no
enp2s0:
dhcp4: no
enp3s0:
dhcp4: no
optional: true
enp4s0:
dhcp4: no
optional: true
enp5s0:
dhcp4: no
optional: true
enp6s0:
dhcp4: no
optional: true
bonds:
bond-lan:
interfaces: [enp2s0, enp3s0]
addresses: [192.168.93.2/24]
parameters:
mode: 802.3ad
mii-monitor-interval: 1
bond-wan:
interfaces: [enp1s0, enp4s0]
addresses: [192.168.1.252/24]
gateway4: 192.168.1.1
nameservers:
search: [local]
addresses: [8.8.8.8, 8.8.4.4]
parameters:
mode: active-backup
mii-monitor-interval: 1
gratuitious-arp: 5
bond-conntrack:
interfaces: [enp5s0, enp6s0]
addresses: [192.168.254.2/24]
parameters:
mode: balance-rr
mii-monitor-interval: 1
netplan.io-0.99/examples/bridge.yaml 0000664 0000000 0000000 00000000234 13646002212 0017453 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
enp3s0:
dhcp4: no
bridges:
br0:
dhcp4: yes
interfaces:
- enp3s0
netplan.io-0.99/examples/bridge_vlan.yaml 0000664 0000000 0000000 00000000365 13646002212 0020500 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
enp0s25:
dhcp4: true
bridges:
br0:
addresses: [ 10.3.99.25/24 ]
interfaces: [ vlan15 ]
vlans:
vlan15:
accept-ra: no
id: 15
link: enp0s25
netplan.io-0.99/examples/dhcp.yaml 0000664 0000000 0000000 00000000126 13646002212 0017135 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
enp3s0:
dhcp4: true
netplan.io-0.99/examples/dhcp_wired8021x.yaml 0000664 0000000 0000000 00000000330 13646002212 0021027 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
enp3s0:
dhcp4: true
auth:
key-management: 802.1x
method: ttls
identity: fluffy@cisco.com
password: hash:83...11
netplan.io-0.99/examples/direct_connect_gateway.yaml 0000664 0000000 0000000 00000000250 13646002212 0022721 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
addresses: [ "10.10.10.1/24" ]
routes:
- to: 0.0.0.0/0
via: 9.9.9.9
on-link: true
netplan.io-0.99/examples/direct_connect_gateway_ipv6.yaml 0000664 0000000 0000000 00000000375 13646002212 0023675 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
addresses: [ "2001:cafe:face:beef::dead:dead/64" ]
routes:
- to: "2001:cafe:face::1/128"
scope: link
- to: "::/0"
via: "2001:cafe:face::1"
on-link: true
netplan.io-0.99/examples/ipv6_tunnel.yaml 0000664 0000000 0000000 00000000467 13646002212 0020500 0 ustar 00root root 0000000 0000000 network:
version: 2
ethernets:
eth0:
addresses:
- 1.1.1.1/24
- "2001:cafe:face::1/64"
gateway4: 1.1.1.254
tunnels:
he-ipv6:
mode: sit
remote: 2.2.2.2
local: 1.1.1.1
addresses:
- "2001:dead:beef::2/64"
gateway6: "2001:dead:beef::1"
netplan.io-0.99/examples/loopback_interface.yaml 0000664 0000000 0000000 00000000176 13646002212 0022036 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
lo:
match:
name: lo
addresses: [ 7.7.7.7/32 ]
netplan.io-0.99/examples/modem.yaml 0000664 0000000 0000000 00000000550 13646002212 0017321 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: NetworkManager
modems:
cdc-wdm1:
mtu: 1600
apn: ISP.CINGULAR
username: ISP@CINGULARGPRS.COM
password: CINGULAR1
number: "*99#"
network-id: 24005
device-id: da812de91eec16620b06cd0ca5cbc7ea25245222
pin: 2345
sim-id: 89148000000060671234
sim-operator-id: 310260
netplan.io-0.99/examples/network_manager.yaml 0000664 0000000 0000000 00000000061 13646002212 0021400 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: NetworkManager
netplan.io-0.99/examples/route_metric.yaml 0000664 0000000 0000000 00000000277 13646002212 0020727 0 ustar 00root root 0000000 0000000 network:
version: 2
ethernets:
enred:
dhcp4: yes
dhcp4-overrides:
route-metric: 100
engreen:
dhcp4: yes
dhcp4-overrides:
route-metric: 200
netplan.io-0.99/examples/source_routing.yaml 0000664 0000000 0000000 00000001036 13646002212 0021267 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
ens3:
addresses:
- 192.168.3.30/24
dhcp4: no
routes:
- to: 192.168.3.0/24
via: 192.168.3.1
table: 101
routing-policy:
- from: 192.168.3.0/24
table: 101
ens5:
addresses:
- 192.168.5.24/24
dhcp4: no
gateway4: 192.168.5.1
routes:
- to: 192.168.5.0/24
via: 192.168.5.1
table: 102
routing-policy:
- from: 192.168.5.0/24
table: 102
netplan.io-0.99/examples/static.yaml 0000664 0000000 0000000 00000000357 13646002212 0017514 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
enp3s0:
addresses:
- 10.10.10.2/24
gateway4: 10.10.10.1
nameservers:
search: [mydomain,otherdomain]
addresses: [10.10.10.1, 1.1.1.1]
netplan.io-0.99/examples/static_multiaddress.yaml 0000664 0000000 0000000 00000000236 13646002212 0022270 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
enp3s0:
addresses:
- 10.100.1.38/24
- 10.100.1.39/24
gateway4: 10.100.1.1
netplan.io-0.99/examples/static_singlenic_multiip_multigateway.yaml 0000664 0000000 0000000 00000000531 13646002212 0026100 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
eno1:
addresses:
- 10.0.0.10/24
- 11.0.0.11/24
nameservers:
addresses:
- 8.8.8.8
- 8.8.4.4
routes:
- to: 0.0.0.0/0
via: 10.0.0.1
metric: 100
- to: 0.0.0.0/0
via: 11.0.0.1
metric: 100
netplan.io-0.99/examples/vlan.yaml 0000664 0000000 0000000 00000001107 13646002212 0017157 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
ethernets:
mainif:
match:
macaddress: "de:ad:be:ef:ca:fe"
set-name: mainif
addresses: [ "10.3.0.5/23" ]
gateway4: 10.3.0.1
nameservers:
addresses: [ "8.8.8.8", "8.8.4.4" ]
search: [ example.com ]
vlans:
vlan15:
id: 15
link: mainif
addresses: [ "10.3.99.5/24" ]
vlan10:
id: 10
link: mainif
addresses: [ "10.3.98.5/24" ]
nameservers:
addresses: [ "127.0.0.1" ]
search: [ domain1.example.com, domain2.example.com ]
netplan.io-0.99/examples/windows_dhcp_server.yaml 0000664 0000000 0000000 00000000133 13646002212 0022273 0 ustar 00root root 0000000 0000000 network:
version: 2
ethernets:
enp3s0:
dhcp4: yes
dhcp-identifier: mac
netplan.io-0.99/examples/wireless.yaml 0000664 0000000 0000000 00000000461 13646002212 0020056 0 ustar 00root root 0000000 0000000 network:
version: 2
renderer: networkd
wifis:
wlp2s0b1:
dhcp4: no
dhcp6: no
addresses: [192.168.0.21/24]
gateway4: 192.168.0.1
nameservers:
addresses: [192.168.0.1, 8.8.8.8]
access-points:
"network_ssid_name":
password: "**********"
netplan.io-0.99/examples/wpa_enterprise.yaml 0000664 0000000 0000000 00000001414 13646002212 0021247 0 ustar 00root root 0000000 0000000 network:
version: 2
wifis:
wl0:
access-points:
workplace:
auth:
key-management: eap
method: ttls
anonymous-identity: "@internal.example.com"
identity: "joe@internal.example.com"
password: "v3ryS3kr1t"
university:
auth:
key-management: eap
method: tls
anonymous-identity: "@cust.example.com"
identity: "cert-joe@cust.example.com"
ca-certificate: /etc/ssl/cust-cacrt.pem
client-certificate: /etc/ssl/cust-crt.pem
client-key: /etc/ssl/cust-key.pem
client-key-password: "d3cryptPr1v4t3K3y"
open-network:
auth:
key-management: none
dhcp4: yes
netplan.io-0.99/netplan.completions 0000664 0000000 0000000 00000001734 13646002212 0017442 0 ustar 00root root 0000000 0000000 # netplan(1) completion -*- shell-script -*-
_compgen_help()
{
local options=$1
shift
compgen -W '${options} help' $@
}
_netplan()
{
local cur prev words cword
_init_completion || return
case $prev in
netplan)
COMPREPLY=( $( _compgen_help 'apply generate ifupdown-migrate ip' "$cur" ) )
return
;;
apply|generate)
return
;;
ifupdown-migrate)
return
;;
ip)
COMPREPLY=( $( _compgen_help 'leases' -- "$cur" ) )
return
;;
leases)
if [ "${COMP_WORDS[COMP_CWORD-2]}" = "ip" ]; then
_available_interfaces -a
fi
return
;;
esac
if [[ $cur == -* ]]; then
COMPREPLY=( $( compgen -W '$( _parse_help "$1" )' -- "$cur" ) )
fi
} &&
complete -F _netplan netplan
# ex: ts=4 sw=4 et filetype=sh
netplan.io-0.99/netplan/ 0000775 0000000 0000000 00000000000 13646002212 0015157 5 ustar 00root root 0000000 0000000 netplan.io-0.99/netplan/__init__.py 0000664 0000000 0000000 00000001374 13646002212 0017275 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 .
from netplan.cli.core import Netplan
__all__ = [Netplan]
netplan.io-0.99/netplan/cli/ 0000775 0000000 0000000 00000000000 13646002212 0015726 5 ustar 00root root 0000000 0000000 netplan.io-0.99/netplan/cli/__init__.py 0000664 0000000 0000000 00000001301 13646002212 0020032 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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.io-0.99/netplan/cli/commands/ 0000775 0000000 0000000 00000000000 13646002212 0017527 5 ustar 00root root 0000000 0000000 netplan.io-0.99/netplan/cli/commands/__init__.py 0000664 0000000 0000000 00000002206 13646002212 0021640 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 .
from netplan.cli.commands.apply import NetplanApply
from netplan.cli.commands.generate import NetplanGenerate
from netplan.cli.commands.ip import NetplanIp
from netplan.cli.commands.migrate import NetplanMigrate
from netplan.cli.commands.try_command import NetplanTry
from netplan.cli.commands.info import NetplanInfo
__all__ = [
'NetplanApply',
'NetplanGenerate',
'NetplanIp',
'NetplanMigrate',
'NetplanTry',
'NetplanInfo',
]
netplan.io-0.99/netplan/cli/commands/apply.py 0000664 0000000 0000000 00000024651 13646002212 0021236 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018-2020 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
# Author: Ćukasz 'sil2100' Zemczak
#
# 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 apply command line'''
import logging
import os
import sys
import glob
import subprocess
import shutil
import netplan.cli.utils as utils
from netplan.configmanager import ConfigManager, ConfigurationError
from netplan.cli.sriov import apply_sriov_config
import netifaces
class NetplanApply(utils.NetplanCommand):
def __init__(self):
super().__init__(command_id='apply',
description='Apply current netplan config to running system',
leaf=True)
def run(self): # pragma: nocover (covered in autopkgtest)
self.func = NetplanApply.command_apply
self.parse_args()
self.run_command()
@staticmethod
def command_apply(run_generate=True, sync=False, exit_on_error=True): # 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 exit_on_error:
sys.exit(res)
elif res == 130:
raise PermissionError(
"failed to communicate with dbus service")
elif res == 1:
raise RuntimeError(
"failed to communicate with dbus service")
else:
return
old_files_networkd = bool(glob.glob('/run/systemd/network/*netplan-*'))
old_files_nm = bool(glob.glob('/run/NetworkManager/system-connections/netplan-*'))
generator_call = []
generate_out = None
if 'NETPLAN_PROFILE' in os.environ:
generator_call.extend(['valgrind', '--leak-check=full'])
generate_out = subprocess.STDOUT
generator_call.append(utils.get_generator_path())
if run_generate and subprocess.call(generator_call, stderr=generate_out) != 0:
if exit_on_error:
sys.exit(os.EX_CONFIG)
else:
raise ConfigurationError("the configuration could not be generated")
config_manager = ConfigManager()
devices = netifaces.interfaces()
# Re-start service when
# 1. We have configuration files for it
# 2. Previously we had config files for it but not anymore
# Ideally we should compare the content of the *netplan-* files before and
# after generation to minimize the number of re-starts, but the conditions
# above works too.
restart_networkd = bool(glob.glob('/run/systemd/network/*netplan-*'))
if not restart_networkd and old_files_networkd:
restart_networkd = True
restart_nm = bool(glob.glob('/run/NetworkManager/system-connections/netplan-*'))
if not restart_nm and old_files_nm:
restart_nm = True
# stop backends
if restart_networkd:
logging.debug('netplan generated networkd configuration changed, restarting networkd')
utils.systemctl_networkd('stop', sync=sync, extra_services=['netplan-wpa@*.service'])
else:
logging.debug('no netplan generated networkd configuration exists')
if restart_nm:
logging.debug('netplan generated NM configuration changed, restarting NM')
if utils.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:
utils.nmcli(['device', 'disconnect', device])
except subprocess.CalledProcessError:
pass
utils.systemctl_network_manager('stop', sync=sync)
else:
logging.debug('no netplan generated NM configuration exists')
# Refresh devices now; restarting a backend might have made something appear.
devices = netifaces.interfaces()
# evaluate config for extra steps we need to take (like renaming)
# for now, only applies to non-virtual (real) devices.
config_manager.parse()
changes = NetplanApply.process_link_changes(devices, config_manager)
# apply any SR-IOV related changes, if applicable
try:
apply_sriov_config(devices, config_manager)
except (ConfigurationError, RuntimeError) as e:
logging.error(str(e))
if exit_on_error:
sys.exit(1)
# if the interface is up, we can still apply some .link file changes
devices = netifaces.interfaces()
for device in devices:
logging.debug('netplan triggering .link rules for %s', device)
try:
subprocess.check_call(['udevadm', 'test-builtin',
'net_setup_link',
'/sys/class/net/' + device],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError:
logging.debug('Ignoring device without syspath: %s', device)
# apply renames to "down" devices
for iface, settings in changes.items():
if settings.get('name'):
subprocess.check_call(['ip', 'link', 'set',
'dev', iface,
'name', settings.get('name')],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
subprocess.check_call(['udevadm', 'settle'])
# (re)start backends
if restart_networkd:
netplan_wpa = [os.path.basename(f) for f in glob.glob('/run/systemd/system/*.wants/netplan-wpa@*.service')]
utils.systemctl_networkd('start', sync=sync, extra_services=netplan_wpa)
if restart_nm:
utils.systemctl_network_manager('start', sync=sync)
@staticmethod
def is_composite_member(composites, phy): # pragma: nocover (covered in autopkgtest)
"""
Is this physical interface a member of a 'composite' virtual
interface? (bond, bridge)
"""
for composite in composites:
for id, settings in composite.items():
members = settings.get('interfaces', [])
for iface in members:
if iface == phy:
return True
return False
@staticmethod
def process_link_changes(interfaces, config_manager): # pragma: nocover (covered in autopkgtest)
"""
Go through the pending changes and pick what needs special
handling. Only applies to "down" interfaces which can be safely
updated.
"""
changes = {}
phys = dict(config_manager.physical_interfaces)
composite_interfaces = [config_manager.bridges, config_manager.bonds]
# TODO (cyphermox): factor out some of this matching code (and make it
# pretty) in its own module.
matches = {'by-driver': {},
'by-mac': {},
}
for phy, settings in phys.items():
if not settings:
continue
if phy == 'renderer':
continue
newname = settings.get('set-name')
if not newname:
continue
match = settings.get('match')
if not match:
continue
driver = match.get('driver')
mac = match.get('macaddress')
if driver:
matches['by-driver'][driver] = newname
if mac:
matches['by-mac'][mac] = newname
# /sys/class/net/ens3/device -> ../../../virtio0
# /sys/class/net/ens3/device/driver -> ../../../../bus/virtio/drivers/virtio_net
for interface in interfaces:
if interface not in phys:
# do not rename virtual devices
logging.debug('Skipping non-physical interface: %s', interface)
continue
if NetplanApply.is_composite_member(composite_interfaces, interface):
logging.debug('Skipping composite member %s', interface)
# do not rename members of virtual devices. MAC addresses
# may be the same for all interface members.
continue
driver_name = utils.get_interface_driver_name(interface, only_down=True)
macaddress = utils.get_interface_macaddress(interface)
if driver_name in matches['by-driver']:
new_name = matches['by-driver'][driver_name]
logging.debug(new_name)
logging.debug(interface)
if new_name != interface:
changes.update({interface: {'name': new_name}})
if macaddress in matches['by-mac']:
new_name = matches['by-mac'][macaddress]
if new_name != interface:
changes.update({interface: {'name': new_name}})
logging.debug(changes)
return changes
netplan.io-0.99/netplan/cli/commands/generate.py 0000664 0000000 0000000 00000003666 13646002212 0021706 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 generate command line'''
import logging
import sys
import subprocess
import netplan.cli.utils as utils
class NetplanGenerate(utils.NetplanCommand):
def __init__(self):
super().__init__(command_id='generate',
description='Generate backend specific configuration files'
' from /etc/netplan/*.yaml',
leaf=True)
def run(self):
self.parser.add_argument('--root-dir',
help='Search for and generate configuration files in this root directory instead of /')
self.parser.add_argument('--mapping',
help='Display the netplan device ID/backend/interface name mapping and exit.')
self.func = self.command_generate
self.parse_args()
self.run_command()
def command_generate(self):
argv = [utils.get_generator_path()]
if self.root_dir:
argv += ['--root-dir', self.root_dir]
if self.mapping:
argv += ['--mapping', self.mapping]
logging.debug('command generate: running %s', argv)
# FIXME: os.execv(argv[0], argv) would be better but fails coverage
sys.exit(subprocess.call(argv))
netplan.io-0.99/netplan/cli/commands/info.py 0000664 0000000 0000000 00000004542 13646002212 0021041 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2019 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 info command line'''
import netplan.cli.utils as utils
import netplan._features
class NetplanInfo(utils.NetplanCommand):
def __init__(self):
super().__init__(command_id='info',
description='Show current netplan version and available features',
leaf=True)
def run(self): # pragma: nocover (covered in autopkgtest)
format_group = self.parser.add_mutually_exclusive_group(required=False)
format_group.add_argument('--json', dest='version_format', action='store_const',
const='json',
help='Output version and features in JSON format')
format_group.add_argument('--yaml', dest='version_format', action='store_const',
const='yaml',
help='Output version and features in YAML format')
self.func = self.command_info
self.parse_args()
self.run_command()
def command_info(self):
netplan_version = {
'netplan.io': {
'website': 'https://netplan.io/',
}
}
flags = netplan._features.NETPLAN_FEATURE_FLAGS
netplan_version['netplan.io'].update({'features': flags})
# Default to output in YAML format.
if self.version_format is None:
self.version_format = 'yaml'
if self.version_format == 'json':
import json
print(json.dumps(netplan_version, indent=2))
elif self.version_format == 'yaml':
import yaml
print(yaml.dump(netplan_version, indent=2, default_flow_style=False))
netplan.io-0.99/netplan/cli/commands/ip.py 0000664 0000000 0000000 00000014310 13646002212 0020510 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 ip command line'''
import logging
import os
import sys
import subprocess
from subprocess import CalledProcessError
import netplan.cli.utils as utils
lease_path = {
'networkd': {
'pattern': 'run/systemd/netif/leases/{lease_id}',
'method': 'ifindex',
},
'NetworkManager': {
'pattern': 'var/lib/NetworkManager/dhclient-{lease_id}-{interface}.lease',
'method': 'nm_connection',
},
}
class NetplanIp(utils.NetplanCommand):
def __init__(self):
super().__init__(command_id='ip',
description='Retrieve IP information from the system',
leaf=False)
def run(self):
self.command_leases = NetplanIpLeases()
# subcommand: leases
p_ip_leases = self.subparsers.add_parser('leases',
help='Display IP leases',
add_help=False)
p_ip_leases.set_defaults(func=self.command_leases.run, commandclass=self.command_leases)
self.parse_args()
self.run_command()
class NetplanIpLeases(utils.NetplanCommand):
def __init__(self):
super().__init__(command_id='ip leases',
description='Display IP leases',
leaf=True)
def run(self):
self.parser.add_argument('interface',
help='Interface for which to display IP lease settings.')
self.parser.add_argument('--root-dir',
help='Search for configuration files in this root directory instead of /')
self.func = self.command_ip_leases
self.parse_args()
self.run_command()
def command_ip_leases(self):
if self.interface == 'help': # pragma: nocover (covered in autopkgtest)
self.print_usage()
def find_lease_file(mapping):
def lease_method_ifindex():
ifindex_f = os.path.join('/sys/class/net', self.interface, 'ifindex')
try:
with open(ifindex_f) as f:
return f.readlines()[0].strip()
except Exception as e:
logging.debug('Cannot read file %s: %s', ifindex_f, str(e))
raise
def lease_method_nm_connection(): # pragma: nocover (covered in autopkgtest)
# FIXME: handle older versions of NM where 'nmcli dev show' doesn't exist
try:
nmcli_dev_out = subprocess.Popen(['nmcli', 'dev', 'show', self.interface],
env={'LC_ALL': 'C'},
stdout=subprocess.PIPE)
for line in nmcli_dev_out.stdout:
line = line.decode('utf-8')
if 'GENERAL.CONNECTION' in line:
conn_id = line.split(':')[1].rstrip().strip()
nmcli_con_out = subprocess.Popen(['nmcli', 'con', 'show', 'id', conn_id],
env={'LC_ALL': 'C'},
stdout=subprocess.PIPE)
for line in nmcli_con_out.stdout:
line = line.decode('utf-8')
if 'connection.uuid' in line:
return line.split(':')[1].rstrip().strip()
except Exception as e:
raise Exception('Could not find a NetworkManager connection for the interface: %s' % str(e))
raise Exception('Could not find a NetworkManager connection for the interface')
lease_pattern = lease_path[mapping['backend']]['pattern']
lease_method = lease_path[mapping['backend']]['method']
try:
lease_id = eval("lease_method_" + lease_method)()
# We found something to build the path to the lease file with,
# at this point we may have something to look at; but if not,
# we'll rely on open() throwing an error.
# This might happen if networkd doesn't use DHCP for the interface,
# for instance.
with open(os.path.join('/',
os.path.abspath(self.root_dir) if self.root_dir else "",
lease_pattern.format(interface=self.interface,
lease_id=lease_id))) as f:
for line in f.readlines():
print(line.rstrip())
except Exception as e:
print("No lease found for interface '%s': %s" % (self.interface, str(e)),
file=sys.stderr)
sys.exit(1)
argv = [utils.get_generator_path()]
if self.root_dir:
argv += ['--root-dir', self.root_dir]
argv += ['--mapping', self.interface]
# Extract out of the generator our mapping in a dict.
logging.debug('command ip leases: running %s', argv)
try:
out = subprocess.check_output(argv, universal_newlines=True)
except CalledProcessError: # pragma: nocover (better be covered in autopkgtest)
sys.exit(1)
mapping = {}
mapping_s = out.split(',')
for keyvalue in mapping_s:
key, value = keyvalue.strip().split('=')
mapping[key] = value
find_lease_file(mapping)
netplan.io-0.99/netplan/cli/commands/migrate.py 0000664 0000000 0000000 00000047227 13646002212 0021545 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 migrate command line'''
import logging
import os
import sys
import re
from glob import glob
import yaml
from collections import OrderedDict
import ipaddress
import netplan.cli.utils as utils
class NetplanMigrate(utils.NetplanCommand):
def __init__(self):
super().__init__(command_id='migrate',
description='Migration of /etc/network/interfaces to netplan',
leaf=True,
testing=True)
def parse_dns_options(self, if_options, if_config):
"""Parse dns options (dns-nameservers and dns-search) from if_options
(an interface options dict) into the interface configuration if_config
Mutates the arguments in place.
"""
if 'dns-nameservers' in if_options:
if 'nameservers' not in if_config:
if_config['nameservers'] = {}
if 'addresses' not in if_config['nameservers']:
if_config['nameservers']['addresses'] = []
for ns in if_options['dns-nameservers'].split(' '):
# allow multiple spaces in the dns-nameservers entry
if not ns:
continue
# validate?
if_config['nameservers']['addresses'] += [ns]
del if_options['dns-nameservers']
if 'dns-search' in if_options:
if 'nameservers' not in if_config:
if_config['nameservers'] = {}
if 'search' not in if_config['nameservers']:
if_config['nameservers']['search'] = []
for domain in if_options['dns-search'].split(' '):
# allow multiple spaces in the dns-search entry
if not domain:
continue
if_config['nameservers']['search'] += [domain]
del if_options['dns-search']
def parse_mtu(self, iface, if_options, if_config):
"""Parse out the MTU. Operates the same way as parse_dns_options
iface is the name of the interface, used only to print error messages
"""
if 'mtu' in if_options:
try:
mtu = int(if_options['mtu'])
except ValueError:
logging.error('%s: cannot parse "%s" as an MTU', iface, if_options['mtu'])
sys.exit(2)
if 'mtu' in if_config and not if_config['mtu'] == mtu:
logging.error('%s: tried to set MTU=%d, but already have MTU=%d', iface, mtu, if_config['mtu'])
sys.exit(2)
if_config['mtu'] = mtu
del if_options['mtu']
def parse_hwaddress(self, iface, if_options, if_config):
"""Parse out the manually configured MAC.
Operates the same way as parse_dns_options
iface is the name of the interface, used only to print error messages
"""
if 'hwaddress' in if_options:
if 'macaddress' in if_config and not if_config['macaddress'] == if_options['hwaddress']:
logging.error('%s: tried to set MAC %s, but already have MAC %s', iface,
if_options['hwaddress'], if_config['macaddress'])
sys.exit(2)
if_config['macaddress'] = if_options['hwaddress']
del if_options['hwaddress']
def run(self):
self.parser.add_argument('--root-dir',
help='Search for and generate configuration files in this root directory instead of /')
self.parser.add_argument('--dry-run', action='store_true',
help='Print converted netplan configuration to stdout instead of writing/changing files')
self.func = self.command_migrate
self.parse_args()
self.run_command()
def command_migrate(self):
netplan_config = {}
try:
ifaces, auto_ifaces = self.parse_ifupdown(self.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':
c = netplan_config.setdefault('network', {}).setdefault('ethernets', {}).setdefault(iface, {})
self.parse_dns_options(config['options'], c)
self.parse_hwaddress(iface, config['options'], c)
if config['options']:
logging.error('%s: option(s) %s are not supported for dhcp method',
iface, ", ".join(config['options'].keys()))
sys.exit(2)
if family == 'inet':
c['dhcp4'] = True
else:
assert family == 'inet6'
c['dhcp6'] = True
elif config['method'] == 'static':
c = netplan_config.setdefault('network', {}).setdefault('ethernets', {}).setdefault(iface, {})
if 'addresses' not in c:
c['addresses'] = []
self.parse_dns_options(config['options'], c)
self.parse_mtu(iface, config['options'], c)
self.parse_hwaddress(iface, config['options'], c)
# ipv4
if family == 'inet':
# Already handled: mtu, hwaddress
# Supported: address netmask gateway
# Not supported yet: metric(?)
# No YAML support: pointopoint scope broadcast
supported_opts = set(['address', 'netmask', 'gateway'])
unsupported_opts = set(['broadcast', 'metric', 'pointopoint', 'scope'])
opts = set(config['options'].keys())
bad_opts = opts - supported_opts
if bad_opts:
for unsupported in bad_opts.intersection(unsupported_opts):
logging.error('%s: unsupported %s option "%s"', iface, family, unsupported)
sys.exit(2)
for unknown in bad_opts - unsupported_opts:
logging.error('%s: unknown %s option "%s"', iface, family, unknown)
sys.exit(2)
# the address may contain a /prefix suffix, or
# the netmask property may be used. It's not clear
# what happens if both are supplied.
if 'address' not in config['options']:
logging.error('%s: no address supplied in static method', iface)
sys.exit(2)
if '/' in config['options']['address']:
addr_spec = config['options']['address'].split('/')[0]
net_spec = config['options']['address']
else:
if 'netmask' not in config['options']:
logging.error('%s: address does not specify prefix length, and netmask not specified',
iface)
sys.exit(2)
addr_spec = config['options']['address']
net_spec = config['options']['address'] + '/' + config['options']['netmask']
try:
ipaddr = ipaddress.IPv4Address(addr_spec)
except ipaddress.AddressValueError as a:
logging.error('%s: error parsing "%s" as an IPv4 address: %s', iface, addr_spec, a)
sys.exit(2)
try:
ipnet = ipaddress.IPv4Network(net_spec, strict=False)
except ipaddress.NetmaskValueError as a:
logging.error('%s: error parsing "%s" as an IPv4 network: %s', iface, net_spec, a)
sys.exit(2)
c['addresses'] += [str(ipaddr) + '/' + str(ipnet.prefixlen)]
if 'gateway' in config['options']:
# validate?
c['gateway4'] = config['options']['gateway']
# ipv6
else:
assert family == 'inet6'
# Already handled: mtu, hwaddress
# supported: address netmask gateway
# partially supported: accept_ra (0/1 supported, 2 has no YAML rep)
# unsupported: metric(?)
# no YAML representation: media autoconf privext scope
# preferred-lifetime dad-attempts dad-interval
supported_opts = set(['address', 'netmask', 'gateway', 'accept_ra'])
unsupported_opts = set(['metric', 'media', 'autoconf', 'privext',
'scope', 'preferred-lifetime', 'dad-attempts', 'dad-interval'])
opts = set(config['options'].keys())
bad_opts = opts - supported_opts
if bad_opts:
for unsupported in bad_opts.intersection(unsupported_opts):
logging.error('%s: unsupported %s option "%s"', iface, family, unsupported)
sys.exit(2)
for unknown in bad_opts - unsupported_opts:
logging.error('%s: unknown %s option "%s"', iface, family, unknown)
sys.exit(2)
# the address may contain a /prefix suffix, or
# the netmask property may be used. It's not clear
# what happens if both are supplied.
if 'address' not in config['options']:
logging.error('%s: no address supplied in static method', iface)
sys.exit(2)
if '/' in config['options']['address']:
addr_spec = config['options']['address'].split('/')[0]
net_spec = config['options']['address']
else:
if 'netmask' not in config['options']:
logging.error('%s: address does not specify prefix length, and netmask not specified',
iface)
sys.exit(2)
addr_spec = config['options']['address']
net_spec = config['options']['address'] + '/' + config['options']['netmask']
try:
ipaddr = ipaddress.IPv6Address(addr_spec)
except ipaddress.AddressValueError as a:
logging.error('%s: error parsing "%s" as an IPv6 address: %s', iface, addr_spec, a)
sys.exit(2)
try:
ipnet = ipaddress.IPv6Network(net_spec, strict=False)
except ipaddress.NetmaskValueError as a:
logging.error('%s: error parsing "%s" as an IPv6 network: %s', iface, net_spec, a)
sys.exit(2)
c['addresses'] += [str(ipaddr) + '/' + str(ipnet.prefixlen)]
if 'gateway' in config['options']:
# validate?
c['gateway6'] = config['options']['gateway']
if 'accept_ra' in config['options']:
if config['options']['accept_ra'] == '0':
c['accept_ra'] = False
elif config['options']['accept_ra'] == '1':
c['accept_ra'] = True
elif config['options']['accept_ra'] == '2':
logging.error('%s: netplan does not support accept_ra=2', iface)
sys.exit(2)
else:
logging.error('%s: unexpected accept_ra value "%s"', iface,
config['options']['accept_ra'])
sys.exit(2)
else: # pragma nocover
# this should be unreachable
logging.error('%s: method %s is not supported', iface, config['method'])
sys.exit(2)
if_config = os.path.join(self.root_dir or '/', 'etc/network/interfaces')
if netplan_config:
netplan_config['network']['version'] = 2
netplan_yaml = yaml.dump(netplan_config)
if self.dry_run:
print(netplan_yaml)
else:
dest = os.path.join(self.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 self.dry_run:
logging.info('renaming %s to %s.netplan-converted', if_config, if_config)
os.rename(if_config, if_config + '.netplan-converted')
def _ifupdown_lines_from_file(self, 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 += self._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 += self._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(self, 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 = self._ifupdown_lines_from_file(rootdir, '/etc/network/interfaces')
ifaces = OrderedDict()
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], OrderedDict())[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)
netplan.io-0.99/netplan/cli/commands/try_command.py 0000664 0000000 0000000 00000016261 13646002212 0022423 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 try command line'''
import os
import time
import signal
import sys
import logging
import subprocess
from netplan.configmanager import ConfigManager
import netplan.cli.utils as utils
from netplan.cli.commands.apply import NetplanApply
import netplan.terminal
# Keep a timeout long enough to allow the network to converge, 60 seconds may
# be slightly short given some complex configs, i.e. if STP must reconverge.
DEFAULT_INPUT_TIMEOUT = 120
class NetplanTry(utils.NetplanCommand):
def __init__(self):
super().__init__(command_id='try',
description='Try to apply a new netplan config to running '
'system, with automatic rollback',
leaf=True)
self.configuration_changed = False
self.new_interfaces = None
self._config_manager = None
self.t_settings = None
self.t = None
@property
def config_manager(self): # pragma: nocover (called by later commands)
if not self._config_manager:
self._config_manager = ConfigManager()
return self._config_manager
def run(self): # pragma: nocover (requires user input)
self.parser.add_argument('--config-file',
help='Apply the config file in argument in addition to current configuration.')
self.parser.add_argument('--timeout',
type=int, default=DEFAULT_INPUT_TIMEOUT,
help="Maximum number of seconds to wait for the user's confirmation")
self.func = self.command_try
self.parse_args()
self.run_command()
def command_try(self): # pragma: nocover (requires user input)
if not self.is_revertable():
sys.exit(os.EX_CONFIG)
try:
fd = sys.stdin.fileno()
self.t = netplan.terminal.Terminal(fd)
self.t.save(self.t_settings)
# we really don't want to be interrupted while doing backup/revert operations
signal.signal(signal.SIGINT, self._signal_handler)
self.backup()
self.setup()
NetplanApply.command_apply(run_generate=True, sync=True, exit_on_error=False)
self.t.get_confirmation_input(timeout=self.timeout)
except netplan.terminal.InputRejected:
print("\nReverting.")
self.revert()
except netplan.terminal.InputAccepted:
print("\nConfiguration accepted.")
except Exception as e:
print("\nAn error occurred: %s" % e)
print("\nReverting.")
self.revert()
finally:
if self.t:
self.t.reset(self.t_settings)
self.cleanup()
def backup(self): # pragma: nocover (requires user input)
backup_config_dir = False
if self.config_file:
backup_config_dir = True
self.config_manager.backup(backup_config_dir=backup_config_dir)
def setup(self): # pragma: nocover (requires user input)
if self.config_file:
dest_dir = os.path.join("/", "etc", "netplan")
dest_name = os.path.basename(self.config_file).rstrip('.yaml')
dest_suffix = time.time()
dest_path = os.path.join(dest_dir, "{}.{}.yaml".format(dest_name, dest_suffix))
self.config_manager.add({self.config_file: dest_path})
self.configuration_changed = True
def revert(self): # pragma: nocover (requires user input)
self.config_manager.revert()
NetplanApply.command_apply(run_generate=False, sync=True, exit_on_error=False)
for ifname in self.new_interfaces:
if ifname not in self.config_manager.bonds and \
ifname not in self.config_manager.bridges and \
ifname not in self.config_manager.vlans:
logging.debug("{} will not be removed: not a virtual interface".format(ifname))
continue
try:
cmd = ['ip', 'link', 'del', ifname]
subprocess.check_call(cmd)
except subprocess.CalledProcessError:
logging.warn("Could not revert (remove) new interface '{}'".format(ifname))
def cleanup(self): # pragma: nocover (requires user input)
self.config_manager.cleanup()
def is_revertable(self): # pragma: nocover (requires user input)
'''
Check if the configuration is revertable, if it doesn't contain bits
that we know are likely to render the system unstable if we apply it,
or if we revert.
Returns True if the parsed config is "revertable", meaning that we
can actually rely on backends to re-apply /all/ of the relevant
configuration to interfaces when their config changes.
Returns False if the parsed config contains options that are known
to not cleanly revert via the backend.
'''
# Parse; including any new config file passed on the command-line:
# new config might include things we can't revert.
extra_config = []
if self.config_file:
extra_config.append(self.config_file)
self.config_manager.parse(extra_config=extra_config)
self.new_interfaces = self.config_manager.new_interfaces
logging.debug("New interfaces: {}".format(self.new_interfaces))
revert_unsupported = []
# Bridges and bonds are special. They typically include (or could include)
# more than one device in them, and they can be set with special parameters
# to tweak their behavior, which are really hard to "revert", especially
# as systemd-networkd doesn't necessarily touch them when config changes.
multi_iface = {}
multi_iface.update(self.config_manager.bridges)
multi_iface.update(self.config_manager.bonds)
for ifname, settings in multi_iface.items():
if settings and 'parameters' in settings:
reason = "reverting custom parameters for bridges and bonds is not supported"
revert_unsupported.append((ifname, reason))
if revert_unsupported:
for ifname, reason in revert_unsupported:
print("{}: {}".format(ifname, reason))
print("\nPlease carefully review the configuration and use 'netplan apply' directly.")
return False
return True
def _signal_handler(self, signal, frame): # pragma: nocover (requires user input)
if self.configuration_changed:
raise netplan.terminal.InputRejected()
netplan.io-0.99/netplan/cli/core.py 0000664 0000000 0000000 00000002770 13646002212 0017236 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Martin Pitt
# Author: Mathieu Trudel-Lapierre
#
# 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 logging
import os
import netplan.cli.utils as utils
class Netplan(utils.NetplanCommand):
def __init__(self):
super().__init__(command_id='',
description='Network configuration in YAML',
leaf=False)
def parse_args(self):
import netplan.cli.commands
self._import_subcommands(netplan.cli.commands)
super().parse_args()
def main(self):
self.parse_args()
if self.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')
self.run_command()
netplan.io-0.99/netplan/cli/sriov.py 0000664 0000000 0000000 00000031460 13646002212 0017446 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2020 Canonical, Ltd.
# Author: Ćukasz 'sil2100' Zemczak
#
# 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 logging
import os
import subprocess
from collections import defaultdict
import netplan.cli.utils as utils
from netplan.configmanager import ConfigurationError
import netifaces
def _get_target_interface(interfaces, config_manager, pf_link, pfs):
if pf_link not in pfs:
# handle the match: syntax, get the actual device name
pf_match = config_manager.ethernets[pf_link].get('match')
if pf_match:
by_name = pf_match.get('name')
by_mac = pf_match.get('macaddress')
by_driver = pf_match.get('driver')
for interface in interfaces:
if ((by_name and not utils.is_interface_matching_name(interface, by_name)) or
(by_mac and not utils.is_interface_matching_macaddress(interface, by_mac)) or
(by_driver and not utils.is_interface_matching_driver_name(interface, by_driver))):
continue
# we have a matching PF
# store the matching interface in the dictionary of
# active PFs, but error out if we matched more than one
if pf_link in pfs:
raise ConfigurationError('matched more than one interface for a PF device: %s' % pf_link)
pfs[pf_link] = interface
else:
# no match field, assume entry name is interface name
if pf_link in interfaces:
pfs[pf_link] = pf_link
return pfs.get(pf_link, None)
def get_vf_count_and_functions(interfaces, config_manager,
vf_counts, vfs, pfs):
"""
Go through the list of netplan ethernet devices and identify which are
PFs and VFs, matching the former with actual networking interfaces.
Count how many VFs each PF will need.
"""
explicit_counts = {}
for ethernet, settings in config_manager.ethernets.items():
if not settings:
continue
if ethernet == 'renderer':
continue
# we now also support explicitly stating how many VFs should be
# allocated for a PF
explicit_num = settings.get('virtual-function-count')
if explicit_num:
pf = _get_target_interface(interfaces, config_manager, ethernet, pfs)
if pf:
explicit_counts[pf] = explicit_num
continue
pf_link = settings.get('link')
if pf_link and pf_link in config_manager.ethernets:
_get_target_interface(interfaces, config_manager, pf_link, pfs)
if pf_link in pfs:
vf_counts[pfs[pf_link]] += 1
else:
logging.warning('could not match physical interface for the defined PF: %s' % pf_link)
# continue looking for other VFs
continue
# we can't yet perform matching on VFs as those are only
# created later - but store, for convenience, all the valid
# VFs that we encounter so far
vfs[ethernet] = None
# sanity check: since we can explicitly state the VF count, make sure
# that this number isn't smaller than the actual number of VFs declared
# the explicit number also overrides the number of actual VFs
for pf, count in explicit_counts.items():
if pf in vf_counts and vf_counts[pf] > count:
raise ConfigurationError(
'more VFs allocated than the explicit size declared: %s > %s' % (vf_counts[pf], count))
vf_counts[pf] = count
def set_numvfs_for_pf(pf, vf_count):
"""
Allocate the required number of VFs for the selected PF.
"""
if vf_count > 256:
raise ConfigurationError(
'cannot allocate more VFs for PF %s than the SR-IOV maximum: %s > 256' % (pf, vf_count))
devdir = os.path.join('/sys/class/net', pf, 'device')
numvfs_path = os.path.join(devdir, 'sriov_numvfs')
totalvfs_path = os.path.join(devdir, 'sriov_totalvfs')
try:
with open(totalvfs_path) as f:
vf_max = int(f.read().strip())
except IOError as e:
raise RuntimeError('failed parsing sriov_totalvfs for %s: %s' % (pf, str(e)))
except ValueError:
raise RuntimeError('invalid sriov_totalvfs value for %s' % pf)
if vf_count > vf_max:
raise ConfigurationError(
'cannot allocate more VFs for PF %s than supported: %s > %s (sriov_totalvfs)' % (pf, vf_count, vf_max))
try:
with open(numvfs_path, 'w') as f:
f.write(str(vf_count))
except IOError as e:
bail = True
if e.errno == 16: # device or resource busy
logging.warning('device or resource busy while setting sriov_numvfs for %s, trying workaround' % pf)
try:
# doing this in two open/close sequences so that
# it's as close to writing via shell as possible
with open(numvfs_path, 'w') as f:
f.write('0')
with open(numvfs_path, 'w') as f:
f.write(str(vf_count))
except IOError as e_inner:
e = e_inner
else:
bail = False
if bail:
raise RuntimeError('failed setting sriov_numvfs to %s for %s: %s' % (vf_count, pf, str(e)))
return True
def perform_hardware_specific_quirks(pf):
"""
Perform any hardware-specific quirks for the given SR-IOV device to make
sure all the VF-count changes are applied.
"""
devdir = os.path.join('/sys/class/net', pf, 'device')
try:
with open(os.path.join(devdir, 'vendor')) as f:
device_id = f.read().strip()[2:]
with open(os.path.join(devdir, 'device')) as f:
vendor_id = f.read().strip()[2:]
except IOError as e:
raise RuntimeError('could not determine vendor and device ID of %s: %s' % (pf, str(e)))
combined_id = ':'.join([vendor_id, device_id])
quirk_devices = () # TODO: add entries to the list
if combined_id in quirk_devices:
# some devices need special handling, so this is the place
# Currently this part is empty, but has been added as a preemptive
# measure, as apparently a lot of SR-IOV cards have issues with
# dynamically allocating VFs. Some cards seem to require a full
# kernel module reload cycle after changing the sriov_numvfs value
# for the changes to come into effect.
# Any identified card/vendor can then be special-cased here, if
# needed.
pass
def apply_vlan_filter_for_vf(pf, vf, vlan_name, vlan_id, prefix='/'):
"""
Apply the hardware VLAN filtering for the selected VF.
"""
# this is more complicated, because to do this, we actually need to have
# the vf index - just knowing the vf interface name is not enough
vf_index = None
# the prefix argument is here only for unit testing purposes
vf_devdir = os.path.join(prefix, 'sys/class/net', vf, 'device')
vf_dev_id = os.path.basename(os.readlink(vf_devdir))
pf_devdir = os.path.join(prefix, 'sys/class/net', pf, 'device')
for f in os.listdir(pf_devdir):
if 'virtfn' in f:
dev_path = os.path.join(pf_devdir, f)
dev_id = os.path.basename(os.readlink(dev_path))
if dev_id == vf_dev_id:
vf_index = f[6:]
break
if not vf_index:
raise RuntimeError(
'could not determine the VF index for %s while configuring vlan %s' % (vf, vlan_name))
# now, create the VLAN filter
# TODO: would be best if we did this directl via python, without calling
# the iproute tooling
try:
subprocess.check_call(['ip', 'link', 'set',
'dev', pf,
'vf', vf_index,
'vlan', str(vlan_id)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL)
except subprocess.CalledProcessError:
raise RuntimeError(
'failed setting SR-IOV VLAN filter for vlan %s (ip link set command failed)' % vlan_name)
def apply_sriov_config(interfaces, config_manager):
"""
Go through all interfaces, identify which ones are SR-IOV VFs, create
them and perform all other necessary setup.
"""
# for sr-iov devices, we identify VFs by them having a link: field
# pointing to an PF. So let's browse through all ethernet devices,
# find all that are VFs and count how many of those are linked to
# particular PFs, as we need to then set the numvfs for each.
vf_counts = defaultdict(int)
# we also store all matches between VF/PF netplan entry names and
# interface that they're currently matching to
vfs = {}
pfs = {}
get_vf_count_and_functions(
interfaces, config_manager, vf_counts, vfs, pfs)
# setup the required number of VFs per PF
# at the same time store which PFs got changed in case the NICs
# require some special quirks for the VF number to change
vf_count_changed = []
if vf_counts:
for pf, vf_count in vf_counts.items():
if not set_numvfs_for_pf(pf, vf_count):
continue
vf_count_changed.append(pf)
if vf_count_changed:
# some cards need special treatment when we want to change the
# number of enabled VFs
for pf in vf_count_changed:
perform_hardware_specific_quirks(pf)
# also, since the VF number changed, the interfaces list also
# changed, so we need to refresh it
interfaces = netifaces.interfaces()
# now in theory we should have all the new VFs set up and existing;
# this is needed because we will have to now match the defined VF
# entries to existing interfaces, otherwise we won't be able to set
# filtered VLANs for those.
# XXX: does matching those even make sense?
for vf in vfs:
settings = config_manager.ethernets.get(vf)
match = settings.get('match')
if match:
# right now we only match by name, as I don't think matching per
# driver and/or macaddress makes sense
by_name = match.get('name')
# by_mac = match.get('macaddress')
# by_driver = match.get('driver')
# TODO: print warning if other matches are provided
for interface in interfaces:
if by_name and not utils.is_interface_matching_name(interface, by_name):
continue
if vf in vfs and vfs[vf]:
raise ConfigurationError('matched more than one interface for a VF device: %s' % vf)
vfs[vf] = interface
else:
if vf in interfaces:
vfs[vf] = vf
filtered_vlans_set = set()
for vlan, settings in config_manager.vlans.items():
# there is a special sriov vlan renderer that one can use to mark
# a selected vlan to be done in hardware (VLAN filtering)
if settings.get('renderer') == 'sriov':
# this only works for SR-IOV VF interfaces
link = settings.get('link')
vlan_id = settings.get('id')
if not vlan_id:
raise ConfigurationError(
'no id property defined for SR-IOV vlan %s' % vlan)
vf = vfs.get(link)
if not vf:
# it is possible this is not an error, for instance when
# the configuration has been defined 'for the future'
# XXX: but maybe we should error out here as well?
logging.warning(
'SR-IOV vlan defined for %s but link %s is either not a VF or has no matches' % (vlan, link))
continue
# get the parent pf interface
# first we fetch the related vf netplan entry
vf_parent_entry = config_manager.ethernets.get(link).get('link')
# and finally, get the matched pf interface
pf = pfs.get(vf_parent_entry)
if vf in filtered_vlans_set:
raise ConfigurationError(
'interface %s for netplan device %s (%s) already has an SR-IOV vlan defined' % (vf, link, vlan))
apply_vlan_filter_for_vf(pf, vf, vlan, vlan_id)
filtered_vlans_set.add(vf)
netplan.io-0.99/netplan/cli/utils.py 0000664 0000000 0000000 00000015755 13646002212 0017455 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018-2020 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
# Author: Ćukasz 'sil2100' Zemczak
#
# 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 sys
import os
import logging
import fnmatch
import argparse
import subprocess
import netifaces
NM_SERVICE_NAME = 'NetworkManager.service'
NM_SNAP_SERVICE_NAME = 'snap.network-manager.networkmanager.service'
def get_generator_path():
return os.environ.get('NETPLAN_GENERATE_PATH', '/lib/netplan/generate')
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, sync=False): # pragma: nocover (covered in autopkgtest)
service_name = NM_SERVICE_NAME
command = ['systemctl', action]
if not sync:
command.append('--no-block')
# 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
command.append(service_name)
subprocess.check_call(command)
def systemctl_networkd(action, sync=False, extra_services=[]): # pragma: nocover (covered in autopkgtest)
command = ['systemctl', action]
if not sync:
command.append('--no-block')
command.append('systemd-networkd.service')
for service in extra_services:
command.append(service)
subprocess.check_call(command)
def get_interface_driver_name(interface, only_down=False): # pragma: nocover (covered in autopkgtest)
devdir = os.path.join('/sys/class/net', interface)
if only_down:
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 changing', interface, state)
return None
except IOError as e:
logging.error('Cannot determine operstate of %s: %s', interface, str(e))
return None
try:
driver = os.path.realpath(os.path.join(devdir, 'device', 'driver'))
driver_name = os.path.basename(driver)
except IOError as e:
logging.debug('Cannot replug %s: cannot read link %s/device: %s', interface, devdir, str(e))
return None
return driver_name
def get_interface_macaddress(interface): # pragma: nocover (covered in autopkgtest)
link = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0]
return link.get('addr')
def is_interface_matching_name(interface, match_driver):
return fnmatch.fnmatchcase(interface, match_driver)
def is_interface_matching_driver_name(interface, match_driver):
driver_name = get_interface_driver_name(interface)
return match_driver == driver_name
def is_interface_matching_macaddress(interface, match_mac):
macaddress = get_interface_macaddress(interface)
return match_mac == macaddress
class NetplanCommand(argparse.Namespace):
def __init__(self, command_id, description, leaf=True, testing=False):
self.command_id = command_id
self.description = description
self.leaf_command = leaf
self.testing = testing
self._args = None
self.debug = False
self.commandclass = None
self.subcommands = {}
self.subcommand = None
self.func = None
self.parser = argparse.ArgumentParser(prog="%s %s" % (sys.argv[0], command_id),
description=description,
add_help=True)
self.parser.add_argument('--debug', action='store_true',
help='Enable debug messages')
if not leaf:
self.subparsers = self.parser.add_subparsers(title='Available commands',
metavar='', dest='subcommand')
p_help = self.subparsers.add_parser('help',
description='Show this help message',
help='Show this help message')
p_help.set_defaults(func=self.print_usage)
def update(self, args):
self._args = args
def parse_args(self):
ns, self._args = self.parser.parse_known_args(args=self._args, namespace=self)
if not self.subcommand and not self.leaf_command:
print('You need to specify a command', file=sys.stderr)
self.print_usage()
def run_command(self):
if self.commandclass:
self.commandclass.update(self._args)
# TODO: (cyphermox) this is actually testable in tests/cli.py; add it.
if self.leaf_command and 'help' in self._args: # pragma: nocover (covered in autopkgtest)
self.print_usage()
self.func()
def print_usage(self):
self.parser.print_help(file=sys.stderr)
sys.exit(os.EX_USAGE)
def _add_subparser_from_class(self, name, commandclass):
instance = commandclass()
self.subcommands[name] = {}
self.subcommands[name]['class'] = name
self.subcommands[name]['instance'] = instance
if instance.testing:
if not os.environ.get('ENABLE_TEST_COMMANDS', None):
return
p = self.subparsers.add_parser(instance.command_id,
description=instance.description,
help=instance.description,
add_help=False)
p.set_defaults(func=instance.run, commandclass=instance)
self.subcommands[name]['parser'] = p
def _import_subcommands(self, submodules):
import inspect
for name, obj in inspect.getmembers(submodules):
if inspect.isclass(obj) and issubclass(obj, NetplanCommand):
self._add_subparser_from_class(name, obj)
netplan.io-0.99/netplan/configmanager.py 0000664 0000000 0000000 00000021107 13646002212 0020332 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 configuration manager'''
import glob
import logging
import os
import shutil
import sys
import tempfile
import yaml
class ConfigManager(object):
def __init__(self, prefix="/", extra_files={}):
self.prefix = prefix
self.tempdir = tempfile.mkdtemp(prefix='netplan_')
self.temp_etc = os.path.join(self.tempdir, "etc")
self.temp_run = os.path.join(self.tempdir, "run")
self.extra_files = extra_files
self.config = {}
self.new_interfaces = set()
@property
def network(self):
return self.config['network']
@property
def interfaces(self):
interfaces = {}
interfaces.update(self.ethernets)
interfaces.update(self.wifis)
interfaces.update(self.bridges)
interfaces.update(self.bonds)
interfaces.update(self.vlans)
return interfaces
@property
def physical_interfaces(self):
interfaces = {}
interfaces.update(self.ethernets)
interfaces.update(self.wifis)
return interfaces
@property
def ethernets(self):
return self.network['ethernets']
@property
def wifis(self):
return self.network['wifis']
@property
def bridges(self):
return self.network['bridges']
@property
def bonds(self):
return self.network['bonds']
@property
def vlans(self):
return self.network['vlans']
def parse(self, extra_config=[]):
"""
Parse all our config files to return an object that describes the system's
entire configuration, so that it can later be interrogated.
Returns a dict that contains the entire, collated and merged YAML.
"""
# TODO: Clean this up, there's no solid reason why we should parse YAML
# in two different spots; here and in parse.c. We'd do better by
# parsing things once, in C form, and having some small glue
# Cpython code to call on the right methods and return an object
# that is meaningful for the Python code; but minimal parsing in
# pure Python will do for now. ~cyphermox
# /run/netplan shadows /etc/netplan/, which shadows /lib/netplan
names_to_paths = {}
for yaml_dir in ['lib', 'etc', 'run']:
for yaml_file in glob.glob(os.path.join(self.prefix, yaml_dir, 'netplan', '*.yaml')):
names_to_paths[os.path.basename(yaml_file)] = yaml_file
files = [names_to_paths[name] for name in sorted(names_to_paths.keys())]
self.config['network'] = {
'ethernets': {},
'wifis': {},
'bridges': {},
'bonds': {},
'vlans': {}
}
for yaml_file in files:
self._merge_yaml_config(yaml_file)
for yaml_file in extra_config:
self.new_interfaces |= self._merge_yaml_config(yaml_file)
logging.debug("Merged config:\n{}".format(yaml.dump(self.config, default_flow_style=False)))
def add(self, config_dict):
for config_file in config_dict:
self._copy_file(config_file, config_dict[config_file])
self.extra_files.update(config_dict)
def backup(self, backup_config_dir=True):
if backup_config_dir:
self._copy_tree(os.path.join(self.prefix, "etc/netplan"),
os.path.join(self.temp_etc, "netplan"))
self._copy_tree(os.path.join(self.prefix, "run/NetworkManager/system-connections"),
os.path.join(self.temp_run, "NetworkManager", "system-connections"),
missing_ok=True)
self._copy_tree(os.path.join(self.prefix, "run/systemd/network"),
os.path.join(self.temp_run, "systemd", "network"),
missing_ok=True)
def revert(self):
try:
for extra_file in dict(self.extra_files):
os.unlink(self.extra_files[extra_file])
del self.extra_files[extra_file]
temp_nm_path = "{}/NetworkManager/system-connections".format(self.temp_run)
temp_networkd_path = "{}/systemd/network".format(self.temp_run)
if os.path.exists(temp_nm_path):
shutil.rmtree(os.path.join(self.prefix, "run/NetworkManager/system-connections"))
self._copy_tree(temp_nm_path,
os.path.join(self.prefix, "run/NetworkManager/system-connections"))
if os.path.exists(temp_networkd_path):
shutil.rmtree(os.path.join(self.prefix, "run/systemd/network"))
self._copy_tree(temp_networkd_path,
os.path.join(self.prefix, "run/systemd/network"))
except Exception as e: # pragma: nocover (only relevant to filesystem failures)
# If we reach here, we're in big trouble. We may have wiped out
# file NM or networkd are using, and we most likely removed the
# "new" config -- or at least our copy of it.
# Given that we're in some halfway done revert; warn the user
# aggressively and drop everything; leaving any remaining backups
# around for the user to handle themselves.
logging.error("Something really bad happened while reverting config: {}".format(e))
logging.error("You should verify the netplan YAML in /etc/netplan and probably run 'netplan apply' again.")
sys.exit(-1)
def cleanup(self):
shutil.rmtree(self.tempdir)
def _copy_file(self, src, dst):
shutil.copy(src, dst)
def _copy_tree(self, src, dst, missing_ok=False):
try:
shutil.copytree(src, dst)
except FileNotFoundError:
if missing_ok:
pass
else:
raise
def _merge_interface_config(self, orig, new):
new_interfaces = set()
changed_ifaces = list(new.keys())
for ifname in changed_ifaces:
iface = new.pop(ifname)
if ifname in orig:
logging.debug("{} exists in {}".format(ifname, orig))
orig[ifname].update(iface)
else:
logging.debug("{} not found in {}".format(ifname, orig))
orig[ifname] = iface
new_interfaces.add(ifname)
return new_interfaces
def _merge_yaml_config(self, yaml_file):
new_interfaces = set()
try:
with open(yaml_file) as f:
yaml_data = yaml.load(f, Loader=yaml.CSafeLoader)
network = None
if yaml_data is not None:
network = yaml_data.get('network')
if network:
if 'ethernets' in network:
new = self._merge_interface_config(self.ethernets, network.get('ethernets'))
new_interfaces |= new
if 'wifis' in network:
new = self._merge_interface_config(self.wifis, network.get('wifis'))
new_interfaces |= new
if 'bridges' in network:
new = self._merge_interface_config(self.bridges, network.get('bridges'))
new_interfaces |= new
if 'bonds' in network:
new = self._merge_interface_config(self.bonds, network.get('bonds'))
new_interfaces |= new
if 'vlans' in network:
new = self._merge_interface_config(self.vlans, network.get('vlans'))
new_interfaces |= new
return new_interfaces
except (IOError, yaml.YAMLError): # pragma: nocover (filesystem failures/invalid YAML)
logging.error('Error while loading {}, aborting.'.format(yaml_file))
sys.exit(1)
class ConfigurationError(Exception):
"""
Configuration could not be parsed or has otherwise failed to apply
"""
pass
netplan.io-0.99/netplan/terminal.py 0000664 0000000 0000000 00000011776 13646002212 0017360 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 .
"""
Terminal / input handling
"""
import fcntl
import os
import termios
import select
import sys
class Terminal(object):
"""
Do minimal terminal mangling to prompt users for input
"""
def __init__(self, fd):
self.fd = fd
self.orig_flags = None
self.orig_term = None
self.save()
def enable_echo(self):
attrs = termios.tcgetattr(self.fd)
attrs[3] = attrs[3] | termios.ICANON
attrs[3] = attrs[3] | termios.ECHO
termios.tcsetattr(self.fd, termios.TCSANOW, attrs)
def disable_echo(self):
attrs = termios.tcgetattr(self.fd)
attrs[3] = attrs[3] & ~termios.ICANON
attrs[3] = attrs[3] & ~termios.ECHO
termios.tcsetattr(self.fd, termios.TCSANOW, attrs)
def enable_nonblocking_io(self):
flags = fcntl.fcntl(self.fd, fcntl.F_GETFL)
fcntl.fcntl(self.fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
def disable_nonblocking_io(self):
flags = fcntl.fcntl(self.fd, fcntl.F_GETFL)
fcntl.fcntl(self.fd, fcntl.F_SETFL, flags & ~os.O_NONBLOCK)
def get_confirmation_input(self, timeout=120, message=None): # pragma: nocover (requires user input)
"""
Get a "confirmation" input from the user, for at most (timeout)
seconds. Optionally, customize the message to be displayed.
timeout -- timeout to wait for input (default 120)
message -- optional customized message ("Press ENTER to (message)")
raises:
InputAccepted -- the user confirmed the changes
InputRejected -- the user rejected the changes
"""
print("Do you want to keep these settings?\n\n")
settings = dict()
self.save(settings)
self.disable_echo()
self.enable_nonblocking_io()
if not message:
message = "accept the new configuration"
print("Press ENTER before the timeout to {}\n\n".format(message))
timeout_now = timeout
while (timeout_now > 0):
print("Changes will revert in {:>{}} seconds".format(timeout_now, len(str(timeout))), end='\r')
# wait at most 1 second for usable input from stdin
select.select([sys.stdin], [], [], 1)
try:
# retrieve any input from the terminal. select() either has
# timed out with no input, or found something we can retrieve.
c = sys.stdin.read()
if (c == '\n'):
self.reset(settings)
# Yay, user has accepted the changes!
raise InputAccepted()
except TypeError:
# read() above is non-blocking, if there is nothing to read it
# will return TypeError, which we should ignore -- on to the
# next iteration until timeout.
pass
timeout_now -= 1
# We reached the timeout for our loop, now revert our change for
# non-blocking I/O and signal the caller the changes were essentially
# rejected.
self.reset(settings)
raise InputRejected()
def save(self, dest=None):
"""
Save the terminal's current attributes and flags
Optional argument:
- dest: if set, save settings to this dict
"""
orig_flags = fcntl.fcntl(self.fd, fcntl.F_GETFL)
orig_term = termios.tcgetattr(self.fd)
if dest is not None:
dest.update({'flags': orig_flags,
'term': orig_term})
else:
self.orig_flags = orig_flags
self.orig_term = orig_term
def reset(self, orig=None):
"""
Reset the terminal to its original attributes and flags
Optional argument:
- orig: if set, reset to settings from this dict
"""
orig_term = None
orig_flags = None
if orig is not None:
orig_term = orig.get('term')
orig_flags = orig.get('flags')
else:
orig_term = self.orig_term
orig_flags = self.orig_flags
termios.tcsetattr(self.fd, termios.TCSAFLUSH, orig_term)
fcntl.fcntl(self.fd, fcntl.F_SETFL, orig_flags)
class InputAccepted(Exception):
""" Denotes has accepted input"""
pass
class InputRejected(Exception):
""" Denotes that the user has rejected input"""
pass
netplan.io-0.99/rpm/ 0000775 0000000 0000000 00000000000 13646002212 0014314 5 ustar 00root root 0000000 0000000 netplan.io-0.99/rpm/netplan.spec 0000664 0000000 0000000 00000007640 13646002212 0016640 0 ustar 00root root 0000000 0000000 # Ensure hardened build on EL7
%global _hardened_build 1
# Ubuntu calls their own software netplan.io in the archive due to name conflicts
%global ubuntu_name netplan.io
# If the definition isn't available for python3_pkgversion, define it
%{?!python3_pkgversion:%global python3_pkgversion 3}
# If this isn't defined, define it
%{?!_systemdgeneratordir:%global _systemdgeneratordir /usr/lib/systemd/system-generators}
# Force auto-byte-compilation to Python 3
%global __python %{__python3}
Name: netplan
Version: 0.95
Release: 0%{?dist}
Summary: Network configuration tool using YAML
Group: System Environment/Base
License: GPLv3
URL: http://netplan.io/
Source0: https://github.com/CanonicalLtd/%{name}/archive/%{version}/%{version}.tar.gz
BuildRequires: gcc
BuildRequires: make
BuildRequires: pkgconfig(bash-completion)
BuildRequires: pkgconfig(systemd)
BuildRequires: pkgconfig(glib-2.0)
BuildRequires: pkgconfig(yaml-0.1)
BuildRequires: pkgconfig(uuid)
BuildRequires: %{_bindir}/pandoc
BuildRequires: python%{python3_pkgversion}-devel
# For tests
BuildRequires: %{_sbindir}/ip
BuildRequires: python%{python3_pkgversion}-coverage
BuildRequires: python%{python3_pkgversion}-netifaces
BuildRequires: python%{python3_pkgversion}-nose
BuildRequires: python%{python3_pkgversion}-pycodestyle
BuildRequires: python%{python3_pkgversion}-pyflakes
BuildRequires: python%{python3_pkgversion}-PyYAML
# /usr/sbin/netplan is a Python 3 script that requires netifaces and PyYAML
Requires: python%{python3_pkgversion}-netifaces
Requires: python%{python3_pkgversion}-PyYAML
# 'ip' command is used in netplan apply subcommand
Requires: %{_sbindir}/ip
# netplan supports either systemd or NetworkManager as backends to configure the network
Requires: systemd
%if 0%{?el7}
# systemd-networkd is a separate subpackage in EL7
Requires: systemd-networkd
%endif
%if 0%{?fedora} || 0%{?rhel} >= 8
# NetworkManager is preferred, but wpa_supplicant can be used directly for Wi-Fi networks
Suggests: (NetworkManager or wpa_supplicant)
%endif
# Provide the package name that Ubuntu uses for it too...
Provides: %{ubuntu_name} = %{version}-%{release}
Provides: %{ubuntu_name}%{?_isa} = %{version}-%{release}
%description
netplan reads network configuration from /etc/netplan/*.yaml which are written by administrators,
installers, cloud image instantiations, or other OS deployments. During early boot, it generates
backend specific configuration files in /run to hand off control of devices to a particular
networking daemon.
Currently supported backends are systemd-networkd and NetworkManager.
%prep
%autosetup -p1
# Drop -Werror to avoid the following error:
# /usr/include/glib-2.0/glib/glib-autocleanups.h:28:3: error: 'ip_str' may be used uninitialized in this function [-Werror=maybe-uninitialized]
sed -e "s/-Werror//g" -i Makefile
%build
%make_build CFLAGS="%{optflags}"
%install
%make_install ROOTPREFIX=%{_prefix}
# Pre-create the config directory
mkdir -p %{buildroot}%{_sysconfdir}/%{name}
%check
make check
%files
%license COPYING
%doc debian/changelog
%doc %{_docdir}/%{name}/
%{_sbindir}/%{name}
%{_datadir}/%{name}/
%{_unitdir}/%{name}*.service
%{_systemdgeneratordir}/%{name}
%{_mandir}/man5/%{name}.5*
%{_mandir}/man8/%{name}*.8*
%dir %{_sysconfdir}/%{name}
%{_prefix}/lib/%{name}/
%{_datadir}/bash-completion/completions/%{name}
%changelog
* Fri Dec 14 2018 Mathieu Trudel-Lapierre - 0.95
- Update to 0.95
* Sat Oct 13 2018 Neal Gompa - 0.40.3-0
- Rebase to 0.40.3
* Tue Mar 13 2018 Neal Gompa - 0.34-0.1
- Update to 0.34
* Wed Mar 7 2018 Neal Gompa - 0.33-0.1
- Rebase to 0.33
* Sat Nov 4 2017 Neal Gompa - 0.30-1
- Rebase to 0.30
* Sun Jul 2 2017 Neal Gompa - 0.23~17.04.1-1
- Initial packaging
netplan.io-0.99/snap/ 0000775 0000000 0000000 00000000000 13646002212 0014457 5 ustar 00root root 0000000 0000000 netplan.io-0.99/snap/snapcraft.yaml 0000664 0000000 0000000 00000002054 13646002212 0017325 0 ustar 00root root 0000000 0000000 name: netplan
version: git
summary: Backend-agnostic network configuration in YAML
description: |
Netplan is a utility for easily configuring networking on a linux system.
You simply create a YAML description of the required network interfaces and
what each should be configured to do. From this description Netplan will
generate all the necessary configuration for your chosen renderer tool.
grade: devel
confinement: classic
apps:
netplan:
command: usr/sbin/netplan
environment:
PYTHONPATH: $PYTHONPATH:$SNAP/usr/lib/python3/dist-packages
parts:
netplan:
source: https://github.com/CanonicalLtd/netplan.git
plugin: make
build-packages:
- bash-completion
- libglib2.0-dev
- libyaml-dev
- uuid-dev
- pandoc
- pkg-config
- python3
- python3-coverage
- python3-yaml
- python3-netifaces
- python3-nose
- pyflakes3
- pep8
- systemd
stage-packages:
- iproute2
- python3
- python3-netifaces
- python3-yaml
- systemd
netplan.io-0.99/src/ 0000775 0000000 0000000 00000000000 13646002212 0014305 5 ustar 00root root 0000000 0000000 netplan.io-0.99/src/dbus.c 0000664 0000000 0000000 00000010630 13646002212 0015406 0 ustar 00root root 0000000 0000000 #include
#include
#include
#include
#include
#include
#include
#include
#include
#include "_features.h"
// LCOV_EXCL_START
/* XXX: (cyphermox)
* This file is completely excluded from coverage on purpose. Tests should
* still include code in here, but sadly coverage does not appear to
* correctly capture tests being run over a DBus bus.
*/
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 int method_info(sd_bus_message *m, void *userdata, sd_bus_error *ret_error) {
sd_bus_message *reply = NULL;
g_autoptr(GError) err = NULL;
g_autofree gchar *stdout = NULL;
g_autofree gchar *stderr = NULL;
gint exit_status = 0;
exit_status = sd_bus_message_new_method_return(m, &reply);
if (exit_status < 0)
return exit_status;
exit_status = sd_bus_message_open_container(reply, 'a', "(sv)");
if (exit_status < 0)
return exit_status;
exit_status = sd_bus_message_open_container(reply, 'r', "sv");
if (exit_status < 0)
return exit_status;
exit_status = sd_bus_message_append(reply, "s", "Features");
if (exit_status < 0)
return exit_status;
exit_status = sd_bus_message_open_container(reply, 'v', "as");
if (exit_status < 0)
return exit_status;
exit_status = sd_bus_message_append_strv(reply, (char**)feature_flags);
if (exit_status < 0)
return exit_status;
exit_status = sd_bus_message_close_container(reply);
if (exit_status < 0)
return exit_status;
exit_status = sd_bus_message_close_container(reply);
if (exit_status < 0)
return exit_status;
exit_status = sd_bus_message_close_container(reply);
if (exit_status < 0)
return exit_status;
return sd_bus_send(NULL, reply, NULL);
}
static const sd_bus_vtable netplan_vtable[] = {
SD_BUS_VTABLE_START(0),
SD_BUS_METHOD("Apply", "", "b", method_apply, 0),
SD_BUS_METHOD("Info", "", "a(sv)", method_info, 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;
}
// LCOV_EXCL_STOP
netplan.io-0.99/src/error.c 0000664 0000000 0000000 00000012543 13646002212 0015607 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2019 Canonical, Ltd.
* Author: Mathieu Trudel-Lapierre
*
* 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 "parse.h"
/****************************************************
* Loading and error handling
****************************************************/
static void
write_error_marker(GString *message, int column)
{
int i;
for (i = 0; (column > 0 && i < column); i++)
g_string_append_printf(message, " ");
g_string_append_printf(message, "^");
}
static char *
get_syntax_error_context(const int line_num, const int column, GError **error)
{
GString *message = NULL;
GFile *cur_file = g_file_new_for_path(current_file);
GFileInputStream *file_stream;
GDataInputStream *stream;
gsize len;
gchar* line = NULL;
message = g_string_sized_new(200);
file_stream = g_file_read(cur_file, NULL, error);
stream = g_data_input_stream_new (G_INPUT_STREAM(file_stream));
g_object_unref(file_stream);
for (int i = 0; i < line_num + 1; i++) {
g_free(line);
line = g_data_input_stream_read_line(stream, &len, NULL, error);
}
g_string_append_printf(message, "%s\n", line);
write_error_marker(message, column);
g_object_unref(stream);
g_object_unref(cur_file);
return g_string_free(message, FALSE);
}
static char *
get_parser_error_context(const yaml_parser_t *parser, GError **error)
{
GString *message = NULL;
unsigned char* line = parser->buffer.pointer;
unsigned char* current = line;
message = g_string_sized_new(200);
while (current > parser->buffer.start) {
current--;
if (*current == '\n') {
line = current + 1;
break;
}
}
if (current <= parser->buffer.start)
line = parser->buffer.start;
current = line + 1;
while (current <= parser->buffer.last) {
if (*current == '\n') {
*current = '\0';
break;
}
current++;
}
g_string_append_printf(message, "%s\n", line);
write_error_marker(message, parser->problem_mark.column);
return g_string_free(message, FALSE);
}
gboolean
parser_error(const yaml_parser_t* parser, const char* yaml, GError** error)
{
char *error_context = get_parser_error_context(parser, error);
if ((char)*parser->buffer.pointer == '\t')
g_set_error(error, G_MARKUP_ERROR, G_MARKUP_ERROR_PARSE,
"%s:%zu:%zu: Invalid YAML: tabs are not allowed for indent:\n%s",
yaml,
parser->problem_mark.line + 1,
parser->problem_mark.column + 1,
error_context);
else if (((char)*parser->buffer.pointer == ' ' || (char)*parser->buffer.pointer == '\0')
&& !parser->token_available)
g_set_error(error, G_MARKUP_ERROR, G_MARKUP_ERROR_PARSE,
"%s:%zu:%zu: Invalid YAML: aliases are not supported:\n%s",
yaml,
parser->problem_mark.line + 1,
parser->problem_mark.column + 1,
error_context);
else if (parser->state == YAML_PARSE_BLOCK_MAPPING_KEY_STATE)
g_set_error(error, G_MARKUP_ERROR, G_MARKUP_ERROR_PARSE,
"%s:%zu:%zu: Invalid YAML: inconsistent indentation:\n%s",
yaml,
parser->problem_mark.line + 1,
parser->problem_mark.column + 1,
error_context);
else {
g_set_error(error, G_MARKUP_ERROR, G_MARKUP_ERROR_PARSE,
"%s:%zu:%zu: Invalid YAML: %s:\n%s",
yaml,
parser->problem_mark.line + 1,
parser->problem_mark.column + 1,
parser->problem,
error_context);
}
g_free(error_context);
return FALSE;
}
/**
* Put a YAML specific error message for @node into @error.
*/
gboolean
yaml_error(const yaml_node_t* node, GError** error, const char* msg, ...)
{
va_list argp;
char* s;
char* error_context = NULL;
va_start(argp, msg);
g_vasprintf(&s, msg, argp);
if (node != NULL) {
error_context = get_syntax_error_context(node->start_mark.line, node->start_mark.column, error);
g_set_error(error, G_MARKUP_ERROR, G_MARKUP_ERROR_PARSE,
"%s:%zu:%zu: Error in network definition: %s\n%s",
current_file,
node->start_mark.line + 1,
node->start_mark.column + 1,
s,
error_context);
} else {
g_set_error(error, G_MARKUP_ERROR, G_MARKUP_ERROR_PARSE,
"Error in network definition: %s", s);
}
g_free(s);
va_end(argp);
return FALSE;
}
netplan.io-0.99/src/error.h 0000664 0000000 0000000 00000001720 13646002212 0015607 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2019 Canonical, Ltd.
* Author: Mathieu Trudel-Lapierre
*
* 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
#include
#include
gboolean
parser_error(const yaml_parser_t* parser, const char* yaml, GError** error);
gboolean
yaml_error(const yaml_node_t* node, GError** error, const char* msg, ...);
netplan.io-0.99/src/generate.c 0000664 0000000 0000000 00000024730 13646002212 0016251 0 ustar 00root root 0000000 0000000 /*
* 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
#include "util.h"
#include "parse.h"
#include "networkd.h"
#include "nm.h"
static gchar* rootdir;
static gchar** files;
static gboolean any_networkd;
static gchar* mapping_iface;
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 ..]"},
{"mapping", 0, 0, G_OPTION_ARG_STRING, &mapping_iface, "Only show the device to backend mapping for the specified interface."},
{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_list(gpointer value, gpointer user_data)
{
if (write_networkd_conf((NetplanNetDefinition*) value, (const char*) user_data))
any_networkd = TRUE;
write_nm_conf((NetplanNetDefinition*) value, (const char*) user_data);
}
static int
find_interface(gchar* interface)
{
GPtrArray *found;
GFileInfo *info;
GFile *driver_file;
gchar *driver_path;
gchar *driver = NULL;
gpointer key, value;
GHashTableIter iter;
int ret = EXIT_FAILURE;
found = g_ptr_array_new ();
/* Try to get the driver name for the interface... */
driver_path = g_strdup_printf("/sys/class/net/%s/device/driver", interface);
driver_file = g_file_new_for_path (driver_path);
info = g_file_query_info (driver_file,
G_FILE_ATTRIBUTE_STANDARD_SYMLINK_TARGET,
0, NULL, NULL);
if (info != NULL) {
/* testing for driver matching is done via autopkgtest */
// LCOV_EXCL_START
driver = g_path_get_basename (g_file_info_get_symlink_target (info));
g_object_unref (info);
// LCOV_EXCL_STOP
}
g_object_unref (driver_file);
g_free (driver_path);
g_hash_table_iter_init (&iter, netdefs);
while (g_hash_table_iter_next (&iter, &key, &value)) {
NetplanNetDefinition *nd = (NetplanNetDefinition *) value;
if (!g_strcmp0(nd->set_name, interface))
g_ptr_array_add (found, (gpointer) nd);
else if (!g_strcmp0(nd->id, interface))
g_ptr_array_add (found, (gpointer) nd);
else if (!g_strcmp0(nd->match.original_name, interface))
g_ptr_array_add (found, (gpointer) nd);
}
if (found->len == 0 && driver != NULL) {
/* testing for driver matching is done via autopkgtest */
// LCOV_EXCL_START
g_hash_table_iter_init (&iter, netdefs);
while (g_hash_table_iter_next (&iter, &key, &value)) {
NetplanNetDefinition *nd = (NetplanNetDefinition *) value;
if (!g_strcmp0(nd->match.driver, driver))
g_ptr_array_add (found, (gpointer) nd);
}
// LCOV_EXCL_STOP
}
if (driver)
g_free (driver); // LCOV_EXCL_LINE
if (found->len != 1) {
goto exit_find;
}
else {
const NetplanNetDefinition *nd = (NetplanNetDefinition *)g_ptr_array_index (found, 0);
g_printf("id=%s, backend=%s, set_name=%s, match_name=%s, match_mac=%s, match_driver=%s\n",
nd->id,
netplan_backend_to_name[nd->backend],
nd->set_name,
nd->match.original_name,
nd->match.mac,
nd->match.driver);
}
ret = EXIT_SUCCESS;
exit_find:
g_ptr_array_free (found, TRUE);
return ret;
}
static void
process_input_file(const char* f)
{
GError* error = NULL;
g_debug("Processing input file %s..", f);
if (!netplan_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) {
// LCOV_EXCL_START
g_fprintf(stderr, "failed to glob for %s: %m\n", glob_lib);
return 1;
// LCOV_EXCL_STOP
}
rc = glob(glob_etc, GLOB_APPEND, NULL, &gl);
if (rc != 0 && rc != GLOB_NOMATCH) {
// LCOV_EXCL_START
g_fprintf(stderr, "failed to glob for %s: %m\n", glob_etc);
return 1;
// LCOV_EXCL_STOP
}
rc = glob(glob_run, GLOB_APPEND, NULL, &gl);
if (rc != 0 && rc != GLOB_NOMATCH) {
// LCOV_EXCL_START
g_fprintf(stderr, "failed to glob for %s: %m\n", glob_run);
return 1;
// LCOV_EXCL_STOP
}
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));
}
netdefs = netplan_finish_parse(&error);
if (error) {
g_fprintf(stderr, "%s\n", error->message);
exit(1);
}
/* Clean up generated config from previous runs */
cleanup_networkd_conf(rootdir);
cleanup_nm_conf(rootdir);
if (mapping_iface && netdefs) {
return find_interface(mapping_iface);
}
/* Generate backend specific configuration files from merged data. */
if (netdefs) {
g_debug("Generating output files..");
g_list_foreach (netdefs_ordered, nd_iterator_list, 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 (netplan_get_global_backend() == NETPLAN_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;
}
netplan.io-0.99/src/netplan.script 0000775 0000000 0000000 00000001436 13646002212 0017203 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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'''
from netplan import Netplan
netplan = Netplan()
netplan.main()
netplan.io-0.99/src/networkd.c 0000664 0000000 0000000 00000117064 13646002212 0016317 0 ustar 00root root 0000000 0000000 /*
* 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 "networkd.h"
#include "parse.h"
#include "util.h"
/**
* Append WiFi frequencies to wpa_supplicant's freq_list=
*/
static void
wifi_append_freq(gpointer key, gpointer value, gpointer user_data)
{
GString* s = user_data;
g_string_append_printf(s, "%d ", GPOINTER_TO_INT(value));
}
/**
* append wowlan_triggers= string for wpa_supplicant.conf
*/
static void
append_wifi_wowlan_flags(NetplanWifiWowlanFlag flag, GString* str) {
if (flag & NETPLAN_WIFI_WOWLAN_TYPES[0].flag || flag >= NETPLAN_WIFI_WOWLAN_TCP) {
g_fprintf(stderr, "ERROR: unsupported wowlan_triggers mask: 0x%x\n", flag);
exit(1);
}
for (unsigned i = 0; NETPLAN_WIFI_WOWLAN_TYPES[i].name != NULL; ++i) {
if (flag & NETPLAN_WIFI_WOWLAN_TYPES[i].flag) {
g_string_append_printf(str, "%s ", NETPLAN_WIFI_WOWLAN_TYPES[i].name);
}
}
/* replace trailing space with newline */
str = g_string_overwrite(str, str->len-1, "\n");
}
/**
* Append [Match] section of @def to @s.
*/
static void
append_match_section(const NetplanNetDefinition* 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 >= NETPLAN_DEF_TYPE_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);
}
/* Workaround for bug LP: #1804861: something outputs netplan config
* that includes using the MAC of the first phy member of a bond as
* default value for the MAC of the bond device itself. This is
* evil, it's an optional field and networkd knows what to do if
* the MAC isn't specified; but work around this by adding an
* arbitrary additional match condition on Path= for the phys.
* This way, hopefully setting a MTU on the phy does not bleed over
* to bond/bridge and any further virtual devices (VLANs?) on top of
* it.
* Make sure to add the extra match only if we're matching by MAC
* already and dealing with a bond or bridge.
*/
if (def->bond || def->bridge) {
/* update if we support new device types */
if (def->match.mac)
g_string_append(s, "Type=!vlan bond bridge\n");
}
}
static void
write_bridge_params(GString* s, const NetplanNetDefinition* 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_tunnel_params(GString* s, const NetplanNetDefinition* def)
{
GString *params = NULL;
params = g_string_sized_new(200);
g_string_printf(params, "Independent=true\n");
if (def->tunnel.mode == NETPLAN_TUNNEL_MODE_IPIP6 || def->tunnel.mode == NETPLAN_TUNNEL_MODE_IP6IP6)
g_string_append_printf(params, "Mode=%s\n", tunnel_mode_to_string(def->tunnel.mode));
g_string_append_printf(params, "Local=%s\n", def->tunnel.local_ip);
g_string_append_printf(params, "Remote=%s\n", def->tunnel.remote_ip);
if (def->tunnel.input_key)
g_string_append_printf(params, "InputKey=%s\n", def->tunnel.input_key);
if (def->tunnel.output_key)
g_string_append_printf(params, "OutputKey=%s\n", def->tunnel.output_key);
g_string_append_printf(s, "\n[Tunnel]\n%s", params->str);
g_string_free(params, TRUE);
}
static void
write_link_file(const NetplanNetDefinition* def, const char* rootdir, const char* path)
{
GString* s = NULL;
mode_t orig_umask;
/* Don't write .link files for virtual devices; they use .netdev instead.
* Don't write .link files for MODEM devices, as they aren't supported by networkd.
*/
if (def->type >= NETPLAN_DEF_TYPE_VIRTUAL || def->type == NETPLAN_DEF_TYPE_MODEM)
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);
orig_umask = umask(022);
g_string_free_to_file(s, rootdir, path, ".link");
umask(orig_umask);
}
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(const NetplanNetDefinition* 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.gratuitous_arp)
g_string_append_printf(params, "\nGratuitousARP=%d", def->bond_params.gratuitous_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(const NetplanNetDefinition* def, const char* rootdir, const char* path)
{
GString* s = NULL;
mode_t orig_umask;
g_assert(def->type >= NETPLAN_DEF_TYPE_VIRTUAL);
if (def->type == NETPLAN_DEF_TYPE_VLAN && def->sriov_vlan_filter) {
g_debug("%s is defined as a hardware SR-IOV filtered VLAN, postponing creation", def->id);
return;
}
/* 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 NETPLAN_DEF_TYPE_BRIDGE:
g_string_append(s, "Kind=bridge\n");
write_bridge_params(s, def);
break;
case NETPLAN_DEF_TYPE_BOND:
g_string_append(s, "Kind=bond\n");
write_bond_parameters(def, s);
break;
case NETPLAN_DEF_TYPE_VLAN:
g_string_append_printf(s, "Kind=vlan\n\n[VLAN]\nId=%u\n", def->vlan_id);
break;
case NETPLAN_DEF_TYPE_TUNNEL:
switch(def->tunnel.mode) {
case NETPLAN_TUNNEL_MODE_GRE:
case NETPLAN_TUNNEL_MODE_GRETAP:
case NETPLAN_TUNNEL_MODE_IPIP:
case NETPLAN_TUNNEL_MODE_IP6GRE:
case NETPLAN_TUNNEL_MODE_IP6GRETAP:
case NETPLAN_TUNNEL_MODE_SIT:
case NETPLAN_TUNNEL_MODE_VTI:
case NETPLAN_TUNNEL_MODE_VTI6:
g_string_append_printf(s,
"Kind=%s\n",
tunnel_mode_to_string(def->tunnel.mode));
break;
case NETPLAN_TUNNEL_MODE_IP6IP6:
case NETPLAN_TUNNEL_MODE_IPIP6:
g_string_append(s, "Kind=ip6tnl\n");
break;
// LCOV_EXCL_START
default:
g_assert_not_reached();
// LCOV_EXCL_STOP
}
write_tunnel_params(s, def);
break;
// LCOV_EXCL_START
default:
g_assert_not_reached();
// LCOV_EXCL_STOP
}
/* these do not contain secrets and need to be readable by
* systemd-networkd - LP: #1736965 */
orig_umask = umask(022);
g_string_free_to_file(s, rootdir, path, ".netdev");
umask(orig_umask);
}
static void
write_route(NetplanIPRoute* r, GString* s)
{
g_string_append_printf(s, "\n[Route]\n");
g_string_append_printf(s, "Destination=%s\n", r->to);
if (r->via)
g_string_append_printf(s, "Gateway=%s\n", r->via);
if (r->from)
g_string_append_printf(s, "PreferredSource=%s\n", r->from);
if (g_strcmp0(r->scope, "global") != 0)
g_string_append_printf(s, "Scope=%s\n", r->scope);
if (g_strcmp0(r->type, "unicast") != 0)
g_string_append_printf(s, "Type=%s\n", r->type);
if (r->onlink)
g_string_append_printf(s, "GatewayOnlink=true\n");
if (r->metric != NETPLAN_METRIC_UNSPEC)
g_string_append_printf(s, "Metric=%d\n", r->metric);
if (r->table != NETPLAN_ROUTE_TABLE_UNSPEC)
g_string_append_printf(s, "Table=%d\n", r->table);
}
static void
write_ip_rule(NetplanIPRule* r, GString* s)
{
g_string_append_printf(s, "\n[RoutingPolicyRule]\n");
if (r->from)
g_string_append_printf(s, "From=%s\n", r->from);
if (r->to)
g_string_append_printf(s, "To=%s\n", r->to);
if (r->table != NETPLAN_ROUTE_TABLE_UNSPEC)
g_string_append_printf(s, "Table=%d\n", r->table);
if (r->priority != NETPLAN_IP_RULE_PRIO_UNSPEC)
g_string_append_printf(s, "Priority=%d\n", r->priority);
if (r->fwmark != NETPLAN_IP_RULE_FW_MARK_UNSPEC)
g_string_append_printf(s, "FirewallMark=%d\n", r->fwmark);
if (r->tos != NETPLAN_IP_RULE_TOS_UNSPEC)
g_string_append_printf(s, "TypeOfService=%d\n", r->tos);
}
#define DHCP_OVERRIDES_ERROR \
"ERROR: %s: networkd requires that %s has the same value in both " \
"dhcp4_overrides and dhcp6_overrides\n"
static void
combine_dhcp_overrides(const NetplanNetDefinition* def, NetplanDHCPOverrides* combined_dhcp_overrides)
{
/* if only one of dhcp4 or dhcp6 is enabled, those overrides are used */
if (def->dhcp4 && !def->dhcp6) {
*combined_dhcp_overrides = def->dhcp4_overrides;
} else if (!def->dhcp4 && def->dhcp6) {
*combined_dhcp_overrides = def->dhcp6_overrides;
} else {
/* networkd doesn't support separately configuring dhcp4 and dhcp6, so
* we enforce that they are the same.
*/
if (def->dhcp4_overrides.use_dns != def->dhcp6_overrides.use_dns) {
g_fprintf(stderr, DHCP_OVERRIDES_ERROR, def->id, "use-dns");
exit(1);
}
if (g_strcmp0(def->dhcp4_overrides.use_domains, def->dhcp6_overrides.use_domains) != 0){
g_fprintf(stderr, DHCP_OVERRIDES_ERROR, def->id, "use-domains");
exit(1);
}
if (def->dhcp4_overrides.use_ntp != def->dhcp6_overrides.use_ntp) {
g_fprintf(stderr, DHCP_OVERRIDES_ERROR, def->id, "use-ntp");
exit(1);
}
if (def->dhcp4_overrides.send_hostname != def->dhcp6_overrides.send_hostname) {
g_fprintf(stderr, DHCP_OVERRIDES_ERROR, def->id, "send-hostname");
exit(1);
}
if (def->dhcp4_overrides.use_hostname != def->dhcp6_overrides.use_hostname) {
g_fprintf(stderr, DHCP_OVERRIDES_ERROR, def->id, "use-hostname");
exit(1);
}
if (def->dhcp4_overrides.use_mtu != def->dhcp6_overrides.use_mtu) {
g_fprintf(stderr, DHCP_OVERRIDES_ERROR, def->id, "use-mtu");
exit(1);
}
if (g_strcmp0(def->dhcp4_overrides.hostname, def->dhcp6_overrides.hostname) != 0) {
g_fprintf(stderr, DHCP_OVERRIDES_ERROR, def->id, "hostname");
exit(1);
}
if (def->dhcp4_overrides.metric != def->dhcp6_overrides.metric) {
g_fprintf(stderr, DHCP_OVERRIDES_ERROR, def->id, "route-metric");
exit(1);
}
if (def->dhcp4_overrides.use_routes != def->dhcp6_overrides.use_routes) {
g_fprintf(stderr, DHCP_OVERRIDES_ERROR, def->id, "use-routes");
exit(1);
}
/* Just use dhcp4_overrides now, since we know they are the same. */
*combined_dhcp_overrides = def->dhcp4_overrides;
}
}
static void
write_network_file(const NetplanNetDefinition* def, const char* rootdir, const char* path)
{
GString* network = NULL;
GString* link = NULL;
GString* s = NULL;
mode_t orig_umask;
if (def->type == NETPLAN_DEF_TYPE_VLAN && def->sriov_vlan_filter) {
g_debug("%s is defined as a hardware SR-IOV filtered VLAN, postponing creation", def->id);
return;
}
/* Prepare the [Link] section of the .network file. */
link = g_string_sized_new(200);
/* Prepare the [Network] section */
network = g_string_sized_new(200);
if (def->optional || def->optional_addresses) {
if (def->optional) {
g_string_append(link, "RequiredForOnline=no\n");
}
for (unsigned i = 0; NETPLAN_OPTIONAL_ADDRESS_TYPES[i].name != NULL; ++i) {
if (def->optional_addresses & NETPLAN_OPTIONAL_ADDRESS_TYPES[i].flag) {
g_string_append_printf(link, "OptionalAddresses=%s\n", NETPLAN_OPTIONAL_ADDRESS_TYPES[i].name);
}
}
}
if (def->mtubytes) {
g_string_append_printf(link, "MTUBytes=%d\n", def->mtubytes);
}
if (def->emit_lldp) {
g_string_append(network, "EmitLLDP=true\n");
}
if (def->dhcp4 && def->dhcp6)
g_string_append(network, "DHCP=yes\n");
else if (def->dhcp4)
g_string_append(network, "DHCP=ipv4\n");
else if (def->dhcp6)
g_string_append(network, "DHCP=ipv6\n");
/* Set link local addressing -- this does not apply to bond and bridge
* member interfaces, which always get it disabled.
*/
if (!def->bond && !def->bridge && (def->linklocal.ipv4 || def->linklocal.ipv6)) {
if (def->linklocal.ipv4 && def->linklocal.ipv6)
g_string_append(network, "LinkLocalAddressing=yes\n");
else if (def->linklocal.ipv4)
g_string_append(network, "LinkLocalAddressing=ipv4\n");
else if (def->linklocal.ipv6)
g_string_append(network, "LinkLocalAddressing=ipv6\n");
} else {
g_string_append(network, "LinkLocalAddressing=no\n");
}
if (def->ip4_addresses)
for (unsigned i = 0; i < def->ip4_addresses->len; ++i)
g_string_append_printf(network, "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(network, "Address=%s\n", g_array_index(def->ip6_addresses, char*, i));
if (def->ip6_addr_gen_mode) {
/* TODO: Figure out how we can configure ipv6-address-generation for networkd.
* IPv6Token= seems to be the corresponding option, but it doesn't do
* exactly what we need and has quite some restrictions, c.f.:
* https://github.com/systemd/systemd/issues/4625
* https://github.com/systemd/systemd/pull/14415 */
g_fprintf(stderr, "ERROR: %s: ipv6-address-generation is not supported by networkd\n", def->id);
exit(1);
}
if (def->accept_ra == NETPLAN_RA_MODE_ENABLED)
g_string_append_printf(network, "IPv6AcceptRA=yes\n");
else if (def->accept_ra == NETPLAN_RA_MODE_DISABLED)
g_string_append_printf(network, "IPv6AcceptRA=no\n");
if (def->ip6_privacy)
g_string_append(network, "IPv6PrivacyExtensions=yes\n");
if (def->gateway4)
g_string_append_printf(network, "Gateway=%s\n", def->gateway4);
if (def->gateway6)
g_string_append_printf(network, "Gateway=%s\n", def->gateway6);
if (def->ip4_nameservers)
for (unsigned i = 0; i < def->ip4_nameservers->len; ++i)
g_string_append_printf(network, "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(network, "DNS=%s\n", g_array_index(def->ip6_nameservers, char*, i));
if (def->search_domains) {
g_string_append_printf(network, "Domains=%s", g_array_index(def->search_domains, char*, 0));
for (unsigned i = 1; i < def->search_domains->len; ++i)
g_string_append_printf(network, " %s", g_array_index(def->search_domains, char*, i));
g_string_append(network, "\n");
}
if (def->ipv6_mtubytes) {
g_string_append_printf(network, "IPv6MTUBytes=%d\n", def->ipv6_mtubytes);
}
if (def->type >= NETPLAN_DEF_TYPE_VIRTUAL)
g_string_append(network, "ConfigureWithoutCarrier=yes\n");
if (def->bridge) {
g_string_append_printf(network, "Bridge=%s\n", def->bridge);
if (def->bridge_params.path_cost || def->bridge_params.port_priority)
g_string_append_printf(network, "\n[Bridge]\n");
if (def->bridge_params.path_cost)
g_string_append_printf(network, "Cost=%u\n", def->bridge_params.path_cost);
if (def->bridge_params.port_priority)
g_string_append_printf(network, "Priority=%u\n", def->bridge_params.port_priority);
}
if (def->bond) {
g_string_append_printf(network, "Bond=%s\n", def->bond);
if (def->bond_params.primary_slave)
g_string_append_printf(network, "PrimarySlave=true\n");
}
if (def->has_vlans) {
/* iterate over all netdefs to find VLANs attached to us */
GList *l = netdefs_ordered;
const NetplanNetDefinition* nd;
for (; l != NULL; l = l->next) {
nd = l->data;
if (nd->vlan_link == def && !nd->sriov_vlan_filter)
g_string_append_printf(network, "VLAN=%s\n", nd->id);
}
}
if (def->routes != NULL) {
for (unsigned i = 0; i < def->routes->len; ++i) {
NetplanIPRoute* cur_route = g_array_index (def->routes, NetplanIPRoute*, i);
write_route(cur_route, network);
}
}
if (def->ip_rules != NULL) {
for (unsigned i = 0; i < def->ip_rules->len; ++i) {
NetplanIPRule* cur_rule = g_array_index (def->ip_rules, NetplanIPRule*, i);
write_ip_rule(cur_rule, network);
}
}
if (def->dhcp4 || def->dhcp6 || def->critical) {
/* NetworkManager compatible route metrics */
g_string_append(network, "\n[DHCP]\n");
}
if (def->critical)
g_string_append_printf(network, "CriticalConnection=true\n");
if (def->dhcp4 || def->dhcp6) {
if (g_strcmp0(def->dhcp_identifier, "duid") != 0)
g_string_append_printf(network, "ClientIdentifier=%s\n", def->dhcp_identifier);
NetplanDHCPOverrides combined_dhcp_overrides;
combine_dhcp_overrides(def, &combined_dhcp_overrides);
if (combined_dhcp_overrides.metric == NETPLAN_METRIC_UNSPEC) {
g_string_append_printf(network, "RouteMetric=%i\n", (def->type == NETPLAN_DEF_TYPE_WIFI ? 600 : 100));
} else {
g_string_append_printf(network, "RouteMetric=%u\n",
combined_dhcp_overrides.metric);
}
/* Only set MTU from DHCP if use-mtu dhcp-override is not false. */
if (!combined_dhcp_overrides.use_mtu) {
/* isc-dhcp dhclient compatible UseMTU, networkd default is to
* not accept MTU, which breaks clouds */
g_string_append_printf(network, "UseMTU=false\n");
} else {
g_string_append_printf(network, "UseMTU=true\n");
}
/* Only write DHCP options that differ from the networkd default. */
if (!combined_dhcp_overrides.use_routes)
g_string_append_printf(network, "UseRoutes=false\n");
if (!combined_dhcp_overrides.use_dns)
g_string_append_printf(network, "UseDNS=false\n");
if (combined_dhcp_overrides.use_domains)
g_string_append_printf(network, "UseDomains=%s\n", combined_dhcp_overrides.use_domains);
if (!combined_dhcp_overrides.use_ntp)
g_string_append_printf(network, "UseNTP=false\n");
if (!combined_dhcp_overrides.send_hostname)
g_string_append_printf(network, "SendHostname=false\n");
if (!combined_dhcp_overrides.use_hostname)
g_string_append_printf(network, "UseHostname=false\n");
if (combined_dhcp_overrides.hostname)
g_string_append_printf(network, "Hostname=%s\n", combined_dhcp_overrides.hostname);
}
if (network->len > 0 || link->len > 0) {
s = g_string_sized_new(200);
append_match_section(def, s, TRUE);
if (link->len > 0)
g_string_append_printf(s, "\n[Link]\n%s", link->str);
if (network->len > 0)
g_string_append_printf(s, "\n[Network]\n%s", network->str);
g_string_free(link, TRUE);
g_string_free(network, TRUE);
/* these do not contain secrets and need to be readable by
* systemd-networkd - LP: #1736965 */
orig_umask = umask(022);
g_string_free_to_file(s, rootdir, path, ".network");
umask(orig_umask);
}
}
static void
write_rules_file(const NetplanNetDefinition* def, const char* rootdir)
{
GString* s = NULL;
g_autofree char* path = g_strjoin(NULL, "run/udev/rules.d/99-netplan-", def->id, ".rules", NULL);
mode_t orig_umask;
/* 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 >= NETPLAN_DEF_TYPE_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);
orig_umask = umask(022);
g_string_free_to_file(s, rootdir, path, NULL);
umask(orig_umask);
}
static void
append_wpa_auth_conf(GString* s, const NetplanAuthenticationSettings* auth, const char* id)
{
switch (auth->key_management) {
case NETPLAN_AUTH_KEY_MANAGEMENT_NONE:
g_string_append(s, " key_mgmt=NONE\n");
break;
case NETPLAN_AUTH_KEY_MANAGEMENT_WPA_PSK:
g_string_append(s, " key_mgmt=WPA-PSK\n");
break;
case NETPLAN_AUTH_KEY_MANAGEMENT_WPA_EAP:
g_string_append(s, " key_mgmt=WPA-EAP\n");
break;
case NETPLAN_AUTH_KEY_MANAGEMENT_8021X:
g_string_append(s, " key_mgmt=IEEE8021X\n");
break;
}
switch (auth->eap_method) {
case NETPLAN_AUTH_EAP_NONE:
break;
case NETPLAN_AUTH_EAP_TLS:
g_string_append(s, " eap=TLS\n");
break;
case NETPLAN_AUTH_EAP_PEAP:
g_string_append(s, " eap=PEAP\n");
break;
case NETPLAN_AUTH_EAP_TTLS:
g_string_append(s, " eap=TTLS\n");
break;
}
if (auth->identity) {
g_string_append_printf(s, " identity=\"%s\"\n", auth->identity);
}
if (auth->anonymous_identity) {
g_string_append_printf(s, " anonymous_identity=\"%s\"\n", auth->anonymous_identity);
}
if (auth->password) {
if (auth->key_management == NETPLAN_AUTH_KEY_MANAGEMENT_WPA_PSK) {
size_t len = strlen(auth->password);
if (len == 64) {
/* must be a hex-digit key representation */
for (unsigned i = 0; i < 64; ++i)
if (!isxdigit(auth->password[i])) {
g_fprintf(stderr, "ERROR: %s: PSK length of 64 is only supported for hex-digit representation\n", id);
exit(1);
}
/* this is required to be unquoted */
g_string_append_printf(s, " psk=%s\n", auth->password);
} else if (len < 8 || len > 63) {
/* per wpa_supplicant spec, passphrase needs to be between 8
and 63 characters */
g_fprintf(stderr, "ERROR: %s: ASCII passphrase must be between 8 and 63 characters (inclusive)\n", id);
exit(1);
} else {
g_string_append_printf(s, " psk=\"%s\"\n", auth->password);
}
} else {
if (strncmp(auth->password, "hash:", 5) == 0) {
g_string_append_printf(s, " password=%s\n", auth->password);
} else {
g_string_append_printf(s, " password=\"%s\"\n", auth->password);
}
}
}
if (auth->ca_certificate) {
g_string_append_printf(s, " ca_cert=\"%s\"\n", auth->ca_certificate);
}
if (auth->client_certificate) {
g_string_append_printf(s, " client_cert=\"%s\"\n", auth->client_certificate);
}
if (auth->client_key) {
g_string_append_printf(s, " private_key=\"%s\"\n", auth->client_key);
}
if (auth->client_key_password) {
g_string_append_printf(s, " private_key_passwd=\"%s\"\n", auth->client_key_password);
}
if (auth->phase2_auth) {
g_string_append_printf(s, " phase2=\"auth=%s\"\n", auth->phase2_auth);
}
}
/* netplan-feature: generated-supplicant */
static void
write_wpa_unit(const NetplanNetDefinition* def, const char* rootdir)
{
g_autoptr(GError) err = NULL;
g_autofree gchar *stdouth = NULL;
g_autofree gchar *stderrh = NULL;
gint exit_status = 0;
gchar *argv[] = {"bin" "/" "systemd-escape", def->id, NULL};
g_spawn_sync("/", argv, NULL, 0, NULL, NULL, &stdouth, &stderrh, &exit_status, &err);
g_spawn_check_exit_status(exit_status, &err);
if (err != NULL) {
// LCOV_EXCL_START
g_fprintf(stderr, "failed to ask systemd to escape %s; exit %d\nstdout: '%s'\nstderr: '%s'", def->id, exit_status, stdouth, stderrh);
exit(1);
// LCOV_EXCL_STOP
}
g_strstrip(stdouth);
GString* s = g_string_new("[Unit]\n");
g_autofree char* path = g_strjoin(NULL, "/run/systemd/system/netplan-wpa-", stdouth, ".service", NULL);
g_string_append_printf(s, "Description=WPA supplicant for netplan %s\n", stdouth);
g_string_append(s, "DefaultDependencies=no\n");
g_string_append_printf(s, "Requires=sys-subsystem-net-devices-%s.device\n", stdouth);
g_string_append_printf(s, "After=sys-subsystem-net-devices-%s.device\n", stdouth);
g_string_append(s, "Before=network.target\nWants=network.target\n\n");
g_string_append(s, "[Service]\nType=simple\n");
g_string_append_printf(s, "ExecStart=/sbin/wpa_supplicant -c /run/netplan/wpa-%s.conf -i%s", stdouth, stdouth);
if (def->type != NETPLAN_DEF_TYPE_WIFI) {
g_string_append(s, " -Dwired\n");
}
g_string_free_to_file(s, rootdir, path, NULL);
}
static void
write_wpa_conf(const NetplanNetDefinition* def, const char* rootdir)
{
GHashTableIter iter;
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);
if (def->type == NETPLAN_DEF_TYPE_WIFI) {
if (def->wowlan && def->wowlan > NETPLAN_WIFI_WOWLAN_DEFAULT) {
g_string_append(s, "wowlan_triggers=");
append_wifi_wowlan_flags(def->wowlan, s);
}
NetplanWifiAccessPoint* ap;
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->bssid) {
g_string_append_printf(s, " bssid=%s\n", ap->bssid);
}
if (ap->band == NETPLAN_WIFI_BAND_24) {
// initialize 2.4GHz frequency hashtable
if(!wifi_frequency_24)
wifi_get_freq24(1);
if (ap->channel) {
g_string_append_printf(s, " freq_list=%d\n", wifi_get_freq24(ap->channel));
} else {
g_string_append_printf(s, " freq_list=");
g_hash_table_foreach(wifi_frequency_24, wifi_append_freq, s);
// overwrite last whitespace with newline
s = g_string_overwrite(s, s->len-1, "\n");
}
} else if (ap->band == NETPLAN_WIFI_BAND_5) {
// initialize 5GHz frequency hashtable
if(!wifi_frequency_5)
wifi_get_freq5(7);
if (ap->channel) {
g_string_append_printf(s, " freq_list=%d\n", wifi_get_freq5(ap->channel));
} else {
g_string_append_printf(s, " freq_list=");
g_hash_table_foreach(wifi_frequency_5, wifi_append_freq, s);
// overwrite last whitespace with newline
s = g_string_overwrite(s, s->len-1, "\n");
}
}
switch (ap->mode) {
case NETPLAN_WIFI_MODE_INFRASTRUCTURE:
/* default in wpasupplicant */
break;
case NETPLAN_WIFI_MODE_ADHOC:
g_string_append(s, " mode=1\n");
break;
case NETPLAN_WIFI_MODE_AP:
g_fprintf(stderr, "ERROR: %s: networkd does not support wifi in access point mode\n", def->id);
exit(1);
}
/* wifi auth trumps netdef auth */
if (ap->has_auth) {
append_wpa_auth_conf(s, &ap->auth, ap->ssid);
}
else {
g_string_append(s, " key_mgmt=NONE\n");
}
g_string_append(s, "}\n");
}
}
else {
/* wired 802.1x auth or similar */
g_string_append(s, "network={\n");
append_wpa_auth_conf(s, &def->auth, def->id);
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(const NetplanNetDefinition* 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 != NETPLAN_BACKEND_NETWORKD) {
g_debug("networkd: definition %s is not for us (backend %i)", def->id, def->backend);
return FALSE;
}
if (def->type == NETPLAN_DEF_TYPE_MODEM) {
g_fprintf(stderr, "ERROR: %s: networkd backend does not support GSM/CDMA modem configuration\n", def->id);
exit(1);
}
if (def->type == NETPLAN_DEF_TYPE_WIFI || def->has_auth) {
g_autofree char* link = g_strjoin(NULL, rootdir ?: "", "/run/systemd/system/systemd-networkd.service.wants/netplan-wpa-", def->id, ".service", NULL);
g_autofree char* slink = g_strjoin(NULL, "/run/systemd/system/netplan-wpa-", def->id, ".service", NULL);
if (def->type == NETPLAN_DEF_TYPE_WIFI && 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);
}
g_debug("Creating wpa_supplicant config");
write_wpa_conf(def, rootdir);
g_debug("Creating wpa_supplicant unit %s", slink);
write_wpa_unit(def, rootdir);
g_debug("Creating wpa_supplicant service enablement link %s", link);
safe_mkdir_p_dir(link);
if (symlink(slink, link) < 0 && errno != EEXIST) {
// LCOV_EXCL_START
g_fprintf(stderr, "failed to create enablement symlink: %m\n");
exit(1);
// LCOV_EXCL_STOP
}
}
if (def->type >= NETPLAN_DEF_TYPE_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/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) {
// LCOV_EXCL_START
g_fprintf(stderr, "failed to create enablement symlink: %m\n");
exit(1);
// LCOV_EXCL_STOP
}
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) {
// LCOV_EXCL_START
g_fprintf(stderr, "failed to create enablement symlink: %m\n");
exit(1);
// LCOV_EXCL_STOP
}
}
netplan.io-0.99/src/networkd.h 0000664 0000000 0000000 00000001577 13646002212 0016325 0 ustar 00root root 0000000 0000000 /*
* 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(const NetplanNetDefinition* def, const char* rootdir);
void cleanup_networkd_conf(const char* rootdir);
void enable_networkd(const char* generator_dir);
netplan.io-0.99/src/nm.c 0000664 0000000 0000000 00000074402 13646002212 0015072 0 ustar 00root root 0000000 0000000 /*
* 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 NetplanNetDefinition* 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 >= NETPLAN_DEF_TYPE_VIRTUAL) {
/* we always have the renamed name here */
g_string_append_printf(s, "interface-name:%s",
(def->type >= NETPLAN_DEF_TYPE_VIRTUAL) ? def->id
: (def->set_name ?: def->match.original_name));
} else {
/* no matches â match all devices of that type */
switch (def->type) {
case NETPLAN_DEF_TYPE_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 NETPLAN_DEF_TYPE_WIFI:
g_string_append(s, "type:wifi");
break;
*/
// LCOV_EXCL_START
default:
g_assert_not_reached();
// LCOV_EXCL_STOP
}
}
}
/**
* Infer if this is a modem netdef of type GSM.
* This is done by checking for certain modem_params, which are only
* applicable to GSM connections.
*/
static const gboolean
modem_is_gsm(const NetplanNetDefinition* def)
{
if (def->type == NETPLAN_DEF_TYPE_MODEM && (def->modem_params.apn ||
def->modem_params.auto_config || def->modem_params.device_id ||
def->modem_params.network_id || def->modem_params.pin ||
def->modem_params.sim_id || def->modem_params.sim_operator_id))
return TRUE;
return FALSE;
}
/**
* Return NM "type=" string.
*/
static const char*
type_str(const NetplanNetDefinition* def)
{
const NetplanDefType type = def->type;
switch (type) {
case NETPLAN_DEF_TYPE_ETHERNET:
return "ethernet";
case NETPLAN_DEF_TYPE_MODEM:
if (modem_is_gsm(def))
return "gsm";
else
return "cdma";
case NETPLAN_DEF_TYPE_WIFI:
return "wifi";
case NETPLAN_DEF_TYPE_BRIDGE:
return "bridge";
case NETPLAN_DEF_TYPE_BOND:
return "bond";
case NETPLAN_DEF_TYPE_VLAN:
return "vlan";
case NETPLAN_DEF_TYPE_TUNNEL:
return "ip-tunnel";
// LCOV_EXCL_START
default:
g_assert_not_reached();
// LCOV_EXCL_STOP
}
}
/**
* Return NM wifi "mode=" string.
*/
static const char*
wifi_mode_str(const NetplanWifiMode mode)
{
switch (mode) {
case NETPLAN_WIFI_MODE_INFRASTRUCTURE:
return "infrastructure";
case NETPLAN_WIFI_MODE_ADHOC:
return "adhoc";
case NETPLAN_WIFI_MODE_AP:
return "ap";
// LCOV_EXCL_START
default:
g_assert_not_reached();
// LCOV_EXCL_STOP
}
}
/**
* Return NM wifi "band=" string.
*/
static const char*
wifi_band_str(const NetplanWifiBand band)
{
switch (band) {
case NETPLAN_WIFI_BAND_5:
return "a";
case NETPLAN_WIFI_BAND_24:
return "bg";
// LCOV_EXCL_START
default:
g_assert_not_reached();
// LCOV_EXCL_STOP
}
}
/**
* Return NM addr-gen-mode string.
*/
static const char*
addr_gen_mode_str(const NetplanAddrGenMode mode)
{
switch (mode) {
case NETPLAN_ADDRGEN_EUI64:
return "0";
case NETPLAN_ADDRGEN_STABLEPRIVACY:
return "1";
// LCOV_EXCL_START
default:
g_assert_not_reached();
// LCOV_EXCL_STOP
}
}
static void
write_search_domains(const NetplanNetDefinition* 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 NetplanNetDefinition* def, GString *s, int family)
{
if (def->routes != NULL) {
for (unsigned i = 0, j = 1; i < def->routes->len; ++i) {
const NetplanIPRoute *cur_route = g_array_index(def->routes, NetplanIPRoute*, i);
if (cur_route->family != family)
continue;
if (cur_route->type && g_ascii_strcasecmp(cur_route->type, "unicast") != 0) {
g_fprintf(stderr, "ERROR: %s: NetworkManager only supports unicast routes\n", def->id);
exit(1);
}
if (cur_route->scope && g_ascii_strcasecmp(cur_route->scope, "global") != 0) {
g_fprintf(stderr, "ERROR: %s: NetworkManager only supports global scoped routes\n", def->id);
exit(1);
}
if (cur_route->table != NETPLAN_ROUTE_TABLE_UNSPEC) {
g_fprintf(stderr, "ERROR: %s: NetworkManager does not support non-default routing tables\n", def->id);
exit(1);
}
if (cur_route->from) {
g_fprintf(stderr, "ERROR: %s: NetworkManager does not support routes with 'from'\n", def->id);
exit(1);
}
if (cur_route->onlink) {
g_fprintf(stderr, "ERROR: %s: NetworkManager does not support on-link routes\n", def->id);
exit(1);
}
g_string_append_printf(s, "route%d=%s,%s",
j, cur_route->to, cur_route->via);
if (cur_route->metric != NETPLAN_METRIC_UNSPEC)
g_string_append_printf(s, ",%d", cur_route->metric);
g_string_append(s, "\n");
j++;
}
}
}
static void
write_bond_parameters(const NetplanNetDefinition* 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.gratuitous_arp) {
g_string_append_printf(params, "\nnum_grat_arp=%d", def->bond_params.gratuitous_arp);
/* Work around issue in NM where unset unsolicited_na will overwrite num_grat_arp:
* https://github.com/NetworkManager/NetworkManager/commit/42b0bef33c77a0921590b2697f077e8ea7805166 */
g_string_append_printf(params, "\nnum_unsol_na=%d", def->bond_params.gratuitous_arp);
}
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 NetplanNetDefinition* 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
write_tunnel_params(const NetplanNetDefinition* def, GString *s)
{
g_string_append(s, "\n[ip-tunnel]\n");
g_string_append_printf(s, "mode=%d\n", def->tunnel.mode);
g_string_append_printf(s, "local=%s\n", def->tunnel.local_ip);
g_string_append_printf(s, "remote=%s\n", def->tunnel.remote_ip);
if (def->tunnel.input_key)
g_string_append_printf(s, "input-key=%s\n", def->tunnel.input_key);
if (def->tunnel.output_key)
g_string_append_printf(s, "output-key=%s\n", def->tunnel.output_key);
}
static void
write_dot1x_auth_parameters(const NetplanAuthenticationSettings* auth, GString *s)
{
if (auth->eap_method == NETPLAN_AUTH_EAP_NONE) {
return;
}
g_string_append_printf(s, "\n[802-1x]\n");
switch (auth->eap_method) {
case NETPLAN_AUTH_EAP_NONE: break; // LCOV_EXCL_LINE
case NETPLAN_AUTH_EAP_TLS:
g_string_append(s, "eap=tls\n");
break;
case NETPLAN_AUTH_EAP_PEAP:
g_string_append(s, "eap=peap\n");
break;
case NETPLAN_AUTH_EAP_TTLS:
g_string_append(s, "eap=ttls\n");
break;
}
if (auth->identity) {
g_string_append_printf(s, "identity=%s\n", auth->identity);
}
if (auth->anonymous_identity) {
g_string_append_printf(s, "anonymous-identity=%s\n", auth->anonymous_identity);
}
if (auth->password && auth->key_management != NETPLAN_AUTH_KEY_MANAGEMENT_WPA_PSK) {
g_string_append_printf(s, "password=%s\n", auth->password);
}
if (auth->ca_certificate) {
g_string_append_printf(s, "ca-cert=%s\n", auth->ca_certificate);
}
if (auth->client_certificate) {
g_string_append_printf(s, "client-cert=%s\n", auth->client_certificate);
}
if (auth->client_key) {
g_string_append_printf(s, "private-key=%s\n", auth->client_key);
}
if (auth->client_key_password) {
g_string_append_printf(s, "private-key-password=%s\n", auth->client_key_password);
}
if (auth->phase2_auth) {
g_string_append_printf(s, "phase2-auth=%s\n", auth->phase2_auth);
}
}
static void
write_wifi_auth_parameters(const NetplanAuthenticationSettings* auth, GString *s)
{
if (auth->key_management == NETPLAN_AUTH_KEY_MANAGEMENT_NONE) {
return;
}
g_string_append(s, "\n[wifi-security]\n");
switch (auth->key_management) {
case NETPLAN_AUTH_KEY_MANAGEMENT_NONE: break; // LCOV_EXCL_LINE
case NETPLAN_AUTH_KEY_MANAGEMENT_WPA_PSK:
g_string_append(s, "key-mgmt=wpa-psk\n");
if (auth->password) {
g_string_append_printf(s, "psk=%s\n", auth->password);
}
break;
case NETPLAN_AUTH_KEY_MANAGEMENT_WPA_EAP:
g_string_append(s, "key-mgmt=wpa-eap\n");
break;
case NETPLAN_AUTH_KEY_MANAGEMENT_8021X:
g_string_append(s, "key-mgmt=ieee8021x\n");
break;
}
write_dot1x_auth_parameters(auth, s);
}
static void
maybe_generate_uuid(NetplanNetDefinition* def)
{
if (uuid_is_null(def->uuid))
uuid_generate(def->uuid);
}
/**
* Generate NetworkManager configuration in @rootdir/run/NetworkManager/ for a
* particular NetplanNetDefinition and NetplanWifiAccessPoint, as NM requires a separate
* connection file for each SSID.
* @def: The NetplanNetDefinition 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(NetplanNetDefinition* def, const char* rootdir, const NetplanWifiAccessPoint* ap)
{
GString *s = NULL;
g_autofree char* conf_path = NULL;
mode_t orig_umask;
char uuidstr[37];
if (def->type == NETPLAN_DEF_TYPE_WIFI)
g_assert(ap);
else
g_assert(ap == NULL);
if (def->type == NETPLAN_DEF_TYPE_VLAN && def->sriov_vlan_filter) {
g_debug("%s is defined as a hardware SR-IOV filtered VLAN, postponing creation", def->id);
return;
}
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));
/* 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 < NETPLAN_DEF_TYPE_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 == NETPLAN_DEF_TYPE_BRIDGE)
write_bridge_params(def, s);
}
if (def->type == NETPLAN_DEF_TYPE_MODEM) {
if (modem_is_gsm(def))
g_string_append_printf(s, "\n[gsm]\n");
else
g_string_append_printf(s, "\n[cdma]\n");
/* Use NetworkManager's auto configuration feature if no APN, username, or password is specified */
if (def->modem_params.auto_config || (!def->modem_params.apn &&
!def->modem_params.username && !def->modem_params.password)) {
g_string_append_printf(s, "auto-config=true\n");
} else {
if (def->modem_params.apn)
g_string_append_printf(s, "apn=%s\n", def->modem_params.apn);
if (def->modem_params.password)
g_string_append_printf(s, "password=%s\n", def->modem_params.password);
if (def->modem_params.username)
g_string_append_printf(s, "username=%s\n", def->modem_params.username);
}
if (def->modem_params.device_id)
g_string_append_printf(s, "device-id=%s\n", def->modem_params.device_id);
if (def->mtubytes)
g_string_append_printf(s, "mtu=%u\n", def->mtubytes);
if (def->modem_params.network_id)
g_string_append_printf(s, "network-id=%s\n", def->modem_params.network_id);
if (def->modem_params.number)
g_string_append_printf(s, "number=%s\n", def->modem_params.number);
if (def->modem_params.pin)
g_string_append_printf(s, "pin=%s\n", def->modem_params.pin);
if (def->modem_params.sim_id)
g_string_append_printf(s, "sim-id=%s\n", def->modem_params.sim_id);
if (def->modem_params.sim_operator_id)
g_string_append_printf(s, "sim-operator-id=%s\n", def->modem_params.sim_operator_id);
}
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->ipv6_mtubytes) {
g_fprintf(stderr, "ERROR: %s: NetworkManager definitions do not support ipv6-mtu\n", def->id);
exit(1);
}
if (def->type < NETPLAN_DEF_TYPE_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 (def->wowlan && def->wowlan > NETPLAN_WIFI_WOWLAN_DEFAULT)
g_string_append_printf(link_str, "wake-on-wlan=%u\n", def->wowlan);
if (link_str->len > 0) {
switch (def->type) {
case NETPLAN_DEF_TYPE_WIFI:
g_string_append_printf(s, "\n[802-11-wireless]\n%s", link_str->str); break;
case NETPLAN_DEF_TYPE_MODEM:
/* Avoid adding an [ethernet] section into the [gsm/cdma] description. */
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 == NETPLAN_DEF_TYPE_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 == NETPLAN_DEF_TYPE_BOND)
write_bond_parameters(def, s);
if (def->type == NETPLAN_DEF_TYPE_TUNNEL)
write_tunnel_params(def, s);
g_string_append(s, "\n[ipv4]\n");
if (ap && ap->mode == NETPLAN_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 if (def->type == NETPLAN_DEF_TYPE_TUNNEL)
/* sit tunnels will not start in link-local apparently */
g_string_append(s, "method=disabled\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");
}
/* We can only write search domains and routes if we have an address */
if (def->ip4_addresses || def->dhcp4) {
write_search_domains(def, s);
write_routes(def, s, AF_INET);
}
if (!def->dhcp4_overrides.use_routes) {
g_string_append(s, "ignore-auto-routes=true\n");
g_string_append(s, "never-default=true\n");
}
if (def->dhcp4 && def->dhcp4_overrides.metric != NETPLAN_METRIC_UNSPEC)
g_string_append_printf(s, "route-metric=%u\n", def->dhcp4_overrides.metric);
if (def->dhcp6 || def->ip6_addresses || def->gateway6 || def->ip6_nameservers || def->ip6_addr_gen_mode) {
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->ip6_addr_gen_mode) {
g_string_append_printf(s, "addr-gen-mode=%s\n", addr_gen_mode_str(def->ip6_addr_gen_mode));
}
if (def->ip6_privacy)
g_string_append(s, "ip6-privacy=2\n");
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] --
* We need to specify it here for the IPv6-only case - see LP: #1786726 */
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);
if (!def->dhcp6_overrides.use_routes) {
g_string_append(s, "ignore-auto-routes=true\n");
g_string_append(s, "never-default=true\n");
}
if (def->dhcp6_overrides.metric != NETPLAN_METRIC_UNSPEC)
g_string_append_printf(s, "route-metric=%u\n", def->dhcp6_overrides.metric);
}
else {
g_string_append(s, "\n[ipv6]\nmethod=ignore\n");
}
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, ".nmconnection", NULL);
g_string_append_printf(s, "\n[wifi]\nssid=%s\nmode=%s\n", ap->ssid, wifi_mode_str(ap->mode));
if (ap->bssid) {
g_string_append_printf(s, "bssid=%s\n", ap->bssid);
}
if (ap->band == NETPLAN_WIFI_BAND_5 || ap->band == NETPLAN_WIFI_BAND_24) {
g_string_append_printf(s, "band=%s\n", wifi_band_str(ap->band));
/* Channel is only unambiguous, if band is set. */
if (ap->channel) {
/* Validate WiFi channel */
if (ap->band == NETPLAN_WIFI_BAND_5)
wifi_get_freq5(ap->channel);
else
wifi_get_freq24(ap->channel);
g_string_append_printf(s, "channel=%u\n", ap->channel);
}
}
if (ap->has_auth) {
write_wifi_auth_parameters(&ap->auth, s);
}
} else {
conf_path = g_strjoin(NULL, "run/NetworkManager/system-connections/netplan-", def->id, ".nmconnection", NULL);
if (def->has_auth) {
write_dot1x_auth_parameters(&def->auth, s);
}
}
/* 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 NetplanNetDefinition.
* @rootdir: If not %NULL, generate configuration in this root directory
* (useful for testing).
*/
void
write_nm_conf(NetplanNetDefinition* def, const char* rootdir)
{
if (def->backend != NETPLAN_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 == NETPLAN_DEF_TYPE_WIFI) {
GHashTableIter iter;
gpointer key;
const NetplanWifiAccessPoint* 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 data, gpointer str)
{
const NetplanNetDefinition* nd = data;
if (nd->backend != NETPLAN_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_list_foreach(netdefs_ordered, 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-*");
}
netplan.io-0.99/src/nm.h 0000664 0000000 0000000 00000001550 13646002212 0015071 0 ustar 00root root 0000000 0000000 /*
* 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(NetplanNetDefinition* def, const char* rootdir);
void write_nm_conf_finish(const char* rootdir);
void cleanup_nm_conf(const char* rootdir);
netplan.io-0.99/src/parse.c 0000664 0000000 0000000 00000230427 13646002212 0015573 0 ustar 00root root 0000000 0000000 /*
* 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 "parse.h"
#include "error.h"
#include "validation.h"
/* convenience macro to put the offset of a NetplanNetDefinition field into "void* data" */
#define netdef_offset(field) GUINT_TO_POINTER(offsetof(NetplanNetDefinition, field))
#define route_offset(field) GUINT_TO_POINTER(offsetof(NetplanIPRoute, field))
#define ip_rule_offset(field) GUINT_TO_POINTER(offsetof(NetplanIPRule, field))
#define auth_offset(field) GUINT_TO_POINTER(offsetof(NetplanAuthenticationSettings, field))
#define access_point_offset(field) GUINT_TO_POINTER(offsetof(NetplanWifiAccessPoint, field))
/* NetplanNetDefinition that is currently being processed */
static NetplanNetDefinition* cur_netdef;
/* NetplanWifiAccessPoint that is currently being processed */
static NetplanWifiAccessPoint* cur_access_point;
/* authentication options that are currently being processed */
static NetplanAuthenticationSettings* cur_auth;
static NetplanIPRoute* cur_route;
static NetplanIPRule* cur_ip_rule;
static NetplanBackend backend_global, backend_cur_type;
/* Global ID â NetplanNetDefinition* map for all parsed config files */
GHashTable* netdefs;
/* Contains the same objects as 'netdefs' but ordered by dependency */
GList* netdefs_ordered;
/* 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 */
static GHashTable* ids_in_file;
/**
* 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)) {
ret = parser_error(&parser, yaml, error);
}
yaml_parser_delete(&parser);
fclose(fyaml);
return ret;
}
#define YAML_VARIABLE_NODE YAML_NO_NODE
/**
* 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_VARIABLE_NODE:
/* Special case, defer sanity checking to the next handlers */
return TRUE;
break;
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 (check indentation)");
break;
// LCOV_EXCL_START
default:
g_assert_not_reached();
// LCOV_EXCL_STOP
}
return FALSE;
}
#define assert_type(n,t) { if (!assert_type_fn(n,t,error)) 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)
{
NetplanMissingNode* 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(NetplanMissingNode, 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;
assert_type(node, 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;
}
/****************************************************
* 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;
g_assert(*error == NULL);
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(key, 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 helper functions to extract data from scalar nodes.
*************************************************************/
/**
* Handler for setting a guint field from a scalar node, inside a given struct
* @entryptr: pointer to the begining of the to-be-modified data structure
* @data: offset into entryptr struct where the guint field to write is located
*/
static gboolean
handle_generic_guint(yaml_document_t* doc, yaml_node_t* node, const void* entryptr, const void* data, GError** error)
{
g_assert(entryptr);
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*) entryptr + offset)) = (guint) v;
return TRUE;
}
/**
* Handler for setting a string field from a scalar node, inside a given struct
* @entryptr: pointer to the beginning of the to-be-modified data structure
* @data: offset into entryptr struct where the const char* field to write is
* located
*/
static gboolean
handle_generic_str(yaml_document_t* doc, yaml_node_t* node, void* entryptr, const void* data, GError** error)
{
g_assert(entryptr);
guint offset = GPOINTER_TO_UINT(data);
char** dest = (char**) ((void*) entryptr + offset);
g_free(*dest);
*dest = g_strdup(scalar(node));
return TRUE;
}
/*
* Handler for setting a MAC address field from a scalar node, inside a given struct
* @entryptr: pointer to the beginning of the to-be-modified data structure
* @data: offset into entryptr struct where the const char* field to write is
* located
*/
static gboolean
handle_generic_mac(yaml_document_t* doc, yaml_node_t* node, void* entryptr, const void* data, GError** error)
{
g_assert(entryptr);
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_generic_str(doc, node, entryptr, data, error);
}
/**
* Generic handler for setting a cur_netdef string field from a scalar node
* @data: offset into NetplanNetDefinition 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)
{
return handle_generic_str(doc, node, cur_netdef, data, error);
}
/**
* Generic handler for setting a cur_netdef ID/iface name field from a scalar node
* @data: offset into NetplanNetDefinition 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 referring to an
* existing ID from a scalar node
* @data: offset into NetplanNetDefinition where the NetplanNetDefinition* 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);
NetplanNetDefinition* ref = NULL;
ref = g_hash_table_lookup(netdefs, scalar(node));
if (!ref) {
add_missing_node(node);
} else {
*((NetplanNetDefinition**) ((void*) cur_netdef + offset)) = ref;
}
return TRUE;
}
/**
* Generic handler for setting a cur_netdef MAC address field from a scalar node
* @data: offset into NetplanNetDefinition 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)
{
return handle_generic_mac(doc, node, cur_netdef, data, error);
}
/**
* Generic handler for setting a cur_netdef gboolean field from a scalar node
* @data: offset into NetplanNetDefinition 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 NetplanNetDefinition 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)
{
return handle_generic_guint(doc, node, cur_netdef, data, error);
}
static gboolean
handle_netdef_ip4(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_autofree char* addr = NULL;
char* prefix_len;
/* these addresses can't have /prefix_len */
addr = g_strdup(scalar(node));
prefix_len = strrchr(addr, '/');
/* FIXME: stop excluding this from coverage; refactor address handling instead */
// LCOV_EXCL_START
if (prefix_len)
return yaml_error(node, error,
"invalid address: a single IPv4 address (without /prefixlength) is required");
/* is it an IPv4 address? */
if (!is_ip4_address(addr))
return yaml_error(node, error,
"invalid IPv4 address: %s", scalar(node));
// LCOV_EXCL_STOP
g_free(*dest);
*dest = g_strdup(scalar(node));
return TRUE;
}
static gboolean
handle_netdef_ip6(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_autofree char* addr = NULL;
char* prefix_len;
/* these addresses can't have /prefix_len */
addr = g_strdup(scalar(node));
prefix_len = strrchr(addr, '/');
/* FIXME: stop excluding this from coverage; refactor address handling instead */
// LCOV_EXCL_START
if (prefix_len)
return yaml_error(node, error,
"invalid address: a single IPv6 address (without /prefixlength) is required");
/* is it an IPv6 address? */
if (!is_ip6_address(addr))
return yaml_error(node, error,
"invalid IPv6 address: %s", scalar(node));
// LCOV_EXCL_STOP
g_free(*dest);
*dest = g_strdup(scalar(node));
return TRUE;
}
static gboolean
handle_netdef_addrgen(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
g_assert(cur_netdef);
if (strcmp(scalar(node), "eui64") == 0)
cur_netdef->ip6_addr_gen_mode = NETPLAN_ADDRGEN_EUI64;
else if (strcmp(scalar(node), "stable-privacy") == 0)
cur_netdef->ip6_addr_gen_mode = NETPLAN_ADDRGEN_STABLEPRIVACY;
else
return yaml_error(node, error, "unknown ipv6-address-generation '%s'", scalar(node));
return TRUE;
}
/****************************************************
* Grammar and handlers for network config "match" entry
****************************************************/
static 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 config "auth" entry
****************************************************/
static gboolean
handle_auth_str(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error)
{
g_assert(cur_auth);
guint offset = GPOINTER_TO_UINT(data);
char** dest = (char**) ((void*) cur_auth + offset);
g_free(*dest);
*dest = g_strdup(scalar(node));
return TRUE;
}
static gboolean
handle_auth_key_management(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
g_assert(cur_auth);
if (strcmp(scalar(node), "none") == 0)
cur_auth->key_management = NETPLAN_AUTH_KEY_MANAGEMENT_NONE;
else if (strcmp(scalar(node), "psk") == 0)
cur_auth->key_management = NETPLAN_AUTH_KEY_MANAGEMENT_WPA_PSK;
else if (strcmp(scalar(node), "eap") == 0)
cur_auth->key_management = NETPLAN_AUTH_KEY_MANAGEMENT_WPA_EAP;
else if (strcmp(scalar(node), "802.1x") == 0)
cur_auth->key_management = NETPLAN_AUTH_KEY_MANAGEMENT_8021X;
else
return yaml_error(node, error, "unknown key management type '%s'", scalar(node));
return TRUE;
}
static gboolean
handle_auth_method(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
g_assert(cur_auth);
if (strcmp(scalar(node), "tls") == 0)
cur_auth->eap_method = NETPLAN_AUTH_EAP_TLS;
else if (strcmp(scalar(node), "peap") == 0)
cur_auth->eap_method = NETPLAN_AUTH_EAP_PEAP;
else if (strcmp(scalar(node), "ttls") == 0)
cur_auth->eap_method = NETPLAN_AUTH_EAP_TTLS;
else
return yaml_error(node, error, "unknown EAP method '%s'", scalar(node));
return TRUE;
}
static const mapping_entry_handler auth_handlers[] = {
{"key-management", YAML_SCALAR_NODE, handle_auth_key_management},
{"method", YAML_SCALAR_NODE, handle_auth_method},
{"identity", YAML_SCALAR_NODE, handle_auth_str, NULL, auth_offset(identity)},
{"anonymous-identity", YAML_SCALAR_NODE, handle_auth_str, NULL, auth_offset(anonymous_identity)},
{"password", YAML_SCALAR_NODE, handle_auth_str, NULL, auth_offset(password)},
{"ca-certificate", YAML_SCALAR_NODE, handle_auth_str, NULL, auth_offset(ca_certificate)},
{"client-certificate", YAML_SCALAR_NODE, handle_auth_str, NULL, auth_offset(client_certificate)},
{"client-key", YAML_SCALAR_NODE, handle_auth_str, NULL, auth_offset(client_key)},
{"client-key-password", YAML_SCALAR_NODE, handle_auth_str, NULL, auth_offset(client_key_password)},
{"phase2-auth", YAML_SCALAR_NODE, handle_auth_str, NULL, auth_offset(phase2_auth)},
{NULL}
};
/****************************************************
* Grammar and handlers for network device definition
****************************************************/
static NetplanBackend
get_default_backend_for_type(NetplanDefType type)
{
if (backend_global != NETPLAN_BACKEND_NONE)
return backend_global;
/* networkd can handle all device types at the moment, so nothing
* type-specific */
return NETPLAN_BACKEND_NETWORKD;
}
static gboolean
handle_access_point_guint(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error)
{
return handle_generic_guint(doc, node, cur_access_point, data, error);
}
static gboolean
handle_access_point_mac(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error)
{
return handle_generic_mac(doc, node, cur_access_point, data, error);
}
static gboolean
handle_access_point_password(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
g_assert(cur_access_point);
/* shortcut for WPA-PSK */
cur_access_point->has_auth = TRUE;
cur_access_point->auth.key_management = NETPLAN_AUTH_KEY_MANAGEMENT_WPA_PSK;
g_free(cur_access_point->auth.password);
cur_access_point->auth.password = g_strdup(scalar(node));
return TRUE;
}
static gboolean
handle_access_point_auth(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
gboolean ret;
g_assert(cur_access_point);
cur_access_point->has_auth = TRUE;
cur_auth = &cur_access_point->auth;
ret = process_mapping(doc, node, auth_handlers, error);
cur_auth = NULL;
return ret;
}
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 = NETPLAN_WIFI_MODE_INFRASTRUCTURE;
else if (strcmp(scalar(node), "adhoc") == 0)
cur_access_point->mode = NETPLAN_WIFI_MODE_ADHOC;
else if (strcmp(scalar(node), "ap") == 0)
cur_access_point->mode = NETPLAN_WIFI_MODE_AP;
else
return yaml_error(node, error, "unknown wifi mode '%s'", scalar(node));
return TRUE;
}
static gboolean
handle_access_point_band(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
g_assert(cur_access_point);
if (strcmp(scalar(node), "5GHz") == 0 || strcmp(scalar(node), "5G") == 0)
cur_access_point->band = NETPLAN_WIFI_BAND_5;
else if (strcmp(scalar(node), "2.4GHz") == 0 || strcmp(scalar(node), "2.4G") == 0)
cur_access_point->band = NETPLAN_WIFI_BAND_24;
else
return yaml_error(node, error, "unknown wifi band '%s'", scalar(node));
return TRUE;
}
static const mapping_entry_handler wifi_access_point_handlers[] = {
{"band", YAML_SCALAR_NODE, handle_access_point_band},
{"bssid", YAML_SCALAR_NODE, handle_access_point_mac, NULL, access_point_offset(bssid)},
{"channel", YAML_SCALAR_NODE, handle_access_point_guint, NULL, access_point_offset(channel)},
{"mode", YAML_SCALAR_NODE, handle_access_point_mode},
{"password", YAML_SCALAR_NODE, handle_access_point_password},
{"auth", YAML_MAPPING_NODE, handle_access_point_auth},
{NULL}
};
/**
* Parse scalar node's string into a netdef_backend.
*/
static gboolean
parse_renderer(yaml_node_t* node, NetplanBackend* backend, GError** error)
{
if (strcmp(scalar(node), "networkd") == 0)
*backend = NETPLAN_BACKEND_NETWORKD;
else if (strcmp(scalar(node), "NetworkManager") == 0)
*backend = NETPLAN_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)
{
if (cur_netdef->type == NETPLAN_DEF_TYPE_VLAN) {
if (strcmp(scalar(node), "sriov") == 0) {
cur_netdef->sriov_vlan_filter = TRUE;
return TRUE;
}
}
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 = NETPLAN_RA_MODE_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 = NETPLAN_RA_MODE_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);
}
struct NetplanWifiWowlanType NETPLAN_WIFI_WOWLAN_TYPES[] = {
{"default", NETPLAN_WIFI_WOWLAN_DEFAULT},
{"any", NETPLAN_WIFI_WOWLAN_ANY},
{"disconnect", NETPLAN_WIFI_WOWLAN_DISCONNECT},
{"magic_pkt", NETPLAN_WIFI_WOWLAN_MAGIC},
{"gtk_rekey_failure", NETPLAN_WIFI_WOWLAN_GTK_REKEY_FAILURE},
{"eap_identity_req", NETPLAN_WIFI_WOWLAN_EAP_IDENTITY_REQ},
{"four_way_handshake", NETPLAN_WIFI_WOWLAN_4WAY_HANDSHAKE},
{"rfkill_release", NETPLAN_WIFI_WOWLAN_RFKILL_RELEASE},
{"tcp", NETPLAN_WIFI_WOWLAN_TCP},
{NULL},
};
static gboolean
handle_wowlan(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);
int found = FALSE;
for (unsigned i = 0; NETPLAN_WIFI_WOWLAN_TYPES[i].name != NULL; ++i) {
if (g_ascii_strcasecmp(scalar(entry), NETPLAN_WIFI_WOWLAN_TYPES[i].name) == 0) {
cur_netdef->wowlan |= NETPLAN_WIFI_WOWLAN_TYPES[i].flag;
found = TRUE;
break;
}
}
if (!found)
return yaml_error(node, error, "invalid value for wakeonwlan: '%s'", scalar(entry));
}
if (cur_netdef->wowlan > NETPLAN_WIFI_WOWLAN_DEFAULT && cur_netdef->wowlan & NETPLAN_WIFI_WOWLAN_TYPES[0].flag)
return yaml_error(node, error, "'default' is an exclusive flag for wakeonwlan");
return TRUE;
}
static gboolean
handle_auth(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
gboolean ret;
cur_netdef->has_auth = TRUE;
cur_auth = &cur_netdef->auth;
ret = process_mapping(doc, node, auth_handlers, error);
cur_auth = NULL;
return ret;
}
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++) {
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? */
if (is_ip4_address(addr)) {
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? */
if (is_ip6_address(addr)) {
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)
{
if (!is_ip4_address(scalar(node)))
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)
{
if (!is_ip6_address(scalar(node)))
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(NetplanWifiAccessPoint, 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)) {
/* Even in the error case, NULL out cur_access_point. Otherwise we
* have an assert failure if we do a multi-pass parse. */
gboolean ret;
ret = yaml_error(key, error, "%s: Duplicate access point SSID '%s'", cur_netdef->id, cur_access_point->ssid);
cur_access_point = NULL;
return ret;
}
if (!process_mapping(doc, value, wifi_access_point_handlers, error)) {
cur_access_point = NULL;
return FALSE;
}
cur_access_point = NULL;
}
return TRUE;
}
/**
* Handler for bridge "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: ignored
*/
static gboolean
handle_bridge_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);
NetplanNetDefinition *component;
assert_type(entry, YAML_SCALAR_NODE);
component = g_hash_table_lookup(netdefs, scalar(entry));
if (!component) {
add_missing_node(entry);
} else {
if (component->bridge && g_strcmp0(component->bridge, cur_netdef->id) != 0)
return yaml_error(node, error, "%s: interface '%s' is already assigned to bridge %s",
cur_netdef->id, scalar(entry), component->bridge);
if (component->bond)
return yaml_error(node, error, "%s: interface '%s' is already assigned to bond %s",
cur_netdef->id, scalar(entry), component->bond);
component->bridge = g_strdup(cur_netdef->id);
}
}
return TRUE;
}
/**
* Handler for bond "mode" types.
* @data: offset into NetplanNetDefinition where the const char* field to write is
* located
*/
static gboolean
handle_bond_mode(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error)
{
if (!(strcmp(scalar(node), "balance-rr") == 0 ||
strcmp(scalar(node), "active-backup") == 0 ||
strcmp(scalar(node), "balance-xor") == 0 ||
strcmp(scalar(node), "broadcast") == 0 ||
strcmp(scalar(node), "802.3ad") == 0 ||
strcmp(scalar(node), "balance-tlb") == 0 ||
strcmp(scalar(node), "balance-alb") == 0))
return yaml_error(node, error, "unknown bond mode '%s'", scalar(node));
return handle_netdef_str(doc, node, data, error);
}
/**
* Handler for bond "interfaces:" list.
* @data: ignored
*/
static gboolean
handle_bond_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);
NetplanNetDefinition *component;
assert_type(entry, YAML_SCALAR_NODE);
component = g_hash_table_lookup(netdefs, scalar(entry));
if (!component) {
add_missing_node(entry);
} else {
if (component->bridge)
return yaml_error(node, error, "%s: interface '%s' is already assigned to bridge %s",
cur_netdef->id, scalar(entry), component->bridge);
if (component->bond && g_strcmp0(component->bond, cur_netdef->id) != 0)
return yaml_error(node, error, "%s: interface '%s' is already assigned to bond %s",
cur_netdef->id, scalar(entry), component->bond);
component->bond = g_strdup(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++) {
yaml_node_t *entry = yaml_document_get_node(doc, *i);
assert_type(entry, YAML_SCALAR_NODE);
/* is it an IPv4 address? */
if (is_ip4_address(scalar(entry))) {
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? */
if (is_ip6_address(scalar(entry))) {
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 gboolean
handle_link_local(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
gboolean ipv4 = FALSE;
gboolean ipv6 = FALSE;
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 (g_ascii_strcasecmp(scalar(entry), "ipv4") == 0)
ipv4 = TRUE;
else if (g_ascii_strcasecmp(scalar(entry), "ipv6") == 0)
ipv6 = TRUE;
else
return yaml_error(node, error, "invalid value for link-local: '%s'", scalar(entry));
}
cur_netdef->linklocal.ipv4 = ipv4;
cur_netdef->linklocal.ipv6 = ipv6;
return TRUE;
}
struct NetplanOptionalAddressType NETPLAN_OPTIONAL_ADDRESS_TYPES[] = {
{"ipv4-ll", NETPLAN_OPTIONAL_IPV4_LL},
{"ipv6-ra", NETPLAN_OPTIONAL_IPV6_RA},
{"dhcp4", NETPLAN_OPTIONAL_DHCP4},
{"dhcp6", NETPLAN_OPTIONAL_DHCP6},
{"static", NETPLAN_OPTIONAL_STATIC},
{NULL},
};
static gboolean
handle_optional_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++) {
yaml_node_t *entry = yaml_document_get_node(doc, *i);
assert_type(entry, YAML_SCALAR_NODE);
int found = FALSE;
for (unsigned i = 0; NETPLAN_OPTIONAL_ADDRESS_TYPES[i].name != NULL; ++i) {
if (g_ascii_strcasecmp(scalar(entry), NETPLAN_OPTIONAL_ADDRESS_TYPES[i].name) == 0) {
cur_netdef->optional_addresses |= NETPLAN_OPTIONAL_ADDRESS_TYPES[i].flag;
found = TRUE;
break;
}
}
if (!found) {
return yaml_error(node, error, "invalid value for optional-addresses: '%s'", scalar(entry));
}
}
return TRUE;
}
static int
get_ip_family(const char* address)
{
g_autofree char *ip_str;
char *prefix_len;
ip_str = g_strdup(address);
prefix_len = strrchr(ip_str, '/');
if (prefix_len)
*prefix_len = '\0';
if (is_ip4_address(ip_str))
return AF_INET;
if (is_ip6_address(ip_str))
return AF_INET6;
return -1;
}
static gboolean
check_and_set_family(int family, guint* dest)
{
if (*dest != -1 && *dest != family)
return FALSE;
*dest = family;
return TRUE;
}
/* TODO: (cyphermox) Refactor the functions below. There's a lot of room for reuse. */
static gboolean
handle_routes_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_route + offset)) = v;
return TRUE;
}
static gboolean
handle_routes_scope(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error)
{
if (cur_route->scope)
g_free(cur_route->scope);
cur_route->scope = g_strdup(scalar(node));
if (g_ascii_strcasecmp(cur_route->scope, "global") == 0 ||
g_ascii_strcasecmp(cur_route->scope, "link") == 0 ||
g_ascii_strcasecmp(cur_route->scope, "host") == 0)
return TRUE;
return yaml_error(node, error, "invalid route scope '%s'", cur_route->scope);
}
static gboolean
handle_routes_type(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error)
{
if (cur_route->type)
g_free(cur_route->type);
cur_route->type = g_strdup(scalar(node));
if (g_ascii_strcasecmp(cur_route->type, "unicast") == 0 ||
g_ascii_strcasecmp(cur_route->type, "unreachable") == 0 ||
g_ascii_strcasecmp(cur_route->type, "blackhole") == 0 ||
g_ascii_strcasecmp(cur_route->type, "prohibit") == 0)
return TRUE;
return yaml_error(node, error, "invalid route type '%s'", cur_route->type);
}
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, &cur_route->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_ip_rule_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_ip_rule + offset);
g_free(*dest);
if (family < 0)
return yaml_error(node, error, "invalid IP family '%d'", family);
if (!check_and_set_family(family, &cur_ip_rule->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_ip_rule_prio(yaml_document_t* doc, yaml_node_t* node, const void* data, 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 priority value '%s'", scalar(node));
cur_ip_rule->priority = (guint) v;
return TRUE;
}
static gboolean
handle_ip_rule_tos(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error)
{
guint64 v;
gchar* endptr;
v = g_ascii_strtoull(scalar(node), &endptr, 10);
if (*endptr != '\0' || v > 255)
return yaml_error(node, error, "invalid ToS (must be between 0 and 255): %s", scalar(node));
cur_ip_rule->tos = (guint) v;
return TRUE;
}
static gboolean
handle_routes_table(yaml_document_t* doc, yaml_node_t* node, const void* data, 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 routing table '%s'", scalar(node));
cur_route->table = (guint) v;
return TRUE;
}
static gboolean
handle_ip_rule_table(yaml_document_t* doc, yaml_node_t* node, const void* data, 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 routing table '%s'", scalar(node));
cur_ip_rule->table = (guint) v;
return TRUE;
}
static gboolean
handle_ip_rule_fwmark(yaml_document_t* doc, yaml_node_t* node, const void* data, 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 fwmark value '%s'", scalar(node));
cur_ip_rule->fwmark = (guint) v;
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;
NetplanNetDefinition *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;
NetplanNetDefinition *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;
}
static 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
****************************************************/
static const mapping_entry_handler routes_handlers[] = {
{"from", YAML_SCALAR_NODE, handle_routes_ip, NULL, route_offset(from)},
{"on-link", YAML_SCALAR_NODE, handle_routes_bool, NULL, route_offset(onlink)},
{"scope", YAML_SCALAR_NODE, handle_routes_scope},
{"table", YAML_SCALAR_NODE, handle_routes_table},
{"to", YAML_SCALAR_NODE, handle_routes_ip, NULL, route_offset(to)},
{"type", YAML_SCALAR_NODE, handle_routes_type},
{"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(NetplanIPRoute, 1);
cur_route->type = g_strdup("unicast");
cur_route->scope = g_strdup("global");
cur_route->family = G_MAXUINT; /* 0 is a valid family ID */
cur_route->metric = NETPLAN_METRIC_UNSPEC; /* 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(NetplanIPRoute*));
}
g_array_append_val(cur_netdef->routes, cur_route);
}
if ( ( g_ascii_strcasecmp(cur_route->scope, "link") == 0
|| g_ascii_strcasecmp(cur_route->scope, "host") == 0)
&& !cur_route->to)
return yaml_error(node, error, "link and host routes must specify a 'to' IP");
else if ( g_ascii_strcasecmp(cur_route->type, "unicast") == 0
&& g_ascii_strcasecmp(cur_route->scope, "global") == 0
&& (!cur_route->to || !cur_route->via))
return yaml_error(node, error, "unicast route must include both a 'to' and 'via' IP");
else if (g_ascii_strcasecmp(cur_route->type, "unicast") != 0 && !cur_route->to)
return yaml_error(node, error, "non-unicast routes must specify a 'to' IP");
cur_route = NULL;
if (error && *error)
return FALSE;
}
return TRUE;
}
static const mapping_entry_handler ip_rules_handlers[] = {
{"from", YAML_SCALAR_NODE, handle_ip_rule_ip, NULL, ip_rule_offset(from)},
{"mark", YAML_SCALAR_NODE, handle_ip_rule_fwmark},
{"priority", YAML_SCALAR_NODE, handle_ip_rule_prio},
{"table", YAML_SCALAR_NODE, handle_ip_rule_table},
{"to", YAML_SCALAR_NODE, handle_ip_rule_ip, NULL, ip_rule_offset(to)},
{"type-of-service", YAML_SCALAR_NODE, handle_ip_rule_tos},
{NULL}
};
static gboolean
handle_ip_rules(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_ip_rule = g_new0(NetplanIPRule, 1);
cur_ip_rule->family = G_MAXUINT; /* 0 is a valid family ID */
cur_ip_rule->priority = NETPLAN_IP_RULE_PRIO_UNSPEC;
cur_ip_rule->table = NETPLAN_ROUTE_TABLE_UNSPEC;
cur_ip_rule->tos = NETPLAN_IP_RULE_TOS_UNSPEC;
cur_ip_rule->fwmark = NETPLAN_IP_RULE_FW_MARK_UNSPEC;
if (process_mapping(doc, entry, ip_rules_handlers, error)) {
if (!cur_netdef->ip_rules) {
cur_netdef->ip_rules = g_array_new(FALSE, FALSE, sizeof(NetplanIPRule*));
}
g_array_append_val(cur_netdef->ip_rules, cur_ip_rule);
}
if (!cur_ip_rule->from && !cur_ip_rule->to)
return yaml_error(node, error, "IP routing policy must include either a 'from' or 'to' IP");
cur_ip_rule = 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++) {
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? */
if (is_ip4_address(addr)) {
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)
{
NetplanNetDefinition *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;
}
static const mapping_entry_handler bond_params_handlers[] = {
{"mode", YAML_SCALAR_NODE, handle_bond_mode, 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)},
{"gratuitous-arp", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(bond_params.gratuitous_arp)},
/* Handle the old misspelling */
{"gratuitious-arp", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(bond_params.gratuitous_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 tunnels
****************************************************/
const char*
tunnel_mode_to_string(NetplanTunnelMode mode)
{
return netplan_tunnel_mode_table[mode];
}
static gboolean
handle_tunnel_addr(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error)
{
g_autofree char* addr = NULL;
char* prefix_len;
/* split off /prefix_len */
addr = g_strdup(scalar(node));
prefix_len = strrchr(addr, '/');
if (prefix_len)
return yaml_error(node, error, "address '%s' should not include /prefixlength", scalar(node));
/* is it an IPv4 address? */
if (is_ip4_address(addr))
return handle_netdef_ip4(doc, node, data, error);
/* is it an IPv6 address? */
if (is_ip6_address(addr))
return handle_netdef_ip6(doc, node, data, error);
return yaml_error(node, error, "malformed address '%s', must be X.X.X.X or X:X:X:X:X:X:X:X", scalar(node));
}
static gboolean
handle_tunnel_mode(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
const char *key = scalar(node);
NetplanTunnelMode i;
// Skip over unknown (0) tunnel mode.
for (i = 1; i < NETPLAN_TUNNEL_MODE_MAX_; ++i) {
if (g_strcmp0(netplan_tunnel_mode_table[i], key) == 0) {
cur_netdef->tunnel.mode = i;
return TRUE;
}
}
return yaml_error(node, error, "%s: tunnel mode '%s' is not supported", cur_netdef->id, key);
}
static gboolean
handle_tunnel_key(yaml_document_t* doc, yaml_node_t* node, const void* data, GError** error)
{
/* Tunnel key should be a number or dotted quad. */
guint offset = GPOINTER_TO_UINT(data);
char** dest = (char**) ((void*) cur_netdef + offset);
guint64 v;
gchar* endptr;
v = g_ascii_strtoull(scalar(node), &endptr, 10);
if (*endptr != '\0' || v > G_MAXUINT) {
/* Not a simple uint, try for a dotted quad */
if (!is_ip4_address(scalar(node)))
return yaml_error(node, error, "invalid tunnel key '%s'", scalar(node));
}
g_free(*dest);
*dest = g_strdup(scalar(node));
return TRUE;
}
static const mapping_entry_handler tunnel_keys_handlers[] = {
{"input", YAML_SCALAR_NODE, handle_tunnel_key, NULL, netdef_offset(tunnel.input_key)},
{"output", YAML_SCALAR_NODE, handle_tunnel_key, NULL, netdef_offset(tunnel.output_key)},
{NULL}
};
static gboolean
handle_tunnel_key_mapping(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
gboolean ret = FALSE;
/* We overload the key 'key' for tunnels; such that it can either be a
* single scalar with the same key to use for both input and output keys,
* or a mapping where one can specify each.
*/
if (node->type == YAML_SCALAR_NODE) {
ret = handle_tunnel_key(doc, node, netdef_offset(tunnel.input_key), error);
if (ret)
ret = handle_tunnel_key(doc, node, netdef_offset(tunnel.output_key), error);
}
else if (node->type == YAML_MAPPING_NODE) {
ret = process_mapping(doc, node, tunnel_keys_handlers, error);
}
else {
return yaml_error(node, error, "invalid type for 'keys': must be a scalar or mapping");
}
return ret;
}
/****************************************************
* Grammar and handlers for network devices
****************************************************/
static const mapping_entry_handler nm_backend_settings_handlers[] = {
{"name", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(backend_settings.nm.name)},
{"uuid", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(backend_settings.nm.uuid)},
{"stable-id", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(backend_settings.nm.stable_id)},
{"device", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(backend_settings.nm.device)},
{NULL}
};
static const mapping_entry_handler nameservers_handlers[] = {
{"search", YAML_SEQUENCE_NODE, handle_nameservers_search},
{"addresses", YAML_SEQUENCE_NODE, handle_nameservers_addresses},
{NULL}
};
/* Handlers for DHCP overrides. */
#define COMMON_DHCP_OVERRIDES_HANDLERS(overrides) \
{"hostname", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(overrides.hostname)}, \
{"route-metric", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(overrides.metric)}, \
{"send-hostname", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(overrides.send_hostname)}, \
{"use-dns", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(overrides.use_dns)}, \
{"use-domains", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(overrides.use_domains)}, \
{"use-hostname", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(overrides.use_hostname)}, \
{"use-mtu", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(overrides.use_mtu)}, \
{"use-ntp", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(overrides.use_ntp)}, \
{"use-routes", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(overrides.use_routes)}
static const mapping_entry_handler dhcp4_overrides_handlers[] = {
COMMON_DHCP_OVERRIDES_HANDLERS(dhcp4_overrides),
{NULL},
};
static const mapping_entry_handler dhcp6_overrides_handlers[] = {
COMMON_DHCP_OVERRIDES_HANDLERS(dhcp6_overrides),
{NULL},
};
/* Handlers shared by all link types */
#define COMMON_LINK_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}, \
{"dhcp4-overrides", YAML_MAPPING_NODE, NULL, dhcp4_overrides_handlers}, \
{"dhcp6-overrides", YAML_MAPPING_NODE, NULL, dhcp6_overrides_handlers}, \
{"gateway4", YAML_SCALAR_NODE, handle_gateway4}, \
{"gateway6", YAML_SCALAR_NODE, handle_gateway6}, \
{"ipv6-address-generation", YAML_SCALAR_NODE, handle_netdef_addrgen}, \
{"ipv6-mtu", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(ipv6_mtubytes)}, \
{"ipv6-privacy", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(ip6_privacy)}, \
{"link-local", YAML_SEQUENCE_NODE, handle_link_local}, \
{"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}, \
{"optional", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(optional)}, \
{"optional-addresses", YAML_SEQUENCE_NODE, handle_optional_addresses}, \
{"renderer", YAML_SCALAR_NODE, handle_netdef_renderer}, \
{"routes", YAML_SEQUENCE_NODE, handle_routes}, \
{"routing-policy", YAML_SEQUENCE_NODE, handle_ip_rules}
#define COMMON_BACKEND_HANDLERS \
{"networkmanager", YAML_MAPPING_NODE, NULL, nm_backend_settings_handlers}
/* Handlers for physical links */
#define PHYSICAL_LINK_HANDLERS \
{"match", YAML_MAPPING_NODE, handle_match}, \
{"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)}, \
{"wakeonwlan", YAML_SEQUENCE_NODE, handle_wowlan, NULL, netdef_offset(wowlan)}, \
{"emit-lldp", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(emit_lldp)}
static const mapping_entry_handler ethernet_def_handlers[] = {
COMMON_LINK_HANDLERS,
COMMON_BACKEND_HANDLERS,
PHYSICAL_LINK_HANDLERS,
{"auth", YAML_MAPPING_NODE, handle_auth},
{"link", YAML_SCALAR_NODE, handle_netdef_id_ref, NULL, netdef_offset(sriov_link)},
{"virtual-function-count", YAML_SCALAR_NODE, handle_netdef_guint, NULL, netdef_offset(sriov_explicit_vf_count)},
{NULL}
};
static const mapping_entry_handler wifi_def_handlers[] = {
COMMON_LINK_HANDLERS,
COMMON_BACKEND_HANDLERS,
PHYSICAL_LINK_HANDLERS,
{"access-points", YAML_MAPPING_NODE, handle_wifi_access_points},
{"auth", YAML_MAPPING_NODE, handle_auth},
{NULL}
};
static const mapping_entry_handler bridge_def_handlers[] = {
COMMON_LINK_HANDLERS,
COMMON_BACKEND_HANDLERS,
{"interfaces", YAML_SEQUENCE_NODE, handle_bridge_interfaces, NULL, NULL},
{"parameters", YAML_MAPPING_NODE, handle_bridge},
{NULL}
};
static const mapping_entry_handler bond_def_handlers[] = {
COMMON_LINK_HANDLERS,
COMMON_BACKEND_HANDLERS,
{"interfaces", YAML_SEQUENCE_NODE, handle_bond_interfaces, NULL, NULL},
{"parameters", YAML_MAPPING_NODE, handle_bonding},
{NULL}
};
static const mapping_entry_handler vlan_def_handlers[] = {
COMMON_LINK_HANDLERS,
COMMON_BACKEND_HANDLERS,
{"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)},
{NULL}
};
static const mapping_entry_handler modem_def_handlers[] = {
COMMON_LINK_HANDLERS,
{"apn", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(modem_params.apn)},
{"auto-config", YAML_SCALAR_NODE, handle_netdef_bool, NULL, netdef_offset(modem_params.auto_config)},
{"device-id", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(modem_params.device_id)},
{"network-id", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(modem_params.network_id)},
{"number", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(modem_params.number)},
{"password", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(modem_params.password)},
{"pin", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(modem_params.pin)},
{"sim-id", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(modem_params.sim_id)},
{"sim-operator-id", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(modem_params.sim_operator_id)},
{"username", YAML_SCALAR_NODE, handle_netdef_str, NULL, netdef_offset(modem_params.username)},
};
static const mapping_entry_handler tunnel_def_handlers[] = {
COMMON_LINK_HANDLERS,
COMMON_BACKEND_HANDLERS,
{"mode", YAML_SCALAR_NODE, handle_tunnel_mode},
{"local", YAML_SCALAR_NODE, handle_tunnel_addr, NULL, netdef_offset(tunnel.local_ip)},
{"remote", YAML_SCALAR_NODE, handle_tunnel_addr, NULL, netdef_offset(tunnel.remote_ip)},
/* Handle key/keys for clarity in config: this can be either a scalar or
* mapping of multiple keys (input and output)
*/
{"key", YAML_NO_NODE, handle_tunnel_key_mapping},
{"keys", YAML_NO_NODE, handle_tunnel_key_mapping},
{NULL}
};
/****************************************************
* Grammar and handlers for network node
****************************************************/
static gboolean
handle_network_version(yaml_document_t* doc, yaml_node_t* node, const void* _, GError** error)
{
long mangled_version;
mangled_version = strtol(scalar(node), NULL, 10);
if (mangled_version < NETPLAN_VERSION_MIN || mangled_version >= NETPLAN_VERSION_MAX)
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 void
initialize_dhcp_overrides(NetplanDHCPOverrides* overrides)
{
overrides->use_dns = TRUE;
overrides->use_domains = NULL;
overrides->use_ntp = TRUE;
overrides->send_hostname = TRUE;
overrides->use_hostname = TRUE;
overrides->use_mtu = TRUE;
overrides->use_routes = TRUE;
overrides->hostname = NULL;
overrides->metric = NETPLAN_METRIC_UNSPEC;
}
/**
* 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(NetplanNetDefinition, 1);
cur_netdef->type = GPOINTER_TO_UINT(data);
cur_netdef->backend = backend_cur_type ?: NETPLAN_BACKEND_NONE;
cur_netdef->id = g_strdup(scalar(key));
/* Set some default values */
cur_netdef->vlan_id = G_MAXUINT; /* 0 is a valid ID */
cur_netdef->tunnel.mode = NETPLAN_TUNNEL_MODE_UNKNOWN;
cur_netdef->dhcp_identifier = g_strdup("duid"); /* keep networkd's default */
/* systemd-networkd defaults to IPv6 LL enabled; keep that default */
cur_netdef->linklocal.ipv6 = TRUE;
g_hash_table_insert(netdefs, cur_netdef->id, cur_netdef);
netdefs_ordered = g_list_append(netdefs_ordered, cur_netdef);
cur_netdef->sriov_vlan_filter = FALSE;
/* DHCP override defaults */
initialize_dhcp_overrides(&cur_netdef->dhcp4_overrides);
initialize_dhcp_overrides(&cur_netdef->dhcp6_overrides);
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 NETPLAN_DEF_TYPE_BOND: handlers = bond_def_handlers; break;
case NETPLAN_DEF_TYPE_BRIDGE: handlers = bridge_def_handlers; break;
case NETPLAN_DEF_TYPE_ETHERNET: handlers = ethernet_def_handlers; break;
case NETPLAN_DEF_TYPE_MODEM: handlers = modem_def_handlers; break;
case NETPLAN_DEF_TYPE_TUNNEL: handlers = tunnel_def_handlers; break;
case NETPLAN_DEF_TYPE_VLAN: handlers = vlan_def_handlers; break;
case NETPLAN_DEF_TYPE_WIFI: handlers = wifi_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_grammar(cur_netdef, value, error))
return FALSE;
/* convenience shortcut: physical device without match: means match
* name on ID */
if (cur_netdef->type < NETPLAN_DEF_TYPE_VIRTUAL && !cur_netdef->has_match)
cur_netdef->match.original_name = cur_netdef->id;
}
backend_cur_type = NETPLAN_BACKEND_NONE;
return TRUE;
}
static const mapping_entry_handler network_handlers[] = {
{"bonds", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(NETPLAN_DEF_TYPE_BOND)},
{"bridges", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(NETPLAN_DEF_TYPE_BRIDGE)},
{"ethernets", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(NETPLAN_DEF_TYPE_ETHERNET)},
{"renderer", YAML_SCALAR_NODE, handle_network_renderer},
{"tunnels", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(NETPLAN_DEF_TYPE_TUNNEL)},
{"version", YAML_SCALAR_NODE, handle_network_version},
{"vlans", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(NETPLAN_DEF_TYPE_VLAN)},
{"wifis", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(NETPLAN_DEF_TYPE_WIFI)},
{"modems", YAML_MAPPING_NODE, handle_network_type, NULL, GUINT_TO_POINTER(NETPLAN_DEF_TYPE_MODEM)},
{NULL}
};
/****************************************************
* Grammar and handlers for root node
****************************************************/
static 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;
g_clear_error(error);
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;
NetplanMissingNode *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 = (NetplanMissingNode*) 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
netplan_parse_yaml(const char* filename, GError** error)
{
yaml_document_t doc;
gboolean ret;
if (!load_yaml(filename, &doc, error))
return FALSE;
if (!netdefs)
netdefs = g_hash_table_new(g_str_hash, g_str_equal);
/* empty file? */
if (yaml_document_get_root_node(&doc) == NULL)
return TRUE;
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)
{
GError **error = (GError **)user_data;
NetplanNetDefinition* nd = value;
/* Take more steps to make sure we always have a backend set for netdefs */
if (nd->backend == NETPLAN_BACKEND_NONE) {
nd->backend = get_default_backend_for_type(nd->type);
g_debug("%s: setting default backend to %i", nd->id, nd->backend);
}
/* Do a final pass of validation for backend-specific conditions */
if (validate_backend_rules(nd, error))
g_debug("Configuration is valid");
}
/**
* Post-processing after parsing all config files
*/
GHashTable *
netplan_finish_parse(GError** error)
{
if (netdefs) {
g_debug("We have some netdefs, pass them through a final round of validation");
g_hash_table_foreach(netdefs, finish_iterator, error);
}
if (error && *error)
return NULL;
return netdefs;
}
/**
* Return current global backend.
*/
NetplanBackend
netplan_get_global_backend()
{
return backend_global;
}
netplan.io-0.99/src/parse.h 0000664 0000000 0000000 00000026140 13646002212 0015573 0 ustar 00root root 0000000 0000000 /*
* 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
#define NETPLAN_VERSION_MIN 2
#define NETPLAN_VERSION_MAX 3
/* file that is currently being processed, for useful error messages */
const char* current_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;
/****************************************************
* Parsed definitions
****************************************************/
typedef enum {
NETPLAN_DEF_TYPE_NONE,
/* physical devices */
NETPLAN_DEF_TYPE_ETHERNET,
NETPLAN_DEF_TYPE_WIFI,
NETPLAN_DEF_TYPE_MODEM,
/* virtual devices */
NETPLAN_DEF_TYPE_VIRTUAL,
NETPLAN_DEF_TYPE_BRIDGE = NETPLAN_DEF_TYPE_VIRTUAL,
NETPLAN_DEF_TYPE_BOND,
NETPLAN_DEF_TYPE_VLAN,
NETPLAN_DEF_TYPE_TUNNEL,
} NetplanDefType;
typedef enum {
NETPLAN_BACKEND_NONE,
NETPLAN_BACKEND_NETWORKD,
NETPLAN_BACKEND_NM,
NETPLAN_BACKEND_MAX_,
} NetplanBackend;
static const char* const netplan_backend_to_name[NETPLAN_BACKEND_MAX_] = {
[NETPLAN_BACKEND_NONE] = "none",
[NETPLAN_BACKEND_NETWORKD] = "networkd",
[NETPLAN_BACKEND_NM] = "NetworkManager",
};
typedef enum {
NETPLAN_RA_MODE_KERNEL,
NETPLAN_RA_MODE_ENABLED,
NETPLAN_RA_MODE_DISABLED,
} NetplanRAMode;
typedef enum {
NETPLAN_OPTIONAL_IPV4_LL = 1<<0,
NETPLAN_OPTIONAL_IPV6_RA = 1<<1,
NETPLAN_OPTIONAL_DHCP4 = 1<<2,
NETPLAN_OPTIONAL_DHCP6 = 1<<3,
NETPLAN_OPTIONAL_STATIC = 1<<4,
} NetplanOptionalAddressFlag;
typedef enum {
NETPLAN_ADDRGEN_DEFAULT,
NETPLAN_ADDRGEN_EUI64,
NETPLAN_ADDRGEN_STABLEPRIVACY,
} NetplanAddrGenMode;
struct NetplanOptionalAddressType {
char* name;
NetplanOptionalAddressFlag flag;
};
extern struct NetplanOptionalAddressType NETPLAN_OPTIONAL_ADDRESS_TYPES[];
/* Tunnel mode enum; sync with NetworkManager's DBUS API */
/* TODO: figure out whether networkd's GRETAP and NM's ISATAP
* are the same thing.
*/
typedef enum {
NETPLAN_TUNNEL_MODE_UNKNOWN = 0,
NETPLAN_TUNNEL_MODE_IPIP = 1,
NETPLAN_TUNNEL_MODE_GRE = 2,
NETPLAN_TUNNEL_MODE_SIT = 3,
NETPLAN_TUNNEL_MODE_ISATAP = 4, // NM only.
NETPLAN_TUNNEL_MODE_VTI = 5,
NETPLAN_TUNNEL_MODE_IP6IP6 = 6,
NETPLAN_TUNNEL_MODE_IPIP6 = 7,
NETPLAN_TUNNEL_MODE_IP6GRE = 8,
NETPLAN_TUNNEL_MODE_VTI6 = 9,
/* systemd-only, apparently? */
NETPLAN_TUNNEL_MODE_GRETAP = 101,
NETPLAN_TUNNEL_MODE_IP6GRETAP = 102,
NETPLAN_TUNNEL_MODE_MAX_,
} NetplanTunnelMode;
static const char* const
netplan_tunnel_mode_table[NETPLAN_TUNNEL_MODE_MAX_] = {
[NETPLAN_TUNNEL_MODE_UNKNOWN] = "unknown",
[NETPLAN_TUNNEL_MODE_IPIP] = "ipip",
[NETPLAN_TUNNEL_MODE_GRE] = "gre",
[NETPLAN_TUNNEL_MODE_SIT] = "sit",
[NETPLAN_TUNNEL_MODE_ISATAP] = "isatap",
[NETPLAN_TUNNEL_MODE_VTI] = "vti",
[NETPLAN_TUNNEL_MODE_IP6IP6] = "ip6ip6",
[NETPLAN_TUNNEL_MODE_IPIP6] = "ipip6",
[NETPLAN_TUNNEL_MODE_IP6GRE] = "ip6gre",
[NETPLAN_TUNNEL_MODE_VTI6] = "vti6",
[NETPLAN_TUNNEL_MODE_GRETAP] = "gretap",
[NETPLAN_TUNNEL_MODE_IP6GRETAP] = "ip6gretap",
};
typedef enum {
NETPLAN_WIFI_WOWLAN_DEFAULT = 1<<0,
NETPLAN_WIFI_WOWLAN_ANY = 1<<1,
NETPLAN_WIFI_WOWLAN_DISCONNECT = 1<<2,
NETPLAN_WIFI_WOWLAN_MAGIC = 1<<3,
NETPLAN_WIFI_WOWLAN_GTK_REKEY_FAILURE = 1<<4,
NETPLAN_WIFI_WOWLAN_EAP_IDENTITY_REQ = 1<<5,
NETPLAN_WIFI_WOWLAN_4WAY_HANDSHAKE = 1<<6,
NETPLAN_WIFI_WOWLAN_RFKILL_RELEASE = 1<<7,
NETPLAN_WIFI_WOWLAN_TCP = 1<<8,
} NetplanWifiWowlanFlag;
struct NetplanWifiWowlanType {
char* name;
NetplanWifiWowlanFlag flag;
};
extern struct NetplanWifiWowlanType NETPLAN_WIFI_WOWLAN_TYPES[];
typedef enum {
NETPLAN_AUTH_KEY_MANAGEMENT_NONE,
NETPLAN_AUTH_KEY_MANAGEMENT_WPA_PSK,
NETPLAN_AUTH_KEY_MANAGEMENT_WPA_EAP,
NETPLAN_AUTH_KEY_MANAGEMENT_8021X,
} NetplanAuthKeyManagementType;
typedef enum {
NETPLAN_AUTH_EAP_NONE,
NETPLAN_AUTH_EAP_TLS,
NETPLAN_AUTH_EAP_PEAP,
NETPLAN_AUTH_EAP_TTLS,
} NetplanAuthEAPMethod;
typedef struct missing_node {
char* netdef_id;
const yaml_node_t* node;
} NetplanMissingNode;
typedef struct authentication_settings {
NetplanAuthKeyManagementType key_management;
NetplanAuthEAPMethod eap_method;
char* identity;
char* anonymous_identity;
char* password;
char* ca_certificate;
char* client_certificate;
char* client_key;
char* client_key_password;
char* phase2_auth; /* netplan-feature: auth-phase2 */
} NetplanAuthenticationSettings;
/* Fields below are valid for dhcp4 and dhcp6 unless otherwise noted. */
typedef struct dhcp_overrides {
gboolean use_dns;
gboolean use_ntp;
gboolean send_hostname;
gboolean use_hostname;
gboolean use_mtu;
gboolean use_routes;
char* use_domains; /* netplan-feature: dhcp-use-domains */
char* hostname;
guint metric;
} NetplanDHCPOverrides;
/**
* Represent a configuration stanza
*/
struct net_definition;
typedef struct net_definition NetplanNetDefinition;
struct net_definition {
NetplanDefType type;
NetplanBackend backend;
char* id;
/* only necessary for NetworkManager connection UUIDs in some cases */
uuid_t uuid;
/* status options */
gboolean optional;
NetplanOptionalAddressFlag optional_addresses;
gboolean critical;
/* addresses */
gboolean dhcp4;
gboolean dhcp6;
char* dhcp_identifier;
NetplanDHCPOverrides dhcp4_overrides;
NetplanDHCPOverrides dhcp6_overrides;
NetplanRAMode accept_ra;
GArray* ip4_addresses;
GArray* ip6_addresses;
gboolean ip6_privacy;
guint ip6_addr_gen_mode;
char* gateway4;
char* gateway6;
GArray* ip4_nameservers;
GArray* ip6_nameservers;
GArray* search_domains;
GArray* routes;
GArray* ip_rules;
struct {
gboolean ipv4;
gboolean ipv6;
} linklocal;
/* master ID for slave devices */
char* bridge;
char* bond;
/* vlan */
guint vlan_id;
NetplanNetDefinition* vlan_link;
gboolean has_vlans;
/* Configured custom MAC address */
char* set_mac;
/* interface mtu */
guint mtubytes;
/* ipv6 mtu */
/* netplan-feature: ipv6-mtu */
guint ipv6_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;
NetplanWifiWowlanFlag wowlan;
gboolean emit_lldp;
/* these properties are only valid for NETPLAN_DEF_TYPE_WIFI */
GHashTable* access_points; /* SSID â NetplanWifiAccessPoint* */
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 gratuitous_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* apn;
gboolean auto_config;
char* device_id;
char* network_id;
char* number;
char* password;
char* pin;
char* sim_id;
char* sim_operator_id;
char* username;
} modem_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;
struct {
NetplanTunnelMode mode;
char *local_ip;
char *remote_ip;
char *input_key;
char *output_key;
} tunnel;
NetplanAuthenticationSettings auth;
gboolean has_auth;
/* these properties are only valid for SR-IOV NICs */
struct net_definition* sriov_link;
gboolean sriov_vlan_filter;
guint sriov_explicit_vf_count;
union {
struct NetplanNMSettings {
char *name;
char *uuid;
char *stable_id;
char *device;
} nm;
struct NetplanNetworkdSettings {
char *unit;
} networkd;
} backend_settings;
};
typedef enum {
NETPLAN_WIFI_MODE_INFRASTRUCTURE,
NETPLAN_WIFI_MODE_ADHOC,
NETPLAN_WIFI_MODE_AP
} NetplanWifiMode;
typedef enum {
NETPLAN_WIFI_BAND_DEFAULT,
NETPLAN_WIFI_BAND_5,
NETPLAN_WIFI_BAND_24
} NetplanWifiBand;
typedef struct {
NetplanWifiMode mode;
char* ssid;
NetplanWifiBand band;
char* bssid;
guint channel;
NetplanAuthenticationSettings auth;
gboolean has_auth;
} NetplanWifiAccessPoint;
#define NETPLAN_METRIC_UNSPEC G_MAXUINT
#define NETPLAN_ROUTE_TABLE_UNSPEC 0
#define NETPLAN_IP_RULE_PRIO_UNSPEC G_MAXUINT
#define NETPLAN_IP_RULE_FW_MARK_UNSPEC 0
#define NETPLAN_IP_RULE_TOS_UNSPEC G_MAXUINT
typedef struct {
guint family;
char* type;
char* scope;
guint table;
char* from;
char* to;
char* via;
gboolean onlink;
/* valid metrics are valid positive integers.
* invalid metrics are represented by METRIC_UNSPEC */
guint metric;
} NetplanIPRoute;
typedef struct {
guint family;
char* from;
char* to;
/* table: Valid values are 1 <= x <= 4294967295) */
guint table;
guint priority;
/* fwmark: Valid values are 1 <= x <= 4294967295) */
guint fwmark;
/* type-of-service: between 0 and 255 */
guint tos;
} NetplanIPRule;
/* Written/updated by parse_yaml(): char* id â net_definition */
extern GHashTable* netdefs;
extern GList* netdefs_ordered;
/****************************************************
* Functions
****************************************************/
gboolean netplan_parse_yaml(const char* filename, GError** error);
GHashTable* netplan_finish_parse(GError** error);
NetplanBackend netplan_get_global_backend();
const char* tunnel_mode_to_string(NetplanTunnelMode mode);
netplan.io-0.99/src/util.c 0000664 0000000 0000000 00000012045 13646002212 0015430 0 ustar 00root root 0000000 0000000 /*
* 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)) {
/* the mkdir() just succeeded, there is no sensible
* method to test this without root privileges, bind mounts, and
* simulating ENOSPC */
// LCOV_EXCL_START
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) {
// LCOV_EXCL_START
g_fprintf(stderr, "failed to glob for %s: %m\n", rglob);
return;
// LCOV_EXCL_STOP
}
for (size_t i = 0; i < gl.gl_pathc; ++i)
unlink(gl.gl_pathv[i]);
}
/**
* Get the frequency of a given 2.4GHz WiFi channel
*/
int
wifi_get_freq24(int channel)
{
if (channel < 1 || channel > 14) {
g_fprintf(stderr, "ERROR: invalid 2.4GHz WiFi channel: %d\n", channel);
exit(1);
}
if (!wifi_frequency_24) {
wifi_frequency_24 = g_hash_table_new(g_direct_hash, g_direct_equal);
/* Initialize 2.4GHz frequencies, as of:
* https://en.wikipedia.org/wiki/List_of_WLAN_channels#2.4_GHz_(802.11b/g/n/ax) */
for (unsigned i = 0; i < 13; i++) {
g_hash_table_insert(wifi_frequency_24, GINT_TO_POINTER(i+1),
GINT_TO_POINTER(2412+i*5));
}
g_hash_table_insert(wifi_frequency_24, GINT_TO_POINTER(14),
GINT_TO_POINTER(2484));
}
return GPOINTER_TO_INT(g_hash_table_lookup(wifi_frequency_24,
GINT_TO_POINTER(channel)));
}
/**
* Get the frequency of a given 5GHz WiFi channel
*/
int
wifi_get_freq5(int channel)
{
int channels[] = { 7, 8, 9, 11, 12, 16, 32, 34, 36, 38, 40, 42, 44, 46, 48,
50, 52, 54, 56, 58, 60, 62, 64, 68, 96, 100, 102, 104,
106, 108, 110, 112, 114, 116, 118, 120, 122, 124, 126,
128, 132, 134, 136, 138, 140, 142, 144, 149, 151, 153,
155, 157, 159, 161, 165, 169, 173 };
gboolean found = FALSE;
for (unsigned i = 0; i < sizeof(channels) / sizeof(int); i++) {
if (channel == channels[i]) {
found = TRUE;
break;
}
}
if (!found) {
g_fprintf(stderr, "ERROR: invalid 5GHz WiFi channel: %d\n", channel);
exit(1);
}
if (!wifi_frequency_5) {
wifi_frequency_5 = g_hash_table_new(g_direct_hash, g_direct_equal);
/* Initialize 5GHz frequencies, as of:
* https://en.wikipedia.org/wiki/List_of_WLAN_channels#5.0_GHz_(802.11j)_WLAN
* Skipping channels 183-196. They are valid only in Japan with registration needed */
for (unsigned i = 0; i < sizeof(channels) / sizeof(int); i++) {
g_hash_table_insert(wifi_frequency_5, GINT_TO_POINTER(channels[i]),
GINT_TO_POINTER(5000+channels[i]*5));
}
}
return GPOINTER_TO_INT(g_hash_table_lookup(wifi_frequency_5,
GINT_TO_POINTER(channel)));
}
netplan.io-0.99/src/util.h 0000664 0000000 0000000 00000002002 13646002212 0015425 0 ustar 00root root 0000000 0000000 /*
* 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
GHashTable* wifi_frequency_24;
GHashTable* wifi_frequency_5;
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);
int wifi_get_freq24(int channel);
int wifi_get_freq5(int channel);
netplan.io-0.99/src/validation.c 0000664 0000000 0000000 00000016627 13646002212 0016617 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2019 Canonical, Ltd.
* Author: Mathieu Trudel-Lapierre
*
* 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 "parse.h"
#include "error.h"
/* Check sanity for address types */
gboolean
is_ip4_address(const char* address)
{
struct in_addr a4;
int ret;
ret = inet_pton(AF_INET, address, &a4);
g_assert(ret >= 0);
if (ret > 0)
return TRUE;
return FALSE;
}
gboolean
is_ip6_address(const char* address)
{
struct in6_addr a6;
int ret;
ret = inet_pton(AF_INET6, address, &a6);
g_assert(ret >= 0);
if (ret > 0)
return TRUE;
return FALSE;
}
/************************************************
* Validation for grammar and backend rules.
************************************************/
static gboolean
validate_tunnel_grammar(NetplanNetDefinition* nd, yaml_node_t* node, GError** error)
{
if (nd->tunnel.mode == NETPLAN_TUNNEL_MODE_UNKNOWN)
return yaml_error(node, error, "%s: missing 'mode' property for tunnel", nd->id);
/* Validate local/remote IPs */
if (!nd->tunnel.local_ip)
return yaml_error(node, error, "%s: missing 'local' property for tunnel", nd->id);
if (!nd->tunnel.remote_ip)
return yaml_error(node, error, "%s: missing 'remote' property for tunnel", nd->id);
switch(nd->tunnel.mode) {
case NETPLAN_TUNNEL_MODE_IPIP6:
case NETPLAN_TUNNEL_MODE_IP6IP6:
case NETPLAN_TUNNEL_MODE_IP6GRE:
case NETPLAN_TUNNEL_MODE_IP6GRETAP:
case NETPLAN_TUNNEL_MODE_VTI6:
if (!is_ip6_address(nd->tunnel.local_ip))
return yaml_error(node, error, "%s: 'local' must be a valid IPv6 address for this tunnel type", nd->id);
if (!is_ip6_address(nd->tunnel.remote_ip))
return yaml_error(node, error, "%s: 'remote' must be a valid IPv6 address for this tunnel type", nd->id);
break;
default:
if (!is_ip4_address(nd->tunnel.local_ip))
return yaml_error(node, error, "%s: 'local' must be a valid IPv4 address for this tunnel type", nd->id);
if (!is_ip4_address(nd->tunnel.remote_ip))
return yaml_error(node, error, "%s: 'remote' must be a valid IPv4 address for this tunnel type", nd->id);
break;
}
return TRUE;
}
static gboolean
validate_tunnel_backend_rules(NetplanNetDefinition* nd, yaml_node_t* node, GError** error)
{
/* Backend-specific validation rules for tunnels */
switch (nd->backend) {
case NETPLAN_BACKEND_NETWORKD:
switch (nd->tunnel.mode) {
case NETPLAN_TUNNEL_MODE_VTI:
case NETPLAN_TUNNEL_MODE_VTI6:
break;
/* TODO: Remove this exception and fix ISATAP handling with the
* networkd backend.
* systemd-networkd has grown ISATAP support in 918049a.
*/
case NETPLAN_TUNNEL_MODE_ISATAP:
return yaml_error(node, error,
"%s: %s tunnel mode is not supported by networkd",
nd->id,
g_ascii_strup(tunnel_mode_to_string(nd->tunnel.mode), -1));
break;
default:
if (nd->tunnel.input_key)
return yaml_error(node, error, "%s: 'input-key' is not required for this tunnel type", nd->id);
if (nd->tunnel.output_key)
return yaml_error(node, error, "%s: 'output-key' is not required for this tunnel type", nd->id);
break;
}
break;
case NETPLAN_BACKEND_NM:
switch (nd->tunnel.mode) {
case NETPLAN_TUNNEL_MODE_GRE:
case NETPLAN_TUNNEL_MODE_IP6GRE:
break;
case NETPLAN_TUNNEL_MODE_GRETAP:
case NETPLAN_TUNNEL_MODE_IP6GRETAP:
return yaml_error(node, error,
"%s: %s tunnel mode is not supported by NetworkManager",
nd->id,
g_ascii_strup(tunnel_mode_to_string(nd->tunnel.mode), -1));
break;
default:
if (nd->tunnel.input_key)
return yaml_error(node, error, "%s: 'input-key' is not required for this tunnel type", nd->id);
if (nd->tunnel.output_key)
return yaml_error(node, error, "%s: 'output-key' is not required for this tunnel type", nd->id);
break;
}
break;
// LCOV_EXCL_START
default:
break;
// LCOV_EXCL_STOP
}
return TRUE;
}
gboolean
validate_netdef_grammar(NetplanNetDefinition* nd, yaml_node_t* node, GError** error)
{
int missing_id_count = g_hash_table_size(missing_id);
gboolean valid = FALSE;
g_assert(nd->type != NETPLAN_DEF_TYPE_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 == NETPLAN_DEF_TYPE_WIFI && nd->access_points == NULL)
return yaml_error(node, error, "%s: No access points defined", nd->id);
if (nd->type == NETPLAN_DEF_TYPE_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);
}
if (nd->type == NETPLAN_DEF_TYPE_TUNNEL) {
valid = validate_tunnel_grammar(nd, node, error);
if (!valid)
goto netdef_grammar_error;
}
valid = TRUE;
netdef_grammar_error:
return valid;
}
gboolean
validate_backend_rules(NetplanNetDefinition* nd, GError** error)
{
gboolean valid = FALSE;
/* Set a dummy, NULL yaml_node_t for error reporting */
yaml_node_t* node = NULL;
g_assert(nd->type != NETPLAN_DEF_TYPE_NONE);
if (nd->type == NETPLAN_DEF_TYPE_TUNNEL) {
valid = validate_tunnel_backend_rules(nd, node, error);
if (!valid)
goto backend_rules_error;
}
valid = TRUE;
backend_rules_error:
return valid;
}
netplan.io-0.99/src/validation.h 0000664 0000000 0000000 00000001755 13646002212 0016620 0 ustar 00root root 0000000 0000000 /*
* Copyright (C) 2019 Canonical, Ltd.
* Author: Mathieu Trudel-Lapierre
*
* 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 is_ip4_address(const char* address);
gboolean is_ip6_address(const char* address);
gboolean
validate_netdef_grammar(NetplanNetDefinition* nd, yaml_node_t* node, GError** error);
gboolean
validate_backend_rules(NetplanNetDefinition* nd, GError** error);
netplan.io-0.99/tests/ 0000775 0000000 0000000 00000000000 13646002212 0014660 5 ustar 00root root 0000000 0000000 netplan.io-0.99/tests/cli.py 0000775 0000000 0000000 00000073577 13646002212 0016027 0 ustar 00root root 0000000 0000000 #!/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.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': '.'})
os.environ.update({'LD_LIBRARY_PATH': '.:{}'.format(os.environ.get('LD_LIBRARY_PATH'))})
def _load_yaml(text):
return yaml.load(text, Loader=yaml.SafeLoader)
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):
p = subprocess.Popen(exe_cli + ['generate', '--root-dir', self.workdir.name], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = p.communicate()
self.assertEqual(out, b'')
self.assertEqual(os.listdir(self.workdir.name), [])
def test_with_empty_config(self):
c = os.path.join(self.workdir.name, 'etc', 'netplan')
os.makedirs(c)
open(os.path.join(c, 'a.yaml'), 'w').close()
with open(os.path.join(c, 'b.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], stderr=subprocess.STDOUT)
self.assertEqual(out, b'')
self.assertEqual(os.listdir(os.path.join(self.workdir.name, 'run', 'systemd', 'network')),
['10-netplan-enlol.network'])
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'])
def test_mapping_for_unknown_iface(self):
os.environ['NETPLAN_GENERATE_PATH'] = os.path.join(rootdir, 'generate')
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}''')
p = subprocess.Popen(exe_cli +
['generate', '--root-dir', self.workdir.name, '--mapping', 'nonexistent'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
self.assertNotEqual(p.returncode, 0)
self.assertNotIn(b'nonexistent', out)
def test_mapping_for_interface(self):
os.environ['NETPLAN_GENERATE_PATH'] = os.path.join(rootdir, 'generate')
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, '--mapping', 'enlol'])
self.assertNotEqual(b'', out)
self.assertIn('enlol', out.decode('utf-8'))
def test_mapping_for_renamed_iface(self):
os.environ['NETPLAN_GENERATE_PATH'] = os.path.join(rootdir, 'generate')
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:
myif:
match:
name: enlol
set-name: renamediface
dhcp4: yes
''')
out = subprocess.check_output(exe_cli +
['generate', '--root-dir', self.workdir.name, '--mapping', 'renamediface'])
self.assertNotEqual(b'', out)
self.assertIn('renamediface', out.decode('utf-8'))
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):
os.environ.update({"ENABLE_TEST_COMMANDS": "1"})
rc = subprocess.call(exe_cli + ['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):
os.environ.update({"ENABLE_TEST_COMMANDS": "1"})
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', '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(_load_yaml(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(_load_yaml(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(_load_yaml(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(_load_yaml(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(_load_yaml(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(_load_yaml(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(_load_yaml(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(_load_yaml(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(_load_yaml(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 = _load_yaml(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))
#
# static
#
def test_static_ipv4_prefix(self):
out = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/8', dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1': {'addresses': ["1.2.3.4/8"]}}}}, out.decode())
def test_static_ipv4_netmask(self):
out = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4\nnetmask 255.0.0.0', dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1': {'addresses': ["1.2.3.4/8"]}}}}, out.decode())
def test_static_ipv4_no_address(self):
out, err = self.do_test('auto en1\niface en1 inet static\nnetmask 1.2.3.4', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'no address supplied', err)
def test_static_ipv4_no_network(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'does not specify prefix length, and netmask not specified', err)
def test_static_ipv4_invalid_addr(self):
out, err = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.400/8', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'error parsing "1.2.3.400" as an IPv4 address', err)
def test_static_ipv4_invalid_netmask(self):
out, err = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4\nnetmask 123.123.123.0', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'error parsing "1.2.3.4/123.123.123.0" as an IPv4 network', err)
def test_static_ipv4_invalid_prefixlen(self):
out, err = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/42', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'error parsing "1.2.3.4/42" as an IPv4 network', err)
def test_static_ipv4_unsupported_option(self):
out, err = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/24\nmetric 1280', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'unsupported inet option "metric"', err)
def test_static_ipv4_unknown_option(self):
out, err = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/24\nxyzzy 1280', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'unknown inet option "xyzzy"', err)
def test_static_ipv6_prefix(self):
out = self.do_test('auto en1\niface en1 inet6 static\naddress fc00:0123:4567:89ab:cdef::1234/64', dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1': {'addresses': ["fc00:123:4567:89ab:cdef::1234/64"]}}}}, out.decode())
def test_static_ipv6_netmask(self):
out = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234\nnetmask 64', dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1': {'addresses': ["fc00:123:4567:89ab:cdef::1234/64"]}}}}, out.decode())
def test_static_ipv6_no_address(self):
out, err = self.do_test('auto en1\niface en1 inet6 static\nnetmask 64', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'no address supplied', err)
def test_static_ipv6_no_network(self):
out, err = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'does not specify prefix length, and netmask not specified', err)
def test_static_ipv6_invalid_addr(self):
out, err = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::12345/64', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'error parsing "fc00:0123:4567:89ab:cdef::12345" as an IPv6 address', err)
def test_static_ipv6_invalid_netmask(self):
out, err = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234\nnetmask 129', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'error parsing "fc00:0123:4567:89ab:cdef::1234/129" as an IPv6 network', err)
def test_static_ipv6_invalid_prefixlen(self):
out, err = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234/129', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'error parsing "fc00:0123:4567:89ab:cdef::1234/129" as an IPv6 network', err)
def test_static_ipv6_unsupported_option(self):
out, err = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234/64\nmetric 1280', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'unsupported inet6 option "metric"', err)
def test_static_ipv6_unknown_option(self):
out, err = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234/64\nxyzzy 1280', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'unknown inet6 option "xyzzy"', err)
def test_static_ipv6_accept_ra_0(self):
out = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234/64\naccept_ra 0', dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1': {'addresses': ["fc00:123:4567:89ab:cdef::1234/64"],
'accept_ra': False}}}}, out.decode())
def test_static_ipv6_accept_ra_1(self):
out = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234/64\naccept_ra 1', dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1': {'addresses': ["fc00:123:4567:89ab:cdef::1234/64"],
'accept_ra': True}}}}, out.decode())
def test_static_ipv6_accept_ra_2(self):
out, err = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234/64\naccept_ra 2', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'netplan does not support accept_ra=2', err)
def test_static_ipv6_accept_ra_unexpected(self):
out, err = self.do_test('auto en1\niface en1 inet6 static\n'
'address fc00:0123:4567:89ab:cdef::1234/64\naccept_ra fish', expect_success=False)
self.assertEqual(out, b'')
self.assertIn(b'unexpected accept_ra value "fish"', err)
def test_static_gateway(self):
out = self.do_test("""auto en1
iface en1 inet static
address 1.2.3.4
netmask 255.0.0.0
gateway 1.1.1.1
iface en1 inet6 static
address fc00:0123:4567:89ab:cdef::1234/64
gateway fc00:0123:4567:89ab::1""", dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1':
{'addresses': ["1.2.3.4/8", "fc00:123:4567:89ab:cdef::1234/64"],
'gateway4': "1.1.1.1",
'gateway6': "fc00:0123:4567:89ab::1"}}}}, out.decode())
def test_static_dns(self):
out = self.do_test("""auto en1
iface en1 inet static
address 1.2.3.4
netmask 255.0.0.0
dns-nameservers 1.2.1.1 1.2.2.1
dns-search weird.network
iface en1 inet6 static
address fc00:0123:4567:89ab:cdef::1234/64
dns-nameservers fc00:0123:4567:89ab:1::1 fc00:0123:4567:89ab:2::1""", dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1':
{'addresses': ["1.2.3.4/8", "fc00:123:4567:89ab:cdef::1234/64"],
'nameservers': {
'search': ['weird.network'],
'addresses': ['1.2.1.1', '1.2.2.1',
'fc00:0123:4567:89ab:1::1', 'fc00:0123:4567:89ab:2::1']
}}}}}, out.decode())
def test_static_dns2(self):
out = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/8\ndns-search foo foo.bar', dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1': {'addresses': ["1.2.3.4/8"],
'nameservers': {
'search': ['foo', 'foo.bar']
}}}}}, out.decode())
def test_static_mtu(self):
out = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/8\nmtu 1280', dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1': {'addresses': ["1.2.3.4/8"],
'mtu': 1280}}}}, out.decode())
def test_static_invalid_mtu(self):
out, err = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/8\nmtu fish', expect_success=False)
self.assertEqual(b'', out)
self.assertIn(b'cannot parse "fish" as an MTU', err)
def test_static_two_different_mtus(self):
out, err = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/8\nmtu 1280\n'
'iface en1 inet6 static\naddress 2001::1/64\nmtu 9000', expect_success=False)
self.assertEqual(b'', out)
self.assertIn(b'tried to set MTU=9000, but already have MTU=1280', err)
def test_static_hwaddress(self):
out = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/8\nhwaddress 52:54:00:6b:3c:59', dry_run=True)[0]
self.assertEqual(_load_yaml(out), {'network': {
'version': 2,
'ethernets': {'en1': {'addresses': ["1.2.3.4/8"],
'macaddress': '52:54:00:6b:3c:59'}}}}, out.decode())
def test_static_two_different_macs(self):
out, err = self.do_test('auto en1\niface en1 inet static\naddress 1.2.3.4/8\nhwaddress 52:54:00:6b:3c:59\n'
'iface en1 inet6 static\naddress 2001::1/64\nhwaddress 52:54:00:6b:3c:58', expect_success=False)
self.assertEqual(b'', out)
self.assertIn(b'tried to set MAC 52:54:00:6b:3c:58, but already have MAC 52:54:00:6b:3c:59', err)
#
# 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'option(s) up are not supported for dhcp method', 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_unsupported(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))
class TestInfo(unittest.TestCase):
'''Test netplan info'''
def test_info_defaults(self):
"""
Check that 'netplan info' outputs at all, should include website URL
"""
out = subprocess.check_output(exe_cli + ['info'])
self.assertIn(b'features:', out)
def test_info_yaml(self):
"""
Verify that 'netplan info --yaml' output looks a bit like YAML
"""
out = subprocess.check_output(exe_cli + ['info', '--yaml'])
self.assertIn(b'features:', out)
def test_info_json(self):
"""
Verify that 'netplan info --json' output looks a bit like JSON
"""
out = subprocess.check_output(exe_cli + ['info', '--json'])
self.assertIn(b'"features": [', out)
class TestIp(unittest.TestCase):
def setUp(self):
self.workdir = tempfile.TemporaryDirectory()
def test_valid_subcommand(self):
p = subprocess.Popen(exe_cli + ['ip'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = p.communicate()
self.assertEqual(out, b'')
self.assertIn(b'Available command', err)
self.assertNotEqual(p.returncode, 0)
def test_ip_leases_networkd(self):
os.environ['NETPLAN_GENERATE_PATH'] = os.path.join(rootdir, 'generate')
c = os.path.join(self.workdir.name, 'etc', 'netplan')
os.makedirs(c)
with open(os.path.join(c, 'a.yaml'), 'w') as f:
# match against loopback so as to successfully get a predictable
# ifindex
f.write('''network:
version: 2
renderer: networkd
ethernets:
enlol:
match:
name: lo
dhcp4: yes
''')
fake_netif_lease_dir = os.path.join(self.workdir.name,
'run', 'systemd', 'netif', 'leases')
os.makedirs(fake_netif_lease_dir)
with open(os.path.join(fake_netif_lease_dir, '1'), 'w') as f:
f.write('''THIS IS A FAKE NETIF LEASE FOR LO''')
out = subprocess.check_output(exe_cli +
['ip', 'leases',
'--root-dir', self.workdir.name, 'lo'])
self.assertNotEqual(out, b'')
self.assertIn('FAKE NETIF', out.decode('utf-8'))
def test_ip_leases_nm(self):
unittest.skip("Cannot be tested offline due to calls required to nmcli."
"This is tested in integration tests.")
def test_ip_leases_no_networkd_lease(self):
os.environ['NETPLAN_GENERATE_PATH'] = os.path.join(rootdir, 'generate')
c = os.path.join(self.workdir.name, 'etc', 'netplan')
os.makedirs(c)
with open(os.path.join(c, 'a.yaml'), 'w') as f:
# match against loopback so as to successfully get a predictable
# ifindex
f.write('''network:
version: 2
ethernets:
enlol:
match:
name: lo
dhcp4: yes
''')
p = subprocess.Popen(exe_cli +
['ip', 'leases', '--root-dir', self.workdir.name, 'enlol'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = p.communicate()
self.assertEqual(out, b'')
self.assertIn(b'No lease found', err)
self.assertNotEqual(p.returncode, 0)
def test_ip_leases_no_nm_lease(self):
os.environ['NETPLAN_GENERATE_PATH'] = os.path.join(rootdir, 'generate')
c = os.path.join(self.workdir.name, 'etc', 'netplan')
os.makedirs(c)
with open(os.path.join(c, 'a.yaml'), 'w') as f:
# match against loopback so as to successfully get a predictable
# ifindex
f.write('''network:
version: 2
renderer: NetworkManager
ethernets:
enlol:
match:
name: lo
dhcp4: yes
''')
p = subprocess.Popen(exe_cli +
['ip', 'leases', '--root-dir', self.workdir.name, 'enlol'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
(out, err) = p.communicate()
self.assertEqual(out, b'')
self.assertIn(b'No lease found', err)
self.assertNotEqual(p.returncode, 0)
unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
netplan.io-0.99/tests/dbus/ 0000775 0000000 0000000 00000000000 13646002212 0015615 5 ustar 00root root 0000000 0000000 netplan.io-0.99/tests/dbus/__init__.py 0000664 0000000 0000000 00000000000 13646002212 0017714 0 ustar 00root root 0000000 0000000 netplan.io-0.99/tests/dbus/test_dbus.py 0000664 0000000 0000000 00000014622 13646002212 0020170 0 ustar 00root root 0000000 0000000 #
# 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_info(self):
BUSCTL_NETPLAN_INFO = [
"busctl", "call", "--system",
"io.netplan.Netplan",
"/io/netplan/Netplan",
"io.netplan.Netplan",
"Info",
]
output = subprocess.check_output(BUSCTL_NETPLAN_INFO)
self.assertIn("Features", output.decode("utf-8"))
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"))
netplan.io-0.99/tests/generator/ 0000775 0000000 0000000 00000000000 13646002212 0016646 5 ustar 00root root 0000000 0000000 netplan.io-0.99/tests/generator/__init__.py 0000664 0000000 0000000 00000001320 13646002212 0020753 0 ustar 00root root 0000000 0000000 #
# __init__ for generator tests.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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.io-0.99/tests/generator/base.py 0000664 0000000 0000000 00000017461 13646002212 0020143 0 ustar 00root root 0000000 0000000 #
# 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 random
import stat
import string
import tempfile
import subprocess
import unittest
exe_generate = os.path.join(os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))), 'generate')
# make sure we point to libnetplan properly.
os.environ.update({'LD_LIBRARY_PATH': '.:{}'.format(os.environ.get('LD_LIBRARY_PATH'))})
# 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\nLinkLocalAddressing=ipv6\n\n[DHCP]\nRouteMetric=100\nUseMTU=true\n'
ND_DHCP4_NOMTU = '[Match]\nName=%s\n\n[Network]\nDHCP=ipv4\nLinkLocalAddressing=ipv6\n\n[DHCP]\nRouteMetric=100\nUseMTU=false\n'
ND_WIFI_DHCP4 = '[Match]\nName=%s\n\n[Network]\nDHCP=ipv4\nLinkLocalAddressing=ipv6\n\n[DHCP]\nRouteMetric=600\nUseMTU=true\n'
ND_DHCP6 = '[Match]\nName=%s\n\n[Network]\nDHCP=ipv6\nLinkLocalAddressing=ipv6\n\n[DHCP]\nRouteMetric=100\nUseMTU=true\n'
ND_DHCP6_NOMTU = '[Match]\nName=%s\n\n[Network]\nDHCP=ipv6\nLinkLocalAddressing=ipv6\n\n[DHCP]\nRouteMetric=100\nUseMTU=false\n'
ND_DHCPYES = '[Match]\nName=%s\n\n[Network]\nDHCP=yes\nLinkLocalAddressing=ipv6\n\n[DHCP]\nRouteMetric=100\nUseMTU=true\n'
ND_DHCPYES_NOMTU = '[Match]\nName=%s\n\n[Network]\nDHCP=yes\nLinkLocalAddressing=ipv6\n\n[DHCP]\nRouteMetric=100\nUseMTU=false\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')
self.maxDiff = None
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: # pragma nocover
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 eth_name(self):
"""Return a link name.
Use when you need a link name for a test but don't want to
encode a made up name in the test.
"""
return 'eth' + ''.join(random.sample(string.ascii_letters + string.digits, k=4))
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 get_network_config_for_link(self, link_name):
"""Return the content of the .network file for `link_name`."""
networkd_dir = os.path.join(self.workdir.name, 'run', 'systemd', 'network')
with open(os.path.join(networkd_dir, '10-netplan-{}.network'.format(link_name))) as f:
return f.read()
def get_optional_addresses(self, eth_name):
config = self.get_network_config_for_link(eth_name)
r = set()
prefix = "OptionalAddresses="
for line in config.splitlines():
if line.startswith(prefix):
r.add(line[len(prefix):])
return r
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: # pragma: nocover
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.split('.nmconnection')[0] + '.nmconnection' for n in connections_map]))
for fname, contents in connections_map.items():
extension = ''
if '.nmconnection' not in fname:
extension = '.nmconnection'
with open(os.path.join(con_dir, 'netplan-' + fname + extension)) 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)
netplan.io-0.99/tests/generator/test_args.py 0000664 0000000 0000000 00000015210 13646002212 0021212 0 ustar 00root root 0000000 0000000 #
# Command-line arguments handling tests for generator
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 subprocess
from .base import TestBase, exe_generate
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])
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.") # pragma: nocover
except subprocess.CalledProcessError as e:
self.assertEqual(e.returncode, 1)
self.assertIn(b'can not be called directly', e.output)
netplan.io-0.99/tests/generator/test_auth.py 0000664 0000000 0000000 00000033230 13646002212 0021221 0 ustar 00root root 0000000 0000000 #
# Tests for network authentication config generated via netplan
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 stat
from .base import TestBase, ND_DHCP4, ND_WIFI_DHCP4
class TestNetworkd(TestBase):
def test_auth_wifi_detailed(self):
self.generate('''network:
version: 2
wifis:
wl0:
access-points:
"Joe's Home":
password: "s0s3kr1t"
"Luke's Home":
auth:
key-management: psk
password: "4lsos3kr1t"
"BobsHome":
password: "e03ce667c87bc81ca968d9120ca37f89eb09aec3c55b80386e5d772efd6b926e"
"BillsHome":
auth:
key-management: psk
password: "db3b0acf5653aeaddd5fe034fb9f07175b2864f847b005aaa2f09182d9411b04"
workplace:
auth:
key-management: eap
method: ttls
anonymous-identity: "@internal.example.com"
identity: "joe@internal.example.com"
password: "v3ryS3kr1t"
workplace2:
auth:
key-management: eap
method: peap
identity: "joe@internal.example.com"
password: "v3ryS3kr1t"
ca-certificate: /etc/ssl/work2-cacrt.pem
workplacehashed:
auth:
key-management: eap
method: ttls
anonymous-identity: "@internal.example.com"
identity: "joe@internal.example.com"
password: hash:9db1636cedc5948537e7bee0cc1e9590
customernet:
auth:
key-management: eap
method: tls
anonymous-identity: "@cust.example.com"
identity: "cert-joe@cust.example.com"
ca-certificate: /etc/ssl/cust-cacrt.pem
client-certificate: /etc/ssl/cust-crt.pem
client-key: /etc/ssl/cust-key.pem
client-key-password: "d3cryptPr1v4t3K3y"
opennet:
auth:
key-management: none
peer2peer:
mode: adhoc
auth: {}
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:
new_config = f.read()
self.assertIn('ctrl_interface=/run/wpa_supplicant', new_config)
self.assertIn('''
network={
ssid="peer2peer"
mode=1
key_mgmt=NONE
}
''', new_config)
self.assertIn('''
network={
ssid="Luke's Home"
key_mgmt=WPA-PSK
psk="4lsos3kr1t"
}
''', new_config)
self.assertIn('''
network={
ssid="BobsHome"
key_mgmt=WPA-PSK
psk=e03ce667c87bc81ca968d9120ca37f89eb09aec3c55b80386e5d772efd6b926e
}
''', new_config)
self.assertIn('''
network={
ssid="BillsHome"
key_mgmt=WPA-PSK
psk=db3b0acf5653aeaddd5fe034fb9f07175b2864f847b005aaa2f09182d9411b04
}
''', new_config)
self.assertIn('''
network={
ssid="workplace2"
key_mgmt=WPA-EAP
eap=PEAP
identity="joe@internal.example.com"
password="v3ryS3kr1t"
ca_cert="/etc/ssl/work2-cacrt.pem"
}
''', new_config)
self.assertIn('''
network={
ssid="workplace"
key_mgmt=WPA-EAP
eap=TTLS
identity="joe@internal.example.com"
anonymous_identity="@internal.example.com"
password="v3ryS3kr1t"
}
''', new_config)
self.assertIn('''
network={
ssid="workplacehashed"
key_mgmt=WPA-EAP
eap=TTLS
identity="joe@internal.example.com"
anonymous_identity="@internal.example.com"
password=hash:9db1636cedc5948537e7bee0cc1e9590
}
''', new_config)
self.assertIn('''
network={
ssid="customernet"
key_mgmt=WPA-EAP
eap=TLS
identity="cert-joe@cust.example.com"
anonymous_identity="@cust.example.com"
ca_cert="/etc/ssl/cust-cacrt.pem"
client_cert="/etc/ssl/cust-crt.pem"
private_key="/etc/ssl/cust-key.pem"
private_key_passwd="d3cryptPr1v4t3K3y"
}
''', new_config)
self.assertIn('''
network={
ssid="opennet"
key_mgmt=NONE
}
''', new_config)
self.assertIn('''
network={
ssid="Joe's Home"
key_mgmt=WPA-PSK
psk="s0s3kr1t"
}
''', new_config)
self.assertEqual(stat.S_IMODE(os.fstat(f.fileno()).st_mode), 0o600)
self.assertTrue(os.path.isfile(os.path.join(
self.workdir.name, 'run/systemd/system/netplan-wpa-wl0.service')))
self.assertTrue(os.path.islink(os.path.join(
self.workdir.name, 'run/systemd/system/systemd-networkd.service.wants/netplan-wpa-wl0.service')))
def test_auth_wired(self):
self.generate('''network:
version: 2
ethernets:
eth0:
auth:
key-management: 802.1x
method: tls
anonymous-identity: "@cust.example.com"
identity: "cert-joe@cust.example.com"
ca-certificate: /etc/ssl/cust-cacrt.pem
client-certificate: /etc/ssl/cust-crt.pem
client-key: /etc/ssl/cust-key.pem
client-key-password: "d3cryptPr1v4t3K3y"
phase2-auth: MSCHAPV2
dhcp4: yes
''')
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)
# generates wpa config and enables wpasupplicant unit
with open(os.path.join(self.workdir.name, 'run/netplan/wpa-eth0.conf')) as f:
self.assertEqual(f.read(), '''ctrl_interface=/run/wpa_supplicant
network={
key_mgmt=IEEE8021X
eap=TLS
identity="cert-joe@cust.example.com"
anonymous_identity="@cust.example.com"
ca_cert="/etc/ssl/cust-cacrt.pem"
client_cert="/etc/ssl/cust-crt.pem"
private_key="/etc/ssl/cust-key.pem"
private_key_passwd="d3cryptPr1v4t3K3y"
phase2="auth=MSCHAPV2"
}
''')
self.assertEqual(stat.S_IMODE(os.fstat(f.fileno()).st_mode), 0o600)
self.assertTrue(os.path.isfile(os.path.join(
self.workdir.name, 'run/systemd/system/netplan-wpa-eth0.service')))
self.assertTrue(os.path.islink(os.path.join(
self.workdir.name, 'run/systemd/system/systemd-networkd.service.wants/netplan-wpa-eth0.service')))
class TestNetworkManager(TestBase):
def test_auth_wifi_detailed(self):
self.generate('''network:
version: 2
renderer: NetworkManager
wifis:
wl0:
access-points:
"Joe's Home":
password: "s0s3kr1t"
"Luke's Home":
auth:
key-management: psk
password: "4lsos3kr1t"
workplace:
auth:
key-management: eap
method: ttls
anonymous-identity: "@internal.example.com"
identity: "joe@internal.example.com"
password: "v3ryS3kr1t"
workplace2:
auth:
key-management: eap
method: peap
identity: "joe@internal.example.com"
password: "v3ryS3kr1t"
ca-certificate: /etc/ssl/work2-cacrt.pem
workplacehashed:
auth:
key-management: eap
method: ttls
anonymous-identity: "@internal.example.com"
identity: "joe@internal.example.com"
password: hash:9db1636cedc5948537e7bee0cc1e9590
customernet:
auth:
key-management: 802.1x
method: tls
anonymous-identity: "@cust.example.com"
identity: "cert-joe@cust.example.com"
ca-certificate: /etc/ssl/cust-cacrt.pem
client-certificate: /etc/ssl/cust-crt.pem
client-key: /etc/ssl/cust-key.pem
client-key-password: "d3cryptPr1v4t3K3y"
phase2-auth: MSCHAPV2
opennet:
auth:
key-management: none
peer2peer:
mode: adhoc
auth: {}
dhcp4: yes
''')
self.assert_networkd({})
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=s0s3kr1t
''',
'wl0-Luke%27s%20Home': '''[connection]
id=netplan-wl0-Luke's Home
type=wifi
interface-name=wl0
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=ignore
[wifi]
ssid=Luke's Home
mode=infrastructure
[wifi-security]
key-mgmt=wpa-psk
psk=4lsos3kr1t
''',
'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-eap
[802-1x]
eap=ttls
identity=joe@internal.example.com
anonymous-identity=@internal.example.com
password=v3ryS3kr1t
''',
'wl0-workplace2': '''[connection]
id=netplan-wl0-workplace2
type=wifi
interface-name=wl0
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=ignore
[wifi]
ssid=workplace2
mode=infrastructure
[wifi-security]
key-mgmt=wpa-eap
[802-1x]
eap=peap
identity=joe@internal.example.com
password=v3ryS3kr1t
ca-cert=/etc/ssl/work2-cacrt.pem
''',
'wl0-workplacehashed': '''[connection]
id=netplan-wl0-workplacehashed
type=wifi
interface-name=wl0
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=ignore
[wifi]
ssid=workplacehashed
mode=infrastructure
[wifi-security]
key-mgmt=wpa-eap
[802-1x]
eap=ttls
identity=joe@internal.example.com
anonymous-identity=@internal.example.com
password=hash:9db1636cedc5948537e7bee0cc1e9590
''',
'wl0-customernet': '''[connection]
id=netplan-wl0-customernet
type=wifi
interface-name=wl0
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=ignore
[wifi]
ssid=customernet
mode=infrastructure
[wifi-security]
key-mgmt=ieee8021x
[802-1x]
eap=tls
identity=cert-joe@cust.example.com
anonymous-identity=@cust.example.com
ca-cert=/etc/ssl/cust-cacrt.pem
client-cert=/etc/ssl/cust-crt.pem
private-key=/etc/ssl/cust-key.pem
private-key-password=d3cryptPr1v4t3K3y
phase2-auth=MSCHAPV2
''',
'wl0-opennet': '''[connection]
id=netplan-wl0-opennet
type=wifi
interface-name=wl0
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=ignore
[wifi]
ssid=opennet
mode=infrastructure
''',
'wl0-peer2peer': '''[connection]
id=netplan-wl0-peer2peer
type=wifi
interface-name=wl0
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=ignore
[wifi]
ssid=peer2peer
mode=adhoc
'''})
self.assert_nm_udev(None)
def test_auth_wired(self):
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
eth0:
auth:
key-management: 802.1x
method: tls
anonymous-identity: "@cust.example.com"
identity: "cert-joe@cust.example.com"
ca-certificate: /etc/ssl/cust-cacrt.pem
client-certificate: /etc/ssl/cust-crt.pem
client-key: /etc/ssl/cust-key.pem
client-key-password: "d3cryptPr1v4t3K3y"
dhcp4: yes
''')
self.assert_nm({'eth0': '''[connection]
id=netplan-eth0
type=ethernet
interface-name=eth0
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=ignore
[802-1x]
eap=tls
identity=cert-joe@cust.example.com
anonymous-identity=@cust.example.com
ca-cert=/etc/ssl/cust-cacrt.pem
client-cert=/etc/ssl/cust-crt.pem
private-key=/etc/ssl/cust-key.pem
private-key-password=d3cryptPr1v4t3K3y
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
class TestConfigErrors(TestBase):
def test_auth_invalid_key_mgmt(self):
err = self.generate('''network:
version: 2
ethernets:
eth0:
auth:
key-management: bogus''', expect_fail=True)
self.assertIn("unknown key management type 'bogus'", err)
def test_auth_invalid_eap_method(self):
err = self.generate('''network:
version: 2
ethernets:
eth0:
auth:
method: bogus''', expect_fail=True)
self.assertIn("unknown EAP method 'bogus'", err)
def test_auth_networkd_wifi_psk_too_big(self):
err = self.generate('''network:
version: 2
wifis:
wl0:
access-points:
"Joe's Home":
password: "LoremipsumdolorsitametconsecteturadipiscingelitCrastemporvelitnunc"
dhcp4: yes''', expect_fail=True)
self.assertIn("ASCII passphrase must be between 8 and 63 characters (inclusive)", err)
def test_auth_networkd_wifi_psk_too_small(self):
err = self.generate('''network:
version: 2
wifis:
wl0:
access-points:
"Joe's Home":
password: "p4ss"
dhcp4: yes''', expect_fail=True)
self.assertIn("ASCII passphrase must be between 8 and 63 characters (inclusive)", err)
def test_auth_networkd_wifi_psk_64_non_hexdigit(self):
err = self.generate('''network:
version: 2
wifis:
wl0:
access-points:
"Joe's Home":
password: "LoremipsumdolorsitametconsecteturadipiscingelitCrastemporvelitnu"
dhcp4: yes''', expect_fail=True)
self.assertIn("PSK length of 64 is only supported for hex-digit representation", err)
netplan.io-0.99/tests/generator/test_bonds.py 0000664 0000000 0000000 00000042505 13646002212 0021372 0 ustar 00root root 0000000 0000000 #
# Tests for bond devices config generated via netplan
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 .
from .base import TestBase
class TestNetworkd(TestBase):
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
LinkLocalAddressing=ipv6
IPv6AcceptRA=yes
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'bond0.netdev': '''[NetDev]
Name=bond0
Kind=bond
''',
'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=no
IPv6AcceptRA=no
Bond=bond0
'''})
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': '''[Match]
Name=bn0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
'''})
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': '''[Match]
Name=bn0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\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': '''[Match]
Name=bn0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\n'})
def test_bond_with_parameters(self):
self.generate('''network:
version: 2
ethernets:
eno1: {}
switchports:
match:
driver: yayroute
bonds:
bn0:
parameters:
mode: 802.3ad
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.3ad\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'
'GratuitousARP=10\n'
'PacketsPerSlave=10\n'
'PrimaryReselectPolicy=none\n'
'ResendIGMP=10\n'
'LearnPacketIntervalSec=10\n',
'bn0.network': '''[Match]
Name=bn0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\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.3ad
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.3ad\n'
'MIIMonitorSec=10ms\n'
'ARPIntervalSec=15m\n'
'UpDelaySec=20ms\n'
'DownDelaySec=30s\n',
'bn0.network': '''[Match]
Name=bn0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\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': '''[Match]
Name=bn0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\nPrimarySlave=true\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\n'})
def test_bond_with_gratuitous_spelling(self):
"""Validate that the correct spelling of gratuitous also works"""
self.generate('''network:
version: 2
ethernets:
eno1: {}
switchports:
match:
driver: yayroute
bonds:
bn0:
parameters:
mode: active-backup
gratuitous-arp: 10
interfaces: [eno1, switchports]
dhcp4: true''')
self.assert_networkd({'bn0.netdev': '[NetDev]\nName=bn0\nKind=bond\n\n'
'[Bond]\n'
'Mode=active-backup\n'
'GratuitousARP=10\n',
'bn0.network': '''[Match]
Name=bn0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBond=bn0\n'})
class TestNetworkManager(TestBase):
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.3ad
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.3ad
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
num_unsol_na=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)
class TestConfigErrors(TestBase):
def test_bond_invalid_mode(self):
err = self.generate('''network:
version: 2
ethernets:
eno1:
match:
name: eth0
bonds:
bond0:
interfaces: [eno1]
parameters:
mode: lacp
arp-ip-targets:
- 2001:dead:beef::1
dhcp4: true''', expect_fail=True)
self.assertIn("unknown bond mode 'lacp'", err)
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_bond_multiple_assignments(self):
err = self.generate('''network:
version: 2
ethernets:
eno1: {}
bonds:
bond0:
interfaces: [eno1]
bond1:
interfaces: [eno1]''', expect_fail=True)
self.assertIn("bond1: interface 'eno1' is already assigned to bond bond0", err)
def test_bond_bridge_cross_assignments1(self):
err = self.generate('''network:
version: 2
ethernets:
eno1: {}
bonds:
bond0:
interfaces: [eno1]
bridges:
br1:
interfaces: [eno1]''', expect_fail=True)
self.assertIn("br1: interface 'eno1' is already assigned to bond bond0", err)
def test_bond_bridge_cross_assignments2(self):
err = self.generate('''network:
version: 2
ethernets:
eno1: {}
bridges:
br0:
interfaces: [eno1]
bonds:
bond1:
interfaces: [eno1]''', expect_fail=True)
self.assertIn("bond1: interface 'eno1' is already assigned to bridge br0", err)
def test_bond_bridge_nested_assignments(self):
self.generate('''network:
version: 2
ethernets:
eno1: {}
bonds:
bond0:
interfaces: [eno1]
bridges:
br1:
interfaces: [bond0]''')
netplan.io-0.99/tests/generator/test_bridges.py 0000664 0000000 0000000 00000034566 13646002212 0021714 0 ustar 00root root 0000000 0000000 #
# Tests for bridge devices config generated via netplan
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 unittest
from .base import TestBase
class TestNetworkd(TestBase):
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': '''[Match]
Name=br0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'br0.netdev': '[NetDev]\nName=br0\nMACAddress=00:01:02:03:04:05\nKind=bridge\n'})
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
LinkLocalAddressing=ipv6
IPv6AcceptRA=no
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'br0.netdev': '''[NetDev]
Name=br0
Kind=bridge
''',
'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=no
IPv6AcceptRA=no
Bridge=br0
'''})
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': '''[Match]
Name=br0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
'''})
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': '''[Match]
Name=br0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
'''})
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
LinkLocalAddressing=ipv6
Address=1.2.3.4/12
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
'''})
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': '''[Match]
Name=br0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBridge=br0\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBridge=br0\n'})
@unittest.skipIf("CODECOV_TOKEN" in os.environ, "Skip on codecov.io: GLib changed hashtable sorting")
def test_eth_bridge_nm_blacklist(self): # pragma: nocover
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': '''[Match]
Name=br0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBridge=br0\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBridge=br0\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
priority: 1000
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'
'Priority=1000\n'
'ForwardDelaySec=12\n'
'HelloTimeSec=6\n'
'MaxAgeSec=24\n'
'STP=true\n',
'br0.network': '''[Match]
Name=br0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBridge=br0\n\n'
'[Bridge]\nCost=70\nPriority=14\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBridge=br0\n'})
class TestNetworkManager(TestBase):
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)
class TestConfigErrors(TestBase):
def test_bridge_unknown_iface(self):
err = self.generate('''network:
version: 2
bridges:
br0:
interfaces: ['foo']''', expect_fail=True)
self.assertIn("br0: interface 'foo' is not defined", 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 bridge br0", err)
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)
netplan.io-0.99/tests/generator/test_common.py 0000664 0000000 0000000 00000067172 13646002212 0021564 0 ustar 00root root 0000000 0000000 #
# Common tests for netplan generator
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 textwrap
from .base import TestBase, ND_DHCP4, ND_DHCP6, ND_DHCPYES
class TestNetworkd(TestBase):
'''networkd output'''
def test_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
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=100
UseMTU=true
'''})
self.assert_networkd_udev(None)
def config_with_optional_addresses(self, eth_name, optional_addresses):
return '''network:
version: 2
ethernets:
{}:
dhcp6: true
optional-addresses: {}'''.format(eth_name, optional_addresses)
def test_optional_addresses(self):
eth_name = self.eth_name()
self.generate(self.config_with_optional_addresses(eth_name, '["dhcp4"]'))
self.assertEqual(self.get_optional_addresses(eth_name), set(["dhcp4"]))
def test_optional_addresses_multiple(self):
eth_name = self.eth_name()
self.generate(self.config_with_optional_addresses(eth_name, '[dhcp4, ipv4-ll, ipv6-ra, dhcp6, dhcp4, static]'))
self.assertEqual(
self.get_optional_addresses(eth_name),
set(["ipv4-ll", "ipv6-ra", "dhcp4", "dhcp6", "static"]))
def test_optional_addresses_invalid(self):
eth_name = self.eth_name()
err = self.generate(self.config_with_optional_addresses(eth_name, '["invalid"]'), expect_fail=True)
self.assertIn('invalid value for optional-addresses', err)
def test_mtu_all(self):
self.generate(textwrap.dedent("""
network:
version: 2
ethernets:
eth1:
mtu: 9000
dhcp4: n
ipv6-mtu: 2000
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.108.network': '''[Match]
Name=bond0.108
[Network]
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
''',
'bond0.netdev': '[NetDev]\nName=bond0\nMTUBytes=9000\nKind=bond\n',
'bond0.network': '''[Match]
Name=bond0
[Link]
MTUBytes=9000
[Network]
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
VLAN=bond0.108
''',
'eth1.link': '[Match]\nOriginalName=eth1\n\n[Link]\nWakeOnLan=off\nMTUBytes=9000\n',
'eth1.network': '''[Match]
Name=eth1
[Link]
MTUBytes=9000
[Network]
LinkLocalAddressing=no
IPv6MTUBytes=2000
Bond=bond0
'''
})
self.assert_networkd_udev(None)
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_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
LinkLocalAddressing=ipv6
IPv6AcceptRA=no
[DHCP]
RouteMetric=100
UseMTU=true
'''})
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
LinkLocalAddressing=ipv6
IPv6AcceptRA=yes
[DHCP]
RouteMetric=100
UseMTU=true
'''})
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
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=100
UseMTU=true
'''})
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]
LinkLocalAddressing=ipv6
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
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
Address=2001:FFfe::1/64
[DHCP]
RouteMetric=100
UseMTU=true
'''})
def test_dhcp_critical_true(self):
self.generate('''network:
version: 2
ethernets:
engreen:
critical: yes
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
[DHCP]
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
LinkLocalAddressing=ipv6
[DHCP]
ClientIdentifier=mac
RouteMetric=100
UseMTU=true
'''})
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
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=100
UseMTU=true
'''})
def test_eth_ipv6_privacy(self):
self.generate('''network:
version: 2
ethernets:
eth0:
dhcp6: true
ipv6-privacy: true''')
self.assert_networkd({'eth0.network': '''[Match]
Name=eth0
[Network]
DHCP=ipv6
LinkLocalAddressing=ipv6
IPv6PrivacyExtensions=yes
[DHCP]
RouteMetric=100
UseMTU=true
'''})
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]
LinkLocalAddressing=ipv6
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]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
DNS=1.2.3.4
DNS=1234::FFFF
''',
'enblue.network': '''[Match]
Name=enblue
[Network]
LinkLocalAddressing=ipv6
Address=192.168.1.3/24
DNS=8.8.8.8
Domains=lab kitchen
'''})
def test_link_local_all(self):
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp6: yes
link-local: [ ipv4, ipv6 ]
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=yes
LinkLocalAddressing=yes
[DHCP]
RouteMetric=100
UseMTU=true
'''})
def test_link_local_ipv4(self):
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp6: yes
link-local: [ ipv4 ]
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=yes
LinkLocalAddressing=ipv4
[DHCP]
RouteMetric=100
UseMTU=true
'''})
def test_link_local_ipv6(self):
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp6: yes
link-local: [ ipv6 ]
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=yes
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=100
UseMTU=true
'''})
def test_link_local_disabled(self):
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp6: yes
link-local: [ ]
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=yes
LinkLocalAddressing=no
[DHCP]
RouteMetric=100
UseMTU=true
'''})
class TestNetworkManager(TestBase):
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_ipv6_mtu(self):
self.generate(textwrap.dedent("""
network:
version: 2
renderer: NetworkManager
ethernets:
eth1:
mtu: 9000
ipv6-mtu: 2000"""), expect_fail=True)
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_ip6_addr_gen_mode(self):
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
engreen:
dhcp6: yes
ipv6-address-generation: stable-privacy
enblue:
dhcp6: yes
ipv6-address-generation: eui64''')
self.assert_nm({'engreen': '''[connection]
id=netplan-engreen
type=ethernet
interface-name=engreen
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=auto
addr-gen-mode=1
''',
'enblue': '''[connection]
id=netplan-enblue
type=ethernet
interface-name=enblue
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=auto
addr-gen-mode=0
'''})
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_eth_ipv6_privacy(self):
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
eth0: {dhcp6: true, ipv6-privacy: 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
ip6-privacy=2
'''})
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
'''})
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': '''[Match]
Name=br0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'bond0.netdev': '[NetDev]\nName=bond0\nKind=bond\n',
'bond0.network': '''[Match]
Name=bond0
[Network]
LinkLocalAddressing=no
ConfigureWithoutCarrier=yes
Bridge=br0
''',
'eth0.link': '''[Match]
MACAddress=00:01:02:03:04:05
Type=!vlan bond bridge
[Link]
Name=eth0
WakeOnLan=off
''',
'eth0.network': '''[Match]
MACAddress=00:01:02:03:04:05
Name=eth0
Type=!vlan bond bridge
[Network]
LinkLocalAddressing=no
Bond=bond0
''',
'eth1.link': '''[Match]
MACAddress=02:01:02:03:04:05
Type=!vlan bond bridge
[Link]
Name=eth1
WakeOnLan=off
''',
'eth1.network': '''[Match]
MACAddress=02:01:02:03:04:05
Name=eth1
Type=!vlan bond bridge
[Network]
LinkLocalAddressing=no
Bond=bond0
'''})
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': '''[Match]
Name=vlan1
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'br0.netdev': '[NetDev]\nName=br0\nKind=bridge\n\n'
'[Bridge]\nSTP=true\n',
'br0.network': '''[Match]
Name=br0
[Network]
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
VLAN=vlan1
''',
'bond0.netdev': '[NetDev]\nName=bond0\nKind=bond\n',
'bond0.network': '''[Match]
Name=bond0
[Network]
LinkLocalAddressing=no
ConfigureWithoutCarrier=yes
Bridge=br0
[Bridge]
Cost=8888
''',
'eth2.network': '[Match]\nName=eth2\n\n'
'[Network]\nLinkLocalAddressing=no\nBridge=br0\n\n'
'[Bridge]\nCost=1000\n',
'br1.netdev': '[NetDev]\nName=br1\nKind=bridge\n',
'br1.network': '''[Match]
Name=br1
[Network]
LinkLocalAddressing=no
ConfigureWithoutCarrier=yes
Bond=bond0
''',
'eth0.link': '''[Match]
MACAddress=00:01:02:03:04:05
Type=!vlan bond bridge
[Link]
Name=eth0
WakeOnLan=off
''',
'eth0.network': '''[Match]
MACAddress=00:01:02:03:04:05
Name=eth0
Type=!vlan bond bridge
[Network]
LinkLocalAddressing=no
Bond=bond0
''',
'eth1.link': '''[Match]
MACAddress=02:01:02:03:04:05
Type=!vlan bond bridge
[Link]
Name=eth1
WakeOnLan=off
''',
'eth1.network': '''[Match]
MACAddress=02:01:02:03:04:05
Name=eth1
Type=!vlan bond bridge
[Network]
LinkLocalAddressing=no
Bridge=br1
'''})
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'})
# Skip on codecov.io; GLib changed hashtable elements ordering between
# releases, so we can't depend on the exact order.
# TODO: (cyphermox) turn this into an "assert_in_nm()" function.
if "CODECOV_TOKEN" not in os.environ: # pragma: nocover
self.assert_nm(None, '''[keyfile]
# devices managed by networkd
unmanaged-devices+=interface-name:engreen,interface-name:enblue,''')
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': '''[Match]
Name=br0
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
''',
'eno1.network': '[Match]\nName=eno1\n\n'
'[Network]\nLinkLocalAddressing=no\nBridge=br0\n',
'switchports.network': '[Match]\nDriver=yayroute\n\n'
'[Network]\nLinkLocalAddressing=no\nBridge=br0\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',
'enred.network': '''[Match]
Name=enred
[Network]
LinkLocalAddressing=ipv6
''',
'enyellow.network': ND_DHCP4 % 'enyellow',
'enblue.network': ND_DHCP4 % 'enblue'})
netplan.io-0.99/tests/generator/test_dhcp_overrides.py 0000664 0000000 0000000 00000025126 13646002212 0023265 0 ustar 00root root 0000000 0000000 #
# Tests for DHCP override handling in netplan generator
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 .
from .base import (TestBase, ND_DHCP4, ND_DHCP4_NOMTU, ND_DHCP6,
ND_DHCP6_NOMTU, ND_DHCPYES, ND_DHCPYES_NOMTU)
class TestNetworkd(TestBase):
# Common tests for dhcp override booleans
def assert_dhcp_overrides_bool(self, override_name, networkd_name):
# dhcp4 yes
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: yes
''' % override_name)
# silently ignored since yes is the default
self.assert_networkd({'engreen.network': ND_DHCP4 % 'engreen'})
# dhcp6 yes
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp6: yes
dhcp6-overrides:
%s: yes
''' % override_name)
# silently ignored since yes is the default
self.assert_networkd({'engreen.network': ND_DHCP6 % 'engreen'})
# dhcp4 and dhcp6 both yes
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: yes
dhcp6: yes
dhcp6-overrides:
%s: yes
''' % (override_name, override_name))
# silently ignored since yes is the default
self.assert_networkd({'engreen.network': ND_DHCPYES % 'engreen'})
# dhcp4 no
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: no
''' % override_name)
self.assert_networkd({'engreen.network': ND_DHCP4 % 'engreen' + '%s=false\n' % networkd_name})
# dhcp6 no
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp6: yes
dhcp6-overrides:
%s: no
''' % override_name)
self.assert_networkd({'engreen.network': ND_DHCP6 % 'engreen' + '%s=false\n' % networkd_name})
# dhcp4 and dhcp6 both no
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: no
dhcp6: yes
dhcp6-overrides:
%s: no
''' % (override_name, override_name))
self.assert_networkd({'engreen.network': ND_DHCPYES % 'engreen' + '%s=false\n' % networkd_name})
# mismatched values
err = self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: yes
dhcp6: yes
dhcp6-overrides:
%s: no
''' % (override_name, override_name), expect_fail=True)
self.assertEqual(err, 'ERROR: engreen: networkd requires that '
'%s has the same value in both dhcp4_overrides and dhcp6_overrides\n' % override_name)
# Common tests for dhcp override strings
def assert_dhcp_overrides_string(self, override_name, networkd_name):
# dhcp4 only
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: foo
''' % override_name)
self.assert_networkd({'engreen.network': ND_DHCP4 % 'engreen' + '%s=foo\n' % networkd_name})
# dhcp6 only
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp6: yes
dhcp6-overrides:
%s: foo
''' % override_name)
self.assert_networkd({'engreen.network': ND_DHCP6 % 'engreen' + '%s=foo\n' % networkd_name})
# dhcp4 and dhcp6
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: foo
dhcp6: yes
dhcp6-overrides:
%s: foo
''' % (override_name, override_name))
self.assert_networkd({'engreen.network': ND_DHCPYES % 'engreen' + '%s=foo\n' % networkd_name})
# mismatched values
err = self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: foo
dhcp6: yes
dhcp6-overrides:
%s: bar
''' % (override_name, override_name), expect_fail=True)
self.assertEqual(err, 'ERROR: engreen: networkd requires that '
'%s has the same value in both dhcp4_overrides and dhcp6_overrides\n' % override_name)
# Common tests for dhcp override booleans
def assert_dhcp_mtu_overrides_bool(self, override_name, networkd_name):
# dhcp4 yes
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: yes
''' % override_name)
self.assert_networkd({'engreen.network': ND_DHCP4 % 'engreen'})
# dhcp6 yes
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp6: yes
dhcp6-overrides:
%s: yes
''' % override_name)
# silently ignored since yes is the default
self.assert_networkd({'engreen.network': ND_DHCP6 % 'engreen'})
# dhcp4 and dhcp6 both yes
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: yes
dhcp6: yes
dhcp6-overrides:
%s: yes
''' % (override_name, override_name))
# silently ignored since yes is the default
self.assert_networkd({'engreen.network': ND_DHCPYES % 'engreen'})
# dhcp4 no
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: no
''' % override_name)
self.assert_networkd({'engreen.network': ND_DHCP4_NOMTU % 'engreen'})
# dhcp6 no
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp6: yes
dhcp6-overrides:
%s: no
''' % override_name)
self.assert_networkd({'engreen.network': ND_DHCP6_NOMTU % 'engreen'})
# dhcp4 and dhcp6 both no
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: no
dhcp6: yes
dhcp6-overrides:
%s: no
''' % (override_name, override_name))
self.assert_networkd({'engreen.network': ND_DHCPYES_NOMTU % 'engreen'})
# mismatched values
err = self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: yes
dhcp6: yes
dhcp6-overrides:
%s: no
''' % (override_name, override_name), expect_fail=True)
self.assertEqual(err, 'ERROR: engreen: networkd requires that '
'%s has the same value in both dhcp4_overrides and dhcp6_overrides\n' % override_name)
def assert_dhcp_overrides_guint(self, override_name, networkd_name):
# dhcp4 only
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: 6000
''' % override_name)
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=6000
UseMTU=true
'''})
# dhcp6 only
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp6: yes
dhcp6-overrides:
%s: 6000
''' % override_name)
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=ipv6
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=6000
UseMTU=true
'''})
# dhcp4 and dhcp6
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: 6000
dhcp6: yes
dhcp6-overrides:
%s: 6000
''' % (override_name, override_name))
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=yes
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=6000
UseMTU=true
'''})
# mismatched values
err = self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
%s: 3333
dhcp6: yes
dhcp6-overrides:
%s: 5555
''' % (override_name, override_name), expect_fail=True)
self.assertEqual(err, 'ERROR: engreen: networkd requires that '
'%s has the same value in both dhcp4_overrides and dhcp6_overrides\n' % override_name)
def test_dhcp_overrides_use_dns(self):
self.assert_dhcp_overrides_bool('use-dns', 'UseDNS')
def test_dhcp_overrides_use_domains(self):
self.assert_dhcp_overrides_string('use-domains', 'UseDomains')
def test_dhcp_overrides_use_ntp(self):
self.assert_dhcp_overrides_bool('use-ntp', 'UseNTP')
def test_dhcp_overrides_send_hostname(self):
self.assert_dhcp_overrides_bool('send-hostname', 'SendHostname')
def test_dhcp_overrides_use_hostname(self):
self.assert_dhcp_overrides_bool('use-hostname', 'UseHostname')
def test_dhcp_overrides_hostname(self):
self.assert_dhcp_overrides_string('hostname', 'Hostname')
def test_dhcp_overrides_use_mtu(self):
self.assert_dhcp_mtu_overrides_bool('use-mtu', 'UseMTU')
def test_dhcp_overrides_default_metric(self):
self.assert_dhcp_overrides_guint('route-metric', 'RouteMetric')
def test_dhcp_overrides_use_routes(self):
self.assert_dhcp_overrides_bool('use-routes', 'UseRoutes')
class TestNetworkManager(TestBase):
def test_override_default_metric_v4(self):
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
engreen:
dhcp4: yes
dhcp4-overrides:
route-metric: 3333
''')
# silently ignored since yes is the default
self.assert_nm({'engreen': '''[connection]
id=netplan-engreen
type=ethernet
interface-name=engreen
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
route-metric=3333
[ipv6]
method=ignore
'''})
def test_override_default_metric_v6(self):
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
engreen:
dhcp4: yes
dhcp6: yes
dhcp6-overrides:
route-metric: 6666
''')
# silently ignored since yes is the default
self.assert_nm({'engreen': '''[connection]
id=netplan-engreen
type=ethernet
interface-name=engreen
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=auto
route-metric=6666
'''})
netplan.io-0.99/tests/generator/test_errors.py 0000664 0000000 0000000 00000046063 13646002212 0021604 0 ustar 00root root 0000000 0000000 #
# Tests for common invalid syntax/errors in config
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 .
from .base import TestBase
class TestConfigErrors(TestBase):
def test_malformed_yaml(self):
err = self.generate('network:\n version: %&', expect_fail=True)
self.assertIn('Invalid YAML', err)
self.assertIn('found character that cannot start any token', err)
def test_wrong_indent(self):
err = self.generate('network:\n version: 2\n foo: *', expect_fail=True)
self.assertIn('Invalid YAML', err)
self.assertIn('inconsistent indentation', 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('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('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("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("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("unknown key 'set_name'", err)
def test_virtual_match(self):
err = self.generate('''network:
version: 2
bridges:
br0:
match:
driver: foo''', expect_fail=True)
self.assertIn("unknown key 'match'", err)
def test_virtual_wol(self):
err = self.generate('''network:
version: 2
bridges:
br0:
wakeonlan: true''', expect_fail=True)
self.assertIn("unknown key 'wakeonlan'", 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("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_wifi_ap_unknown_band(self):
err = self.generate('''network:
version: 2
wifis:
wl0:
access-points:
workplace:
band: bogus''', expect_fail=True)
self.assertIn("unknown wifi band 'bogus'", err)
def test_wifi_ap_invalid_freq24(self):
err = self.generate('''network:
version: 2
renderer: NetworkManager
wifis:
wl0:
access-points:
workplace:
band: 2.4GHz
channel: 15''', expect_fail=True)
self.assertIn("ERROR: invalid 2.4GHz WiFi channel: 15", err)
def test_wifi_ap_invalid_freq5(self):
err = self.generate('''network:
version: 2
wifis:
wl0:
access-points:
workplace:
band: 5GHz
channel: 14''', expect_fail=True)
self.assertIn("ERROR: invalid 5GHz WiFi channel: 14", 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_addr_gen_mode(self):
err = self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
engreen:
ipv6-address-generation: 0''', expect_fail=True)
self.assertIn("unknown ipv6-address-generation '0'", err)
def test_addr_gen_mode_not_supported(self):
err = self.generate('''network:
version: 2
ethernets:
engreen:
ipv6-address-generation: eui64''', expect_fail=True)
self.assertIn("ERROR: engreen: ipv6-address-generation is not supported by networkd", 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", err)
def test_vlan_unknown_renderer(self):
err = self.generate('''network:
version: 2
ethernets: {en1: {}}
vlans:
ena: {id: 1, link: en1, renderer: foo}''', expect_fail=True)
self.assertIn("unknown renderer 'foo'", 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_device_route_type_missing_to(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routes:
- via: 2001:dead:beef::2
type: prohibit
metric: 1
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_route_scope_link_missing_to(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routes:
- via: 2001:dead:beef::2
scope: link
metric: 1
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_route_invalid_onlink(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routes:
- via: 2001:dead:beef::2
to: 2000:cafe:cafe::1/24
on-link: 1
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_route_invalid_table(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routes:
- via: 2001:dead:beef::2
to: 2000:cafe:cafe::1/24
table: -1
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_route_invalid_type(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routes:
- via: 2001:dead:beef::2
to: 2000:cafe:cafe::1/24
type: thisisinvalidtype
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_route_invalid_scope(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routes:
- via: 2001:dead:beef::2
to: 2000:cafe:cafe::1/24
scope: linky
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_ip_rule_mismatched_addresses(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routing-policy:
- from: 10.10.10.0/24
to: 2000:dead:beef::3/64
table: 50
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_ip_rule_missing_address(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routing-policy:
- table: 50
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_ip_rule_invalid_tos(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routing-policy:
- from: 10.10.10.0/24
type-of-service: 256
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_ip_rule_invalid_prio(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routing-policy:
- from: 10.10.10.0/24
priority: -1
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_ip_rule_invalid_table(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routing-policy:
- from: 10.10.10.0/24
table: -1
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_ip_rule_invalid_fwmark(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routing-policy:
- from: 10.10.10.0/24
mark: -1
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', expect_fail=True)
def test_device_ip_rule_invalid_address(self):
self.generate('''network:
version: 2
ethernets:
engreen:
routing-policy:
- to: 10.10.10.0/24
from: someinvalidaddress
mark: 1
addresses:
- 192.168.14.2/24
- 2001:FFfe::1/64''', 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)
def test_invalid_link_local_set(self):
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp6: yes
link-local: invalid''', expect_fail=True)
def test_invalid_link_local_value(self):
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: yes
dhcp6: yes
link-local: [ invalid, ]''', expect_fail=True)
def test_invalid_yaml_tabs(self):
err = self.generate('''\t''', expect_fail=True)
self.assertIn("tabs are not allowed for indent", err)
def test_invalid_yaml_undefined_alias(self):
err = self.generate('''network:
version: 2
ethernets:
*engreen:
dhcp4: yes''', expect_fail=True)
self.assertIn("aliases are not supported", err)
def test_invalid_yaml_undefined_alias_at_eof(self):
err = self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: *yes''', expect_fail=True)
self.assertIn("aliases are not supported", err)
netplan.io-0.99/tests/generator/test_ethernets.py 0000664 0000000 0000000 00000036436 13646002212 0022274 0 ustar 00root root 0000000 0000000 #
# Tests for ethernet devices config generated via netplan
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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
from .base import TestBase, ND_DHCP4, UDEV_MAC_RULE, UDEV_NO_MAC_RULE
class TestNetworkd(TestBase):
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',
'eth0.network': '''[Match]
Name=eth0
[Network]
LinkLocalAddressing=ipv6
'''})
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_lldp(self):
self.generate('''network:
version: 2
ethernets:
eth0:
dhcp4: n
emit-lldp: true''')
self.assert_networkd({'eth0.network': '''[Match]
Name=eth0
[Network]
EmitLLDP=true
LinkLocalAddressing=ipv6
'''})
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',
'eth1.network': '''[Match]
Name=eth1
[Link]
MTUBytes=1280
[Network]
LinkLocalAddressing=ipv6
'''})
self.assert_networkd_udev(None)
def test_eth_sriov_vlan_filterv_link(self):
self.generate('''network:
version: 2
ethernets:
enp1:
dhcp4: n
enp1s16f1:
dhcp4: n
link: enp1''')
self.assert_networkd({'enp1.network': '''[Match]
Name=enp1
[Network]
LinkLocalAddressing=ipv6
''',
'enp1s16f1.network': '''[Match]
Name=enp1s16f1
[Network]
LinkLocalAddressing=ipv6
'''})
self.assert_networkd_udev(None)
def test_eth_sriov_virtual_functions(self):
self.generate('''network:
version: 2
ethernets:
enp1:
virtual-function-count: 8''')
self.assert_networkd({'enp1.network': '''[Match]
Name=enp1
[Network]
LinkLocalAddressing=ipv6
'''})
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',
'def1.network': '''[Match]
Driver=ixgbe
Name=lom1
[Network]
LinkLocalAddressing=ipv6
'''})
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',
'def1.network': '''[Match]
MACAddress=11:22:33:44:55:66
Name=lom1
[Network]
LinkLocalAddressing=ipv6
'''})
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
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=100
UseMTU=true
'''})
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\nLinkLocalAddressing=ipv6\n\n'
'[DHCP]\nRouteMetric=100\nUseMTU=true\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
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=100
UseMTU=true
'''})
self.assert_nm(None, '''[keyfile]
# devices managed by networkd
unmanaged-devices+=mac:00:11:22:33:44:55,''')
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_eth_sriov_link(self):
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
enp1:
dhcp4: n
enp1s16f1:
dhcp4: n
link: enp1''')
self.assert_networkd({})
self.assert_nm({'enp1': '''[connection]
id=netplan-enp1
type=ethernet
interface-name=enp1
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
''',
'enp1s16f1': '''[connection]
id=netplan-enp1s16f1
type=ethernet
interface-name=enp1s16f1
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
def test_eth_sriov_virtual_functions(self):
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
enp1:
dhcp4: n
virtual-function-count: 8''')
self.assert_networkd({})
self.assert_nm({'enp1': '''[connection]
id=netplan-enp1
type=ethernet
interface-name=enp1
[ethernet]
wake-on-lan=0
[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)
netplan.io-0.99/tests/generator/test_modems.py 0000664 0000000 0000000 00000015602 13646002212 0021547 0 ustar 00root root 0000000 0000000 #
# Tests for gsm/cdma modem devices config generated via netplan
#
# Copyright (C) 2020 Canonical, Ltd.
# Author: Lukas MĂ€rdian
#
# 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 .
from .base import TestBase
class TestNetworkd(TestBase):
'''networkd output'''
def test_not_supported(self):
# does not produce any output, but fails with:
# "networkd backend does not support GSM modem configuration"
err = self.generate('''network:
version: 2
modems:
mobilephone:
auto-config: true''', expect_fail=True)
self.assertIn("ERROR: mobilephone: networkd backend does not support GSM/CDMA modem configuration", err)
self.assert_networkd({})
self.assert_nm({})
class TestNetworkManager(TestBase):
'''networkmanager output'''
def test_cdma_config(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
mtu: 0
number: "#666"
username: test-user
password: s0s3kr1t''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=cdma
interface-name=mobilephone
[cdma]
password=s0s3kr1t
username=test-user
number=#666
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_auto_config(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
auto-config: true''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=gsm
interface-name=mobilephone
[gsm]
auto-config=true
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_auto_config_implicit(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
number: "*99#"
mtu: 1600
pin: "1234"''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=gsm
interface-name=mobilephone
[gsm]
auto-config=true
mtu=1600
number=*99#
pin=1234
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_apn(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
apn: internet''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=gsm
interface-name=mobilephone
[gsm]
apn=internet
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_apn_username_password(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
apn: internet
username: some-user
password: some-pass''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=gsm
interface-name=mobilephone
[gsm]
apn=internet
password=some-pass
username=some-user
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_device_id(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
device-id: test''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=gsm
interface-name=mobilephone
[gsm]
auto-config=true
device-id=test
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_network_id(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
network-id: test''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=gsm
interface-name=mobilephone
[gsm]
auto-config=true
network-id=test
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_pin(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
pin: 1234''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=gsm
interface-name=mobilephone
[gsm]
auto-config=true
pin=1234
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_sim_id(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
sim-id: test''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=gsm
interface-name=mobilephone
[gsm]
auto-config=true
sim-id=test
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_sim_operator_id(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
mobilephone:
sim-operator-id: test''')
self.assert_nm({'mobilephone': '''[connection]
id=netplan-mobilephone
type=gsm
interface-name=mobilephone
[gsm]
auto-config=true
sim-operator-id=test
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
def test_gsm_example(self):
self.generate('''network:
version: 2
renderer: NetworkManager
modems:
cdc-wdm1:
mtu: 1600
apn: ISP.CINGULAR
username: ISP@CINGULARGPRS.COM
password: CINGULAR1
number: "*99#"
network-id: 24005
device-id: da812de91eec16620b06cd0ca5cbc7ea25245222
pin: 2345
sim-id: 89148000000060671234
sim-operator-id: 310260''')
self.assert_nm({'cdc-wdm1': '''[connection]
id=netplan-cdc-wdm1
type=gsm
interface-name=cdc-wdm1
[gsm]
apn=ISP.CINGULAR
password=CINGULAR1
username=ISP@CINGULARGPRS.COM
device-id=da812de91eec16620b06cd0ca5cbc7ea25245222
mtu=1600
network-id=24005
number=*99#
pin=2345
sim-id=89148000000060671234
sim-operator-id=310260
[ethernet]
wake-on-lan=0
[ipv4]
method=link-local
[ipv6]
method=ignore
'''})
self.assert_networkd({})
self.assert_nm_udev(None)
netplan.io-0.99/tests/generator/test_routing.py 0000664 0000000 0000000 00000044476 13646002212 0021765 0 ustar 00root root 0000000 0000000 #
# Routing / IP rule tests for netplan generator
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 .
from .base import TestBase
class TestNetworkd(TestBase):
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]
LinkLocalAddressing=ipv6
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]
LinkLocalAddressing=ipv6
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_v4_onlink(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
on-link: true
metric: 100
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=10.10.10.0/24
Gateway=192.168.14.20
GatewayOnlink=true
Metric=100
'''})
def test_route_v4_onlink_no(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
on-link: n
metric: 100
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=10.10.10.0/24
Gateway=192.168.14.20
Metric=100
'''})
def test_route_v4_scope(self):
self.generate('''network:
version: 2
ethernets:
engreen:
addresses: ["192.168.14.2/24"]
routes:
- to: 10.10.10.0/24
scope: link
metric: 100
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=10.10.10.0/24
Scope=link
Metric=100
'''})
def test_route_v4_scope_redefine(self):
self.generate('''network:
version: 2
ethernets:
engreen:
addresses: ["192.168.14.2/24"]
routes:
- to: 10.10.10.0/24
scope: host
via: 192.168.14.20
scope: link
metric: 100
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=10.10.10.0/24
Gateway=192.168.14.20
Scope=link
Metric=100
'''})
def test_route_v4_type_blackhole(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
type: blackhole
metric: 100
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=10.10.10.0/24
Gateway=192.168.14.20
Type=blackhole
Metric=100
'''})
def test_route_v4_type_redefine(self):
self.generate('''network:
version: 2
ethernets:
engreen:
addresses: ["192.168.14.2/24"]
routes:
- to: 10.10.10.0/24
type: prohibit
via: 192.168.14.20
type: unicast
metric: 100
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=10.10.10.0/24
Gateway=192.168.14.20
Metric=100
'''})
def test_route_v4_table(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
table: 201
metric: 100
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=10.10.10.0/24
Gateway=192.168.14.20
Metric=100
Table=201
'''})
def test_route_v4_from(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
from: 192.168.14.2
metric: 100
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=10.10.10.0/24
Gateway=192.168.14.20
PreferredSource=192.168.14.2
Metric=100
'''})
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]
LinkLocalAddressing=ipv6
Address=192.168.1.3/24
[Route]
Destination=2001:dead:beef::2/64
Gateway=2001:beef:beef::1
'''})
def test_route_v6_type(self):
self.generate('''network:
version: 2
ethernets:
engreen:
addresses: ["192.168.14.2/24"]
routes:
- to: 2001:dead:beef::2/64
via: 2001:beef:beef::1
type: prohibit''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=2001:dead:beef::2/64
Gateway=2001:beef:beef::1
Type=prohibit
'''})
def test_route_v6_scope_host(self):
self.generate('''network:
version: 2
ethernets:
engreen:
addresses: ["192.168.14.2/24"]
routes:
- to: 2001:dead:beef::2/64
via: 2001:beef:beef::1
scope: host''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[Route]
Destination=2001:dead:beef::2/64
Gateway=2001:beef:beef::1
Scope=host
'''})
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]
LinkLocalAddressing=ipv6
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_ip_rule_table(self):
self.generate('''network:
version: 2
ethernets:
engreen:
addresses: ["192.168.14.2/24"]
routing-policy:
- to: 10.10.10.0/24
table: 100
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[RoutingPolicyRule]
To=10.10.10.0/24
Table=100
'''})
def test_ip_rule_priority(self):
self.generate('''network:
version: 2
ethernets:
engreen:
addresses: ["192.168.14.2/24"]
routing-policy:
- to: 10.10.10.0/24
priority: 99
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[RoutingPolicyRule]
To=10.10.10.0/24
Priority=99
'''})
def test_ip_rule_fwmark(self):
self.generate('''network:
version: 2
ethernets:
engreen:
addresses: ["192.168.14.2/24"]
routing-policy:
- from: 10.10.10.0/24
mark: 50
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[RoutingPolicyRule]
From=10.10.10.0/24
FirewallMark=50
'''})
def test_ip_rule_tos(self):
self.generate('''network:
version: 2
ethernets:
engreen:
addresses: ["192.168.14.2/24"]
routing-policy:
- to: 10.10.10.0/24
type-of-service: 250
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
LinkLocalAddressing=ipv6
Address=192.168.14.2/24
[RoutingPolicyRule]
To=10.10.10.0/24
TypeOfService=250
'''})
def test_use_routes(self):
"""[networkd] Validate config generation when use-routes DHCP override is used"""
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: true
dhcp4-overrides:
use-routes: false
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=ipv4
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=100
UseMTU=true
UseRoutes=false
'''})
def test_default_metric(self):
"""[networkd] Validate config generation when metric DHCP override is used"""
self.generate('''network:
version: 2
ethernets:
engreen:
dhcp4: true
dhcp6: true
dhcp4-overrides:
route-metric: 3333
dhcp6-overrides:
route-metric: 3333
enred:
dhcp4: true
dhcp6: true
''')
self.assert_networkd({'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=yes
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=3333
UseMTU=true
''',
'enred.network': '''[Match]
Name=enred
[Network]
DHCP=yes
LinkLocalAddressing=ipv6
[DHCP]
RouteMetric=100
UseMTU=true
'''})
class TestNetworkManager(TestBase):
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_route_reject_from(self):
err = self.generate('''network:
version: 2
ethernets:
engreen:
renderer: NetworkManager
addresses: ["192.168.14.2/24"]
routes:
- to: 10.10.10.0/24
via: 192.168.14.20
from: 192.168.14.2
''', expect_fail=True)
self.assertIn("NetworkManager does not support routes with 'from'", err)
self.assert_nm({})
self.assert_networkd({})
def test_route_reject_onlink(self):
err = self.generate('''network:
version: 2
ethernets:
engreen:
renderer: NetworkManager
addresses: ["192.168.14.2/24"]
routes:
- to: 10.10.10.0/24
via: 192.168.1.20
on-link: true
''', expect_fail=True)
self.assertIn('NetworkManager does not support on-link routes', err)
self.assert_nm({})
self.assert_networkd({})
def test_route_reject_table(self):
err = self.generate('''network:
version: 2
ethernets:
engreen:
renderer: NetworkManager
addresses: ["192.168.14.2/24"]
routes:
- to: 10.10.10.0/24
via: 192.168.1.20
table: 31337
''', expect_fail=True)
self.assertIn('NetworkManager does not support non-default routing tables', err)
self.assert_nm({})
self.assert_networkd({})
def test_route_reject_scope(self):
err = self.generate('''network:
version: 2
ethernets:
engreen:
renderer: NetworkManager
addresses: ["192.168.14.2/24"]
routes:
- to: 10.10.10.0/24
via: 192.168.1.20
scope: host
''', expect_fail=True)
self.assertIn('NetworkManager only supports global scoped routes', err)
self.assert_nm({})
self.assert_networkd({})
def test_route_reject_type(self):
err = self.generate('''network:
version: 2
ethernets:
engreen:
renderer: NetworkManager
addresses: ["192.168.14.2/24"]
routes:
- to: 10.10.10.0/24
via: 192.168.1.20
type: blackhole
''', expect_fail=True)
self.assertIn('NetworkManager only supports unicast routes', err)
self.assert_nm({})
self.assert_networkd({})
def test_use_routes_v4(self):
"""[NetworkManager] Validate config when use-routes DHCP4 override is used"""
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
engreen:
dhcp4: true
dhcp4-overrides:
use-routes: false
''')
self.assert_nm({'engreen': '''[connection]
id=netplan-engreen
type=ethernet
interface-name=engreen
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
ignore-auto-routes=true
never-default=true
[ipv6]
method=ignore
'''})
def test_use_routes_v6(self):
"""[NetworkManager] Validate config when use-routes DHCP6 override is used"""
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
engreen:
dhcp4: true
dhcp6: true
dhcp6-overrides:
use-routes: false
''')
self.assert_nm({'engreen': '''[connection]
id=netplan-engreen
type=ethernet
interface-name=engreen
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=auto
ignore-auto-routes=true
never-default=true
'''})
def test_default_metric_v4(self):
"""[NetworkManager] Validate config when setting a default metric for DHCPv4"""
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
engreen:
dhcp4: true
dhcp6: true
dhcp4-overrides:
route-metric: 4000
''')
self.assert_nm({'engreen': '''[connection]
id=netplan-engreen
type=ethernet
interface-name=engreen
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
route-metric=4000
[ipv6]
method=auto
'''})
def test_default_metric_v6(self):
"""[NetworkManager] Validate config when setting a default metric for DHCPv6"""
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
engreen:
dhcp4: true
dhcp6: true
dhcp6-overrides:
route-metric: 5050
''')
self.assert_nm({'engreen': '''[connection]
id=netplan-engreen
type=ethernet
interface-name=engreen
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=auto
route-metric=5050
'''})
netplan.io-0.99/tests/generator/test_tunnels.py 0000664 0000000 0000000 00000054574 13646002212 0021766 0 ustar 00root root 0000000 0000000 #
# Tests for tunnel devices config generated via netplan
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 .
from .base import TestBase
def prepare_config_for_mode(renderer, mode, key=None):
config = """network:
version: 2
renderer: {}
""".format(renderer)
if mode == "ip6gre" \
or mode == "ip6ip6" \
or mode == "vti6" \
or mode == "ipip6" \
or mode == "ip6gretap":
local_ip = "fe80::dead:beef"
remote_ip = "2001:fe:ad:de:ad:be:ef:1"
else:
local_ip = "10.10.10.10"
remote_ip = "20.20.20.20"
config += """
tunnels:
tun0:
mode: {}
local: {}
remote: {}
addresses: [ 15.15.15.15/24 ]
gateway4: 20.20.20.21
""".format(mode, local_ip, remote_ip)
# Handle key/keys as str or dict as required by the test
if type(key) is str:
config += """
key: {}
""".format(key)
elif type(key) is dict:
config += """
keys:
input: {}
output: {}
""".format(key['input'], key['output'])
return config
class TestNetworkd(TestBase):
def test_sit(self):
"""[networkd] Validate generation of SIT tunnels"""
config = prepare_config_for_mode('networkd', 'sit')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=sit
[Tunnel]
Independent=true
Local=10.10.10.10
Remote=20.20.20.20
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_sit_he(self):
"""[networkd] Validate generation of SIT tunnels (HE example)"""
# Test specifically a config like one that would enable Hurricane
# Electric IPv6 tunnels.
config = '''network:
version: 2
renderer: networkd
ethernets:
eth0:
addresses:
- 1.1.1.1/24
- "2001:cafe:face::1/64" # provided by HE as routed /64
gateway4: 1.1.1.254
tunnels:
he-ipv6:
mode: sit
remote: 2.2.2.2
local: 1.1.1.1
addresses:
- "2001:dead:beef::2/64"
gateway6: "2001:dead:beef::1"
'''
self.generate(config)
self.assert_networkd({'eth0.network': '''[Match]
Name=eth0
[Network]
LinkLocalAddressing=ipv6
Address=1.1.1.1/24
Address=2001:cafe:face::1/64
Gateway=1.1.1.254
''',
'he-ipv6.netdev': '''[NetDev]
Name=he-ipv6
Kind=sit
[Tunnel]
Independent=true
Local=1.1.1.1
Remote=2.2.2.2
''',
'he-ipv6.network': '''[Match]
Name=he-ipv6
[Network]
LinkLocalAddressing=ipv6
Address=2001:dead:beef::2/64
Gateway=2001:dead:beef::1
ConfigureWithoutCarrier=yes
'''})
def test_vti(self):
"""[networkd] Validate generation of VTI tunnels"""
config = prepare_config_for_mode('networkd', 'vti')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=vti
[Tunnel]
Independent=true
Local=10.10.10.10
Remote=20.20.20.20
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_vti_with_key_str(self):
"""[networkd] Validate generation of VTI tunnels with input/output keys"""
config = prepare_config_for_mode('networkd', 'vti', key='1.1.1.1')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=vti
[Tunnel]
Independent=true
Local=10.10.10.10
Remote=20.20.20.20
InputKey=1.1.1.1
OutputKey=1.1.1.1
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_vti_with_key_dict(self):
"""[networkd] Validate generation of VTI tunnels with key dict"""
config = prepare_config_for_mode('networkd', 'vti', key={'input': 1234, 'output': 5678})
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=vti
[Tunnel]
Independent=true
Local=10.10.10.10
Remote=20.20.20.20
InputKey=1234
OutputKey=5678
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_vti_invalid_key(self):
"""[networkd] Validate VTI tunnel generation key handling"""
config = prepare_config_for_mode('networkd', 'vti', key='invalid')
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: invalid tunnel key 'invalid'", out)
def test_vti6(self):
"""[networkd] Validate generation of VTI6 tunnels"""
config = prepare_config_for_mode('networkd', 'vti6')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=vti6
[Tunnel]
Independent=true
Local=fe80::dead:beef
Remote=2001:fe:ad:de:ad:be:ef:1
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_vti6_with_key(self):
"""[networkd] Validate generation of VTI6 tunnels with input/output keys"""
config = prepare_config_for_mode('networkd', 'vti6', key='1.1.1.1')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=vti6
[Tunnel]
Independent=true
Local=fe80::dead:beef
Remote=2001:fe:ad:de:ad:be:ef:1
InputKey=1.1.1.1
OutputKey=1.1.1.1
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_vti6_invalid_key(self):
"""[networkd] Validate VTI6 tunnel generation key handling"""
config = prepare_config_for_mode('networkd', 'vti6', key='invalid')
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: invalid tunnel key 'invalid'", out)
def test_ipip6(self):
"""[networkd] Validate generation of IPIP6 tunnels"""
config = prepare_config_for_mode('networkd', 'ipip6')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=ip6tnl
[Tunnel]
Independent=true
Mode=ipip6
Local=fe80::dead:beef
Remote=2001:fe:ad:de:ad:be:ef:1
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_ipip(self):
"""[networkd] Validate generation of IPIP tunnels"""
config = prepare_config_for_mode('networkd', 'ipip')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=ipip
[Tunnel]
Independent=true
Local=10.10.10.10
Remote=20.20.20.20
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_isatap(self):
"""[networkd] Warning for ISATAP tunnel generation not supported"""
config = prepare_config_for_mode('networkd', 'isatap')
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: ISATAP tunnel mode is not supported", out)
def test_gre(self):
"""[networkd] Validate generation of GRE tunnels"""
config = prepare_config_for_mode('networkd', 'gre')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=gre
[Tunnel]
Independent=true
Local=10.10.10.10
Remote=20.20.20.20
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_ip6gre(self):
"""[networkd] Validate generation of IP6GRE tunnels"""
config = prepare_config_for_mode('networkd', 'ip6gre')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=ip6gre
[Tunnel]
Independent=true
Local=fe80::dead:beef
Remote=2001:fe:ad:de:ad:be:ef:1
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_gretap(self):
"""[networkd] Validate generation of GRETAP tunnels"""
config = prepare_config_for_mode('networkd', 'gretap')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=gretap
[Tunnel]
Independent=true
Local=10.10.10.10
Remote=20.20.20.20
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
def test_ip6gretap(self):
"""[networkd] Validate generation of IP6GRETAP tunnels"""
config = prepare_config_for_mode('networkd', 'ip6gretap')
self.generate(config)
self.assert_networkd({'tun0.netdev': '''[NetDev]
Name=tun0
Kind=ip6gretap
[Tunnel]
Independent=true
Local=fe80::dead:beef
Remote=2001:fe:ad:de:ad:be:ef:1
''',
'tun0.network': '''[Match]
Name=tun0
[Network]
LinkLocalAddressing=ipv6
Address=15.15.15.15/24
Gateway=20.20.20.21
ConfigureWithoutCarrier=yes
'''})
class TestNetworkManager(TestBase):
def test_isatap(self):
"""[NetworkManager] Validate ISATAP tunnel generation"""
config = prepare_config_for_mode('NetworkManager', 'isatap')
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=4
local=10.10.10.10
remote=20.20.20.20
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
def test_sit(self):
"""[NetworkManager] Validate generation of SIT tunnels"""
config = prepare_config_for_mode('NetworkManager', 'sit')
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=3
local=10.10.10.10
remote=20.20.20.20
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
def test_sit_he(self):
"""[NetworkManager] Validate generation of SIT tunnels (HE example)"""
# Test specifically a config like one that would enable Hurricane
# Electric IPv6 tunnels.
config = '''network:
version: 2
renderer: NetworkManager
ethernets:
eth0:
addresses:
- 1.1.1.1/24
- "2001:cafe:face::1/64" # provided by HE as routed /64
gateway4: 1.1.1.254
tunnels:
he-ipv6:
mode: sit
remote: 2.2.2.2
local: 1.1.1.1
addresses:
- "2001:dead:beef::2/64"
gateway6: "2001:dead:beef::1"
'''
self.generate(config)
self.assert_nm({'eth0': '''[connection]
id=netplan-eth0
type=ethernet
interface-name=eth0
[ethernet]
wake-on-lan=0
[ipv4]
method=manual
address1=1.1.1.1/24
gateway=1.1.1.254
[ipv6]
method=manual
address1=2001:cafe:face::1/64
''',
'he-ipv6': '''[connection]
id=netplan-he-ipv6
type=ip-tunnel
interface-name=he-ipv6
[ip-tunnel]
mode=3
local=1.1.1.1
remote=2.2.2.2
[ipv4]
method=disabled
[ipv6]
method=manual
address1=2001:dead:beef::2/64
gateway=2001:dead:beef::1
'''})
def test_vti(self):
"""[NetworkManager] Validate generation of VTI tunnels"""
config = prepare_config_for_mode('NetworkManager', 'vti')
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=5
local=10.10.10.10
remote=20.20.20.20
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
def test_vti6(self):
"""[NetworkManager] Validate generation of VTI6 tunnels"""
config = prepare_config_for_mode('NetworkManager', 'vti6')
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=9
local=fe80::dead:beef
remote=2001:fe:ad:de:ad:be:ef:1
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
def test_ip6ip6(self):
"""[NetworkManager] Validate generation of IP6IP6 tunnels"""
config = prepare_config_for_mode('NetworkManager', 'ip6ip6')
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=6
local=fe80::dead:beef
remote=2001:fe:ad:de:ad:be:ef:1
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
def test_ipip(self):
"""[NetworkManager] Validate generation of IPIP tunnels"""
config = prepare_config_for_mode('NetworkManager', 'ipip')
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=1
local=10.10.10.10
remote=20.20.20.20
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
def test_gre(self):
"""[NetworkManager] Validate generation of GRE tunnels"""
config = prepare_config_for_mode('NetworkManager', 'gre')
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=2
local=10.10.10.10
remote=20.20.20.20
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
def test_gre_with_keys(self):
"""[NetworkManager] Validate generation of GRE tunnels with keys"""
config = prepare_config_for_mode('NetworkManager', 'gre', key={'input': 1111, 'output': 5555})
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=2
local=10.10.10.10
remote=20.20.20.20
input-key=1111
output-key=5555
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
def test_ip6gre(self):
"""[NetworkManager] Validate generation of IP6GRE tunnels"""
config = prepare_config_for_mode('NetworkManager', 'ip6gre')
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=8
local=fe80::dead:beef
remote=2001:fe:ad:de:ad:be:ef:1
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
def test_ip6gre_with_key(self):
"""[NetworkManager] Validate generation of IP6GRE tunnels with key"""
config = prepare_config_for_mode('NetworkManager', 'ip6gre', key='9999')
self.generate(config)
self.assert_nm({'tun0': '''[connection]
id=netplan-tun0
type=ip-tunnel
interface-name=tun0
[ip-tunnel]
mode=8
local=fe80::dead:beef
remote=2001:fe:ad:de:ad:be:ef:1
input-key=9999
output-key=9999
[ipv4]
method=manual
address1=15.15.15.15/24
gateway=20.20.20.21
[ipv6]
method=ignore
'''})
class TestConfigErrors(TestBase):
def test_missing_mode(self):
"""Fail if tunnel mode is missing"""
config = '''network:
version: 2
tunnels:
tun0:
remote: 20.20.20.20
local: 10.10.10.10
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: missing 'mode' property for tunnel", out)
def test_invalid_mode(self):
"""Ensure an invalid tunnel mode shows an error message"""
config = prepare_config_for_mode('networkd', 'invalid')
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: tunnel mode 'invalid' is not supported", out)
def test_invalid_mode_for_nm(self):
"""Show an error if a mode is selected that can't be handled by the renderer"""
config = prepare_config_for_mode('NetworkManager', 'gretap')
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: GRETAP tunnel mode is not supported by NetworkManager", out)
def test_malformed_tunnel_ip(self):
"""Fail if local/remote IP for tunnel are malformed"""
config = '''network:
version: 2
tunnels:
tun0:
mode: gre
remote: 20.20.20.20
local: 10.10.1invalid
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: malformed address '10.10.1invalid', must be X.X.X.X or X:X:X:X:X:X:X:X", out)
def test_cidr_tunnel_ip(self):
"""Fail if local/remote IP for tunnel include /prefix"""
config = '''network:
version: 2
tunnels:
tun0:
mode: gre
remote: 20.20.20.20
local: 10.10.10.10/21
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: address '10.10.10.10/21' should not include /prefixlength", out)
def test_missing_local_ip(self):
"""Fail if local IP is missing"""
config = '''network:
version: 2
tunnels:
tun0:
mode: gre
remote: 20.20.20.20
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: missing 'local' property for tunnel", out)
def test_missing_remote_ip(self):
"""Fail if remote IP is missing"""
config = '''network:
version: 2
tunnels:
tun0:
mode: gre
local: 20.20.20.20
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: missing 'remote' property for tunnel", out)
def test_wrong_local_ip_for_mode_v4(self):
"""Show an error when an IPv6 local addr is used for an IPv4 tunnel mode"""
config = '''network:
version: 2
tunnels:
tun0:
mode: gre
local: fe80::2
remote: 20.20.20.20
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: 'local' must be a valid IPv4 address for this tunnel type", out)
def test_wrong_remote_ip_for_mode_v4(self):
"""Show an error when an IPv6 remote addr is used for an IPv4 tunnel mode"""
config = '''network:
version: 2
tunnels:
tun0:
mode: gre
local: 10.10.10.10
remote: 2006::1
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: 'remote' must be a valid IPv4 address for this tunnel type", out)
def test_wrong_local_ip_for_mode_v6(self):
"""Show an error when an IPv4 local addr is used for an IPv6 tunnel mode"""
config = '''network:
version: 2
tunnels:
tun0:
mode: ip6gre
local: 10.10.10.10
remote: 2001::3
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: 'local' must be a valid IPv6 address for this tunnel type", out)
def test_wrong_remote_ip_for_mode_v6(self):
"""Show an error when an IPv4 remote addr is used for an IPv6 tunnel mode"""
config = '''network:
version: 2
tunnels:
tun0:
mode: ip6gre
local: 2001::face
remote: 20.20.20.20
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: 'remote' must be a valid IPv6 address for this tunnel type", out)
def test_malformed_keys(self):
"""Show an error if tunnel keys stanza is malformed"""
config = '''network:
version: 2
tunnels:
tun0:
mode: ipip
local: 10.10.10.10
remote: 20.20.20.20
keys:
- input: 1234
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: invalid type for 'keys'", out)
def test_networkd_invalid_input_key_use(self):
"""[networkd] Show an error if input-key is used for a mode that does not support it"""
config = '''network:
version: 2
renderer: networkd
tunnels:
tun0:
mode: ipip
local: 10.10.10.10
remote: 20.20.20.20
keys:
input: 1234
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: 'input-key' is not required for this tunnel type", out)
def test_networkd_invalid_output_key_use(self):
"""[networkd] Show an error if output-key is used for a mode that does not support it"""
config = '''network:
version: 2
renderer: networkd
tunnels:
tun0:
mode: ipip
local: 10.10.10.10
remote: 20.20.20.20
keys:
output: 1234
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: 'output-key' is not required for this tunnel type", out)
def test_nm_invalid_input_key_use(self):
"""[NetworkManager] Show an error if input-key is used for a mode that does not support it"""
config = '''network:
version: 2
renderer: NetworkManager
tunnels:
tun0:
mode: ipip
local: 10.10.10.10
remote: 20.20.20.20
keys:
input: 1234
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: 'input-key' is not required for this tunnel type", out)
def test_nm_invalid_output_key_use(self):
"""[NetworkManager] Show an error if output-key is used for a mode that does not support it"""
config = '''network:
version: 2
renderer: NetworkManager
tunnels:
tun0:
mode: ipip
local: 10.10.10.10
remote: 20.20.20.20
keys:
output: 1234
'''
out = self.generate(config, expect_fail=True)
self.assertIn("Error in network definition: tun0: 'output-key' is not required for this tunnel type", out)
netplan.io-0.99/tests/generator/test_vlans.py 0000664 0000000 0000000 00000014063 13646002212 0021406 0 ustar 00root root 0000000 0000000 #
# Tests for VLAN devices config generated via netplan
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 unittest
from .base import TestBase
class TestNetworkd(TestBase):
@unittest.skipIf("CODECOV_TOKEN" in os.environ, "Skipping on codecov.io: GLib changed hashtable elements order")
def test_vlan(self): # pragma: nocover
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]
Name=en1
[Network]
LinkLocalAddressing=ipv6
VLAN=enblue
VLAN=enred
VLAN=engreen
''',
'enblue.netdev': '''[NetDev]
Name=enblue
Kind=vlan
[VLAN]
Id=1
''',
'engreen.netdev': '''[NetDev]
Name=engreen
Kind=vlan
[VLAN]
Id=2
''',
'enred.netdev': '''[NetDev]
Name=enred
MACAddress=aa:bb:cc:dd:ee:11
Kind=vlan
[VLAN]
Id=3
''',
'enblue.network': '''[Match]
Name=enblue
[Network]
LinkLocalAddressing=ipv6
Address=1.2.3.4/24
ConfigureWithoutCarrier=yes
''',
'enred.network': '''[Match]
Name=enred
[Network]
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
''',
'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=ipv6
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
'''})
self.assert_nm(None, '''[keyfile]
# devices managed by networkd
unmanaged-devices+=interface-name:en1,interface-name:enblue,interface-name:enred,interface-name:engreen,''')
self.assert_nm_udev(None)
def test_vlan_sriov(self):
# we need to make sure renderer: sriov vlans are not saved as part of
# the NM/networkd config
self.generate('''network:
version: 2
ethernets:
en1: {}
vlans:
enblue:
id: 1
link: en1
renderer: sriov
engreen: {id: 2, link: en1, dhcp6: true}''')
self.assert_networkd({'en1.network': '''[Match]
Name=en1
[Network]
LinkLocalAddressing=ipv6
VLAN=engreen
''',
'engreen.netdev': '''[NetDev]
Name=engreen
Kind=vlan
[VLAN]
Id=2
''',
'engreen.network': '''[Match]
Name=engreen
[Network]
DHCP=ipv6
LinkLocalAddressing=ipv6
ConfigureWithoutCarrier=yes
[DHCP]
RouteMetric=100
UseMTU=true
'''})
self.assert_nm(None, '''[keyfile]
# devices managed by networkd
unmanaged-devices+=interface-name:en1,interface-name:enblue,interface-name:engreen,''')
self.assert_nm_udev(None)
class TestNetworkManager(TestBase):
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.nmconnection')) 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)
def test_vlan_sriov(self):
# we need to make sure renderer: sriov vlans are not saved as part of
# the NM/networkd config
self.generate('''network:
version: 2
renderer: NetworkManager
ethernets:
en1: {}
vlans:
enblue:
id: 1
link: en1
addresses: [1.2.3.4/24]
renderer: sriov
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
''',
'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)
netplan.io-0.99/tests/generator/test_wifis.py 0000664 0000000 0000000 00000032011 13646002212 0021375 0 ustar 00root root 0000000 0000000 #
# Tests for VLAN devices config generated via netplan
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 stat
from .base import TestBase, ND_WIFI_DHCP4
class TestNetworkd(TestBase):
def test_wifi(self):
self.generate('''network:
version: 2
wifis:
wl0:
access-points:
"Joe's Home":
password: "s0s3kr1t"
bssid: 00:11:22:33:44:55
band: 2.4GHz
channel: 11
workplace:
password: "c0mpany1"
bssid: de:ad:be:ef:ca:fe
band: 5GHz
channel: 100
peer2peer:
mode: adhoc
channel-no-band:
channel: 7
band-no-channel:
band: 2.4G
band-no-channel2:
band: 5G
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:
new_config = f.read()
network = 'ssid="{}"\n freq_list='.format('band-no-channel2')
freqs_5GHz = [5610, 5310, 5620, 5320, 5630, 5640, 5340, 5035, 5040, 5045, 5055, 5060, 5660, 5680, 5670, 5080, 5690,
5700, 5710, 5720, 5825, 5745, 5755, 5805, 5765, 5160, 5775, 5170, 5480, 5180, 5795, 5190, 5500, 5200,
5510, 5210, 5520, 5220, 5530, 5230, 5540, 5240, 5550, 5250, 5560, 5260, 5570, 5270, 5580, 5280, 5590,
5290, 5600, 5300, 5865, 5845, 5785]
freqs = new_config.split(network)
freqs = freqs[1].split('\n')[0]
self.assertEqual(len(freqs.split(' ')), len(freqs_5GHz))
for freq in freqs_5GHz:
self.assertRegexpMatches(new_config, '{}[ 0-9]*{}[ 0-9]*\n'.format(network, freq))
network = 'ssid="{}"\n freq_list='.format('band-no-channel')
freqs_24GHz = [2412, 2417, 2422, 2427, 2432, 2442, 2447, 2437, 2452, 2457, 2462, 2467, 2472, 2484]
freqs = new_config.split(network)
freqs = freqs[1].split('\n')[0]
self.assertEqual(len(freqs.split(' ')), len(freqs_24GHz))
for freq in freqs_24GHz:
self.assertRegexpMatches(new_config, '{}[ 0-9]*{}[ 0-9]*\n'.format(network, freq))
self.assertIn('''
network={
ssid="channel-no-band"
key_mgmt=NONE
}
''', new_config)
self.assertIn('''
network={
ssid="peer2peer"
mode=1
key_mgmt=NONE
}
''', new_config)
self.assertIn('''
network={
ssid="workplace"
bssid=de:ad:be:ef:ca:fe
freq_list=5500
key_mgmt=WPA-PSK
psk="c0mpany1"
}
''', new_config)
self.assertIn('''
network={
ssid="Joe's Home"
bssid=00:11:22:33:44:55
freq_list=2462
key_mgmt=WPA-PSK
psk="s0s3kr1t"
}
''', new_config)
self.assertEqual(stat.S_IMODE(os.fstat(f.fileno()).st_mode), 0o600)
self.assertTrue(os.path.isfile(os.path.join(
self.workdir.name, 'run/systemd/system/netplan-wpa-wl0.service')))
self.assertTrue(os.path.islink(os.path.join(
self.workdir.name, 'run/systemd/system/systemd-networkd.service.wants/netplan-wpa-wl0.service')))
def test_wifi_route(self):
self.generate('''network:
version: 2
wifis:
wl0:
access-points:
workplace:
password: "c0mpany1"
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
LinkLocalAddressing=ipv6
[Route]
Destination=10.10.10.0/24
Gateway=8.8.8.8
[DHCP]
RouteMetric=600
UseMTU=true
'''})
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: "c0mpany1"
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: "c0mpany1"
mode: ap
dhcp4: yes''', expect_fail=True)
self.assertIn('networkd does not support wifi in access point mode', err)
def test_wifi_wowlan(self):
self.generate('''network:
version: 2
wifis:
wl0:
wakeonwlan:
- any
- disconnect
- magic_pkt
- gtk_rekey_failure
- eap_identity_req
- four_way_handshake
- rfkill_release
access-points:
homenet: {mode: infrastructure}''')
self.assert_networkd({'wl0.network': '''[Match]
Name=wl0
[Network]
LinkLocalAddressing=ipv6
'''})
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:
new_config = f.read()
self.assertIn('''
wowlan_triggers=any disconnect magic_pkt gtk_rekey_failure eap_identity_req four_way_handshake rfkill_release
network={
ssid="homenet"
key_mgmt=NONE
}
''', new_config)
self.assertEqual(stat.S_IMODE(os.fstat(f.fileno()).st_mode), 0o600)
self.assertTrue(os.path.isfile(os.path.join(
self.workdir.name, 'run/systemd/system/netplan-wpa-wl0.service')))
self.assertTrue(os.path.islink(os.path.join(
self.workdir.name, 'run/systemd/system/systemd-networkd.service.wants/netplan-wpa-wl0.service')))
def test_wifi_wowlan_default(self):
self.generate('''network:
version: 2
wifis:
wl0:
wakeonwlan: [default]
access-points:
homenet: {mode: infrastructure}''')
self.assert_networkd({'wl0.network': '''[Match]
Name=wl0
[Network]
LinkLocalAddressing=ipv6
'''})
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:
new_config = f.read()
self.assertIn('''
network={
ssid="homenet"
key_mgmt=NONE
}
''', new_config)
self.assertEqual(stat.S_IMODE(os.fstat(f.fileno()).st_mode), 0o600)
self.assertTrue(os.path.isfile(os.path.join(
self.workdir.name, 'run/systemd/system/netplan-wpa-wl0.service')))
self.assertTrue(os.path.islink(os.path.join(
self.workdir.name, 'run/systemd/system/systemd-networkd.service.wants/netplan-wpa-wl0.service')))
class TestNetworkManager(TestBase):
def test_wifi_default(self):
self.generate('''network:
version: 2
renderer: NetworkManager
wifis:
wl0:
access-points:
"Joe's Home":
password: "s0s3kr1t"
bssid: 00:11:22:33:44:55
band: 2.4GHz
channel: 11
workplace:
password: "c0mpany1"
bssid: de:ad:be:ef:ca:fe
band: 5GHz
channel: 100
channel-no-band:
channel: 22
band-no-channel:
band: 5GHz
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
bssid=00:11:22:33:44:55
band=bg
channel=11
[wifi-security]
key-mgmt=wpa-psk
psk=s0s3kr1t
''',
'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
bssid=de:ad:be:ef:ca:fe
band=a
channel=100
[wifi-security]
key-mgmt=wpa-psk
psk=c0mpany1
''',
'wl0-channel-no-band': '''[connection]
id=netplan-wl0-channel-no-band
type=wifi
interface-name=wl0
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=ignore
[wifi]
ssid=channel-no-band
mode=infrastructure
''',
'wl0-band-no-channel': '''[connection]
id=netplan-wl0-band-no-channel
type=wifi
interface-name=wl0
[ethernet]
wake-on-lan=0
[ipv4]
method=auto
[ipv6]
method=ignore
[wifi]
ssid=band-no-channel
mode=infrastructure
band=a
'''})
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: s0s3cret''')
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=s0s3cret
'''})
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_wifi_wowlan(self):
self.generate('''network:
version: 2
renderer: NetworkManager
wifis:
wl0:
wakeonwlan: [any, tcp, four_way_handshake, magic_pkt]
access-points:
homenet: {mode: infrastructure}''')
self.assert_nm({'wl0-homenet': '''[connection]
id=netplan-wl0-homenet
type=wifi
interface-name=wl0
[ethernet]
wake-on-lan=0
[802-11-wireless]
wake-on-wlan=330
[ipv4]
method=link-local
[ipv6]
method=ignore
[wifi]
ssid=homenet
mode=infrastructure
'''})
def test_wifi_wowlan_default(self):
self.generate('''network:
version: 2
renderer: NetworkManager
wifis:
wl0:
wakeonwlan: [default]
access-points:
homenet: {mode: infrastructure}''')
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=infrastructure
'''})
class TestConfigErrors(TestBase):
def test_wifi_invalid_wowlan(self):
err = self.generate('''network:
version: 2
wifis:
wl0:
wakeonwlan: [bogus]
access-points:
homenet: {mode: infrastructure}''', expect_fail=True)
self.assertIn("Error in network definition: invalid value for wakeonwlan: 'bogus'", err)
def test_wifi_wowlan_unsupported(self):
err = self.generate('''network:
version: 2
wifis:
wl0:
wakeonwlan: [tcp]
access-points:
homenet: {mode: infrastructure}''', expect_fail=True)
self.assertIn("ERROR: unsupported wowlan_triggers mask: 0x100", err)
def test_wifi_wowlan_exclusive(self):
err = self.generate('''network:
version: 2
wifis:
wl0:
wakeonwlan: [default, magic_pkt]
access-points:
homenet: {mode: infrastructure}''', expect_fail=True)
self.assertIn("Error in network definition: 'default' is an exclusive flag for wakeonwlan", err)
netplan.io-0.99/tests/integration/ 0000775 0000000 0000000 00000000000 13646002212 0017203 5 ustar 00root root 0000000 0000000 netplan.io-0.99/tests/integration/__init__.py 0000664 0000000 0000000 00000001305 13646002212 0021313 0 ustar 00root root 0000000 0000000 #
# Integration tests.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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.io-0.99/tests/integration/base.py 0000664 0000000 0000000 00000041473 13646002212 0020500 0 ustar 00root root 0000000 0000000 #
# 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) 2018 Canonical, Ltd.
# Author: Martin Pitt
# Author: Mathieu Trudel-Lapierre
#
# 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
import gi
# make sure we point to libnetplan properly.
os.environ.update({'LD_LIBRARY_PATH': '.:{}'.format(os.environ.get('LD_LIBRARY_PATH'))})
test_backends = "networkd NetworkManager" if "NETPLAN_TEST_BACKENDS" not in os.environ else os.environ["NETPLAN_TEST_BACKENDS"]
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 IntegrationTestsBase(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 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'])
# ensure we have this so that iw works
try:
subprocess.check_call(['modprobe', 'cfg80211'])
# 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(r'^(?:global\n)?country (\S+):', out)
assert m
klass.orig_country = m.group(1)
subprocess.check_call(['iw', 'reg', 'set', 'EU'])
except Exception:
raise unittest.SkipTest("cfg80211 (wireless) is unavailable, can't test")
@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'
klass.dev_e_ap_ip4 = '192.168.5.1/24'
klass.dev_e_ap_ip6 = '2600::1/64'
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'
klass.dev_e2_ap_ip4 = '192.168.6.1/24'
klass.dev_e2_ap_ip6 = '2601::1/64'
out = subprocess.check_output(['ip', '-br', 'link', 'show', 'dev', 'eth43'],
universal_newlines=True)
klass.dev_e2_client_mac = out.split()[2]
os.makedirs('/run/NetworkManager/conf.d', exist_ok=True)
# 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=')
# 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
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)
@classmethod
def shutdown_devices(klass):
'''Remove test devices'''
subprocess.check_call(['ip', 'link', 'del', 'dev', klass.dev_e_ap])
subprocess.check_call(['ip', 'link', 'del', 'dev', klass.dev_e2_ap])
klass.dev_e_ap = None
klass.dev_e_client = None
klass.dev_e2_ap = None
klass.dev_e2_client = None
klass.dev_w_ap = None
klass.dev_w_client = None
subprocess.call(['ip', 'link', 'del', 'dev', 'mybr'],
stderr=subprocess.PIPE)
subprocess.check_call(['rmmod', 'mac80211_hwsim'])
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', self.dev_e_ap_ip6, 'dev', self.dev_w_ap])
else:
subprocess.check_call(['ip', 'a', 'add', self.dev_e_ap_ip4, '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', self.dev_e_ap_ip6, 'dev', self.dev_e_ap])
subprocess.check_call(['ip', 'a', 'add', self.dev_e2_ap_ip6, 'dev', self.dev_e2_ap])
else:
subprocess.check_call(['ip', 'a', 'add', self.dev_e_ap_ip4, 'dev', self.dev_e_ap])
subprocess.check_call(['ip', 'a', 'add', self.dev_e2_ap_ip4, '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', 500)
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(self, iface, expected_ip_a=None, unexpected_ip_a=None):
'''Assert that client interface has been created'''
out = subprocess.check_output(['ip', 'a', 'show', 'dev', iface],
universal_newlines=True)
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)
return out
def assert_iface_up(self, iface, expected_ip_a=None, unexpected_ip_a=None):
'''Assert that client interface is up'''
out = self.assert_iface(iface, expected_ip_a=None, unexpected_ip_a=None)
if 'bond' not in iface:
self.assertIn('state UP', 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=240', '--wait-for-startup']) != 0:
self.fail('timed out waiting for NetworkManager to settle down')
def nm_online_full(self, iface, timeout=60):
'''Wait for NetworkManager connection to be completed (incl. IP4 & DHCP)'''
gi.require_version('NM', '1.0')
from gi.repository import NM
for t in range(timeout):
c = NM.Client.new(None)
con = c.get_device_by_iface(iface).get_active_connection()
if not con:
self.fail('no active connection for %s by NM' % iface)
flags = NM.utils_enum_to_str(NM.ActivationStateFlags, con.get_state_flags())
if "ip4-ready" in flags:
break
time.sleep(1)
else:
self.fail('timed out waiting for %s to get ready by NM' % iface)
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')
netplan.io-0.99/tests/integration/bonds.py 0000664 0000000 0000000 00000071676 13646002212 0020703 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Integration tests for bonds
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 sys
import subprocess
import unittest
from base import IntegrationTestsBase, test_backends
class _CommonTests():
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}
%(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: {}
%(e2c)s: {}
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}
%(e2c)s: {}
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}
%(e2c)s: {}
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}
%(e2c)s: {}
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}
%(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}
%(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}
%(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}
%(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}
%(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}
ethb2:
match: {name: %(e2c)s}
bonds:
mybond:
interfaces: [ethbn, ethb2]
parameters:
mode: balance-rr
mii-monitor-interval: 50s
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.skipIf("networkd" not in test_backends,
"skipping as networkd backend tests are disabled")
class TestNetworkd(IntegrationTestsBase, _CommonTests):
backend = 'networkd'
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
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_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: 5
down-delay: 10s
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: 5
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: 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}
%(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')
def test_bond_arp_targets_many_lp1829264(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, 192.168.5.34 ]
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:
result = f.read().strip()
self.assertIn('192.168.5.1', result)
self.assertIn('192.168.5.34', result)
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_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}
%(e2c)s: {}
bonds:
mybond:
interfaces: [ethbn]
parameters:
mode: balance-xor
arp-ip-targets: [192.168.5.1]
arp-interval: 50000
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')
@unittest.skipIf("NetworkManager" not in test_backends,
"skipping as NetworkManager backend tests are disabled")
class TestNetworkManager(IntegrationTestsBase, _CommonTests):
backend = 'NetworkManager'
@unittest.skip("NetworkManager does not support setting MAC for a bond")
def test_bond_mac(self):
pass
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: 5
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: 5
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')
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: 5
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')
unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
netplan.io-0.99/tests/integration/bridges.py 0000664 0000000 0000000 00000043734 13646002212 0021207 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Integration tests for bridges
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 sys
import subprocess
import time
import unittest
from base import IntegrationTestsBase, test_backends
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
ethbr:
match: {name: %(e2c)s}
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, r'%s\s+(ethernet|bridge)\s+%s' % (i, expected_state))
def test_bridge_path_cost(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(e2c)s}
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.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(e2c)s}
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.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(e2c)s}
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.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(e2c)s}
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_forward_delay(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(e2c)s}
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.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(e2c)s}
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')
@unittest.skipIf("networkd" not in test_backends,
"skipping as networkd backend tests are disabled")
class TestNetworkd(IntegrationTestsBase, _CommonTests):
backend = 'networkd'
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
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_bridge_anonymous(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(e2c)s}
bridges:
mybr:
interfaces: [ethbr]''' % {'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])
def test_bridge_isolated(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(e2c)s}
bridges:
mybr:
interfaces: []
addresses: [10.10.10.10/24]''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client})
subprocess.check_call(['netplan', 'apply'])
time.sleep(1)
out = subprocess.check_output(['ip', 'a', 'show', 'dev', 'mybr'],
universal_newlines=True)
self.assertIn('inet 10.10.10.10/24', out)
def test_bridge_port_priority(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(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.skipIf("NetworkManager" not in test_backends,
"skipping as NetworkManager backend tests are disabled")
class TestNetworkManager(IntegrationTestsBase, _CommonTests):
backend = 'NetworkManager'
@unittest.skip("NetworkManager does not support setting MAC for a bridge")
def test_bridge_mac(self):
pass
def test_bridge_priority(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(e2c)s}
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_port_priority(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'mybr'], 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: %(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))
netplan.io-0.99/tests/integration/ethernets.py 0000664 0000000 0000000 00000024021 13646002212 0021555 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Integration tests for ethernet devices and features common to all device
# types.
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 sys
import subprocess
import unittest
from base import IntegrationTestsBase, nm_uses_dnsmasq, resolved_in_use, test_backends
class _CommonTests():
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_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()
if self.backend == 'NetworkManager':
self.nm_online_full(self.dev_e_client)
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, r'%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('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'via 9876:bbbb::1',
subprocess.check_output(['ip', '-6', 'route', 'show', 'default']))
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
accept-ra: 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'])
@unittest.skipIf("networkd" not in test_backends,
"skipping as networkd backend tests are disabled")
class TestNetworkd(IntegrationTestsBase, _CommonTests):
backend = 'networkd'
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
accept-ra: yes
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:'])
@unittest.skipIf("NetworkManager" not in test_backends,
"skipping as NetworkManager backend tests are disabled")
class TestNetworkManager(IntegrationTestsBase, _CommonTests):
backend = 'NetworkManager'
@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.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
netplan.io-0.99/tests/integration/regressions.py 0000664 0000000 0000000 00000006013 13646002212 0022120 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Regression tests to catch previously-fixed issues.
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 sys
import subprocess
import unittest
from base import IntegrationTestsBase, test_backends
class _CommonTests():
def test_empty_yaml_lp1795343(self):
with open(self.config, 'w') as f:
f.write('''''')
self.generate_and_settle()
@unittest.skipIf("networkd" not in test_backends,
"skipping as networkd backend tests are disabled")
class TestNetworkd(IntegrationTestsBase, _CommonTests):
backend = 'networkd'
def test_lp1802322_bond_mac_rename(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:
ethbn1:
match: {name: %(ec)s}
dhcp4: no
ethbn2:
match: {name: %(e2c)s}
dhcp4: no
bonds:
mybond:
interfaces: [ethbn1, ethbn2]
macaddress: 00:0a:f7:72:a7:28
mtu: 9000
addresses: [ 192.168.5.9/24 ]
gateway4: 192.168.5.1
parameters:
down-delay: 0
lacp-rate: fast
mii-monitor-interval: 100
mode: 802.3ad
transmit-hash-policy: layer3+4
up-delay: 0
''' % {'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', '00:0a:f7:72:a7:28'],
['inet '])
self.assert_iface_up(self.dev_e2_client,
['master mybond', '00:0a:f7:72:a7:28'],
['inet '])
self.assert_iface_up('mybond',
['inet 192.168.5.[0-9]+/24'])
with open('/sys/class/net/mybond/bonding/slaves') as f:
self.assertIn(self.dev_e_client, f.read().strip())
@unittest.skipIf("NetworkManager" not in test_backends,
"skipping as NetworkManager backend tests are disabled")
class TestNetworkManager(IntegrationTestsBase, _CommonTests):
backend = 'NetworkManager'
unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
netplan.io-0.99/tests/integration/routing.py 0000664 0000000 0000000 00000020176 13646002212 0021252 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Integration tests for routing functions
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 sys
import subprocess
import unittest
from base import IntegrationTestsBase, test_backends
class _CommonTests():
@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_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'via 9876:bbbb::1',
subprocess.check_output(['ip', '-6', 'route', 'show', 'default']))
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']))
@unittest.skipIf("networkd" not in test_backends,
"skipping as networkd backend tests are disabled")
class TestNetworkd(IntegrationTestsBase, _CommonTests):
backend = 'networkd'
def test_link_route_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
scope: link
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 proto static scope link',
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']))
@unittest.skip("networkd does not handle non-unicast routes correctly yet (Invalid argument)")
def test_route_type_blackhole(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:
ethbn:
match: {name: %(ec)s}
addresses: [ "10.20.10.1/24" ]
routes:
- to: 10.10.10.0/24
via: 10.20.10.100
type: blackhole''' % {'r': self.backend, 'ec': self.dev_e_client})
self.generate_and_settle()
self.assert_iface_up(self.dev_e_client,
['inet '])
self.assertIn(b'blackhole 10.10.10.0/24',
subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e_client]))
def test_route_on_link(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:
ethbn:
match: {name: %(ec)s}
dhcp4: no
addresses: [ "10.20.10.1/24" ]
routes:
- to: 20.0.0.0/24
via: 10.10.10.10
on-link: true''' % {'r': self.backend, 'ec': self.dev_e_client})
self.generate_and_settle()
self.assert_iface_up(self.dev_e_client,
['inet '])
self.assertIn(b'20.0.0.0/24 via 10.10.10.10 proto static onlink',
subprocess.check_output(['ip', 'route', 'show', 'dev', self.dev_e_client]))
def test_route_with_policy(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:
ethbn:
match: {name: %(ec)s}
addresses: [ "10.20.10.1/24" ]
routes:
- to: 40.0.0.0/24
via: 10.20.10.55
metric: 50
- to: 40.0.0.0/24
via: 10.20.10.88
table: 99
metric: 50
routing-policy:
- from: 10.20.10.0/24
to: 40.0.0.0/24
table: 99''' % {'r': self.backend, 'ec': self.dev_e_client})
self.generate_and_settle()
self.assert_iface_up(self.dev_e_client,
['inet '])
self.assertIn(b'to 40.0.0.0/24 lookup 99',
subprocess.check_output(['ip', 'rule', 'show']))
self.assertIn(b'40.0.0.0/24 via 10.20.10.88',
subprocess.check_output(['ip', 'route', 'show', 'table', '99']))
@unittest.skipIf("NetworkManager" not in test_backends,
"skipping as NetworkManager backend tests are disabled")
class TestNetworkManager(IntegrationTestsBase, _CommonTests):
backend = 'NetworkManager'
unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
netplan.io-0.99/tests/integration/run.py 0000775 0000000 0000000 00000005024 13646002212 0020365 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Test runner for netplan integration tests.
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 argparse
import glob
import os
import subprocess
import textwrap
import sys
tests_dir = os.path.dirname(os.path.abspath(__file__))
default_backends = [ 'networkd', 'NetworkManager' ]
fixtures = [ "__init__.py", "base.py", "run.py" ]
possible_tests = []
testfiles = glob.glob(os.path.join(tests_dir, "*.py"))
for pyfile in testfiles:
filename = os.path.basename(pyfile)
if filename not in fixtures:
possible_tests.append(filename.split('.')[0])
def dedupe(duped_list):
deduped = set()
for item in duped_list:
real_items = item.split(",")
for real_item in real_items:
deduped.add(real_item)
return deduped
# XXX: omg, this is ugly :)
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent("""
Test runner for netplan integration tests
Available tests:
{}
""".format("\n".join(" - {}".format(x) for x in sorted(possible_tests)))))
parser.add_argument('--test', action='append', help="List of tests to be run")
parser.add_argument('--backend', action='append', help="List of backends to test (NetworkManager, networkd)")
args = parser.parse_args()
requested_tests = set()
backends = set()
if args.test is not None:
requested_tests = dedupe(args.test)
else:
requested_tests.update(possible_tests)
if args.backend is not None:
backends = dedupe(args.backend)
else:
backends.update(default_backends)
os.environ["NETPLAN_TEST_BACKENDS"] = ",".join(backends)
returncode = 0
for test in requested_tests:
ret = subprocess.call(['python3', os.path.join(tests_dir, "{}.py".format(test))])
if returncode == 0 and ret != 0:
returncode = ret
sys.exit(returncode)
netplan.io-0.99/tests/integration/scenarios.py 0000664 0000000 0000000 00000010541 13646002212 0021544 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Integration tests for complex networking scenarios
# (ie. mixes of various features, may test real live cases)
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 sys
import subprocess
import unittest
from base import IntegrationTestsBase, test_backends
class _CommonTests():
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: [ethb2]
parameters:
mode: balance-rr
ethernets:
ethbn:
match: {name: %(ec)s}
ethb2:
match: {name: %(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_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_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']
parameters:
stp: false
path-cost:
bond0: 1000
vlan2: 2000
bonds:
bond0:
interfaces: ['br1']
parameters:
mode: balance-rr
bridges:
br1:
interfaces: ['ethb2']
vlans:
vlan2:
link: ethbn
id: 2
ethernets:
ethbn:
match: {name: %(ec)s}
ethb2:
match: {name: %(e2c)s}
''' % {'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'])
@unittest.skipIf("networkd" not in test_backends,
"skipping as networkd backend tests are disabled")
class TestNetworkd(IntegrationTestsBase, _CommonTests):
backend = 'networkd'
@unittest.skipIf("NetworkManager" not in test_backends,
"skipping as NetworkManager backend tests are disabled")
class TestNetworkManager(IntegrationTestsBase, _CommonTests):
backend = 'NetworkManager'
unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
netplan.io-0.99/tests/integration/tunnels.py 0000664 0000000 0000000 00000014037 13646002212 0021252 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
# Tunnel integration tests. NM and networkd are started on the generated
# configuration, using emulated ethernets (veth).
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 sys
import subprocess
import unittest
from base import IntegrationTestsBase, test_backends
class _CommonTests():
def test_tunnel_sit(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'sit-tun0'], stderr=subprocess.DEVNULL)
with open(self.config, 'w') as f:
f.write('''network:
renderer: %(r)s
version: 2
ethernets:
ethbn:
match: {name: %(ec)s}
ethb2:
match: {name: %(e2c)s}
tunnels:
sit-tun0:
mode: sit
local: 192.168.5.1
remote: 99.99.99.99
''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client})
self.generate_and_settle()
self.assert_iface('sit-tun0', ['sit-tun0@NONE', 'link.* 192.168.5.1 peer 99.99.99.99'])
def test_tunnel_ipip(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'tun0'], stderr=subprocess.DEVNULL)
with open(self.config, 'w') as f:
f.write('''network:
renderer: %(r)s
version: 2
ethernets:
ethbn:
match: {name: %(ec)s}
ethb2:
match: {name: %(e2c)s}
tunnels:
tun0:
mode: ipip
local: 192.168.5.1
remote: 99.99.99.99
''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client})
self.generate_and_settle()
self.assert_iface('tun0', ['tun0@NONE', 'link.* 192.168.5.1 peer 99.99.99.99'])
@unittest.skipIf("networkd" not in test_backends,
"skipping as networkd backend tests are disabled")
class TestNetworkd(IntegrationTestsBase, _CommonTests):
backend = 'networkd'
def test_tunnel_gre(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'tun0'], stderr=subprocess.DEVNULL)
with open(self.config, 'w') as f:
f.write('''network:
renderer: %(r)s
version: 2
ethernets:
ethbn:
match: {name: %(ec)s}
ethb2:
match: {name: %(e2c)s}
tunnels:
tun0:
mode: gre
local: 192.168.5.1
remote: 99.99.99.99
''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client})
self.generate_and_settle()
self.assert_iface('tun0', ['tun0@NONE', 'link.* 192.168.5.1 peer 99.99.99.99'])
def test_tunnel_gre6(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'tun0'], stderr=subprocess.DEVNULL)
with open(self.config, 'w') as f:
f.write('''network:
renderer: %(r)s
version: 2
ethernets:
ethbn:
match: {name: %(ec)s}
ethb2:
match: {name: %(e2c)s}
tunnels:
tun0:
mode: ip6gre
local: fe80::1
remote: 2001:dead:beef::2
''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client})
self.generate_and_settle()
self.assert_iface('tun0', ['tun0@NONE', 'link.* fe80::1 brd 2001:dead:beef::2'])
def test_tunnel_vti(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'tun0'], stderr=subprocess.DEVNULL)
with open(self.config, 'w') as f:
f.write('''network:
renderer: %(r)s
version: 2
ethernets:
ethbn:
match: {name: %(ec)s}
ethb2:
match: {name: %(e2c)s}
tunnels:
tun0:
mode: vti
keys: 1234
local: 192.168.5.1
remote: 99.99.99.99
''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client})
self.generate_and_settle()
self.assert_iface('tun0', ['tun0@NONE', 'link.* 192.168.5.1 peer 99.99.99.99'])
def test_tunnel_vti6(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'tun0'], stderr=subprocess.DEVNULL)
with open(self.config, 'w') as f:
f.write('''network:
renderer: %(r)s
version: 2
ethernets:
ethbn:
match: {name: %(ec)s}
ethb2:
match: {name: %(e2c)s}
tunnels:
tun0:
mode: vti6
keys: 1234
local: fe80::1
remote: 2001:dead:beef::2
''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client})
self.generate_and_settle()
self.assert_iface('tun0', ['tun0@NONE', 'link.* fe80::1 brd 2001:dead:beef::2'])
@unittest.skipIf("NetworkManager" not in test_backends,
"skipping as NetworkManager backend tests are disabled")
class TestNetworkManager(IntegrationTestsBase, _CommonTests):
backend = 'NetworkManager'
def test_tunnel_gre(self):
self.setup_eth(None)
self.addCleanup(subprocess.call, ['ip', 'link', 'delete', 'tun0'], stderr=subprocess.DEVNULL)
with open(self.config, 'w') as f:
f.write('''network:
renderer: %(r)s
version: 2
ethernets:
ethbn:
match: {name: %(ec)s}
ethb2:
match: {name: %(e2c)s}
tunnels:
tun0:
mode: gre
keys: 1234
local: 192.168.5.1
remote: 99.99.99.99
''' % {'r': self.backend, 'ec': self.dev_e_client, 'e2c': self.dev_e2_client})
self.generate_and_settle()
self.assert_iface('tun0', ['tun0@NONE', 'link.* 192.168.5.1 peer 99.99.99.99'])
unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
netplan.io-0.99/tests/integration/vlans.py 0000664 0000000 0000000 00000007233 13646002212 0020705 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Integration tests for VLAN virtual devices
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 sys
import subprocess
import unittest
from base import IntegrationTestsBase, test_backends
class _CommonTests():
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')
@unittest.skipIf("networkd" not in test_backends,
"skipping as networkd backend tests are disabled")
class TestNetworkd(IntegrationTestsBase, _CommonTests):
backend = 'networkd'
@unittest.skipIf("NetworkManager" not in test_backends,
"skipping as NetworkManager backend tests are disabled")
class TestNetworkManager(IntegrationTestsBase, _CommonTests):
backend = 'NetworkManager'
unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
netplan.io-0.99/tests/integration/wifi.py 0000664 0000000 0000000 00000015306 13646002212 0020520 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Integration tests for wireless devices
#
# These need to be run in a VM and do change the system
# configuration.
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 sys
import subprocess
import unittest
from base import IntegrationTestsBase, test_backends
class _CommonTests():
@unittest.skip("Unsupported matching by driver / wifi matching makes this untestable for now")
def test_mapping_for_driver(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:
wifi_ifs:
match:
driver: mac80211_hwsim
dhcp4: yes
access-points:
"fake net": {}
decoy: {}''' % {'r': self.backend})
self.generate_and_settle()
p = subprocess.Popen(['netplan', 'generate', '--mapping', 'mac80211_hwsim'],
stdout=subprocess.PIPE)
out = p.communicate()[0]
self.assertEquals(p.returncode, 1)
self.assertIn(b'mac80211_hwsim', out)
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')
@unittest.skipIf("networkd" not in test_backends,
"skipping as networkd backend tests are disabled")
class TestNetworkd(IntegrationTestsBase, _CommonTests):
backend = 'networkd'
@unittest.skipIf("NetworkManager" not in test_backends,
"skipping as NetworkManager backend tests are disabled")
class TestNetworkManager(IntegrationTestsBase, _CommonTests):
backend = 'NetworkManager'
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)
unittest.main(testRunner=unittest.TextTestRunner(stream=sys.stdout, verbosity=2))
netplan.io-0.99/tests/test_configmanager.py 0000664 0000000 0000000 00000020545 13646002212 0021077 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
# Validate ConfigManager methods
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 tempfile
import unittest
from netplan.configmanager import ConfigManager
class TestConfigManager(unittest.TestCase):
def setUp(self):
self.workdir = tempfile.TemporaryDirectory()
self.configmanager = ConfigManager(prefix=self.workdir.name, extra_files={})
os.makedirs(os.path.join(self.workdir.name, "etc/netplan"))
os.makedirs(os.path.join(self.workdir.name, "run/systemd/network"))
os.makedirs(os.path.join(self.workdir.name, "run/NetworkManager/system-connections"))
with open(os.path.join(self.workdir.name, "newfile.yaml"), 'w') as fd:
print('''network:
version: 2
ethernets:
ethtest:
dhcp4: yes
''', file=fd)
with open(os.path.join(self.workdir.name, "newfile_merging.yaml"), 'w') as fd:
print('''network:
version: 2
ethernets:
eth0:
dhcp6: on
ethbr1:
dhcp4: on
''', file=fd)
with open(os.path.join(self.workdir.name, "newfile_emptydict.yaml"), 'w') as fd:
print('''network:
version: 2
ethernets:
eth0: {}
bridges:
br666: {}
''', file=fd)
with open(os.path.join(self.workdir.name, "etc/netplan/test.yaml"), 'w') as fd:
print('''network:
version: 2
renderer: networkd
ethernets:
eth0:
dhcp4: false
ethbr1:
dhcp4: false
ethbr2:
dhcp4: false
ethbond1:
dhcp4: false
ethbond2:
dhcp4: false
wifis:
wlan1:
access-points:
testAP: {}
vlans:
vlan2:
id: 2
link: eth99
bridges:
br3:
interfaces: [ ethbr1 ]
br4:
interfaces: [ ethbr2 ]
parameters:
stp: on
bonds:
bond5:
interfaces: [ ethbond1 ]
bond6:
interfaces: [ ethbond2 ]
parameters:
mode: 802.3ad
''', file=fd)
with open(os.path.join(self.workdir.name, "run/systemd/network/01-pretend.network"), 'w') as fd:
print("pretend .network", file=fd)
with open(os.path.join(self.workdir.name, "run/NetworkManager/system-connections/pretend"), 'w') as fd:
print("pretend NM config", file=fd)
def test_parse(self):
self.configmanager.parse()
self.assertIn('eth0', self.configmanager.ethernets)
self.assertIn('bond6', self.configmanager.bonds)
self.assertIn('eth0', self.configmanager.physical_interfaces)
self.assertNotIn('bond7', self.configmanager.interfaces)
self.assertNotIn('bond6', self.configmanager.physical_interfaces)
self.assertNotIn('parameters', self.configmanager.bonds.get('bond5'))
self.assertIn('parameters', self.configmanager.bonds.get('bond6'))
def test_parse_merging(self):
self.configmanager.parse(extra_config=[os.path.join(self.workdir.name, "newfile_merging.yaml")])
self.assertIn('eth0', self.configmanager.ethernets)
self.assertIn('dhcp4', self.configmanager.ethernets['eth0'])
self.assertEquals(True, self.configmanager.ethernets['eth0'].get('dhcp6'))
self.assertEquals(True, self.configmanager.ethernets['ethbr1'].get('dhcp4'))
def test_parse_emptydict(self):
self.configmanager.parse(extra_config=[os.path.join(self.workdir.name, "newfile_emptydict.yaml")])
self.assertIn('br666', self.configmanager.bridges)
self.assertEquals(False, self.configmanager.ethernets['eth0'].get('dhcp4'))
self.assertEquals(False, self.configmanager.ethernets['ethbr1'].get('dhcp4'))
def test_parse_extra_config(self):
self.configmanager.parse(extra_config=[os.path.join(self.workdir.name, "newfile.yaml")])
self.assertIn('ethtest', self.configmanager.ethernets)
self.assertIn('bond6', self.configmanager.bonds)
def test_add(self):
self.configmanager.add({os.path.join(self.workdir.name, "newfile.yaml"):
os.path.join(self.workdir.name, "etc/netplan/newfile.yaml")})
self.assertIn(os.path.join(self.workdir.name, "newfile.yaml"),
self.configmanager.extra_files)
self.assertTrue(os.path.exists(os.path.join(self.workdir.name, "etc/netplan/newfile.yaml")))
def test_backup_missing_dirs(self):
backup_dir = self.configmanager.tempdir
shutil.rmtree(os.path.join(self.workdir.name, "run/systemd/network"))
self.configmanager.backup(backup_config_dir=False)
self.assertTrue(os.path.exists(os.path.join(backup_dir, "run/NetworkManager/system-connections/pretend")))
# no source dir means no backup as well
self.assertFalse(os.path.exists(os.path.join(backup_dir, "run/systemd/network/01-pretend.network")))
self.assertFalse(os.path.exists(os.path.join(backup_dir, "etc/netplan/test.yaml")))
def test_backup_without_config_file(self):
backup_dir = self.configmanager.tempdir
self.configmanager.backup(backup_config_dir=False)
self.assertTrue(os.path.exists(os.path.join(backup_dir, "run/NetworkManager/system-connections/pretend")))
self.assertTrue(os.path.exists(os.path.join(backup_dir, "run/systemd/network/01-pretend.network")))
self.assertFalse(os.path.exists(os.path.join(backup_dir, "etc/netplan/test.yaml")))
def test_backup_with_config_file(self):
backup_dir = self.configmanager.tempdir
self.configmanager.backup(backup_config_dir=True)
self.assertTrue(os.path.exists(os.path.join(backup_dir, "run/NetworkManager/system-connections/pretend")))
self.assertTrue(os.path.exists(os.path.join(backup_dir, "run/systemd/network/01-pretend.network")))
self.assertTrue(os.path.exists(os.path.join(backup_dir, "etc/netplan/test.yaml")))
def test_revert(self):
self.configmanager.backup()
with open(os.path.join(self.workdir.name, "run/systemd/network/01-pretend.network"), 'a+') as fd:
print("CHANGED", file=fd)
with open(os.path.join(self.workdir.name, "run/systemd/network/01-pretend.network"), 'r') as fd:
lines = fd.readlines()
self.assertIn("CHANGED\n", lines)
self.configmanager.revert()
with open(os.path.join(self.workdir.name, "run/systemd/network/01-pretend.network"), 'r') as fd:
lines = fd.readlines()
self.assertNotIn("CHANGED\n", lines)
def test_revert_extra_files(self):
self.configmanager.add({os.path.join(self.workdir.name, "newfile.yaml"):
os.path.join(self.workdir.name, "etc/netplan/newfile.yaml")})
self.assertIn(os.path.join(self.workdir.name, "newfile.yaml"),
self.configmanager.extra_files)
self.assertTrue(os.path.exists(os.path.join(self.workdir.name, "etc/netplan/newfile.yaml")))
self.configmanager.revert()
self.assertNotIn(os.path.join(self.workdir.name, "newfile.yaml"),
self.configmanager.extra_files)
self.assertFalse(os.path.exists(os.path.join(self.workdir.name, "etc/netplan/newfile.yaml")))
def test_cleanup(self):
backup_dir = self.configmanager.tempdir
self.assertTrue(os.path.exists(backup_dir))
self.configmanager.cleanup()
self.assertFalse(os.path.exists(backup_dir))
def test__copy_tree(self):
self.configmanager._copy_tree(os.path.join(self.workdir.name, "etc"),
os.path.join(self.workdir.name, "etc2"))
self.assertTrue(os.path.exists(os.path.join(self.workdir.name, "etc2/netplan/test.yaml")))
@unittest.expectedFailure
def test__copy_tree_missing_source(self):
self.configmanager._copy_tree(os.path.join(self.workdir.name, "nonexistent"),
os.path.join(self.workdir.name, "nonexistent2"), missing_ok=False)
netplan.io-0.99/tests/test_sriov.py 0000664 0000000 0000000 00000054505 13646002212 0017444 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
#
# Copyright (C) 2020 Canonical, Ltd.
# Author: Ćukasz 'sil2100' Zemczak
#
# 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 unittest
import tempfile
from subprocess import CalledProcessError
from collections import defaultdict
from unittest.mock import patch, mock_open, call
import netplan.cli.sriov as sriov
from netplan.configmanager import ConfigManager, ConfigurationError
class MockSRIOVOpen():
def __init__(self):
# now this is a VERY ugly hack to make mock_open() better
self.read_queue = []
self.write_queue = []
def sriov_read():
action = self.read_queue.pop(0)
if isinstance(action, str):
return action
else:
raise action
def sriov_write(data):
if not self.write_queue:
return
action = self.write_queue.pop(0)
if isinstance(action, Exception):
raise action
self.open = mock_open()
self.open.return_value.read.side_effect = sriov_read
self.open.return_value.write.side_effect = sriov_write
def mock_set_counts(interfaces, config_manager, vf_counts, active_vfs, active_pfs):
counts = {'enp1': 2, 'enp2': 1}
vfs = {'enp1s16f1': None, 'enp1s16f2': None, 'customvf1': None}
pfs = {'enp1': 'enp1', 'enpx': 'enp2'}
vf_counts.update(counts)
active_vfs.update(vfs)
active_pfs.update(pfs)
class TestSRIOV(unittest.TestCase):
def setUp(self):
self.workdir = tempfile.TemporaryDirectory()
os.makedirs(os.path.join(self.workdir.name, 'etc/netplan'))
self.configmanager = ConfigManager(prefix=self.workdir.name, extra_files={})
def _prepare_sysfs_dir_structure(self):
# prepare a directory hierarchy for testing the matching
# this might look really scary, but that's how sysfs presents devices
# such as these
os.makedirs(os.path.join(self.workdir.name, 'sys/class/net'))
# first the VF
vf_iface_path = os.path.join(self.workdir.name, 'sys/devices/pci0000:00/0000:00:1f.6/net/enp2s16f1')
vf_dev_path = os.path.join(self.workdir.name, 'sys/devices/pci0000:00/0000:00:1f.6')
os.makedirs(vf_iface_path)
with open(os.path.join(vf_dev_path, 'vendor'), 'w') as f:
f.write('0x001f\n')
with open(os.path.join(vf_dev_path, 'device'), 'w') as f:
f.write('0xb33f\n')
os.symlink('../../devices/pci0000:00/0000:00:1f.6/net/enp2s16f1',
os.path.join(self.workdir.name, 'sys/class/net/enp2s16f1'))
os.symlink('../../../0000:00:1f.6', os.path.join(self.workdir.name, 'sys/class/net/enp2s16f1/device'))
# now the PF
os.path.join(self.workdir.name, 'sys/class/net/enp2')
pf_iface_path = os.path.join(self.workdir.name, 'sys/devices/pci0000:00/0000:00:1f.0/net/enp2')
pf_dev_path = os.path.join(self.workdir.name, 'sys/devices/pci0000:00/0000:00:1f.0')
os.makedirs(pf_iface_path)
with open(os.path.join(pf_dev_path, 'vendor'), 'w') as f:
f.write('0x001f\n')
with open(os.path.join(pf_dev_path, 'device'), 'w') as f:
f.write('0x1337\n')
os.symlink('../../devices/pci0000:00/0000:00:1f.0/net/enp2',
os.path.join(self.workdir.name, 'sys/class/net/enp2'))
os.symlink('../../../0000:00:1f.0', os.path.join(self.workdir.name, 'sys/class/net/enp2/device'))
# the PF additionally has device links to all the VFs defined for it
os.symlink('../../../0000:00:1f.4', os.path.join(pf_dev_path, 'virtfn1'))
os.symlink('../../../0000:00:1f.5', os.path.join(pf_dev_path, 'virtfn2'))
os.symlink('../../../0000:00:1f.6', os.path.join(pf_dev_path, 'virtfn3'))
os.symlink('../../../0000:00:1f.7', os.path.join(pf_dev_path, 'virtfn4'))
@patch('netplan.cli.utils.get_interface_driver_name')
@patch('netplan.cli.utils.get_interface_macaddress')
def test_get_vf_count_and_functions(self, gim, gidn):
# we mock-out get_interface_driver_name and get_interface_macaddress
# to return useful values for the test
gim.side_effect = lambda x: '00:01:02:03:04:05' if x == 'enp3' else '00:00:00:00:00:00'
gidn.side_effect = lambda x: 'foo' if x == 'enp2' else 'bar'
with open(os.path.join(self.workdir.name, "etc/netplan/test.yaml"), 'w') as fd:
print('''network:
version: 2
renderer: networkd
ethernets:
renderer: networkd
enp1:
mtu: 9000
enp2:
match:
driver: foo
enp3:
match:
macaddress: 00:01:02:03:04:05
enpx:
match:
name: enp[4-5]
enp0:
mtu: 9000
enp8:
virtual-function-count: 7
enp9: {}
wlp6s0: {}
enp1s16f1:
link: enp1
macaddress: 01:02:03:04:05:00
enp1s16f2:
link: enp1
macaddress: 01:02:03:04:05:01
enp2s16f1:
link: enp2
enp2s16f2: {link: enp2}
enp3s16f1:
link: enp3
enpxs16f1:
match:
name: enp[4-5]s16f1
link: enpx
enp9s16f1:
link: enp9
''', file=fd)
self.configmanager.parse()
interfaces = ['enp1', 'enp2', 'enp3', 'enp5', 'enp0', 'enp8']
vf_counts = defaultdict(int)
vfs = {}
pfs = {}
# call the function under test
sriov.get_vf_count_and_functions(interfaces, self.configmanager,
vf_counts, vfs, pfs)
# check if the right vf counts have been recorded in vf_counts
self.assertDictEqual(
vf_counts,
{'enp1': 2, 'enp2': 2, 'enp3': 1, 'enp5': 1, 'enp8': 7})
# also check if the vfs and pfs dictionaries got properly set
self.assertDictEqual(
vfs,
{'enp1s16f1': None, 'enp1s16f2': None, 'enp2s16f1': None,
'enp2s16f2': None, 'enp3s16f1': None, 'enpxs16f1': None})
self.assertDictEqual(
pfs,
{'enp1': 'enp1', 'enp2': 'enp2', 'enp3': 'enp3',
'enpx': 'enp5', 'enp8': 'enp8'})
@patch('netplan.cli.utils.get_interface_driver_name')
@patch('netplan.cli.utils.get_interface_macaddress')
def test_get_vf_count_and_functions_many_match(self, gim, gidn):
# we mock-out get_interface_driver_name and get_interface_macaddress
# to return useful values for the test
gim.side_effect = lambda x: '00:01:02:03:04:05' if x == 'enp3' else '00:00:00:00:00:00'
gidn.side_effect = lambda x: 'foo' if x == 'enp2' else 'bar'
with open(os.path.join(self.workdir.name, "etc/netplan/test.yaml"), 'w') as fd:
print('''network:
version: 2
renderer: networkd
ethernets:
renderer: networkd
enpx:
match:
name: enp*
mtu: 9000
enpxs16f1:
link: enpx
''', file=fd)
self.configmanager.parse()
interfaces = ['enp1', 'wlp6s0', 'enp2', 'enp3']
vf_counts = defaultdict(int)
vfs = {}
pfs = {}
# call the function under test
with self.assertRaises(ConfigurationError) as e:
sriov.get_vf_count_and_functions(interfaces, self.configmanager,
vf_counts, vfs, pfs)
self.assertIn('matched more than one interface for a PF device: enpx',
str(e.exception))
@patch('netplan.cli.utils.get_interface_driver_name')
@patch('netplan.cli.utils.get_interface_macaddress')
def test_get_vf_count_and_functions_not_enough_explicit(self, gim, gidn):
# we mock-out get_interface_driver_name and get_interface_macaddress
# to return useful values for the test
gim.side_effect = lambda x: '00:01:02:03:04:05' if x == 'enp3' else '00:00:00:00:00:00'
gidn.side_effect = lambda x: 'foo' if x == 'enp2' else 'bar'
with open(os.path.join(self.workdir.name, "etc/netplan/test.yaml"), 'w') as fd:
print('''network:
version: 2
renderer: networkd
ethernets:
renderer: networkd
enp1:
virtual-function-count: 2
mtu: 9000
enp1s16f1:
link: enp1
enp1s16f2:
link: enp1
enp1s16f3:
link: enp1
''', file=fd)
self.configmanager.parse()
interfaces = ['enp1', 'wlp6s0']
vf_counts = defaultdict(int)
vfs = {}
pfs = {}
# call the function under test
with self.assertRaises(ConfigurationError) as e:
sriov.get_vf_count_and_functions(interfaces, self.configmanager,
vf_counts, vfs, pfs)
self.assertIn('more VFs allocated than the explicit size declared: 3 > 2',
str(e.exception))
def test_set_numvfs_for_pf(self):
sriov_open = MockSRIOVOpen()
sriov_open.read_queue = ['8\n']
with patch('builtins.open', sriov_open.open):
ret = sriov.set_numvfs_for_pf('enp1', 2)
self.assertTrue(ret)
self.assertListEqual(sriov_open.open.call_args_list,
[call('/sys/class/net/enp1/device/sriov_totalvfs'),
call('/sys/class/net/enp1/device/sriov_numvfs', 'w')])
handle = sriov_open.open()
handle.write.assert_called_once_with('2')
def test_set_numvfs_for_pf_failsafe(self):
sriov_open = MockSRIOVOpen()
sriov_open.read_queue = ['8\n']
sriov_open.write_queue = [IOError(16, 'Error'), None, None]
with patch('builtins.open', sriov_open.open):
ret = sriov.set_numvfs_for_pf('enp1', 2)
self.assertTrue(ret)
handle = sriov_open.open()
self.assertEqual(handle.write.call_count, 3)
def test_set_numvfs_for_pf_over_max(self):
sriov_open = MockSRIOVOpen()
sriov_open.read_queue = ['8\n']
with patch('builtins.open', sriov_open.open):
with self.assertRaises(ConfigurationError) as e:
sriov.set_numvfs_for_pf('enp1', 9)
self.assertIn('cannot allocate more VFs for PF enp1 than supported',
str(e.exception))
def test_set_numvfs_for_pf_over_theoretical_max(self):
sriov_open = MockSRIOVOpen()
sriov_open.read_queue = ['1337\n']
with patch('builtins.open', sriov_open.open):
with self.assertRaises(ConfigurationError) as e:
sriov.set_numvfs_for_pf('enp1', 345)
self.assertIn('cannot allocate more VFs for PF enp1 than the SR-IOV maximum',
str(e.exception))
def test_set_numvfs_for_pf_read_failed(self):
sriov_open = MockSRIOVOpen()
cases = (
[IOError],
['not a number\n'],
)
with patch('builtins.open', sriov_open.open):
for case in cases:
sriov_open.read_queue = case
with self.assertRaises(RuntimeError):
sriov.set_numvfs_for_pf('enp1', 3)
def test_set_numvfs_for_pf_write_failed(self):
sriov_open = MockSRIOVOpen()
sriov_open.read_queue = ['8\n']
sriov_open.write_queue = [IOError(16, 'Error'), IOError(16, 'Error')]
with patch('builtins.open', sriov_open.open):
with self.assertRaises(RuntimeError) as e:
sriov.set_numvfs_for_pf('enp1', 2)
self.assertIn('failed setting sriov_numvfs to 2 for enp1',
str(e.exception))
def test_perform_hardware_specific_quirks(self):
# for now we have no custom quirks defined, so we just
# check if the function succeeds
sriov_open = MockSRIOVOpen()
sriov_open.read_queue = ['0x001f\n', '0x1337\n']
with patch('builtins.open', sriov_open.open):
sriov.perform_hardware_specific_quirks('enp1')
# it's good enough if it did all the matching
self.assertListEqual(sriov_open.open.call_args_list,
[call('/sys/class/net/enp1/device/vendor'),
call('/sys/class/net/enp1/device/device'), ])
def test_perform_hardware_specific_quirks_failed(self):
sriov_open = MockSRIOVOpen()
cases = (
[IOError],
['0x001f\n', IOError],
)
with patch('builtins.open', sriov_open.open):
for case in cases:
sriov_open.read_queue = case
with self.assertRaises(RuntimeError) as e:
sriov.perform_hardware_specific_quirks('enp1')
self.assertIn('could not determine vendor and device ID of enp1',
str(e.exception))
@patch('subprocess.check_call')
def test_apply_vlan_filter_for_vf(self, check_call):
self._prepare_sysfs_dir_structure()
sriov.apply_vlan_filter_for_vf('enp2', 'enp2s16f1', 'vlan10', 10, prefix=self.workdir.name)
self.assertEqual(check_call.call_count, 1)
self.assertListEqual(check_call.call_args[0][0],
['ip', 'link', 'set', 'dev', 'enp2',
'vf', '3', 'vlan', '10'])
@patch('subprocess.check_call')
def test_apply_vlan_filter_for_vf_failed_no_index(self, check_call):
self._prepare_sysfs_dir_structure()
# we remove the PF -> VF link, simulating a system error
os.unlink(os.path.join(self.workdir.name, 'sys/class/net/enp2/device/virtfn3'))
with self.assertRaises(RuntimeError) as e:
sriov.apply_vlan_filter_for_vf('enp2', 'enp2s16f1', 'vlan10', 10, prefix=self.workdir.name)
self.assertIn('could not determine the VF index for enp2s16f1 while configuring vlan vlan10',
str(e.exception))
self.assertEqual(check_call.call_count, 0)
@patch('subprocess.check_call')
def test_apply_vlan_filter_for_vf_failed_ip_link_set(self, check_call):
self._prepare_sysfs_dir_structure()
check_call.side_effect = CalledProcessError(-1, None)
with self.assertRaises(RuntimeError) as e:
sriov.apply_vlan_filter_for_vf('enp2', 'enp2s16f1', 'vlan10', 10, prefix=self.workdir.name)
self.assertIn('failed setting SR-IOV VLAN filter for vlan vlan10',
str(e.exception))
@patch('netifaces.interfaces')
@patch('netplan.cli.sriov.get_vf_count_and_functions')
@patch('netplan.cli.sriov.set_numvfs_for_pf')
@patch('netplan.cli.sriov.perform_hardware_specific_quirks')
@patch('netplan.cli.sriov.apply_vlan_filter_for_vf')
@patch('netplan.cli.utils.get_interface_driver_name')
@patch('netplan.cli.utils.get_interface_macaddress')
def test_apply_sriov_config(self, gim, gidn, apply_vlan, quirks,
set_numvfs, get_counts, netifs):
# set up the environment
with open(os.path.join(self.workdir.name, "etc/netplan/test.yaml"), 'w') as fd:
print('''network:
version: 2
renderer: networkd
ethernets:
enp1:
mtu: 9000
enpx:
match:
name: enp[2-3]
enp1s16f1:
link: enp1
macaddress: 01:02:03:04:05:00
enp1s16f2:
link: enp1
customvf1:
match:
name: enp[2-3]s16f[1-4]
link: enpx
vlans:
vf1.15:
renderer: sriov
id: 15
link: customvf1
vf1.16:
renderer: sriov
id: 16
link: foobar
''', file=fd)
self.configmanager.parse()
interfaces = ['enp1', 'enp2', 'enp5', 'wlp6s0']
# set up all the mock objects
netifs.return_value = ['enp1', 'enp2', 'enp5', 'wlp6s0',
'enp1s16f1', 'enp1s16f2', 'enp2s16f1']
get_counts.side_effect = mock_set_counts
set_numvfs.side_effect = lambda pf, _: False if pf == 'enp2' else True
gidn.return_value = 'foodriver'
gim.return_value = '00:01:02:03:04:05'
# call method under test
sriov.apply_sriov_config(interfaces, self.configmanager)
# check if the config got applied as expected
# we had 2 PFs, one having two VFs and the other only one
self.assertEqual(set_numvfs.call_count, 2)
self.assertListEqual(set_numvfs.call_args_list,
[call('enp1', 2),
call('enp2', 1)])
# one of the pfs already had sufficient VFs allocated, so only enp1
# changed the vf count and only that one should trigger quirks
quirks.assert_called_once_with('enp1')
# only one had a hardware vlan
apply_vlan.assert_called_once_with('enp2', 'enp2s16f1', 'vf1.15', 15)
@patch('netifaces.interfaces')
@patch('netplan.cli.sriov.get_vf_count_and_functions')
@patch('netplan.cli.sriov.set_numvfs_for_pf')
@patch('netplan.cli.sriov.perform_hardware_specific_quirks')
@patch('netplan.cli.sriov.apply_vlan_filter_for_vf')
@patch('netplan.cli.utils.get_interface_driver_name')
@patch('netplan.cli.utils.get_interface_macaddress')
def test_apply_sriov_config_invalid_vlan(self, gim, gidn, apply_vlan, quirks,
set_numvfs, get_counts, netifs):
# set up the environment
with open(os.path.join(self.workdir.name, "etc/netplan/test.yaml"), 'w') as fd:
print('''network:
version: 2
renderer: networkd
ethernets:
enp1:
mtu: 9000
enpx:
match:
name: enp[2-3]
enp1s16f1:
link: enp1
macaddress: 01:02:03:04:05:00
enp1s16f2:
link: enp1
customvf1:
match:
name: enp[2-3]s16f[1-4]
link: enpx
vlans:
vf1.15:
renderer: sriov
link: customvf1
''', file=fd)
self.configmanager.parse()
interfaces = ['enp1', 'enp2', 'enp5', 'wlp6s0']
# set up all the mock objects
netifs.return_value = ['enp1', 'enp2', 'enp5', 'wlp6s0',
'enp1s16f1', 'enp1s16f2', 'enp2s16f1']
get_counts.side_effect = mock_set_counts
set_numvfs.side_effect = lambda pf, _: False if pf == 'enp2' else True
gidn.return_value = 'foodriver'
gim.return_value = '00:01:02:03:04:05'
# call method under test
with self.assertRaises(ConfigurationError) as e:
sriov.apply_sriov_config(interfaces, self.configmanager)
self.assertIn('no id property defined for SR-IOV vlan vf1.15',
str(e.exception))
self.assertEqual(apply_vlan.call_count, 0)
@patch('netifaces.interfaces')
@patch('netplan.cli.sriov.get_vf_count_and_functions')
@patch('netplan.cli.sriov.set_numvfs_for_pf')
@patch('netplan.cli.sriov.perform_hardware_specific_quirks')
@patch('netplan.cli.sriov.apply_vlan_filter_for_vf')
@patch('netplan.cli.utils.get_interface_driver_name')
@patch('netplan.cli.utils.get_interface_macaddress')
def test_apply_sriov_config_too_many_vlans(self, gim, gidn, apply_vlan, quirks,
set_numvfs, get_counts, netifs):
# set up the environment
with open(os.path.join(self.workdir.name, "etc/netplan/test.yaml"), 'w') as fd:
print('''network:
version: 2
renderer: networkd
ethernets:
enp1:
mtu: 9000
enpx:
match:
name: enp[2-3]
enp1s16f1:
link: enp1
macaddress: 01:02:03:04:05:00
enp1s16f2:
link: enp1
customvf1:
match:
name: enp[2-3]s16f[1-4]
link: enpx
vlans:
vf1.15:
renderer: sriov
id: 15
link: customvf1
vf1.16:
renderer: sriov
id: 16
link: customvf1
''', file=fd)
self.configmanager.parse()
interfaces = ['enp1', 'enp2', 'enp5', 'wlp6s0']
# set up all the mock objects
netifs.return_value = ['enp1', 'enp2', 'enp5', 'wlp6s0',
'enp1s16f1', 'enp1s16f2', 'enp2s16f1']
get_counts.side_effect = mock_set_counts
set_numvfs.side_effect = lambda pf, _: False if pf == 'enp2' else True
gidn.return_value = 'foodriver'
gim.return_value = '00:01:02:03:04:05'
# call method under test
with self.assertRaises(ConfigurationError) as e:
sriov.apply_sriov_config(interfaces, self.configmanager)
self.assertIn('interface enp2s16f1 for netplan device customvf1 (vf1.16) already has an SR-IOV vlan defined',
str(e.exception))
self.assertEqual(apply_vlan.call_count, 1)
@patch('netifaces.interfaces')
@patch('netplan.cli.sriov.get_vf_count_and_functions')
@patch('netplan.cli.sriov.set_numvfs_for_pf')
@patch('netplan.cli.sriov.perform_hardware_specific_quirks')
@patch('netplan.cli.sriov.apply_vlan_filter_for_vf')
@patch('netplan.cli.utils.get_interface_driver_name')
@patch('netplan.cli.utils.get_interface_macaddress')
def test_apply_sriov_config_many_match(self, gim, gidn, apply_vlan, quirks,
set_numvfs, get_counts, netifs):
# set up the environment
with open(os.path.join(self.workdir.name, "etc/netplan/test.yaml"), 'w') as fd:
print('''network:
version: 2
renderer: networkd
ethernets:
enp1:
mtu: 9000
enpx:
match:
name: enp[2-3]
enp1s16f1:
link: enp1
macaddress: 01:02:03:04:05:00
enp1s16f2:
link: enp1
customvf1:
match:
name: enp*s16f[1-4]
link: enpx
''', file=fd)
self.configmanager.parse()
interfaces = ['enp1', 'enp2', 'enp5', 'wlp6s0']
# set up all the mock objects
netifs.return_value = ['enp1', 'enp2', 'enp5', 'wlp6s0',
'enp1s16f1', 'enp1s16f2', 'enp2s16f1']
get_counts.side_effect = mock_set_counts
set_numvfs.side_effect = lambda pf, _: False if pf == 'enp2' else True
gidn.return_value = 'foodriver'
gim.return_value = '00:01:02:03:04:05'
# call method under test
with self.assertRaises(ConfigurationError) as e:
sriov.apply_sriov_config(interfaces, self.configmanager)
self.assertIn('matched more than one interface for a VF device: customvf1',
str(e.exception))
netplan.io-0.99/tests/test_terminal.py 0000664 0000000 0000000 00000006266 13646002212 0020116 0 ustar 00root root 0000000 0000000 #!/usr/bin/python3
# Validate Terminal handling
#
# Copyright (C) 2018 Canonical, Ltd.
# Author: Mathieu Trudel-Lapierre
#
# 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 fcntl
import sys
import os
import termios
import unittest
import netplan.terminal
@unittest.skipUnless(sys.__stdin__.isatty(), "not supported when run from a script")
class TestTerminal(unittest.TestCase):
def setUp(self):
self.terminal = netplan.terminal.Terminal(sys.stdin.fileno())
def test_echo(self):
self.terminal.disable_echo()
attrs = termios.tcgetattr(self.terminal.fd)
self.assertFalse(attrs[3] & termios.ECHO)
self.terminal.enable_echo()
attrs = termios.tcgetattr(self.terminal.fd)
self.assertTrue(attrs[3] & termios.ECHO)
def test_nonblocking_io(self):
orig_flags = flags = fcntl.fcntl(self.terminal.fd, fcntl.F_GETFL)
self.assertFalse(flags & os.O_NONBLOCK)
self.terminal.enable_nonblocking_io()
flags = fcntl.fcntl(self.terminal.fd, fcntl.F_GETFL)
self.assertTrue(flags & os.O_NONBLOCK)
self.assertNotEquals(flags, orig_flags)
self.terminal.disable_nonblocking_io()
flags = fcntl.fcntl(self.terminal.fd, fcntl.F_GETFL)
self.assertFalse(flags & os.O_NONBLOCK)
self.assertEquals(flags, orig_flags)
def test_save(self):
self.terminal.enable_nonblocking_io()
flags = self.terminal.orig_flags
self.terminal.save()
self.terminal.disable_nonblocking_io()
self.assertNotEquals(flags, self.terminal.orig_flags)
self.terminal.reset()
flags = fcntl.fcntl(self.terminal.fd, fcntl.F_GETFL)
self.assertEquals(flags, self.terminal.orig_flags)
self.terminal.disable_nonblocking_io()
self.terminal.save()
def test_save_and_restore_with_dict(self):
self.terminal.enable_nonblocking_io()
orig_settings = dict()
self.terminal.save(orig_settings)
self.terminal.disable_nonblocking_io()
flags = fcntl.fcntl(self.terminal.fd, fcntl.F_GETFL)
self.assertNotEquals(flags, orig_settings.get('flags'))
self.terminal.reset(orig_settings)
flags = fcntl.fcntl(self.terminal.fd, fcntl.F_GETFL)
self.assertEquals(flags, orig_settings.get('flags'))
self.terminal.disable_nonblocking_io()
def test_reset(self):
self.terminal.enable_nonblocking_io()
flags = fcntl.fcntl(self.terminal.fd, fcntl.F_GETFL)
self.assertTrue(flags & os.O_NONBLOCK)
self.terminal.reset()
flags = fcntl.fcntl(self.terminal.fd, fcntl.F_GETFL)
self.assertFalse(flags & os.O_NONBLOCK)
netplan.io-0.99/tests/validate_docs.sh 0000775 0000000 0000000 00000003174 13646002212 0020025 0 ustar 00root root 0000000 0000000 #!/bin/bash
# find everything that looks like
# {"driver", YAML_SCALAR_NODE,...,
# extract the thing in quotes.
# sanity check: make sure none have disappeared, as might happen from a reformat.
count=$(sed -n 's/[ ]\+{"\([a-z0-9-]\+\)", YAML_[A-Z]\+_NODE.*/\1/p' src/parse.c | sort | uniq | wc -l)
# 71 is based on the 0.36.1 definitions, and should be updated periodically.
if [ $count -lt 71 ]; then
echo "ERROR: fewer YAML keys defined in src/parse.c than expected!"
echo " Has the file been reformatted or refactored? If so, modify"
echo " validate_docs.sh appropriately."
exit 1
fi
# iterate through the keys
for term in $(sed -n 's/[ ]\+{"\([a-z0-9-]\+\)", YAML_[A-Z]\+_NODE.*/\1/p' src/parse.c | sort | uniq); do
# it can be documented in the following ways.
# 1. "Properties for device type ``blah:``
if egrep "## Properties for device type \`\`$term:\`\`" doc/netplan.md > /dev/null; then
continue
fi
# 2. "[blah, ]``blah``[, ``blah2``]: (scalar|bool|...)
if egrep "\`\`$term\`\`.*\((scalar|bool|mapping|sequence of scalars)" doc/netplan.md > /dev/null; then
continue
fi
# 3. we give a pass to network and version
if [[ $term = "network" ]] || [[ $term = "version" ]]; then
continue
fi
# 4. search doesn't get a full description but it's good enough
if [[ $term = "search" ]]; then
continue
fi
# 5. gratuit_i_ous arp gets a special note
if [[ $term = "gratuitious-arp" ]]; then
continue
fi
echo ERROR: The key "$term" is defined in the parser but not documented.
exit 1
done
echo "validate_docs: OK"