pax_global_header00006660000000000000000000000064145470502010014510gustar00rootroot0000000000000052 comment=54db334d834017e0f97641a0172ca91358d4cf59 mdevctl-mdevctl-54db334/000077500000000000000000000000001454705020100151345ustar00rootroot00000000000000mdevctl-mdevctl-54db334/.github/000077500000000000000000000000001454705020100164745ustar00rootroot00000000000000mdevctl-mdevctl-54db334/.github/workflows/000077500000000000000000000000001454705020100205315ustar00rootroot00000000000000mdevctl-mdevctl-54db334/.github/workflows/main.yml000066400000000000000000000030361454705020100222020ustar00rootroot00000000000000 on: [push, pull_request] name: Continuous integration jobs: check: name: Check runs-on: ubuntu-latest steps: - name: Install builddeps run: | sudo apt-get update sudo apt-get -y install python3-docutils - name: Checkout code uses: actions/checkout@v3 - name: Install rust toolchain uses: dtolnay/rust-toolchain@stable - run: cargo check test: name: Test Suite runs-on: ubuntu-latest steps: - name: Install builddeps run: | sudo apt-get update sudo apt-get -y install python3-docutils - name: Checkout code uses: actions/checkout@v3 - name: Install rust toolchain uses: dtolnay/rust-toolchain@stable - run: cargo test env: MDEVCTL_LOG: debug RUST_BACKTRACE: full fmt: name: Rustfmt runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v3 - name: Install rust toolchain uses: dtolnay/rust-toolchain@stable - run: rustup component add rustfmt - run: cargo fmt --all -- --check clippy: name: Clippy runs-on: ubuntu-latest steps: - name: Install builddeps run: | sudo apt-get update sudo apt-get -y install python3-docutils - name: Checkout code uses: actions/checkout@v3 - name: Install rust toolchain uses: dtolnay/rust-toolchain@stable - run: rustup component add clippy - run: cargo clippy -- -D warnings mdevctl-mdevctl-54db334/.github/workflows/release.yml000066400000000000000000000021571454705020100227010ustar00rootroot00000000000000name: Release tasks on: release: types: [published] jobs: upload-vendor-sources: env: VENDOR_TARBALL: mdevctl-${{ github.event.release.name }}-vendor.tar.gz GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} name: Attach vendor source tarball runs-on: ubuntu-latest steps: - name: checkout code uses: actions/checkout@v3 - name: install rust toolchain uses: dtolnay/rust-toolchain@stable - name: get vendor sources run: cargo vendor - name: package vendor sources run: tar -czvf ${VENDOR_TARBALL} vendor/ - name: upload vendor source package run: hub release edit -m "" -a "${VENDOR_TARBALL}" "${{ github.event.release.tag_name }}" publish-crate: name: Publish to crates.io runs-on: ubuntu-latest steps: - name: checkout code uses: actions/checkout@v3 - name: install rust toolchain uses: dtolnay/rust-toolchain@stable - name: publish to crates.io uses: katyo/publish-crates@v2 with: args: --no-verify registry-token: ${{ secrets.CARGO_REGISTRY_TOKEN }} mdevctl-mdevctl-54db334/.gitignore000066400000000000000000000000771454705020100171300ustar00rootroot00000000000000/target *.sw? Cargo.lock Makefile mdevctl.spec /vendor/ /*.rpm mdevctl-mdevctl-54db334/60-mdevctl.rules000066400000000000000000000013101454705020100200640ustar00rootroot00000000000000# When registered with mdev, try to start any persistent devices. Note that # this uevent is not triggered on older kernels. ACTION=="change", ENV{MDEV_STATE}=="registered", TEST=="/etc/mdevctl.d/$kernel", RUN+="/bin/sh -c '{ /usr/sbin/mdevctl start-parent-mdevs %k 2>&3 | logger -t mdevctl; } 3>&1 1>&2 | logger -t mdevctl -p 2'" # For compatibility with kernels where mdev doesn't trigger the change uevent # on parent device registration, try to start mdevs when the device is added; # if the device is setup early this may still work. ACTION=="add", TEST=="/etc/mdevctl.d/$kernel", RUN+="/bin/sh -c '{ /usr/sbin/mdevctl start-parent-mdevs %k 2>&3 | logger -t mdevctl; } 3>&1 1>&2 | logger -t mdevctl -p 2'" mdevctl-mdevctl-54db334/COPYING000066400000000000000000000636421454705020100162020ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, 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 this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), 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 distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey 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 library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! mdevctl-mdevctl-54db334/Cargo.toml000066400000000000000000000016041454705020100170650ustar00rootroot00000000000000[package] name = "mdevctl" # For now, just bump the y version on release (x.y.z) version = "1.3.0" authors = ["Jonathon Jongsma "] edition = "2018" license = "LGPL-2.1" description = "A mediated device management utility for Linux" repository = "https://github.com/mdevctl/mdevctl" homepage = "https://github.com/mdevctl/mdevctl" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] anyhow = "1.0" clap = { version = "4.0", features = ["derive", "wrap_help"] } env_logger = "0.9.0" log = "0.4" serde = { version = "1.0", features = ["derive"] } serde_json = {version = "1.0", features = ["preserve_order"]} uuid = {version = "1.0", features = ["v4"]} [build-dependencies] clap = { version = "4.0", features = ["derive"]} clap_complete = "4.0" uuid = "1.0" [dev-dependencies] nix = "0.26" libc = "0.2" tempfile = "3" mdevctl-mdevctl-54db334/Makefile.in000066400000000000000000000035141454705020100172040ustar00rootroot00000000000000@@generated_notice@@ PREFIX?=/usr UDEVDIR=$(shell pkg-config --variable=udevdir udev) SBINDIR=$(PREFIX)/sbin CONFDIR=/etc/mdevctl.d SCRIPTDIR=$(PREFIX)/lib/mdevctl/scripts.d CALLOUTS_DIR=$(SCRIPTDIR)/callouts NOTIFIERS_DIR=$(SCRIPTDIR)/notifiers DATADIR=$(PREFIX)/share MANDIR=$(DATADIR)/man BASH_COMPLETION_DIR=$(DATADIR)/bash-completion/completions all: @echo "Run 'make install' to install the program" # since we generate a Makefile, we have to use --no-verify to stop cargo from # complaining that we modified the source directory during build. archive: cargo package --allow-dirty --no-verify cargo vendor tar -caf target/package/mdevctl-@@mdevctl_version@@-vendor.crate vendor/ mdevctl.spec: mdevctl.spec.in cargo build srpm: mdevctl.spec archive rpmbuild -bs --define "_sourcedir $(PWD)/target/package" \ --define "_specdir $(PWD)" \ --define "_builddir $(PWD)" \ --define "_srcrpmdir $(PWD)" \ --define "_rpmdir $(PWD)" $< rpm: mdevctl.spec archive rpmbuild -bb --define "_sourcedir $(PWD)/target/package" \ --define "_specdir $(PWD)" \ --define "_builddir $(PWD)" \ --define "_srcrpmdir $(PWD)" \ --define "_rpmdir $(PWD)" $< install: mkdir -p $(DESTDIR)$(CONFDIR) mkdir -p $(DESTDIR)$(UDEVDIR)/rules.d/ install -m 644 60-mdevctl.rules $(DESTDIR)$(UDEVDIR)/rules.d/ mkdir -p $(DESTDIR)$(SBINDIR) install -m 755 @@mdevctl@@ $(DESTDIR)$(SBINDIR)/ ln -sf mdevctl $(DESTDIR)$(SBINDIR)/lsmdev mkdir -p $(DESTDIR)$(MANDIR)/man8 install -m 644 @@outdir@@/mdevctl.8 $(DESTDIR)$(MANDIR)/man8/ ln -sf mdevctl.8 $(DESTDIR)$(MANDIR)/man8/lsmdev.8 mkdir -p $(DESTDIR)$(BASH_COMPLETION_DIR)/ install -m 644 -T @@outdir@@/mdevctl.bash $(DESTDIR)$(BASH_COMPLETION_DIR)/mdevctl install -m 644 -T @@outdir@@/lsmdev.bash $(DESTDIR)$(BASH_COMPLETION_DIR)/lsmdev mkdir -p $(DESTDIR)$(CALLOUTS_DIR) mkdir -p $(DESTDIR)$(NOTIFIERS_DIR) mdevctl-mdevctl-54db334/README.md000066400000000000000000000210201454705020100164060ustar00rootroot00000000000000# mdevctl - a mediated device management utility for Linux ## Description mdevctl is a utility for managing and persisting devices in the mediated device device framework of the Linux kernel. Mediated devices are sub-devices of a parent device (ex. a vGPU) which can be dynamically created and potentially used by drivers like vfio-mdev for assignment to virtual machines. ## License Licensed under the GNU Lesser General Public License aka LGPL v2.1. See [COPYING](COPYING) for details. ## Source repository https://github.com/mdevctl/mdevctl ## Installation mdevctl is built with rust's `cargo` tool. To build the executable, run `cargo build`. This will compile the code and also generate a Makefile that can be used for installing the executable and all support files into your system. On RPM based systems, you can run `make rpm` then install the resulting package. Otherwise, run `make install`. ## Architecture mdevctl stores defined mediated devices in /etc/mdevctl.d/ with directories matching the parent device name and config files named by the UUID of the mdev device itself. The format used is JSON; a configuration file for an mdev device looks like follows: ``` { "mdev_type": "$VENDOR_TYPE", "start": "auto|manual", "attrs": [ ...optional list of device-specific attributes... ] } ``` When a known parent device add udev event occurs (or, for more recent kernels, change events with MDEV_STATE values), mdevctl is called by a udev rule to create defined devices with "start": "auto" configured. mdevctl defines three classes of commands, those that manage device config files, those that manage the device itself, and listing commands for showing defined, active, or potential mdev devices. Starting with the latter, mdevctl is able to manage mdev devices created either with mdevctl or externally, such as through direct sysfs interactions. Likewise, when generating a list of currently active mdev devices via the `list` command, all mdevs are included. When provided with the `--defined` option, the list command will show mdev device configs defined on the system, regardless of whether they are currently active. The `types` command provides details of the mdev types supported on the system, including the number of instances of each that may be created, the API exposed for each, as well as vendor provided name and description as available. Mediated device definitions can be created with the `define` command, which not only accepts a fully specified configuration via options, but can also create a config for a currently running mdev. Thus a transient device created either through mdevctl or sysfs can be promoted to a defined device. The `undefine` command simply removes the config definition without modifying the running device, while the `modify` command allows device config to be modified. Config modifications to a running device to not take effect until the device is stopped and restarted. This leads to the final class of commands, which provides the `start` and `stop` functionality. The start command can operate either on a previously defined mdev or the mdev can be fully specified via options to create a transient device, ie. a running device with no persistence. # Usage List running mdev devices: ``` # mdevctl list 85006552-1b4b-45ef-ad62-de05be9171df 0000:00:02.0 i915-GVTg_V4_4 83c32df7-d52e-4ec1-9668-1f3c7e4df107 0000:00:02.0 i915-GVTg_V4_8 (defined) ``` List defined mdev devices: ``` # mdevctl list -d 83c32df7-d52e-4ec1-9668-1f3c7e4df107 0000:00:02.0 i915-GVTg_V4_8 auto b0a3989f-8138-4d49-b63a-59db28ec8b48 0000:00:02.0 i915-GVTg_V4_8 auto 5cf14a12-a437-4c82-a13f-70e945782d7b 0000:00:02.0 i915-GVTg_V4_4 manual ``` List mdev types supported on the host system: ``` # mdevctl types 0000:00:02.0 i915-GVTg_V4_2 Available instances: 1 Device API: vfio-pci Description: low_gm_size: 256MB high_gm_size: 1024MB fence: 4 resolution: 1920x1200 weight: 8 i915-GVTg_V4_1 Available instances: 0 Device API: vfio-pci Description: low_gm_size: 512MB high_gm_size: 2048MB fence: 4 resolution: 1920x1200 weight: 16 i915-GVTg_V4_8 Available instances: 4 Device API: vfio-pci Description: low_gm_size: 64MB high_gm_size: 384MB fence: 4 resolution: 1024x768 weight: 2 i915-GVTg_V4_4 Available instances: 3 Device API: vfio-pci Description: low_gm_size: 128MB high_gm_size: 512MB fence: 4 resolution: 1920x1200 weight: 4 ``` Modify a defined device from automatic start to manual: ``` # mdevctl modify --uuid 83c32df7-d52e-4ec1-9668-1f3c7e4df107 --manual # mdevctl list -d 83c32df7-d52e-4ec1-9668-1f3c7e4df107 0000:00:02.0 i915-GVTg_V4_8 manual b0a3989f-8138-4d49-b63a-59db28ec8b48 0000:00:02.0 i915-GVTg_V4_8 auto 5cf14a12-a437-4c82-a13f-70e945782d7b 0000:00:02.0 i915-GVTg_V4_4 manual ``` Stop a running mdev device: ``` # mdevctl stop -u 83c32df7-d52e-4ec1-9668-1f3c7e4df107 ``` Start an mdev device that is not defined ``` # uuidgen 6eba5b41-176e-40db-b93e-7f18e04e0b93 # mdevctl start -u 6eba5b41-176e-40db-b93e-7f18e04e0b93 -p 0000:00:02.0 --type i915-GVTg_V4_1 # mdevctl list 85006552-1b4b-45ef-ad62-de05be9171df 0000:00:02.0 i915-GVTg_V4_4 6eba5b41-176e-40db-b93e-7f18e04e0b93 0000:00:02.0 i915-GVTg_V4_1 ``` Promote the new created mdev to a defined device: ``` # mdevctl define --uuid 6eba5b41-176e-40db-b93e-7f18e04e0b93 # mdevctl list -d 83c32df7-d52e-4ec1-9668-1f3c7e4df107 0000:00:02.0 i915-GVTg_V4_8 manual 6eba5b41-176e-40db-b93e-7f18e04e0b93 0000:00:02.0 i915-GVTg_V4_1 manual b0a3989f-8138-4d49-b63a-59db28ec8b48 0000:00:02.0 i915-GVTg_V4_8 auto 5cf14a12-a437-4c82-a13f-70e945782d7b 0000:00:02.0 i915-GVTg_V4_4 manual ``` ## Advanced usage (attributes and JSON) mdevctl provides support for specifying additional configuration via device-specific attributes. It also provides support for inspecting and modifying its internal JSON representation of the configuration directly. Example: ``` # mdevctl list -d 783e6dbb-ea0e-411f-94e2-717eaad438bf matrix vfio_ap-passthrough manual ``` Add some attributes: ``` # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_adapter --value=5 # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_adapter --value=6 # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_domain --value=0xab # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_control_domain --value=0xab # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_domain --value=4 # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_control_domain --value=4 # mdevctl list -dv 783e6dbb-ea0e-411f-94e2-717eaad438bf matrix vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} @{4}: {"assign_domain":"4"} @{5}: {"assign_control_domain":"4"} ``` Dump the JSON configuration: ``` # mdevctl list -d -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --dumpjson { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } ``` Remove some attributes: ``` # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --delattr --index=5 # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --delattr --index=4 # mdevctl list -dv 783e6dbb-ea0e-411f-94e2-717eaad438bf matrix vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} ``` Define an mdev device from a file: ``` # cat vfio_ap_device.json { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_domain": "0x47" }, { "assign_domain": "0xff" } ] } # mdevctl define -p matrix --jsonfile vfio_ap_device.json e2e73122-cc39-40ee-89eb-b0a47d334cae # mdevctl list -dv 783e6dbb-ea0e-411f-94e2-717eaad438bf matrix vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} e2e73122-cc39-40ee-89eb-b0a47d334cae matrix vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_domain":"0x47"} @{2}: {"assign_domain":"0xff"} ``` See `mdevctl --help` or the manpage for more information. mdevctl-mdevctl-54db334/build.rs000066400000000000000000000066171454705020100166130ustar00rootroot00000000000000use clap::CommandFactory; use clap_complete::{generate_to, Shell}; use std::env; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; #[path = "src/cli.rs"] mod cli; fn apply_template(template: &Path) -> String { let outdir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR environment variable not defined")); fs::create_dir_all(&outdir).expect("unable to create out dir"); let profile = env::var_os("PROFILE").expect("PROFILE environment variable not defined"); let mdevctl_bin_path = PathBuf::from("target").join(profile).join("mdevctl"); let version = env::var("CARGO_PKG_VERSION").expect("CARGO_PKG_VERSION not set"); fs::read_to_string(template) .unwrap_or_else(|_| panic!("Failed to read template {:?}", template)) .replace("@@mdevctl@@", mdevctl_bin_path.to_str().unwrap()) .replace("@@outdir@@", outdir.to_str().unwrap()) .replace("@@mdevctl_version@@", version.as_str()) .replace( "@@generated_notice@@", format!( "# DO NOT EDIT\n# This file is automatically generated from {:?}", template ) .as_str(), ) } fn generate_manpage>(outdir: P) { let rst2man = env::var("RST2MAN").unwrap_or_else(|_| "rst2man".to_owned()); let infile = PathBuf::from("mdevctl.rst"); println!("cargo:rerun-if-changed={}", infile.to_str().unwrap()); let outfile = outdir.as_ref().join("mdevctl.8"); Command::new(rst2man) .arg(infile) .arg(outfile) .output() .expect("Unable to generate manpage. Is 'rst2man' installed? You can specify a custom 'rst2man' executable by setting the RST2MAN environment variable."); } fn generate_completion(cmd: &mut clap::Command, outdir: &PathBuf) { let name = cmd.get_name().to_string(); generate_to(Shell::Bash, cmd, name, outdir).expect("Unable to generate shell completion files"); } fn main() { let outdir = PathBuf::from(env::var_os("OUT_DIR").expect("OUT_DIR environment variable not defined")); // generate bash completions for both executables generate_completion(&mut cli::MdevctlCommands::command(), &outdir); generate_completion(&mut cli::LsmdevOptions::command(), &outdir); // generate manpage generate_manpage(outdir); // generate a rpm spec file from the spec.in template let rpm_in = PathBuf::from("mdevctl.spec.in"); let rpm_out = PathBuf::from(rpm_in.file_stem().unwrap()); let contents = apply_template(&rpm_in); std::fs::write(&rpm_out, contents).unwrap_or_else(|_| panic!("Failed to write {:?}", rpm_out)); println!("cargo:rerun-if-changed={}", rpm_in.to_str().unwrap()); // Generate a makefile for installing the auxiliary files based on the Makefile.in template let makefile_in = PathBuf::from("Makefile.in"); let makefile_out = PathBuf::from(makefile_in.file_stem().unwrap()); let contents = apply_template(&makefile_in); // FIXME: build.rs really shouldn't touch anything outside of OUT_DIR, but generating the // Makefile in a directory named ./target/$PROFILE/build/mdevctl-$HASH/out/ is very // undiscoverable and kind of defeats the purpose. Need to find a better solution. std::fs::write(&makefile_out, contents) .unwrap_or_else(|_| panic!("Failed to write {:?}", makefile_out)); println!("cargo:rerun-if-changed={}", makefile_in.to_str().unwrap()); } mdevctl-mdevctl-54db334/mdevctl.rst000066400000000000000000000544621454705020100173370ustar00rootroot00000000000000======= mdevctl ======= ---------------------------------- Mediated device management utility ---------------------------------- :Manual section: 8 SYNOPSIS ======== ``mdevctl`` {COMMAND} [OPTIONS...] ``lsmdev`` [OPTIONS...] DESCRIPTION =========== ``mdevctl`` is a utility for managing and persisting devices in the mediated device device framework of the Linux kernel. Mediated devices are sub-devices of a parent device (ex. a vGPU) which can be dynamically created and potentially used by drivers like vfio-mdev for assignment to virtual machines. ``lsmdev`` is an alias for ``mdevctl list``. OPTIONS ======= The following options are understood: ``--addattr=ATTRIBUTE`` Add an attribute *ATTRIBUTE*. Valid for the ``modify`` command. ``-a|--auto`` Automatically start the device on parent availability. Valid for ``define`` and ``modify`` commands. ``-d|--defined`` List all defined devices, even if not active. Valid for the ``list`` command. Modify the defined configuration of a device, even if the device is active. Valid for the ``modify`` command. ``--delattr`` Delete an attribute entry. Valid for the ``modify`` command. ``--dumpjson`` Dump the configuration for a device in JSON format when filtered to as single device and used with the ``list`` command. When used with the ``types`` command, output machine readable type information. ``-i|--index=INDEX`` Act on the attribute *INDEX*. Valid for the ``modify`` command. ``--jsonfile=FILE`` Read the configuration for a device from a JSON file *FILE*. Valid for the ``define`` and ``start`` commands. ``-l|--live`` Modify active device without modifying the defined configuration of the device. Valid for the ``modify`` command. ``-m|--manual`` Do not start a device automatically on parent availability. Valid for the ``modify`` command. ``-p|--parent=PARENT`` Specify or identify the device by its parent device. Note that the parent device is specified by its kernel sysfs name and is case-sensitive. ``-t|--type=TYPE`` Specify or identify the device by its type. ``-u|--uuid=UUID`` Specify or identify the device by its UUID. ``--value=VALUE`` Set an attribute to *VALUE*, in the format accepted by the attribute. Valid for the ``modify`` command. ``-v|--verbose`` Increase output verbosity, currently only adds attribute output to the ``list`` command. ``-V|--version`` Print mdevctl version. COMMANDS ======== The following commands are understood: ``define`` *DEVICESPEC* Define a config for an mdev device, identified either by an UUID (if the device already exists), or by the parent device and either the type or a JSON configuration file, and, optionally, the UUID. If no UUID is specified, one is autogenerated and printed. If no file is used, *-a|--auto* may be used to specify that the device should be started automatically. ``list`` List mdev devices. With no options, currently running devices are listed. With ``-d|--defined``, previously defined devices are listed. Can be restricted to list only devices for a given parent or UUID. With ``--dumpjson`` output is provided in machine readable JSON format. When a UUID is provided and the output results in a single device, the JSON output format is compatible with the configuration file format. ``modify`` *DEVICESPEC* Modify the configuration for an mdev device, identified via its UUID and optionally its parent. Type and startup mode (auto or manual) can be modified by this command. Attributes can be added or deleted. Attributes to be deleted must be specified by their index; if an attribute is specified without an index, it is appended at the end of the attribute list. Active devices are unaffected by this command; changes in the configuration are applied the next time the device is started. Depending on installed callout scripts active devices can be modified. With ``-l|--live`` modifications can be applied to active devices if a callout scripts supports the event ``live``. The option ``-d|--defined`` also direct the modification to the started device configuration. ``start`` *DEVICESPEC* Start a mediated device. This command can be used to start either a previously-defined device or a newly-created transient device. If the UUID and optional parent argument matches an existing device definition, then the existing device will be started. It is an error to specify a device type that conflicts with the existing device definition. If the UUID argument is omitted or if the specified UUID and parent does not match an existing device definition, a new transient device will be started. If the UUID is omitted, a new UUID will be automatically generated. When starting a new transient device, the parent and device type must be specified. A ``--jsonfile`` may replace the ``--type`` specification and also include additional attributes in JSON format to be applied to the started device. ``stop`` *DEVICESPEC* Stop an mdev device, specified via its UUID. ``types`` List the mdev device types known to the system by parent device. Output may be limited to a single parent device with the ``-p|--parent`` option. JSON output format is used with the ``--dumpjson`` option. ``undefine`` *DEVICESPEC* Undefine, or remove the configuration for an mdev device, specified by its UUID and optionally its parent. If a UUID exists for multiple parents, all of them will be removed unless restricted to a single parent. Running devices are unaffected by this command. NOTE ON DEVICE SPECIFICATION ============================ For a given UUID, only one device with that UUID may be running at the same time. However, it is possible to define multiple devices with the same UUID under different parent devices. Therefore, it is sometimes necessary to specify the parent device alongside the UUID to uniquely identify a device. EXIT STATUS =========== On success, 0 is returned, a non-zero failure code otherwise. EXAMPLES ======== List running mdev devices:: # mdevctl list 85006552-1b4b-45ef-ad62-de05be9171df 0000:00:02.0 i915-GVTg_V4_4 83c32df7-d52e-4ec1-9668-1f3c7e4df107 0000:00:02.0 i915-GVTg_V4_8 (defined) List defined mdev devices:: # mdevctl list -d 83c32df7-d52e-4ec1-9668-1f3c7e4df107 0000:00:02.0 i915-GVTg_V4_8 auto b0a3989f-8138-4d49-b63a-59db28ec8b48 0000:00:02.0 i915-GVTg_V4_8 auto 5cf14a12-a437-4c82-a13f-70e945782d7b 0000:00:02.0 i915-GVTg_V4_4 manual List mdev types supported on the host system:: # mdevctl types 0000:00:02.0 i915-GVTg_V4_2 Available instances: 1 Device API: vfio-pci Description: low_gm_size: 256MB high_gm_size: 1024MB fence: 4 resolution: 1920x1200 weight: 8 i915-GVTg_V4_1 Available instances: 0 Device API: vfio-pci Description: low_gm_size: 512MB high_gm_size: 2048MB fence: 4 resolution: 1920x1200 weight: 16 i915-GVTg_V4_8 Available instances: 4 Device API: vfio-pci Description: low_gm_size: 64MB high_gm_size: 384MB fence: 4 resolution: 1024x768 weight: 2 i915-GVTg_V4_4 Available instances: 3 Device API: vfio-pci Description: low_gm_size: 128MB high_gm_size: 512MB fence: 4 resolution: 1920x1200 weight: 4 Modify a defined device from automatic start to manual:: # mdevctl modify --uuid 83c32df7-d52e-4ec1-9668-1f3c7e4df107 --manual # mdevctl list -d 83c32df7-d52e-4ec1-9668-1f3c7e4df107 0000:00:02.0 i915-GVTg_V4_8 manual b0a3989f-8138-4d49-b63a-59db28ec8b48 0000:00:02.0 i915-GVTg_V4_8 auto 5cf14a12-a437-4c82-a13f-70e945782d7b 0000:00:02.0 i915-GVTg_V4_4 manual Stop a running mdev device:: # mdevctl stop -u 83c32df7-d52e-4ec1-9668-1f3c7e4df107 Start an mdev device that is not defined:: # uuidgen 6eba5b41-176e-40db-b93e-7f18e04e0b93 # mdevctl start -u 6eba5b41-176e-40db-b93e-7f18e04e0b93 -p 0000:00:02.0 --type i915-GVTg_V4_1 # mdevctl list 85006552-1b4b-45ef-ad62-de05be9171df 0000:00:02.0 i915-GVTg_V4_4 6eba5b41-176e-40db-b93e-7f18e04e0b93 0000:00:02.0 i915-GVTg_V4_1 Promote the new created mdev to a defined device:: # mdevctl define --uuid 6eba5b41-176e-40db-b93e-7f18e04e0b93 # mdevctl list -d 83c32df7-d52e-4ec1-9668-1f3c7e4df107 0000:00:02.0 i915-GVTg_V4_8 manual 6eba5b41-176e-40db-b93e-7f18e04e0b93 0000:00:02.0 i915-GVTg_V4_1 manual b0a3989f-8138-4d49-b63a-59db28ec8b48 0000:00:02.0 i915-GVTg_V4_8 auto 5cf14a12-a437-4c82-a13f-70e945782d7b 0000:00:02.0 i915-GVTg_V4_4 manual ADVANCED EXAMPLES (ATTRIBUTES AND JSON) --------------------------------------- :: # mdevctl list -d 783e6dbb-ea0e-411f-94e2-717eaad438bf matrix vfio_ap-passthrough manual Add some attributes:: # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_adapter --value=5 # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_adapter --value=6 # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_domain --value=0xab # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_control_domain --value=0xab # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_domain --value=4 # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --addattr=assign_control_domain --value=4 # mdevctl list -dv 783e6dbb-ea0e-411f-94e2-717eaad438bf matrix vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} @{4}: {"assign_domain":"4"} @{5}: {"assign_control_domain":"4"} Dump the JSON configuration:: # mdevctl list -d -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --dumpjson { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } Remove some attributes:: # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --delattr --index=5 # mdevctl modify -u 783e6dbb-ea0e-411f-94e2-717eaad438bf --delattr --index=4 # mdevctl list -dv 783e6dbb-ea0e-411f-94e2-717eaad438bf matrix vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} Define an mdev device from a file:: # cat vfio_ap_device.json { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_domain": "0x47" }, { "assign_domain": "0xff" } ] } # mdevctl define -p matrix --jsonfile vfio_ap_device.json e2e73122-cc39-40ee-89eb-b0a47d334cae # mdevctl list -dv 783e6dbb-ea0e-411f-94e2-717eaad438bf matrix vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} e2e73122-cc39-40ee-89eb-b0a47d334cae matrix vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_domain":"0x47"} @{2}: {"assign_domain":"0xff"} CONFIGURATION FILE FORMAT ========================= Configuration files are in JSON. Attributes in "``attrs``" are optional. :: { "mdev_type": "TYPE", "start": "auto|manual", "attrs": [ { "attribute0": "VALUE" }, { "attribute1": "VALUE" } ] } INVOKING EXTERNAL SCRIPTS FOR DEVICE EVENTS =========================================== mdevctl supports invoking external scripts to handle additional device type-specific configurations and to broadcast notifications regarding changes or updates to a device. These scripts are invoked before, after, and/or during mdevctl's "primary command execution" (e.g. writing the device configuration file for define, or activating a device for start). Essentially, the procedure in mdevctl looks like this: - command-line parsing & setup - invoke live-command call-out [1]_ - invoke pre-command call-out - primary command execution [2]_ - invoke post-command call-out [2]_ - invoke notifier .. [1] executed only if live update is requested. .. [2] skipped if step ``invoke pre-command call-out`` fails. EVENT SCRIPTS ------------- A call-out or notification event invokes a script along with a set of parameters detailing the type of call-out, mdevctl's command execution progress, and the mediated device. The parameters are as follows: | SCRIPT <``-t=``\ *type* ``-e=``\ *event* ``-a=``\ *action* ``-s=``\ *state* ``-u=``\ *UUID* ``-p=``\ *parent*> ``CONFIG`` The device's JSON configuration, provided via standard input. ``-t=``\ *type* The device type. ``-e=``\ *event* Event type of call-out that is invoked. For call-out scripts, this may be ``pre``, ``live``, ``post``, or ``get``. For notification scripts, this will always be ``notify``. ``-a=``\ *action* An action synonymous with an mdevctl command (e.g. define, start). ``-s=``\ *state* A trinary state of the mdevctl command execution. The possibilities are ``none`` if the mdevctl command has yet to execute, ``success`` if the mdevctl command completed successfully, or ``failure`` if there was a problem executing the mdevctl command. ``-u=``\ *UUID* UUID of the mediated device. ``-p=``\ *parent* Parent of the mediated the device. CALL-OUT EVENT SCRIPTS ---------------------- A call-out event script is invoked during a ``live``, ``pre``, ``post`` or ``get`` event. mdevctl will attempt each script stored in the mdevctl callouts directory until either a script that satisfies the device type is found or all scripts have been attempted. A device script must check the "TYPE" parameter to ensure the specified device type is supported, otherwise error code 2 should be returned. If no script is found for the specified device type, then mdevctl will carry on as normal. These scripts are stored in */usr/lib/mdevctl/scripts.d/callouts*. The same script is invoked for ``live``, ``pre``, ``post``, and ``get`` call-out events for the device type. ``Live-Command`` A live-command call-out event is invoked once before the pre-command call-out event execution. This only occurs if the ``live`` option is specified on the ``modify`` command and the device modified is active. Event type is ``live``. State will always be ``none``. If the ``live`` command line option is specified any non-zero return code results in a live modification failure except for all call-outs return with return code 2 resulting in a ``live update not supported`` information. The return code is disruptive if also the option ``defined`` is provided and will prevent the update of the defined device configuration. A notification event will follow if the ``live`` command line option is specified. This event is only supported for the ``modify`` command. ``Pre-Command`` A pre-command call-out event is invoked once prior to primary command execution. Event type is ``pre``. State will always be ``none``. Any non-zero return code (exempting 2) will prevent mdevctl from performing the primary command execution and mdevctl will abort early. A notification event will follow only if an error code (exempting 2) is observed. This event is not supported for the ``list``, ``types``, or ``version`` commands. ``Post-Command`` A post-command call-out event is invoked once after primary command execution. Event type is ``post``. State will be ``success`` if mdevctl was able to finish primary command execution successfully, or ``failure`` otherwise. The same script used for the pre event is used for the post event. Any return code is non-disruptive. A notification event will always follow a post-command call-out. This event is not supported for the ``list``, ``types``, or ``version`` commands. ``Get-attributes`` A get event is invoked during a ``define`` and ``list`` command to acquire device attributes from an active device. Event type is ``get``. Action is ``attributes``. State is ``none``. Note that, unlike other call-outs events, **get-attributes does not expect a device config on stdin, and an array of JSON formatted device attributes is returned via stdout**. The same script used for the pre event is used for the get event. If the script is not designed to support a get event, then the return code is 0. For ``define``, a non-zero return code (exempting 2) will disrupt the define command entirely. For ``list``, any return code is non-disruptive. A script must return a JSON formatted array of device attributes on standard output. Example:: [ { "attribute0": "VALUE" }, { "attribute1": "VALUE" } ] ``Get-capabilities`` A get event is invoked on every new mdevctl execution to find a matching script supporting versioning for the device type. Event type is ``get``. Action is ``capabilities``. State is ``none``. Note that, unlike other call-outs events, **get-capabilities provides a versioning JSON on stdin, and expects a versioning JSON is returned via stdout**. The provided JSON on stdin explains in ``provides`` which ``actions`` and ``events`` mdevctl supports. The information is offered to the script to derive its supported ``actions`` and ``events`` from but it there is no obligation for scripts to follow this pattern. A valid versioning JSON response provides in ``supports`` the supported actions in ``actions`` and the supported events in ``events``. If a valid versioning JSON is returned on stdout by the script and the return code is NOT 2 the script is considered a positive match for the provided device type. A script providing versioning is the primary choice for a device type when mdevctl is executing callouts or in other words if a script which supports versioning is found the script is used for every event and action for the device type. Should no versioning supporting script be found the none versioning search pattern is used. A script is provided on standard in with a versioning JSON describing the mdevctl supported version, actions and events. Example:: { "provides": { "version": 1, "actions": [ "start", "stop", "define", "undefine", "modify", "attributes", "capabilities" ], "events": [ "pre", "post", "notify", "get" ] } } A script that wants to support versioning must return a versioning JSON on standard output. The script should list all supported actions in the actions array and all supported events in the events array. It is possible to add additional actions or events in the array but if mdevctl did not have these in the arrays in provides they are ignored. Example:: { "supports": { "version": 1, "actions": [ "start", "stop", "define", "undefine", "modify", "attributes", "capabilities" ], "events": [ "pre", "post", "notify", "get" ] } } AUTO-START CALL-OUTS -------------------- For each device set to start automatically during system boot, mdevctl will invoke the pre and post events. Action is the string ``start``. Return code and notification event behavior is the same as documented for the pre and post events. Errors reported by a script will disrupt the auto-start for that particular device and the message will be reported to the system log before attempting to the next auto-start device. Note that if a notification script is used to convey information to another program or daemon during the auto-start procedure, it is not guaranteed that the program will already be active prior to mdevctl's invocation (e.g. the auto-start event may occur before the libvirt daemon is activated). NOTIFICATION EVENT SCRIPTS -------------------------- Notification event scripts may be used to signal the state of the mediated device or the state of an mdevctl command to other programs or loggers. Unlike call-out scripts, notifier scripts are device-type agnostic. ``Notify`` A notification event is invoked once either following a pre-command call-out failure or after a post-command call-out. Event is ``notify``. If following a pre event, then state will be ``none``. If following a post event, then state will mirror the value passed to the post-command call-out. These scripts are stored in */usr/lib/mdevctl/scripts.d/notifiers*. **All notification scripts will be invoked during a notification event**. A non-zero return code is ignored. This event is not supported for the ``list``, ``types``, or ``version`` commands. SCRIPT RETURN VALUES -------------------- A call-out script should return one of the following values: - 0 if OK, - 1 if an error occurred, - 2 if the script does not support the device type FILES ===== */etc/mdevctl.d/** Configuration files are in one subdirectory per parent device and named by UUID. */usr/lib/mdevctl/scripts.d/callouts/** Scripts for pre/post/get call-out events. **NOTE**: these scripts were previously located at */etc/mdevctl.d/scripts.d/callouts/**, but that location is now deprecated. */usr/lib/mdevctl/scripts.d/notifiers/** Scripts for notification call-out events. **NOTE**: these scripts were previously located at */etc/mdevctl.d/scripts.d/notifiers/**, but that location is now deprecated. SEE ALSO ======== udev(7), udevadm(8), driverctl(8) mdevctl-mdevctl-54db334/mdevctl.spec.in000066400000000000000000000035501454705020100200560ustar00rootroot00000000000000@@generated_notice@@ # Generated by rust2rpm 13 %bcond_without check %global __cargo_skip_build 0 %define mdevctlscriptsdir %{_prefix}/lib/mdevctl/scripts.d %global crate mdevctl %if ! (0%{?fedora} >= 34 || 0%{?rhel} >= 8) %{error: RPM generation is not yet supported on this distribution} %endif %if 0%{?fedora} >= 34 Name: rust-%{crate} %else Name: mdevctl %endif Version: @@mdevctl_version@@ Release: 1%{?dist} Summary: A mediated device management utility for Linux # Upstream license specification: LGPL-2.1 License: LGPLv2 URL: https://github.com/mdevctl/mdevctl Source0: mdevctl-%{version}.crate %if 0%{?rhel} >= 8 Source1: mdevctl-%{version}-vendor.crate %endif ExclusiveArch: %{rust_arches} %if 0%{?fedora} >= 34 BuildRequires: rust-packaging %endif %if 0%{?rhel} BuildRequires: rust-toolset %endif BuildRequires: systemd python3-docutils %global _description %{expand: %{summary}.} %description %{_description} %if 0%{?fedora} >= 34 %package -n %{crate} Summary: %{summary} %description -n %{crate} %{_description} %files -n %{crate} %else %files %endif %license COPYING %doc README.md %{_sbindir}/mdevctl %{_sbindir}/lsmdev %{_udevrulesdir}/60-mdevctl.rules %dir %{_sysconfdir}/mdevctl.d %dir %{mdevctlscriptsdir}/callouts %dir %{mdevctlscriptsdir}/notifiers %{_mandir}/man8/mdevctl.8* %{_mandir}/man8/lsmdev.8* %{_datadir}/bash-completion/completions/mdevctl %{_datadir}/bash-completion/completions/lsmdev %prep %if 0%{?fedora} >= 34 %autosetup -n %{crate}-%{version_no_tilde} -p1 %cargo_prep %generate_buildrequires %cargo_generate_buildrequires %else %setup -q -n %{name}-%{version} %cargo_prep -V 1 %endif %build %cargo_build %install make DESTDIR=%{buildroot} install %if %{with check} %check export RUST_BACKTRACE=1 export MDEVCTL_LOG=debug %cargo_test %endif %changelog mdevctl-mdevctl-54db334/src/000077500000000000000000000000001454705020100157235ustar00rootroot00000000000000mdevctl-mdevctl-54db334/src/callouts.rs000066400000000000000000000606561454705020100201340ustar00rootroot00000000000000use anyhow::{anyhow, Context, Result}; use log::{debug, warn}; use serde::{Deserialize, Serialize}; use std::borrow::Cow; use std::ffi::OsStr; use std::fmt::{self, Display, Formatter}; use std::io::{ErrorKind, Write}; use std::path::{Path, PathBuf}; use std::process::{Command, Output, Stdio}; use crate::mdev::*; #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Event { Pre, Post, Live, Notify, Get, #[serde(skip_serializing)] #[serde(other)] Unknown, // used for forward compatibility to newer callout scripts } fn invocation_failure(path: &PathBuf, code: Option) -> anyhow::Error { anyhow!( "Script '{:?}' failed with status '{}'", path, match code { Some(i) => i.to_string(), None => "unknown".to_string(), } ) } impl Display for Event { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Event::Pre => write!(f, "pre"), Event::Post => write!(f, "post"), Event::Live => write!(f, "live"), Event::Notify => write!(f, "notify"), Event::Get => write!(f, "get"), Event::Unknown => write!(f, "unknown"), } } } #[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum Action { Start, Stop, Define, Undefine, Modify, Attributes, Capabilities, #[serde(skip_serializing)] Test, // used for tests only #[serde(skip_serializing)] #[serde(other)] Unknown, // used for forward compatibility to newer callout scripts } impl Display for Action { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { Action::Start => write!(f, "start"), Action::Stop => write!(f, "stop"), Action::Define => write!(f, "define"), Action::Undefine => write!(f, "undefine"), Action::Modify => write!(f, "modify"), Action::Attributes => write!(f, "attributes"), Action::Capabilities => write!(f, "capabilities"), Action::Test => write!(f, "test"), Action::Unknown => write!(f, "unknown"), } } } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "lowercase")] pub struct CalloutVersion { version: Cow<'static, u32>, actions: Cow<'static, [Action]>, events: Cow<'static, [Event]>, } impl CalloutVersion { pub const fn new_const( version: &'static u32, actions: &'static [Action], events: &'static [Event], ) -> Self { Self { version: Cow::Borrowed(version), actions: Cow::Borrowed(actions), events: Cow::Borrowed(events), } } pub const NOT_FOUND: CalloutVersion = CalloutVersion::new_const(&0, &[], &[]); pub const V_1: CalloutVersion = CalloutVersion::new_const( &1, &[ Action::Start, Action::Stop, Action::Define, Action::Undefine, Action::Modify, Action::Attributes, ], &[Event::Pre, Event::Post, Event::Notify, Event::Get], ); #[allow(dead_code)] pub const V_2: CalloutVersion = CalloutVersion::new_const( &2, &[ Action::Start, Action::Stop, Action::Define, Action::Undefine, Action::Modify, Action::Attributes, Action::Capabilities, ], &[ Event::Pre, Event::Post, Event::Notify, Event::Get, Event::Live, ], ); pub fn has_action(&self, action: Action) -> bool { self.actions.contains(&action) } pub fn has_event(&self, event: Event) -> bool { self.events.contains(&event) } } #[derive(Debug, Serialize, Deserialize)] pub struct CalloutVersionProvides { provides: Option, } #[derive(Debug, Serialize, Deserialize)] pub struct CalloutVersionSupports { supports: Option, } #[derive(Clone, Copy)] pub enum State { None, Success, Failure, } impl Display for State { fn fmt(&self, f: &mut Formatter) -> fmt::Result { match self { State::None => write!(f, "none"), State::Success => write!(f, "success"), State::Failure => write!(f, "failure"), } } } #[derive(Clone, Debug)] pub struct CalloutScriptInfo { path: PathBuf, parent: String, mdev_type: String, supports: CalloutVersion, } impl CalloutScriptInfo { fn new( path: PathBuf, parent: String, mdev_type: String, supports: CalloutVersion, ) -> CalloutScriptInfo { CalloutScriptInfo { path, parent, mdev_type, supports, } } fn supports_event_action(&self, event: Event, action: Action) -> Result<()> { if !self.supports.has_action(action) { debug!( "Callout script {:?} does not support action '{:?}'", self.path.clone(), action ); return Err(anyhow!( "Script {:?} does not support action '{:?}'", self.path.clone(), action )); } if !self.supports.has_event(event) { debug!( "Callout script {:?} does not support event '{:?}'", self.path.clone(), event ); return Err(anyhow!( "Script {:?} does not support event '{:?}'", self.path.clone(), event )); } Ok(()) } } impl AsRef for CalloutScriptInfo { fn as_ref(&self) -> &Path { &self.path } } #[derive(Debug)] pub struct CalloutScriptCache { callouts: Vec, } impl CalloutScriptCache { pub const fn new() -> Self { CalloutScriptCache { callouts: Vec::new(), } } fn parse_script_capabilities(output: &Output) -> Option { let stdout = String::from_utf8(output.clone().stdout).unwrap(); match serde_json::from_str::(stdout.trim_end_matches('\0')) { Ok(ce) => ce.supports.or_else(|| { debug!(" Callout script does not provide version support"); None }), Err(e) => { debug!( " Callout script has no version support (unparsable stdout): {:?}", e ); None } } } fn lookup_callout_script(&self, parent: &str, mdev_type: &str) -> Option { self.callouts .iter() .find(|cs| cs.mdev_type == mdev_type && cs.parent == parent) .cloned() } pub fn find_versioned_script(&mut self, dev: &MDev) -> Option { // check already found scripts let mut dev = dev.clone(); let mut callout = callout(&mut dev); let mdev_type = match callout.dev.mdev_type() { Ok(t) => t.clone(), Err(_) => { debug!("mdev_type is required on device => cannot find a callout script"); return None; } }; let parent = match callout.dev.parent() { Ok(p) => p.clone(), Err(_) => { debug!("parent is required on device => cannot find a callout script"); return None; } }; debug!("Looking up callout script for mdev type '{:?}'", mdev_type); match self.lookup_callout_script(&parent, &mdev_type) { Some(cs) => { debug!( "Callout script lookup for mdev type '{:?}' and parent {:?} successful", mdev_type, parent ); if cs.supports == CalloutVersion::NOT_FOUND && cs.path.as_os_str().is_empty() { debug!("Callout script search returned empty before: no script with versioning available"); return None; } else { debug!("Callout script looked up: {:?}", cs.path); return Some(cs); } } None => { debug!( "Callout script lookup failed. Start searching for mdev type '{:?}' and parent {:?}", mdev_type, parent ); } } let ce_ver = CalloutVersionProvides { provides: Some(CalloutVersion::V_2), }; let json_ce_ver = serde_json::to_string(&ce_ver).expect("CalloutVersion JSON could not be generated"); match callout.callout( Event::Get, Action::Capabilities, Some(&json_ce_ver), &CapabilitiesCheckProcessOutput, ) { Ok(op) => match op { Some(_) => { self.callouts.push(callout.script.clone().unwrap()); callout.script } None => { // When lookup and search turned out empty create a did-not-find entry. self.callouts.push(CalloutScriptInfo::new( PathBuf::new(), parent, mdev_type, CalloutVersion::NOT_FOUND, )); None } }, Err(_) => None, } } } pub trait CheckProcessOutput { fn check(&self, p: PathBuf, o: Output) -> Result<(PathBuf, Output)>; fn process(&self, c: &mut Callout<'_, '_>, p: PathBuf, o: Output) -> Result>; } struct DefaultCheckProcessOutput; impl CheckProcessOutput for DefaultCheckProcessOutput { fn check(&self, p: PathBuf, o: Output) -> Result<(PathBuf, Output)> { Ok((p, o)) } fn process(&self, c: &mut Callout<'_, '_>, p: PathBuf, o: Output) -> Result> { c.print_err(&o, &p); match o.status.code() { Some(0) => { c.script = Some(CalloutScriptInfo::new( p, c.dev.parent().unwrap().to_string(), c.dev.mdev_type().unwrap().to_string(), CalloutVersion::V_1, )); Ok(Some(o)) } Some(n) => Err(invocation_failure(&p, Some(n))), None => Ok(None), } } } struct CapabilitiesCheckProcessOutput; impl CheckProcessOutput for CapabilitiesCheckProcessOutput { fn check(&self, p: PathBuf, o: Output) -> Result<(PathBuf, Output)> { match CalloutScriptCache::parse_script_capabilities(&o) { Some(_) => Ok((p, o)), None => Err(anyhow!( "Output of callout script {:?} is not a valid capabilities XML response", p )), } } fn process(&self, c: &mut Callout<'_, '_>, p: PathBuf, o: Output) -> Result> { c.print_err(&o, &p); match CalloutScriptCache::parse_script_capabilities(&o) { Some(cv) => { debug!(" Script supports versioning: {:?}", cv); if cv.has_action(Action::Unknown) { warn!("Callout script {:?} provides unknown Action type", p); } if cv.has_event(Event::Unknown) { warn!("Callout script {:?} provides unknown Event type", p); } c.script = Some(CalloutScriptInfo::new( p, c.dev.parent().unwrap().to_string(), c.dev.mdev_type().unwrap().to_string(), cv, )); Ok(Some(o)) } None => Ok(None), } } } pub struct Callout<'a, 'b> { state: State, script: Option, pub dev: &'b mut MDev<'a>, } pub fn callout<'a, 'b>(dev: &'b mut MDev<'a>) -> Callout<'a, 'b> { Callout::new(dev) } impl<'a, 'b> Callout<'a, 'b> { pub fn new(dev: &'b mut MDev<'a>) -> Callout<'a, 'b> { if dev.mdev_type.is_none() { panic!("Device dev must have a defined mdev_type!") } Callout { state: State::None, script: None, dev, } } fn find_callout_script(&self) -> Option { self.dev.env.find_script(self.dev) } pub fn invoke_modify_live(&mut self) -> Result<()> { self.script = self.find_callout_script(); if self.script.is_none() { // live is only supported when script with versioning exists debug!("No callout script with version support found that supports live modify"); return Err(anyhow!( "No callout script with version support found that supports live modify" )); } let mut res = Ok(()); let mut existing = MDev::new(self.dev.env, self.dev.uuid); if existing.load_from_sysfs().is_ok() && existing.active { if existing.parent != self.dev.parent { debug!("Device exists under different parent - cannot run live update"); res = Err(anyhow!( "Device exists under different parent - cannot run live update" )); } else if existing.mdev_type != self.dev.mdev_type { debug!("Device exists with different type - cannot run live update"); res = Err(anyhow!( "Device exists with different type - cannot run live update" )); } else { self.script .clone() .unwrap() .supports_event_action(Event::Live, Action::Modify)?; let conf = self.dev.to_json(false)?.to_string(); res = self .callout( Event::Live, Action::Modify, Some(&conf), &DefaultCheckProcessOutput, ) .map(|_output| ()); self.notify(Action::Modify); } } // else mdev is not active res } pub fn invoke(&mut self, action: Action, force: bool, func: F) -> Result<()> where F: Fn(&mut Self) -> Result<()>, { self.script = self.find_callout_script(); if self.script.is_none() { debug!("No callout script with version support found"); } let conf = self.dev.to_json(false)?.to_string(); let res = self .callout(Event::Pre, action, Some(&conf), &DefaultCheckProcessOutput) .map(|_output| ()) // can ignore output for general callouts .or_else(|e| { force .then(|| { warn!( "Forcing operation '{}' despite callout failure. Error was: {}", action, e ); }) .ok_or(e) }) .and_then(|_| { let tmp_res = func(self); self.state = match tmp_res { Ok(_) => State::Success, Err(_) => State::Failure, }; let post_res = self.callout(Event::Post, action, Some(&conf), &DefaultCheckProcessOutput); if post_res.is_err() { debug!("Error occurred when executing post callout script"); } tmp_res }); self.notify(action); res } pub fn get_attributes(&mut self) -> Result { self.script = self.find_callout_script(); if self.script.is_none() { debug!("No callout script with version support found"); } match self.callout( Event::Get, Action::Attributes, None, &DefaultCheckProcessOutput, )? { Some(output) => { if output.status.success() { debug!("Get attributes successfully from callout script"); let mut st = String::from_utf8_lossy(&output.stdout).to_string(); if st.is_empty() { debug!( "Script output for {} is empty", self.dev.uuid.hyphenated().to_string() ); return Ok(serde_json::Value::Null); } if &st == "[{}]" { debug!( "Attribute field for {} is empty", self.dev.uuid.hyphenated().to_string() ); st = "[]".to_string(); } debug!( "Script output for {} is: '{}'", self.dev.uuid.hyphenated().to_string(), st ); serde_json::from_str(st.trim_end_matches('\0')) .with_context(|| "Invalid JSON received from callout script") } else { let path = &self.script.as_ref().unwrap().path; self.print_err(&output, path); Err(invocation_failure(path, output.status.code())) } } None => { debug!( "Script execution for {} returned without error but also without output", self.dev.uuid.hyphenated().to_string() ); Ok(serde_json::Value::Null) } } } fn invoke_script>( &self, script: P, event: Event, action: Action, stdin: Option<&str>, ) -> Result { debug!( "{}-{}: executing {:?}", event, action, script.as_ref().as_os_str() ); let mut cmd = Command::new(script.as_ref().as_os_str()); cmd.arg("-t") .arg(self.dev.mdev_type()?) .arg("-e") .arg(event.to_string()) .arg("-a") .arg(action.to_string()) .arg("-s") .arg(self.state.to_string()) .arg("-u") .arg(self.dev.uuid.to_string()) .arg("-p") .arg(self.dev.parent()?) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()); let mut child = cmd.spawn()?; if let Some(input) = stdin { if let Some(mut child_stdin) = child.stdin.take() { match child_stdin.write_all(input.as_bytes()) { Ok(_) => (), Err(e) if e.kind() == ErrorKind::BrokenPipe => { debug!( "Callout script {:?} closed stdin before all data was written", script.as_ref().as_os_str() ) } Err(e) => Err(e).with_context(|| "Failed to write to stdin of command")?, } } } child.wait_with_output().map_err(anyhow::Error::from) } fn print_err>(&self, output: &Output, script: P) { let sname = script .as_ref() .file_name() .unwrap_or_else(|| OsStr::new("unknown script name")) .to_string_lossy(); let st = String::from_utf8_lossy(&output.stderr); if !st.is_empty() { eprint!("{}: {}", &sname, st); } } fn invoke_first_matching_script + std::fmt::Debug>( &self, dir: P, event: Event, action: Action, stdin: Option<&str>, check_result_fn: impl Fn(PathBuf, Output) -> Result<(PathBuf, Output)>, ) -> Option<(PathBuf, Output)> { debug!( "{}-{}: looking for a matching callout script for dev type '{}' in {:?}", event, action, self.dev.mdev_type.as_ref()?, dir ); let mut sorted_paths = dir .as_ref() .read_dir() .ok()? .filter_map(|k| k.ok().map(|e| e.path())) .collect::>(); sorted_paths.sort(); for path in sorted_paths { match self.invoke_script(&path, event, action, stdin) { Ok(res) => { if res.status.code().is_none() { warn!("callout script {:?} was terminated by a signal", path); continue; } else if res.status.code() == Some(2) { debug!( "callout script {:?} does not match device type {:?}", path, self.dev.mdev_type().ok()? ); } else { debug!( "found callout script {:?} matching device type {:?}", path, self.dev.mdev_type().ok()? ); match check_result_fn(path, res) { Ok((p, r)) => return Some((p, r)), Err(_) => { debug!("found callout script rejected by check_result method"); continue; } } } } Err(e) => { debug!("failed to execute callout script {:?}: {:?}", path, e); continue; } } } None } fn callout( &mut self, event: Event, action: Action, stdin: Option<&str>, check_process: &dyn CheckProcessOutput, ) -> Result> { match self.script { Some(ref s) => { s.supports_event_action(event, action)?; let output = self.invoke_script(s, event, action, stdin)?; self.print_err(&output, s); match output.status.code() { None | Some(0) => Ok(Some(output)), Some(n) => Err(invocation_failure(&s.path, Some(n))), } } None => { let mut res = Ok(None); for dir in self.dev.env.callout_dirs() { if !dir.is_dir() { continue; } let r = match self.invoke_first_matching_script( dir, event, action, stdin, |p, o| check_process.check(p, o), ) { Some((p, o)) => match check_process.process(self, p, o)? { Some(o) => Ok(Some(o)), None => continue, }, None => continue, }; res = r; break; } res } } } fn notify(&mut self, action: Action) { let event = Event::Notify; let dirs = self.dev.env.notification_dirs(); debug!( "{}-{}: executing notification scripts for device {}", event, action, self.dev.uuid ); for dir in dirs { if !dir.is_dir() { continue; } if let Ok(readdir) = dir.read_dir() { for path in readdir.filter_map(|x| x.ok().map(|y| y.path())) { match self.invoke_script(&path, event, action, None) { Ok(output) => { if !output.status.success() { debug!("Error occurred when executing notify script {:?}", path); } } _ => { debug!("Failed to execute callout script {:?}", path); continue; } } } } } } } mdevctl-mdevctl-54db334/src/cli.rs000066400000000000000000000241301454705020100170400ustar00rootroot00000000000000//! Command line options for mdevctl pub use clap::Parser; use std::path::PathBuf; use uuid::Uuid; const FORCE_HELP: &str = "Force command execution even if device-specific callout script fails NOTE: only use this option if you are sure you know what you are doing"; const LIST_LONG_ABOUT: &str = "List mediated devices\n\n\ With no options, information about the currently running mediated devices is \ provided. Specifying 'defined' lists the configuration of defined devices, \ regardless of their running state. This may be further reduced by specifying \ specific 'uuid' or 'parent' devices to list. The 'dumpjson' option provides output \ listing in machine readable JSON format. When a 'uuid' option is provided and the \ result is a single device, the output contains only the JSON fields necessary to \ recreate a config file for the device (minus attributes for listings of running \ devices). When the verbose option is provided, the human readable listing will \ include attributes for the device(s)."; #[derive(Parser, Debug)] #[command(version, about = "List mediated devices", long_about = LIST_LONG_ABOUT, name = "lsmdev")] pub struct LsmdevOptions { #[arg(short, long, help = "Show defined devices")] pub defined: bool, #[arg(long, help = "Output device list in json format")] pub dumpjson: bool, #[arg(short, long, help = "Print additional information about the devices")] pub verbose: bool, #[arg(short, long, help = "List devices matching the specified UUID")] pub uuid: Option, #[arg( short, long, help = "List devices associated with the specified Parent device" )] pub parent: Option, } // command-line argument definitions. #[derive(Parser)] #[command(version, about = "A mediated device management utility for Linux")] pub enum MdevctlCommands { #[command( about = "Define a persistent mediated device", long_about = "Define a persistent mediated device\n\n\ If the device specified by the UUID currently exists, 'parent' and 'type' may be \ omitted to use the existing values. The 'auto' option marks the device to start on \ parent availability. If defined via 'jsonfile', then 'type', 'startup', and any \ attributes are provided via the file.\n\n\ Running devices are unaffected by this command." )] Define { #[arg( short, long, required_unless_present("parent"), help = "Assign UUID to the device" )] uuid: Option, #[arg( short, long, help = "Automatically start device on parent availability" )] auto: bool, #[arg( short, long, required_unless_present("uuid"), help = "Specify the parent of the device" )] parent: Option, #[arg(id = "type", short, long, help = "Specify the mdev type of the device")] mdev_type: Option, #[arg( long, conflicts_with_all(&["type", "auto"]), help = "Specify device details in JSON format" )] jsonfile: Option, #[arg( short, long, help = FORCE_HELP )] force: bool, }, #[command( about = "Undefine a persistent mediated device", long_about = "Undefine, or remove a config for an mdev device\n\n\ If a UUID exists for multiple parents, all will be removed unless a parent is specified. \n\n\ Running devices are unaffected by this command." )] Undefine { #[arg(short, long, help = "UUID of the device to be undefined")] uuid: Uuid, #[arg(short, long, help = "Parent of the device to be undefined")] parent: Option, #[arg( short, long, help = FORCE_HELP )] force: bool, }, #[command( about = "Modify the definition of a mediated device", long_about = "Modify the definition of a mediated device\n\n\ The 'parent' option further identifies a UUID if it is not unique. The parent for a \ device cannot be modified via this command; undefine and re-define should be used \ instead. An attribute can be added or removed, which correlates to a sysfs \ attribute under the created device. Unless an 'index' value is provided, operations \ are performed at the end of the attribute list. 'value' is to be specified in the \ format that is accepted by the attribute. Upon device start, mdevctl will go \ through each attribute in order, writing the value into the corresponding sysfs \ attribute for the device. The startup mode of the device can also be selected, auto \ or manual. Alternatively, the 'jsonfile' option may be used to replace the startup \ mode and any attributes with the contents of the specified file.\n\n\ Running devices are unaffected by this command.", group( clap::ArgGroup::new("modify") .required(true) .args(&["auto", "manual", "addattr", "delattr", "jsonfile"]), ), )] Modify { #[arg(short, long, help = "UUID of the mdev to modify")] uuid: Uuid, #[arg(short, long, help = "Parent of the mdev to modify")] parent: Option, #[arg( id = "type", short, long, help = "Modify the mdev type for this device" )] mdev_type: Option, #[arg( long, requires("value"), help = "Add a new attribute", value_name = "attr_name" )] addattr: Option, #[arg(long, help = "Delete an attribute")] delattr: bool, #[arg(long, short, help = "Index of the attribute to modify")] index: Option, #[arg( long, conflicts_with("delattr"), requires("addattr"), help = "Value for the attribute specified by --addattr", value_name = "attr_value" )] value: Option, #[arg( short, long, conflicts_with_all(&["index", "value"]), help = "Device will be started automatically")] auto: bool, #[arg( short, long, conflicts_with_all(&["index", "value"]), help = "Device must be started manually" )] manual: bool, #[arg( short, long, conflicts_with_all(&["type", "index", "value"]), requires("jsonfile"), help = "Modify the running device definition only unless used together with defined option" )] live: bool, #[arg(short, long, help = "Modify the stored device definition")] defined: bool, #[arg( long, conflicts_with_all(&["type", "index", "value"]), help = "Specify device details in JSON format" )] jsonfile: Option, #[arg( short, long, help = FORCE_HELP )] force: bool, }, #[command( about = "Start a mediated device", long_about = "Start a mediated device\n\n\ If the UUID is previously defined and unique, the UUID is sufficient to start the \ device (UUIDs may not collide between running devices). If a UUID is used in \ multiple defined configurations, the 'parent' is necessary to identify the device \ to be started. When specified with 'parent' and 'type', the device is fully \ specified and will be started based only on these parameters. The UUID is optional \ in this case. If not provided, a UUID is generated and returned as output. A \ 'jsonfile' may replace the 'type' specification and also include additional \ attributes to be applied to the started device." )] Start { #[arg( short, long, required_unless_present("parent"), help = "UUID of the device to start" )] uuid: Option, #[arg( short, long, required_unless_present("uuid"), help = "Parent of the device to start" )] parent: Option, #[arg(id = "type", short, long, help = "Mdev type of the device to start")] mdev_type: Option, #[arg( long, conflicts_with("type"), help = "Details of the device to be started, in JSON format" )] jsonfile: Option, #[arg( short, long, help = FORCE_HELP )] force: bool, }, #[command(about = "Stop a mediated device")] Stop { #[arg(short, long, help = "UUID of the device to stop")] uuid: Uuid, #[arg( short, long, help = FORCE_HELP )] force: bool, }, #[command( about = "List mediated devices", long_about = LIST_LONG_ABOUT )] List(LsmdevOptions), #[command( about = "List available mediated device types", long_about = "List available mediated device types\n\n\ Specifying a 'parent' lists only the types provided by the given parent device. \ The 'dumpjson' option provides output in machine readable JSON format." )] Types { #[arg(short, long, help = "Show supported types for the specified parent")] parent: Option, #[arg(long, help = "Output mdev types list in JSON format")] dumpjson: bool, }, #[command(hide = true)] StartParentMdevs { parent: String }, } #[test] fn test_cli() { use clap::CommandFactory; MdevctlCommands::command().debug_assert() } mdevctl-mdevctl-54db334/src/environment.rs000066400000000000000000000070501454705020100206370ustar00rootroot00000000000000//! A filesystem environment for mdevctl use crate::callouts::{CalloutScriptCache, CalloutScriptInfo}; use crate::mdev::MDev; use anyhow::{anyhow, Result}; use log::debug; use std::env; use std::path::{Path, PathBuf}; use std::sync::Mutex; /// A trait which provides filesystem paths for certain system resources. /// /// The main purpose of this trait is to enable testability of the mdevctl commands by abstracting /// out the filesystem locations. Tests can implement [`Environment`] and provide filesystem paths /// within a mock filesystem environment that will not affect the system. pub trait Environment { fn root(&self) -> &Path; fn find_script(&self, dev: &MDev) -> Option; fn mdev_base(&self) -> PathBuf { self.root().join("sys/bus/mdev/devices") } fn config_base(&self) -> PathBuf { self.root().join("etc/mdevctl.d") } fn parent_base(&self) -> PathBuf { self.root().join("sys/class/mdev_bus") } fn config_scripts_base(&self) -> PathBuf { self.config_base().join("scripts.d") } fn scripts_base(&self) -> PathBuf { self.root().join("usr/lib/mdevctl/scripts.d") } fn callout_dir(&self) -> PathBuf { self.scripts_base().join("callouts") } fn old_callout_dir(&self) -> PathBuf { self.config_scripts_base().join("callouts") } fn callout_dirs(&self) -> Vec { vec![self.callout_dir(), self.old_callout_dir()] } fn notification_dir(&self) -> PathBuf { self.scripts_base().join("notifiers") } fn old_notification_dir(&self) -> PathBuf { self.config_scripts_base().join("notifiers") } fn notification_dirs(&self) -> Vec { vec![self.notification_dir(), self.old_notification_dir()] } fn self_check(&self) -> Result<()> { debug!("checking that the environment is sane"); // ensure required system dirs exist. Generally distro packages or 'make install' should // create these dirs. for dir in [ self.config_base(), self.callout_dir(), self.notification_dir(), ] { if !dir.exists() { return Err(anyhow!("Required directory {:?} doesn't exist. This may indicate a packaging or installation error", dir)); } } Ok(()) } } /// A default implementation of the Environment trait which uses '/' as the filesystem root. #[derive(Debug)] pub struct DefaultEnvironment { rootpath: PathBuf, callout_scripts: Mutex, } impl std::fmt::Debug for &dyn Environment { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.debug_struct("Environment") .field("mdev_base", &self.mdev_base()) .field("config_base", &self.config_base()) .field("parent_base", &self.parent_base()) .finish() } } impl Environment for DefaultEnvironment { fn root(&self) -> &Path { self.rootpath.as_path() } fn find_script(&self, dev: &MDev) -> Option { return self .callout_scripts .lock() .unwrap() .find_versioned_script(dev); } } impl DefaultEnvironment { pub fn new() -> DefaultEnvironment { let root = match env::var("MDEVCTL_ENV_ROOT") { Ok(d) => d, _ => "/".to_string(), }; DefaultEnvironment { rootpath: PathBuf::from(root), callout_scripts: Mutex::new(CalloutScriptCache::new()), } } } mdevctl-mdevctl-54db334/src/logger.rs000066400000000000000000000003641454705020100175530ustar00rootroot00000000000000//! Logging implementation for mdevctl pub fn logger() -> env_logger::Builder { let env = env_logger::Env::new() .filter_or("MDEVCTL_LOG", "warn") .write_style("MDEVCTL_LOG_STYLE"); env_logger::Builder::from_env(env) } mdevctl-mdevctl-54db334/src/main.rs000066400000000000000000001007111454705020100172150ustar00rootroot00000000000000//! mdevctl is a utility for managing and persisting devices in the mediated device framework of //! the Linux kernel. Mediated devices are sub-devices of a parent device (ex. a vGPU) which can //! be dynamically created and potentially used by drivers like vfio-mdev for assignment to virtual //! machines. //! //! See `mdevctl help` or the manpage for more information. use anyhow::{anyhow, ensure, Context, Result}; use clap::Parser; use log::{debug, warn}; use std::cmp::Ordering; use std::collections::BTreeMap; use std::fmt::Write; use std::fs; use std::io::Read; use std::path::PathBuf; use std::vec::Vec; use uuid::Uuid; use crate::callouts::*; use crate::cli::{LsmdevOptions, MdevctlCommands}; use crate::environment::{DefaultEnvironment, Environment}; use crate::logger::logger; use crate::mdev::*; mod callouts; mod cli; mod environment; mod logger; mod mdev; #[cfg(test)] mod tests; /// Format a map of mediated devices into a json string fn format_json(devices: BTreeMap>) -> Result { let mut parents = serde_json::map::Map::new(); for (parentname, children) in devices { let mut childrenarray = Vec::new(); for child in children { childrenarray.push(child.to_json(true)?); } parents.insert(parentname, childrenarray.into()); } // don't serialize an empty object if there are no devices let jsonval = match parents.len() { 0 => serde_json::json!([]), _ => serde_json::json!([parents]), }; serde_json::to_string_pretty(&jsonval).map_err(|_e| anyhow!("Unable to serialize json")) } /// convert 'define' command arguments into a MDev struct fn define_command_helper( env: &dyn Environment, uuid: Option, auto: bool, parent: Option, mdev_type: Option, jsonfile: Option, ) -> Result { let uuid_provided = uuid.is_some(); let uuid = uuid.unwrap_or_else(Uuid::new_v4); let mut dev = MDev::new(env, uuid); if let Some(jsonfile) = jsonfile { let _ = std::fs::File::open(&jsonfile) .with_context(|| format!("Unable to read file {:?}", jsonfile))?; if mdev_type.is_some() { return Err(anyhow!( "Device type cannot be specified separately from {:?}", jsonfile )); } let parent = parent .ok_or_else(|| anyhow!("Parent device required to define device via {:?}", jsonfile))?; let devs = defined_devices(env, Some(&uuid), Some(&parent))?; if !devs.is_empty() { return Err(anyhow!( "Cowardly refusing to overwrite existing config for {}/{}", parent, uuid.hyphenated().to_string() )); } let filecontents = fs::read_to_string(&jsonfile) .with_context(|| format!("Unable to read jsonfile {:?}", jsonfile))?; let jsonval = serde_json::from_str(&filecontents)?; dev.load_from_json(parent, &jsonval)?; } else { if uuid_provided { dev.load_from_sysfs()?; if parent.is_none() && (!dev.active || mdev_type.is_some()) { return Err(anyhow!("No parent specified")); } } dev.autostart = auto; if parent.is_some() { dev.parent = parent; } if mdev_type.is_some() { dev.mdev_type = mdev_type; } if dev.parent.is_none() { return Err(anyhow!("No parent specified")); } if dev.mdev_type.is_none() { return Err(anyhow!("No type specified")); } if dev.is_defined() { return Err(anyhow!( "Device {} on {} already defined", dev.uuid.hyphenated().to_string(), dev.parent()? )); } } Ok(dev) } /// Implementation of the `mdevctl define` command fn define_command( env: &dyn Environment, uuid: Option, auto: bool, parent: Option, mdev_type: Option, jsonfile: Option, force: bool, ) -> Result<()> { debug!("Defining mdev {:?}", uuid); let mut dev = define_command_helper(env, uuid, auto, parent, mdev_type, jsonfile)?; /* Call Callout::get_attributes() when defining an active device without a config file. This function allows callout script to acquire device-specific attributes from sysfs, and populate the attrs field correspondingly before the device is defined in the system. The device config file will contain the same attributes that were used to start this device。 */ let mut c = callout(&mut dev); c.invoke(Action::Define, force, |c| { if c.dev.active { let attrs = c.get_attributes()?; c.dev.add_attributes(&attrs)?; } c.dev.define() }) .map(|_| { if uuid.is_none() { println!("{}", dev.uuid.hyphenated()); } }) } /// Implementation of the `mdevctl undefine` command fn undefine_command( env: &dyn Environment, uuid: Uuid, parent: Option, force: bool, ) -> Result<()> { debug!("Undefining mdev {:?}", uuid); let mut failed = false; let devs = defined_devices(env, Some(&uuid), parent.as_ref())?; if devs.is_empty() { return Err(anyhow!("No devices match the specified uuid")); } for (_, mut children) in devs { for child in children.iter_mut() { let mut c = callout(child); if let Err(e) = c.invoke(Action::Undefine, force, |c| c.dev.undefine()) { failed = true; for x in e.chain() { warn!( "Undefine of {} on parent {} failed with error: {}", c.dev.uuid, c.dev.parent().unwrap().to_string(), x ); } } } } if failed { return Err(anyhow!("Undefine failed")); } Ok(()) } fn dev_from_jsonfile( env: &dyn Environment, uuid: Uuid, parent: String, jsonfile: PathBuf, ) -> Result { let _ = std::fs::File::open(&jsonfile) .with_context(|| format!("Unable to read file {:?}", jsonfile))?; let filecontents = fs::read_to_string(&jsonfile) .with_context(|| format!("Unable to read jsonfile {:?}", jsonfile))?; let jsonval = serde_json::from_str(&filecontents)?; let mut d = MDev::new(env, uuid); d.load_from_json(parent, &jsonval)?; Ok(d) } /// Implementation of the `mdevctl modify` command #[allow(clippy::too_many_arguments)] fn modify_command( env: &dyn Environment, uuid: Uuid, parent: Option, mdev_type: Option, addattr: Option, delattr: bool, index: Option, value: Option, auto: bool, manual: bool, live: bool, defined: bool, jsonfile: Option, force: bool, ) -> Result<()> { debug!("Modifying mdev {:?}", uuid); if live { if mdev_type.is_some() { return Err(anyhow!("'type' cannot be changed on active mdev")); } if auto { return Err(anyhow!("'auto' cannot be changed on active mdev")); } if manual { return Err(anyhow!("'manual' cannot be changed on active mdev")); } let mut act_dev = get_active_device(env, uuid, parent.as_ref())?; if let Some(f) = jsonfile { let act_parent = act_dev .parent .clone() .ok_or_else(|| anyhow!("Parent device required to modify device via json file"))?; let json_dev = dev_from_jsonfile(env, uuid, act_parent, f)?; if json_dev.mdev_type != act_dev.mdev_type { return Err(anyhow!("'type' cannot be changed on active mdev")); } if json_dev.parent != act_dev.parent { return Err(anyhow!("'parent' cannot be changed on active mdev")); } act_dev = json_dev; } else { return Err(anyhow!("'live' option must be used with 'jsonfile' option")); } if defined { // live and stored modify - defined dev config exists and types match let def_dev = get_defined_device(env, uuid, act_dev.parent.as_ref())?; if def_dev.mdev_type != act_dev.mdev_type { return Err(anyhow!("'type' of active and defined mdev does not match")); } let mut c = callout(&mut act_dev); debug!("mdev device used for live update '{:?}'", c.dev); return c .invoke_modify_live() .and_then(|_| c.invoke(Action::Modify, force, |c| c.dev.write_config())); } // live modify only callout(&mut act_dev).invoke_modify_live() } else { let mut dev: MDev; // stored configuration modify if let Some(f) = jsonfile { let parent = parent .ok_or_else(|| anyhow!("Parent device required to modify device via json file"))?; dev = dev_from_jsonfile(env, uuid, parent, f)?; } else { dev = get_defined_device(env, uuid, parent.as_ref())?; if mdev_type.is_some() { dev.mdev_type = mdev_type; } if auto && manual { return Err(anyhow!("'auto' and 'manual' are mutually exclusive")); } if auto { dev.autostart = true; } else if manual { dev.autostart = false; } } let index = index.map(|n| n as usize); match addattr { Some(attr) => match value { None => return Err(anyhow!("No attribute value provided")), Some(v) => dev.add_attribute(attr, v, index)?, }, None => { if delattr { dev.delete_attribute(index)?; } } } callout(&mut dev).invoke(Action::Modify, force, |c| c.dev.write_config()) } } /// convert 'start' command arguments into a MDev struct fn start_command_helper( env: &dyn Environment, uuid: Option, parent: Option, mdev_type: Option, jsonfile: Option, ) -> Result { debug!("Starting device '{:?}'", uuid); let mut dev: Option = None; match jsonfile { Some(fname) => { let contents = fs::read_to_string(&fname) .with_context(|| format!("Unable to read jsonfile {:?}", fname))?; let val = serde_json::from_str(&contents)?; if mdev_type.is_some() { return Err(anyhow!( "Device type cannot be specified separately from json file" )); } let parent = parent .ok_or_else(|| anyhow!("Parent device required to start device via json file"))?; let mut d = MDev::new(env, uuid.unwrap_or_else(Uuid::new_v4)); d.load_from_json(parent, &val)?; dev = Some(d); } _ => { // if the user specified a uuid, check to see if they're referring to a defined device if uuid.is_some() { let devs = defined_devices(env, uuid.as_ref(), parent.as_ref())?; let n = devs.values().flatten().count(); match n.cmp(&1) { Ordering::Greater => { return Err(anyhow!( "Multiple definitions found for device {}. Please specify a parent.", uuid.unwrap().hyphenated().to_string() )); } Ordering::Equal => { // FIXME: use into_values() to consume the iterator and avoid cloning below // when we can require rust 1.54.0 let d = devs.values().flatten().next(); if let Some(d) = d { // See https://github.com/mdevctl/mdevctl/issues/38 // If a user specifies the uuid (and optional parent) of a defined device if mdev_type.is_some() && mdev_type != d.mdev_type { return Err(anyhow!( "Device {} already exists on parent {} with type {}", d.uuid.hyphenated().to_string(), d.parent().unwrap(), d.mdev_type.as_ref().unwrap() )); } else { dev = Some(d.clone()); } } } _ => (), } } if dev.is_none() { let mut d = MDev::new(env, uuid.unwrap_or_else(Uuid::new_v4)); d.parent = parent; d.mdev_type = mdev_type; dev = Some(d); } if let Some(ref d) = dev { if d.mdev_type.is_some() && d.parent.is_none() { return Err(anyhow!("can't provide type without parent")); } if d.mdev_type.is_none() || d.parent.is_none() { return Err(anyhow!("Device is insufficiently specified")); } } } } dev.ok_or_else(|| anyhow!("Unknown error")) } /// Implementation of the `mdevctl start` command fn start_command( env: &dyn Environment, uuid: Option, parent: Option, mdev_type: Option, jsonfile: Option, force: bool, ) -> Result<()> { let mut dev = start_command_helper(env, uuid, parent, mdev_type, jsonfile)?; let mut c = callout(&mut dev); c.invoke(Action::Start, force, |c| c.dev.start()).map(|_| { if uuid.is_none() { println!("{}", c.dev.uuid.hyphenated()); } }) } /// Implementation of the `mdevctl stop` command fn stop_command(env: &dyn Environment, uuid: Uuid, force: bool) -> Result<()> { debug!("Stopping '{}'", uuid); let mut dev = MDev::new(env, uuid); dev.load_from_sysfs()?; callout(&mut dev).invoke(Action::Stop, force, |c| c.dev.stop()) } /// convenience function to lookup a defined device by uuid and parent fn get_defined_device<'a>( env: &'a dyn Environment, uuid: Uuid, parent: Option<&String>, ) -> Result> { let devs = defined_devices(env, Some(&uuid), parent)?; if devs.is_empty() { match parent { None => Err(anyhow!( "Mediated device {} is not defined", uuid.hyphenated().to_string() )), Some(p) => Err(anyhow!( "Mediated device {}/{} is not defined", p, uuid.hyphenated().to_string() )), } } else if devs.len() > 1 { match parent { None => Err(anyhow!( "Multiple definitions found for {}, specify a parent", uuid.hyphenated().to_string() )), Some(p) => Err(anyhow!( "Multiple definitions found for {}/{}", p, uuid.hyphenated().to_string() )), } } else { let (parent, children) = devs.iter().next().unwrap(); if children.len() > 1 { return Err(anyhow!( "Multiple definitions found for {}/{}", parent, uuid.hyphenated().to_string() )); } Ok(children.first().unwrap().clone()) } } /// Get a map of all defined devices, optionally filtered by uuid and parent fn defined_devices<'a>( env: &'a dyn Environment, uuid: Option<&Uuid>, parent: Option<&String>, ) -> Result>>> { let mut devices: BTreeMap> = BTreeMap::new(); debug!( "Looking up defined mdevs: uuid={:?}, parent={:?}", uuid, parent ); for parentpath in env.config_base().read_dir()?.skip_while(|x| match x { Ok(d) => d.path() == env.scripts_base(), _ => false, }) { let parentpath = parentpath?; let parentname = parentpath.file_name(); let parentname = parentname.to_str().unwrap(); if (parent.is_some() && parent.unwrap() != parentname) || !parentpath.metadata()?.is_dir() { debug!("Ignoring child devices for parent {}", parentname); continue; } let mut childdevices = Vec::new(); match parentpath.path().read_dir() { Ok(res) => { for child in res { let child = child?; match child.metadata() { Ok(metadata) => { if !metadata.is_file() { continue; } } Err(e) => { warn!("unable to access file {:?}: {}", child.path(), e); continue; } } let path = child.path(); let basename = path.file_name().unwrap().to_str().unwrap(); let u = Uuid::parse_str(basename); if u.is_err() { warn!("Can't determine uuid for file '{}'", basename); continue; } let u = u.unwrap(); debug!("found mdev {:?}", u); if uuid.is_some() && uuid != Some(&u) { debug!( "Ignoring device {} because it doesn't match uuid {}", u, uuid.unwrap() ); continue; } match fs::File::open(&path) { Ok(mut f) => { let mut contents = String::new(); f.read_to_string(&mut contents)?; let val = serde_json::from_str(&contents)?; let mut dev = MDev::new(env, u); dev.load_from_json(parentname.to_string(), &val)?; dev.load_from_sysfs()?; childdevices.push(dev); } Err(e) => { warn!("Unable to open file {:?}: {}", path, e); continue; } }; } } Err(e) => warn!("Unable to read directory {:?}: {}", parentpath.path(), e), } if !childdevices.is_empty() { devices.insert(parentname.to_string(), childdevices); } } Ok(devices) } /// convenience function to lookup an active device by uuid and parent fn get_active_device<'a>( env: &'a dyn Environment, uuid: Uuid, parent: Option<&String>, ) -> Result> { let devs = active_devices(env, Some(&uuid), parent)?; if devs.is_empty() { match parent { None => Err(anyhow!( "Mediated device {} is not active", uuid.hyphenated().to_string() )), Some(p) => Err(anyhow!( "Mediated device {}/{} is not active", p, uuid.hyphenated().to_string() )), } } else if devs.len() > 1 { Err(anyhow!( "Multiple parents found for {}. System error?", uuid.hyphenated().to_string() )) } else { let (parent, children) = devs.iter().next().unwrap(); if children.len() > 1 { return Err(anyhow!( "Multiple definitions found for {}/{}", parent, uuid.hyphenated().to_string() )); } Ok(children.first().unwrap().clone()) } } /// Get a map of all active devices, optionally filtered by uuid and parent fn active_devices<'a>( env: &'a dyn Environment, uuid: Option<&Uuid>, parent: Option<&String>, ) -> Result>>> { let mut devices: BTreeMap> = BTreeMap::new(); debug!( "Looking up active mdevs: uuid={:?}, parent={:?}", uuid, parent ); if let Ok(dir) = env.mdev_base().read_dir() { for dir_dev in dir { let dir_dev = dir_dev?; let fname = dir_dev.file_name(); let basename = fname.to_str().unwrap(); debug!("found defined mdev {}", basename); let u = Uuid::parse_str(basename); if u.is_err() { warn!("Can't determine uuid for file '{}'", basename); continue; } let u = u.unwrap(); if uuid.is_some() && uuid != Some(&u) { debug!( "Ignoring device {} because it doesn't match uuid {}", u, uuid.unwrap() ); continue; } let mut dev = MDev::new(env, u); if dev.load_from_sysfs().is_ok() { if parent.is_some() && (parent != dev.parent.as_ref()) { debug!( "Ignoring device {} because it doesn't match parent {}", dev.uuid, parent.as_ref().unwrap() ); continue; } // retrieve autostart from persisted mdev if possible let mut per_dev = MDev::new(env, u); per_dev.parent = dev.parent.clone(); if per_dev.load_definition().is_ok() { dev.autostart = per_dev.autostart; } // if the device is supported by a callout script that gets attributes, show // those in the output let mut c = callout(&mut dev); if let Ok(attrs) = c.get_attributes() { let _ = c.dev.add_attributes(&attrs); } let devparent = dev.parent()?; if !devices.contains_key(devparent) { devices.insert(devparent.clone(), Vec::new()); }; devices.get_mut(devparent).unwrap().push(dev); }; } } Ok(devices) } /// Implementation of the `mdevctl list` command fn list_command( env: &dyn Environment, defined: bool, dumpjson: bool, verbose: bool, uuid: Option, parent: Option, ) -> Result<()> { let output = list_command_helper(env, defined, dumpjson, verbose, uuid, parent)?; println!("{}", output); Ok(()) } /// convert 'list' command arguments into a text output fn list_command_helper( env: &dyn Environment, defined: bool, dumpjson: bool, verbose: bool, uuid: Option, parent: Option, ) -> Result { let mut devices: BTreeMap>; if defined { devices = defined_devices(env, uuid.as_ref(), parent.as_ref())?; } else { devices = active_devices(env, uuid.as_ref(), parent.as_ref())?; } // ensure that devices are sorted in a stable order for v in devices.values_mut() { v.sort_by_key(|e| e.uuid); } let output = match dumpjson { true => { // if specified to a single device, output such that it can be piped into a config // file, else print entire heirarchy if uuid.is_none() || devices.values().flatten().count() > 1 { format_json(devices)? } else { let jsonval = match devices.values().next() { Some(children) => children .first() .ok_or_else(|| anyhow!("Failed to get device"))? .to_json(false)?, None => serde_json::json!([]), }; serde_json::to_string_pretty(&jsonval) .map_err(|_e| anyhow!("Unable to serialize json"))? } } false => { let ft = match defined { true => FormatType::Defined, false => FormatType::Active, }; devices .values() // convert child vector into an iterator over the vector's elements .flat_map(|v| v.iter()) // convert MDev elements to a text representation, filtering out errors .flat_map(|d| d.to_text(ft, verbose)) .collect::() } }; Ok(output) } /// Get a map of all mediated device types that are supported on this machine fn supported_types( env: &dyn Environment, parent: Option, ) -> Result>> { debug!("Finding supported mdev types"); let mut types: BTreeMap> = BTreeMap::new(); if let Ok(dir) = env.parent_base().read_dir() { for parentpath in dir { let parentpath = parentpath?; let parentname = parentpath.file_name(); let parentname = parentname.to_str().unwrap(); debug!("Looking for supported types for device {}", parentname); if parent.is_some() && parent.as_ref().unwrap() != parentname { debug!("Ignoring types for parent {}", parentname); continue; } let mut childtypes = Vec::new(); let mut parentpath = parentpath.path(); parentpath.push("mdev_supported_types"); for child in parentpath.read_dir()? { let child = child?; if !child.metadata()?.is_dir() { continue; } let mut t = MDevType::new(); t.parent = parentname.to_string(); let mut path = child.path(); t.typename = path.file_name().unwrap().to_str().unwrap().to_string(); debug!("found mdev type {}", t.typename); path.push("available_instances"); debug!("Checking available instances: {:?}", path); t.available_instances = fs::read_to_string(&path)?.trim().parse()?; path.pop(); path.push("device_api"); t.device_api = fs::read_to_string(&path)?.trim().to_string(); path.pop(); path.push("name"); if path.exists() { t.name = fs::read_to_string(&path)?.trim().to_string(); } path.pop(); path.push("description"); if path.exists() { t.description = fs::read_to_string(&path)? .trim() .replace('\n', ", ") .to_string(); } childtypes.push(t); } types.insert(parentname.to_string(), childtypes); } } for v in types.values_mut() { v.sort_by(|a, b| a.typename.cmp(&b.typename)); } Ok(types) } /// convert 'types' command arguments into a text output fn types_command_helper( env: &dyn Environment, parent: Option, dumpjson: bool, ) -> Result { let types = supported_types(env, parent)?; let mut output = String::new(); debug!("{:?}", types); if dumpjson { let mut parents = serde_json::map::Map::new(); for (parent, children) in types { let mut childarray = Vec::new(); for child in children { childarray.push(child.to_json()?); } parents.insert(parent, childarray.into()); } let jsonval = match parents.len() { 0 => serde_json::json!([]), _ => serde_json::json!([parents]), }; let jsonstr = serde_json::to_string_pretty(&jsonval) .map_err(|_e| anyhow!("Unable to serialize json"))?; output.push_str(&jsonstr); } else { for (parent, children) in types { let _ = writeln!(output, "{}", parent); for child in children { let _ = writeln!(output, " {}", child.typename); let _ = writeln!( output, " Available instances: {}", child.available_instances ); let _ = writeln!(output, " Device API: {}", child.device_api); if !child.name.is_empty() { let _ = writeln!(output, " Name: {}", child.name); } if !child.description.is_empty() { let _ = writeln!(output, " Description: {}", child.description); } } } } Ok(output) } /// Implementation of the `mdevctl types` command fn types_command(env: &dyn Environment, parent: Option, dumpjson: bool) -> Result<()> { let output = types_command_helper(env, parent, dumpjson)?; println!("{}", output); Ok(()) } /// Implementation of the `start-parent-mdevs` command fn start_parent_mdevs_command(env: &dyn Environment, parent: String) -> Result<()> { let mut devs = defined_devices(env, None, Some(&parent))?; if devs.is_empty() { // nothing to do return Ok(()); } ensure!(devs.len() == 1, "More than one parent found"); for (_, children) in devs.iter_mut() { for child in children { if child.autostart { debug!("Autostarting {:?}", child.uuid); if let Err(e) = callout(child).invoke(Action::Start, false, |c| c.dev.start()) { for x in e.chain() { warn!("{}", x); } } } } } Ok(()) } /// parse command line arguments and dispatch to command-specific functions fn main() -> Result<()> { logger().init(); debug!("Starting up"); let env = DefaultEnvironment::new(); debug!("{:?}", env); // make sure the environment is sane env.self_check()?; // check if we're running as the symlink executable 'lsmdev'. If so, just execute the 'list' // command directly let exe = std::env::args_os().next().unwrap(); match exe.to_str() { Some(val) if val.ends_with("lsmdev") => { debug!("running as 'lsmdev'"); let opts = LsmdevOptions::parse(); list_command( &env, opts.defined, opts.dumpjson, opts.verbose, opts.uuid, opts.parent, ) } _ => match MdevctlCommands::parse() { MdevctlCommands::Define { uuid, auto, parent, mdev_type, jsonfile, force, } => define_command(&env, uuid, auto, parent, mdev_type, jsonfile, force), MdevctlCommands::Undefine { uuid, parent, force, } => undefine_command(&env, uuid, parent, force), MdevctlCommands::Modify { uuid, parent, mdev_type, addattr, delattr, index, value, auto, manual, live, defined, jsonfile, force, } => modify_command( &env, uuid, parent, mdev_type, addattr, delattr, index, value, auto, manual, live, defined, jsonfile, force, ), MdevctlCommands::Start { uuid, parent, mdev_type, jsonfile, force, } => start_command(&env, uuid, parent, mdev_type, jsonfile, force), MdevctlCommands::Stop { uuid, force } => stop_command(&env, uuid, force), MdevctlCommands::List(list) => list_command( &env, list.defined, list.dumpjson, list.verbose, list.uuid, list.parent, ), MdevctlCommands::Types { parent, dumpjson } => types_command(&env, parent, dumpjson), MdevctlCommands::StartParentMdevs { parent } => { start_parent_mdevs_command(&env, parent) } }, } } mdevctl-mdevctl-54db334/src/mdev.rs000066400000000000000000000417201454705020100172300ustar00rootroot00000000000000//! Structures for representing a mediated device use crate::environment::Environment; use anyhow::{anyhow, Context, Result}; use log::{debug, warn}; use std::fs; use std::io::Read; use std::path::{Path, PathBuf}; use std::vec::Vec; use uuid::Uuid; #[derive(Clone, Copy)] pub enum FormatType { Active, Defined, } /// Representation of a mediated device #[derive(Debug, Clone)] pub struct MDev<'a> { pub uuid: Uuid, pub active: bool, pub autostart: bool, pub parent: Option, pub mdev_type: Option, pub attrs: Vec<(String, String)>, pub env: &'a dyn Environment, } impl<'a> MDev<'a> { pub fn new(env: &'a dyn Environment, uuid: Uuid) -> MDev<'a> { MDev { uuid, active: false, autostart: false, parent: None, mdev_type: None, attrs: Vec::new(), env, } } pub fn path(&self) -> PathBuf { let mut p = self.env.mdev_base(); p.push(self.uuid.hyphenated().to_string()); p } // get parent and propagate a consistent error to the caller if absent pub fn parent(&self) -> Result<&String> { self.parent.as_ref().ok_or_else(|| { anyhow!( "Device {} is missing a parent", self.uuid.hyphenated().to_string() ) }) } // get mdev_type and propagate a consistent error to the caller if absent pub fn mdev_type(&self) -> Result<&String> { self.mdev_type.as_ref().ok_or_else(|| { anyhow!( "Device {} is missing a mdev_type", self.uuid.hyphenated().to_string() ) }) } pub fn persist_path(&self) -> Option { self.parent.as_ref().map(|x| { let mut path = self.env.config_base(); path.push(x); path.push(self.uuid.hyphenated().to_string()); path }) } pub fn is_defined(&self) -> bool { match self.persist_path() { Some(p) => p.exists(), None => false, } } pub fn load_from_sysfs(&mut self) -> Result<()> { debug!("Loading device '{:?}' from sysfs", self.uuid); if !self.path().exists() { debug!("loaded device {:?}", self); return Ok(()); } let canonpath = self.path().canonicalize()?; let sysfsparent = canonpath.parent().unwrap(); let parentname = canonical_basename(sysfsparent)?; if self.parent.is_some() && self.parent.as_ref() != Some(&parentname) { debug!( "Active mdev {:?} has different parent: {}!={}. No match.", self.uuid, self.parent.as_ref().unwrap(), parentname ); return Ok(()); } let mut typepath = self.path(); typepath.push("mdev_type"); let mdev_type = canonical_basename(typepath)?; if self.mdev_type.is_some() && self.mdev_type.as_ref() != Some(&mdev_type) { debug!( "Active mdev {:?} has different type: {}!={}. No match.", self.uuid, self.mdev_type.as_ref().unwrap(), mdev_type ); return Ok(()); } // active device in sysfs matches this device. update information self.mdev_type = Some(mdev_type); self.parent = Some(parentname); self.active = true; debug!("loaded device {:?}", self); Ok(()) } pub fn add_attributes(&mut self, attrs: &serde_json::Value) -> Result<()> { if !attrs.is_array() && !attrs.is_null() { return Err(anyhow!("attributes field is not an array")); } if let Some(attrarray) = attrs.as_array() { if !attrarray.is_empty() { for attr in attrarray { let attrobj = attr.as_object().ok_or_else(|| { anyhow!("invalid JSON format for attribute: not an object") })?; // attributes are represented by JSON objects with a single field. if attrobj.len() != 1 { return Err(anyhow!( "invalid JSON format for attribute: too many fields" )); } // get the key and value from the first (only) map entry if let Some((key, val)) = attrobj.iter().next() { let valstr = val.as_str().unwrap(); self.attrs.push((key.to_string(), valstr.to_string())); } } } } Ok(()) } pub fn load_from_json(&mut self, parent: String, json: &serde_json::Value) -> Result<()> { debug!( "Loading device '{:?}' from json (parent: {})", self.uuid, parent ); if self.parent.is_some() && self.parent.as_ref() != Some(&parent) { warn!( "Overwriting parent for mdev {:?}: {} => {}", self.uuid, self.parent.as_ref().unwrap(), parent ); } self.parent = Some(parent); if json["mdev_type"].is_null() || json["start"].is_null() { return Err(anyhow!("invalid json")); } let mdev_type = json["mdev_type"].as_str().unwrap().to_string(); if self.mdev_type.is_some() && self.mdev_type.as_ref() != Some(&mdev_type) { warn!( "Overwriting mdev type for mdev {:?}: {} => {}", self.uuid, self.mdev_type.as_ref().unwrap(), mdev_type ); } self.mdev_type = Some(mdev_type); let startval = json["start"].as_str(); self.autostart = matches!(startval, Some("auto")); self.add_attributes(&json["attrs"])?; debug!("loaded device {:?}", self); Ok(()) } // load the stored definition from disk if it exists pub fn load_definition(&mut self) -> Result<()> { if let Some(path) = self.persist_path() { let mut f = fs::File::open(path)?; let mut contents = String::new(); f.read_to_string(&mut contents)?; let val = serde_json::from_str(&contents)?; let parent = self.parent.as_ref().unwrap().clone(); self.load_from_json(parent, &val)?; } Ok(()) } pub fn to_text(&self, fmt: FormatType, verbose: bool) -> Result { match fmt { FormatType::Defined => { if !self.is_defined() { return Err(anyhow!("Device is not defined")); } } FormatType::Active => { if !self.active { return Err(anyhow!("Device is not active")); } } } let mut output = self.uuid.hyphenated().to_string(); output.push(' '); output.push_str(self.parent()?); output.push(' '); output.push_str(self.mdev_type()?); output.push(' '); output.push_str(match self.autostart { true => "auto", false => "manual", }); match fmt { FormatType::Defined => { if self.active { output.push_str(" (active)"); } } FormatType::Active => { if self.is_defined() { output.push_str(" (defined)"); } } } output.push('\n'); if verbose { let attr_string = self.fmt_attrs(); output.push_str(&attr_string); } Ok(output) } fn fmt_attrs(&self) -> String { let mut output = String::new(); if !self.attrs.is_empty() { output.push_str(" Attrs:\n"); for (i, (key, value)) in self.attrs.iter().enumerate() { let txtattr = format!(" @{{{}}}: {{\"{}\":\"{}\"}}\n", i, key, value); output.push_str(&txtattr); } } output } pub fn to_json(&self, include_uuid: bool) -> Result { let autostart = match self.autostart { true => "auto", false => "manual", }; let mut partial = serde_json::Map::new(); partial.insert("mdev_type".to_string(), self.mdev_type()?.clone().into()); partial.insert("start".to_string(), autostart.into()); let jsonattrs: Vec<_> = self .attrs .iter() .map(|(key, value)| serde_json::json!({ key: value })) .collect(); partial.insert("attrs".to_string(), jsonattrs.into()); let full = serde_json::json!({ self.uuid.hyphenated().to_string(): partial }); match include_uuid { true => Ok(full), false => Ok(partial.into()), } } pub fn stop(&mut self) -> Result<()> { debug!("Removing mdev {:?}", self.uuid); let mut remove_path = self.path(); remove_path.push("remove"); debug!("remove path '{:?}'", remove_path); match fs::write(remove_path, "1") { Ok(_) => { self.active = false; Ok(()) } Err(e) => Err(e).with_context(|| format!("Error removing device {:?}", self.uuid)), } } fn find_parent_dir(&self) -> Result { let parent = self.parent()?; let path: PathBuf = self.env.parent_base().join(parent); if path.is_dir() { return Ok(path); } // check if there's a similar parent dir with different capitalization let parentsdir = self.env.parent_base().read_dir()?; for subdir in parentsdir { let dir = subdir?; let parentname = dir.file_name(); if parentname.to_string_lossy().to_lowercase() == parent.to_lowercase() { return Err(anyhow!( "Unable to find parent device '{}'. Did you mean '{}'?", parent, parentname.to_string_lossy() )); } } Err(anyhow!("Unable to find parent device '{}'", parent)) } fn create(&mut self) -> Result<()> { debug!("Creating mdev {:?}", self.uuid); let parent = self.parent()?; let mdev_type = self.mdev_type()?; let mut existing = MDev::new(self.env, self.uuid); if existing.load_from_sysfs().is_ok() && existing.active { if existing.parent != self.parent { return Err(anyhow!("Device exists under different parent")); } if existing.mdev_type != self.mdev_type { return Err(anyhow!("Device exists with different type")); } return Err(anyhow!("Device already exists")); } let mut path = self.find_parent_dir()?; path.push("mdev_supported_types"); debug!("Checking parent for mdev support: {:?}", path); if !path.is_dir() { return Err(anyhow!( "Parent {} is not currently registered for mdev support", parent )); } path.push(mdev_type); debug!("Checking parent for mdev type {}: {:?}", mdev_type, path); if !path.is_dir() { return Err(anyhow!( "Parent {} does not support mdev type {}", parent, mdev_type )); } path.push("available_instances"); debug!("Checking available instances: {:?}", path); let avail: i32 = fs::read_to_string(&path)?.trim().parse()?; debug!("Available instances: {}", avail); if avail == 0 { return Err(anyhow!( "No available instances of {} on {}", mdev_type, parent )); } path.pop(); path.push("create"); debug!("Creating mediated device: {:?} -> {:?}", self.uuid, path); match fs::write(path, self.uuid.hyphenated().to_string()) { Ok(_) => { self.active = true; Ok(()) } Err(e) => Err(e).with_context(|| { format!( "Failed to create mdev {}, type {} on {}", self.uuid.hyphenated(), mdev_type, parent ) }), } } pub fn start(&mut self) -> Result<()> { self.create()?; debug!("Setting attributes for mdev {:?}", self.uuid); for (k, v) in self.attrs.iter() { if let Err(e) = write_attr(&self.path(), k, v) { self.stop()?; return Err(e); } } Ok(()) } pub fn write_config(&self) -> Result<()> { let jsonstring = serde_json::to_string_pretty(&self.to_json(false)?)?; let path = self.persist_path().unwrap(); let parentdir = path.parent().unwrap(); debug!("Ensuring parent directory {:?} exists", parentdir); fs::create_dir_all(parentdir)?; debug!("Writing config for {:?} to {:?}", self.uuid, path); fs::write(path, jsonstring.as_bytes()) .with_context(|| format!("Failed to write config for device {:?}", self.uuid)) } pub fn define(&self) -> Result<()> { self.write_config() } pub fn undefine(&mut self) -> Result<()> { let p = self .persist_path() .ok_or_else(|| anyhow!("Failed to undefine {}", self.uuid.hyphenated().to_string()))?; fs::remove_file(&p).with_context(|| format!("Failed to remove file {:?}", p))?; Ok(()) } fn attribute_hint(&self) -> String { match self.attrs.is_empty() { true => format!("Device {} has no attributes", self.uuid.hyphenated()), false => self.fmt_attrs(), } } pub fn add_attribute( &mut self, name: String, value: String, index: Option, ) -> Result<()> { match index { Some(i) => { if i > self.attrs.len() { return Err(anyhow!( "Attribute index {} is invalid\n{}", i, self.attribute_hint() )); } self.attrs.insert(i, (name, value)); } None => self.attrs.push((name, value)), } Ok(()) } pub fn delete_attribute(&mut self, index: Option) -> Result<()> { match index { Some(i) => { if i >= self.attrs.len() { return Err(anyhow!( "Attribute index {} is invalid\n{}", i, self.attribute_hint() )); } self.attrs.remove(i); } None => { self.attrs.pop(); } } Ok(()) } } fn canonical_basename>(path: P) -> Result { let path = fs::canonicalize(path)?; let fname = path.file_name(); if fname.is_none() { return Err(anyhow!("Invalid path")); } let fname = fname.unwrap().to_str(); match fname { Some(x) => Ok(x.to_string()), None => Err(anyhow!("Invalid file name")), } } fn write_attr(basepath: &Path, attr: &str, val: &str) -> Result<()> { debug!("Writing attribute '{}' -> '{}'", attr, val); let path = basepath.join(attr); if !path.exists() { return Err(anyhow!("Invalid attribute '{}'", attr)); } fs::write(path, val).with_context(|| format!("Failed to write {} to attribute {}", val, attr)) } /// Representation of a mediated device type #[derive(Debug, Clone)] pub struct MDevType { pub parent: String, pub typename: String, pub available_instances: i32, pub device_api: String, pub name: String, pub description: String, } impl MDevType { pub fn new() -> MDevType { MDevType { parent: String::new(), typename: String::new(), available_instances: 0, device_api: String::new(), name: String::new(), description: String::new(), } } pub fn to_json(&self) -> Result { let mut jsonobj = serde_json::json!({ "available_instances": self.available_instances, "device_api": self.device_api, }); if !self.name.is_empty() { jsonobj.as_object_mut().unwrap().insert( "name".to_string(), serde_json::Value::String(self.name.clone()), ); } if !self.description.is_empty() { jsonobj.as_object_mut().unwrap().insert( "description".to_string(), serde_json::Value::String(self.description.clone()), ); } Ok(serde_json::json!({ &self.typename: jsonobj })) } } mdevctl-mdevctl-54db334/src/tests.rs000066400000000000000000002516231454705020100174440ustar00rootroot00000000000000use anyhow::{anyhow, Result}; use log::info; use nix::sys::wait::waitpid; use nix::unistd::{fork, ForkResult}; use std::collections::BTreeMap; use std::env; use std::fs; use std::path::{Path, PathBuf}; use std::sync::Mutex; use tempfile::Builder; use tempfile::TempDir; use uuid::Uuid; use crate::callouts::*; use crate::environment::Environment; use crate::logger::logger; use crate::mdev::MDev; const TEST_DATA_DIR: &str = "tests"; fn init() { let _ = logger().is_test(true).try_init(); } #[derive(PartialEq, Clone, Copy)] enum Expect<'a> { Pass, Fail(Option<&'a str>), } #[derive(Debug)] struct TestEnvironment { datapath: PathBuf, scratch: TempDir, name: String, case: String, callout_scripts: Mutex, } impl Environment for TestEnvironment { fn root(&self) -> &Path { self.scratch.path() } fn find_script(&self, dev: &MDev) -> Option { return self .callout_scripts .lock() .unwrap() .find_versioned_script(dev); } } impl TestEnvironment { pub fn new(testname: &str, testcase: &str) -> TestEnvironment { let path: PathBuf = [TEST_DATA_DIR, testname].iter().collect(); let scratchdir = Builder::new().prefix("mdevctl-test").tempdir().unwrap(); let test = TestEnvironment { datapath: path, scratch: scratchdir, name: testname.to_owned(), case: testcase.to_owned(), callout_scripts: Mutex::new(CalloutScriptCache::new()), }; // populate the basic directories in the environment fs::create_dir_all(test.mdev_base()).expect("Unable to create mdev_base"); fs::create_dir_all(test.config_base()).expect("Unable to create config_base"); fs::create_dir_all(test.parent_base()).expect("Unable to create parent_base"); for dir in test.callout_dirs() { fs::create_dir_all(&dir) .expect(format!("Unable to create callout_dir {:?}", &dir).as_str()); } for dir in test.notification_dirs() { fs::create_dir_all(&dir) .expect(format!("Unable to create notification_dir '{:?}'", &dir).as_str()); } info!("---- Running test '{}/{}' ----", testname, testcase); test } // set up a few files in the test environment to simulate an defined mediated device fn populate_defined_device(&self, uuid: &str, parent: &str, filename: &str) { let jsonfile = self.datapath.join(filename); let parentdir = self.config_base().join(parent); fs::create_dir_all(&parentdir).expect("Unable to setup parent dir"); let deffile = parentdir.join(uuid); assert!(jsonfile.exists()); assert!(!deffile.exists()); fs::copy(jsonfile, deffile).expect("Unable to copy device def"); } // set up a few files in the test environment to simulate an active mediated device fn populate_active_device(&self, uuid: &str, parent: &str, mdev_type: &str) { use std::os::unix::fs::symlink; let (parentdir, parenttypedir) = self.populate_parent_device(parent, mdev_type, 1, "", "", None); let parentdevdir = parentdir.join(uuid); fs::create_dir_all(&parentdevdir).expect("Unable to setup parent device dir"); let devdir = self.mdev_base().join(uuid); fs::create_dir_all(&devdir.parent().unwrap()).expect("Unable to setup mdev dir"); symlink(&parentdevdir, &devdir).expect("Unable to setup mdev dir"); let typefile = devdir.join("mdev_type"); symlink(&parenttypedir, &typefile).expect("Unable to setup mdev type"); } // set up a script in the test environment to simulate a callout fn populate_callout_script(&self, filename: &str) { self.populate_callout_script_full(filename, None, true) } // set up a script in the test environment to simulate a callout fn populate_callout_script_full( &self, filename: &str, destname: Option<&str>, default_dir: bool, ) { let calloutscriptdir: PathBuf = [TEST_DATA_DIR, "callouts"].iter().collect(); let calloutscript = calloutscriptdir.join(filename); let dest = match default_dir { true => self.callout_dir(), false => self.old_callout_dir(), } .join(destname.unwrap_or(filename)); assert!(calloutscript.exists()); /* Because the test suite is multi-threaded, we end up having the same flaky failures * described in this bug: https://github.com/golang/go/issues/22315. When we copy the * callout script into the test environment, another thread might be in the middle of * forking. This fork would then inherit the open writable file descriptor from the parent. * If that child process file descriptor stays open until we try to execute this callout * script, the script will fail to run and we'll get an ETXTBSY error from the OS. In order * to avoid this, we need to avoid the possibility of having any open writable file * descriptors to executable files in the parent process that could be inherited by forks * in other threads. Copying executable files in a child process avoid this. */ match unsafe { fork() }.expect("failed to fork") { ForkResult::Parent { child } => { waitpid(child, None).expect("Failed to wait for child"); } ForkResult::Child => { fs::copy(calloutscript, &dest).expect("Unable to copy callout script"); unsafe { libc::_exit(0); } } } } // set up a few files in the test environment to simulate a parent device that supports // mediated devices fn populate_parent_device( &self, parent: &str, supported_type: &str, instances: i32, device_api: &str, name: &str, description: Option<&str>, ) -> (PathBuf, PathBuf) { let parentdir = self.parent_base().join(parent); let parenttypedir = parentdir.join("mdev_supported_types").join(supported_type); fs::create_dir_all(&parenttypedir).expect("Unable to setup mdev parent type"); let instancefile = parenttypedir.join("available_instances"); fs::write(instancefile, format!("{}", instances)) .expect("Unable to write available_instances"); let apifile = parenttypedir.join("device_api"); fs::write(apifile, format!("{}", device_api)).expect("Unable to write device_api"); let namefile = parenttypedir.join("name"); fs::write(namefile, format!("{}", name)).expect("Unable to write name"); if let Some(desc) = description { let descfile = parenttypedir.join("description"); fs::write(descfile, format!("{}", desc)).expect("Unable to write description"); } (parentdir, parenttypedir) } fn compare_to_file(&self, filename: &str, actual: &str) { let path = self.datapath.join(filename); let flag = get_flag(REGEN_FLAG); if flag { regen(&path, actual).expect("Failed to regenerate expected output"); } let expected = fs::read_to_string(path).unwrap_or_else(|e| { if e.kind() == std::io::ErrorKind::NotFound { println!( "File {:?} not found, run tests with {}=1 to automatically \ generate expected output", filename, REGEN_FLAG ); } Default::default() }); assert_eq!(expected, actual); } fn load_from_json<'a>(&'a self, uuid: &str, parent: &str, filename: &str) -> Result> { let path = self.datapath.join(filename); let uuid = Uuid::parse_str(uuid); assert!(uuid.is_ok()); let uuid = uuid.unwrap(); let mut dev = MDev::new(self, uuid); let jsonstr = fs::read_to_string(path)?; let jsonval: serde_json::Value = serde_json::from_str(&jsonstr)?; dev.load_from_json(parent.to_string(), &jsonval)?; Ok(dev) } fn assert_result( &self, res: Result, expect: Expect, msg: Option<&str>, ) -> Result { let mut testname = format!("{}/{}", self.name, self.case); if let Some(msg) = msg { testname = format!("{}/{}", testname, msg); } match expect { Expect::Fail(msg) => { let e = res.expect_err(format!("Expected {} to fail", testname).as_str()); if let Some(msg) = msg { assert_eq!(msg, e.to_string()); } Err(anyhow!(e)) } Expect::Pass => Ok(res.expect(format!("Expected {} to pass", testname).as_str())), } } } fn get_flag(varname: &str) -> bool { match env::var(varname) { Err(_) => { return false; } Ok(s) => match s.trim().parse::() { Err(_) => return false, Ok(n) => return n > 0, }, } } fn regen(filename: &PathBuf, data: &str) -> Result<()> { let parentdir = filename.parent().unwrap(); fs::create_dir_all(parentdir)?; fs::write(filename, data.as_bytes()) .and_then(|_| { println!("Regenerated expected data file {:?}", filename); Ok(()) }) .map_err(|err| err.into()) } const REGEN_FLAG: &str = "MDEVCTL_TEST_REGENERATE_OUTPUT"; fn test_load_json_helper(uuid: &str, parent: &str, expect: Expect) { let test = TestEnvironment::new("load-json", uuid); let res = test.load_from_json(uuid, parent, &format!("{}.in", uuid)); if let Ok(dev) = test.assert_result(res, expect, None) { let jsonval = dev.to_json(false).unwrap(); let jsonstr = serde_json::to_string_pretty(&jsonval).unwrap(); test.compare_to_file(&format!("{}.out", uuid), &jsonstr); assert_eq!(uuid, dev.uuid.hyphenated().to_string()); assert_eq!(Some(parent.to_string()), dev.parent); } } #[test] fn test_load_json() { init(); test_load_json_helper( "c07ab7b2-8aa2-427a-91c6-ffc949bb77f9", "0000:00:02.0", Expect::Pass, ); test_load_json_helper( "783e6dbb-ea0e-411f-94e2-717eaad438bf", "0001:00:03.1", Expect::Pass, ); test_load_json_helper( "5269fe7a-18d1-48ad-88e1-3fda4176f536", "0000:00:03.0", Expect::Pass, ); test_load_json_helper( "5269fe7a-18d1-48ad-88e1-3fda4176f536", "0000:00:03.0", Expect::Pass, ); // json file has malformed attributes - an array of one object with multiple fields test_load_json_helper( "b6f7e33f-ea28-4f9d-8c42-797ff0ec2888", "0000:00:03.0", Expect::Fail(None), ); // json file has malformed attributes - an array of strings test_load_json_helper( "fe7a39db-973b-47b4-9b77-1d7b97267d59", "0000:00:03.0", Expect::Fail(None), ); // json file has malformed attributes - no array test_load_json_helper( "37ccb149-a0ce-49e3-8391-a952ef07bdc2", "0000:00:03.0", Expect::Fail(None), ); } fn test_define_command_callout( testname: &str, expect: Expect, uuid: Option, parent: Option, mdev_type: Option, force: bool, setupfn: F, ) where F: Fn(&TestEnvironment), { let test = TestEnvironment::new("define-callouts", testname); setupfn(&test); use crate::define_command; let res = define_command(&test, uuid, false, parent, mdev_type, None, force); let _ = test.assert_result(res, expect, None); } fn test_define_helper( testname: &str, expect: Expect, uuid: Option, auto: bool, parent: Option, mdev_type: Option, jsonfile: Option, setupfn: F, ) where F: Fn(&TestEnvironment), { use crate::define_command_helper; let test = TestEnvironment::new("define", testname); // load the jsonfile from the test path. let jsonfile = match jsonfile { Some(f) => Some(test.datapath.join(f)), None => None, }; setupfn(&test); let res = define_command_helper(&test, uuid, auto, parent, mdev_type, jsonfile); if let Ok(def) = test.assert_result(res, expect, None) { let path = def.persist_path().unwrap(); assert!(!path.exists()); def.define().expect("Failed to define device"); assert!(path.exists()); assert!(def.is_defined()); let filecontents = fs::read_to_string(&path).unwrap(); test.compare_to_file(&format!("{}.expected", testname), &filecontents); } } #[test] fn test_define() { init(); const DEFAULT_UUID: &str = "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9"; const DEFAULT_PARENT: &str = "0000:00:03.0"; test_define_helper( "no-uuid-no-type", Expect::Fail(None), None, true, Some(DEFAULT_PARENT.to_string()), None, None, |_| {}, ); // if no uuid is specified, one will be auto-generated test_define_helper( "no-uuid", Expect::Pass, None, true, Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), None, |_| {}, ); // specify autostart test_define_helper( "uuid-auto", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).ok(), true, Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), None, |_| {}, ); // specify manual start test_define_helper( "uuid-manual", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).ok(), false, Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), None, |_| {}, ); // invalid to specify an separate mdev_type if defining via jsonfile test_define_helper( "jsonfile-type", Expect::Fail(None), Uuid::parse_str(DEFAULT_UUID).ok(), false, Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), Some(PathBuf::from("defined.json")), |_| {}, ); // specifying via jsonfile properly test_define_helper( "jsonfile", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).ok(), false, Some(DEFAULT_PARENT.to_string()), None, Some(PathBuf::from("defined.json")), |_| {}, ); // If uuid is already active, specifying mdev_type will result in an error test_define_helper( "uuid-running-no-parent", Expect::Fail(None), Uuid::parse_str(DEFAULT_UUID).ok(), false, None, Some("i915-GVTg_V5_4".to_string()), None, |test| { test.populate_active_device(DEFAULT_UUID, DEFAULT_PARENT, "i915-GVTg_V5_4"); }, ); // If uuid is already active, should use mdev_type from running mdev test_define_helper( "uuid-running-no-type", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).ok(), false, Some(DEFAULT_PARENT.to_string()), None, None, |test| { test.populate_active_device(DEFAULT_UUID, DEFAULT_PARENT, "i915-GVTg_V5_4"); }, ); // ok to define a device with the same uuid as a running device even if they have different // parent devices test_define_helper( "uuid-running-diff-parent", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).ok(), false, Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), None, |test| { test.populate_active_device(DEFAULT_UUID, "0000:00:02.0", "i915-GVTg_V5_4"); }, ); // ok to define a device with the same uuid as a running device even if they have different // mdev_types test_define_helper( "uuid-running-diff-type", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).ok(), false, Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), None, |test| { test.populate_active_device(DEFAULT_UUID, DEFAULT_PARENT, "different_type"); }, ); // defining a device that is already defined should result in an error test_define_helper( "uuid-already-defined", Expect::Fail(None), Uuid::parse_str(DEFAULT_UUID).ok(), false, Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), None, |test| { test.populate_defined_device(DEFAULT_UUID, DEFAULT_PARENT, "defined.json"); }, ); // test define with callouts test_define_command_callout( "define-with-callout-all-pass", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), false, |test| { test.populate_callout_script("rc0.sh"); }, ); test_define_command_callout( "define-with-callout-all-fail", Expect::Fail(None), Uuid::parse_str(DEFAULT_UUID).ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), false, |test| { test.populate_callout_script("rc1.sh"); }, ); // test define with get attributes test_define_command_callout( "define-with-callout-all-good-json", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), false, |test| { test.populate_active_device(DEFAULT_UUID, DEFAULT_PARENT, "i915-GVTg_V5_4"); test.populate_callout_script("good-json.sh"); }, ); test_define_command_callout( "define-with-callout-all-bad-json", Expect::Fail(None), Uuid::parse_str(DEFAULT_UUID).ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), false, |test| { test.populate_active_device(DEFAULT_UUID, DEFAULT_PARENT, "i915-GVTg_V5_4"); test.populate_callout_script("bad-json.sh"); }, ); test_define_command_callout( "define-with-callout-all-fail-force", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), true, |test| { test.populate_callout_script("rc1.sh"); }, ); // test define with versioning callouts // uuid=11111111-1111-0000-0000-000000000000 has a supported version test_define_command_callout( "define-with-version-callout-all-pass", Expect::Pass, Uuid::parse_str("11111111-1111-0000-0000-000000000000").ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), false, |test| { test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_define_command_callout( "define-with-version-callout-all-fail", Expect::Fail(None), Uuid::parse_str("11111111-1111-0000-0000-000000000000").ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), false, |test| { test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); test_define_command_callout( "define-with-version-callout-multiple-with-version-pass", Expect::Pass, Uuid::parse_str("11111111-1111-0000-0000-000000000000").ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), false, |test| { test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_define_command_callout( "define-with-version-callout-multiple-with-version-pass2", Expect::Pass, Uuid::parse_str("11111111-1111-0000-0000-000000000000").ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), false, |test| { test.populate_callout_script("rc1.sh"); // no versioning error test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_define_command_callout( "define-with-version-callout-multiple-with-version-fail", Expect::Fail(None), Uuid::parse_str("11111111-1111-0000-0000-000000000000").ok(), Some(DEFAULT_PARENT.to_string()), Some("i915-GVTg_V5_4".to_string()), false, |test| { test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); } fn test_modify_helper( testname: &str, expect: Expect, uuid: &str, parent: Option, mdev_type: Option, addattr: Option, delattr: bool, index: Option, value: Option, auto: bool, manual: bool, live: bool, defined: bool, jsonfile: Option, force: bool, setupfn: F, ) where F: Fn(&TestEnvironment), { use crate::modify_command; let test = TestEnvironment::new("modify", testname); // load the jsonfile from the test path. let jsonfile = match jsonfile { Some(f) => Some(test.datapath.join(f)), None => None, }; setupfn(&test); let uuid = Uuid::parse_str(uuid).unwrap(); let result = modify_command( &test, uuid, parent.clone(), mdev_type, addattr, delattr, index, value, auto, manual, live, defined, jsonfile, force, ); if test.assert_result(result, expect, None).is_err() { return; } let def = crate::get_defined_device(&test, uuid, parent.as_ref()) .expect("Couldn't find defined device"); let path = def.persist_path().unwrap(); assert!(path.exists()); assert!(def.is_defined()); let filecontents = fs::read_to_string(&path).unwrap(); test.compare_to_file(&format!("{}.expected", testname), &filecontents); } fn test_modify_defined_active_helper( testname: &str, expect: Expect, uuid: &str, parent: Option, mdev_type: Option, addattr: Option, delattr: bool, index: Option, value: Option, auto: bool, manual: bool, live: bool, defined: bool, jsonfile: Option, force: bool, setupfn: F, ) where F: Fn(&TestEnvironment), { use crate::modify_command; let test = TestEnvironment::new("modify", testname); // load the jsonfile from the test path. let jsonfile = match jsonfile { Some(f) => Some(test.datapath.join(f)), None => None, }; setupfn(&test); let uuid = Uuid::parse_str(uuid).unwrap(); let result = modify_command( &test, uuid, parent.clone(), mdev_type, addattr, delattr, index, value, auto, manual, live, defined, jsonfile, force, ); if test .assert_result(result, expect, Some("modify command")) .is_err() { return; } let def_active = crate::get_active_device(&test, uuid, parent.as_ref()) .expect("Couldn't find defined device"); assert!(def_active.active); let def_json = serde_json::to_string_pretty( &def_active .to_json(false) .expect("Couldn't get json from active device"), ) .expect("Couldn't get json from active device"); test.compare_to_file(&format!("{}.active.expected", testname), &def_json); let def = crate::get_defined_device(&test, uuid, parent.as_ref()) .expect("Couldn't find defined device"); let path = def.persist_path().unwrap(); assert!(path.exists()); assert!(def.is_defined()); let filecontents = fs::read_to_string(&path).unwrap(); test.compare_to_file(&format!("{}.defined.expected", testname), &filecontents); } #[test] fn test_modify() { init(); const UUID: &str = "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9"; const PARENT: &str = "0000:00:03.0"; test_modify_helper( "device-not-defined", Expect::Fail(None), UUID, None, None, None, false, None, None, false, false, false, false, None, false, |_| {}, ); test_modify_helper( "auto", Expect::Pass, UUID, Some(PARENT.to_string()), None, None, false, None, None, true, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_modify_helper( "manual", Expect::Pass, UUID, Some(PARENT.to_string()), None, None, false, None, None, false, true, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_modify_helper( "delattr", Expect::Pass, UUID, Some(PARENT.to_string()), None, None, true, Some(2), None, false, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_modify_helper( "delattr-noindex", Expect::Pass, UUID, Some(PARENT.to_string()), None, None, true, None, None, false, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_modify_helper( "addattr", Expect::Pass, UUID, Some(PARENT.to_string()), None, Some("added-attr".to_string()), false, Some(3), Some("added-attr-value".to_string()), false, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_modify_helper( "addattr-noindex", Expect::Pass, UUID, Some(PARENT.to_string()), None, Some("added-attr".to_string()), false, None, Some("added-attr-value".to_string()), false, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_modify_helper( "mdev_type", Expect::Pass, UUID, Some(PARENT.to_string()), Some("changed-mdev-type".to_string()), None, false, None, None, false, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_modify_helper( "multiple-noparent", Expect::Fail(None), UUID, None, None, None, false, None, None, true, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_defined_device(UUID, "0000:00:02.0", "defined.json"); }, ); test_modify_helper( "multiple-parent", Expect::Pass, UUID, Some(PARENT.to_string()), None, None, false, None, None, true, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_defined_device(UUID, "0000:00:02.0", "defined.json"); }, ); test_modify_helper( "auto-manual", Expect::Fail(None), UUID, Some(PARENT.to_string()), None, None, false, None, None, true, true, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); // specifying via jsonfile properly test_modify_helper( "jsonfile", Expect::Pass, UUID, Some(PARENT.to_string()), None, None, false, None, None, false, false, false, false, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); // callouts for device succeed test_modify_helper( "callout-pass", Expect::Pass, UUID, Some(PARENT.to_string()), None, None, false, None, None, true, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_callout_script("rc0.sh"); }, ); // callouts for device fail test_modify_helper( "callout-fail", Expect::Fail(None), UUID, Some(PARENT.to_string()), None, None, false, None, None, true, false, false, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_callout_script("rc1.sh"); }, ); // override a callout failure test_modify_helper( "callout-fail-force", Expect::Pass, UUID, Some(PARENT.to_string()), None, None, false, None, None, true, false, false, false, None, true, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_callout_script("rc1.sh"); }, ); // test modify with versioning callouts // uuid=11111111-1111-0000-0000-000000000000 has a supported version const UUID_VER: &str = "11111111-1111-0000-0000-000000000000"; test_modify_helper( "modify-jsonfile-with-version-callout-all-pass", Expect::Pass, UUID_VER, Some(PARENT.to_string()), None, None, false, None, None, false, false, false, false, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_modify_helper( "modify-jsonfile-with-version-callout-all-fail", Expect::Fail(None), UUID_VER, Some(PARENT.to_string()), None, None, false, None, None, false, false, false, false, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); test_modify_helper( "modify-jsonfile-with-version-callout-multiple-with-version-pass", Expect::Pass, UUID_VER, Some(PARENT.to_string()), None, None, false, None, None, false, false, false, false, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_modify_helper( "modify-jsonfile-with-version-callout-multiple-with-version-pass2", Expect::Pass, UUID_VER, Some(PARENT.to_string()), None, None, false, None, None, false, false, false, false, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("rc1.sh"); // no versioning error test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_modify_helper( "modify-jsonfile-with-version-callout-multiple-with-version-fail", Expect::Fail(None), UUID_VER, Some(PARENT.to_string()), None, None, false, None, None, false, false, false, false, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); // uuid=11111111-1111-0000-0000-000000000000 has a supported version const UUID_NO_LIVE: &str = "11111111-1111-0000-0000-000000000000"; const UUID_LIVE: &str = "11111111-1111-1111-0000-000000000000"; test_modify_helper( "live-event-supported", Expect::Pass, UUID_LIVE, Some(PARENT.to_string()), None, None, false, None, None, false, false, true, false, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_LIVE, PARENT, "defined.json"); test.populate_active_device(UUID_LIVE, PARENT, "vfio_ap-passthrough"); test.populate_callout_script("live-rc0.sh"); }, ); test_modify_helper( "live-event-unsupported-by-callout", Expect::Fail(None), UUID_NO_LIVE, Some(PARENT.to_string()), None, None, false, None, None, false, false, true, false, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_NO_LIVE, PARENT, "defined.json"); test.populate_active_device(UUID_NO_LIVE, PARENT, "vfio_ap-passthrough"); test.populate_callout_script("live-rc0.sh"); }, ); test_modify_helper( "live-unsupported-script-without-version-support", Expect::Fail(Some( format!("'live' option must be used with 'jsonfile' option").as_str(), )), UUID, Some(PARENT.to_string()), None, None, false, None, None, false, false, true, false, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_active_device(UUID, PARENT, "vfio_ap-passthrough"); test.populate_callout_script("live-rc0.sh"); }, ); test_modify_helper( "live-supported-but-fails", Expect::Fail(None), UUID_LIVE, Some(PARENT.to_string()), None, None, false, None, None, false, false, true, false, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_LIVE, PARENT, "defined.json"); test.populate_active_device(UUID_LIVE, PARENT, "vfio_ap-passthrough"); test.populate_callout_script("live-rc1.sh"); }, ); test_modify_helper( "live-fail-without-jsonfile", Expect::Fail(Some( format!("'live' option must be used with 'jsonfile' option").as_str(), )), UUID_LIVE, Some(PARENT.to_string()), None, None, false, None, None, false, false, true, false, None, false, |test| { test.populate_defined_device(UUID_LIVE, PARENT, "defined.json"); test.populate_active_device(UUID_LIVE, PARENT, "vfio_ap-passthrough"); test.populate_callout_script("live-rc0.sh"); }, ); test_modify_defined_active_helper( "live-defined-supported", Expect::Pass, UUID_LIVE, Some(PARENT.to_string()), None, None, false, None, None, false, false, true, true, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_LIVE, PARENT, "defined.json"); test.populate_active_device(UUID_LIVE, PARENT, "vfio_ap-passthrough"); test.populate_callout_script("modify-active.sh"); }, ); test_modify_defined_active_helper( "live-defined-live-event-unsupported", Expect::Fail(None), UUID_NO_LIVE, Some(PARENT.to_string()), None, None, false, None, None, false, false, true, true, Some(PathBuf::from("modified.json")), false, |test| { test.populate_defined_device(UUID_NO_LIVE, PARENT, "defined.json"); test.populate_active_device(UUID_NO_LIVE, PARENT, "vfio_ap-passthrough"); test.populate_callout_script("modify-active.sh"); }, ); test_modify_defined_active_helper( "defined-only", Expect::Pass, UUID, Some(PARENT.to_string()), None, Some("added-attr".to_string()), false, None, Some("added-attr-value".to_string()), false, false, false, true, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_active_device(UUID, PARENT, "vfio_ap-passthrough"); test.populate_callout_script("modify-active.sh"); }, ); } fn test_undefine_helper( testname: &str, expect: Expect, uuid: &str, parent: Option, force: bool, setupfn: F, ) where F: Fn(&TestEnvironment), { let test = TestEnvironment::new("undefine", testname); setupfn(&test); let uuid = Uuid::parse_str(uuid).unwrap(); let result = crate::undefine_command(&test, uuid, parent.clone(), force); if test.assert_result(result, expect, None).is_err() { return; } let devs = crate::defined_devices(&test, Some(&uuid), parent.as_ref()) .expect("failed to query defined devices"); assert!(devs.is_empty()); } #[test] fn test_undefine() { init(); const UUID: &str = "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9"; const PARENT: &str = "0000:00:03.0"; const PARENT2: &str = "0000:00:02.0"; test_undefine_helper( "single", Expect::Pass, UUID, Some(PARENT.to_string()), false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); // if multiple devices with the same uuid exists, the one with the matching parent should // be undefined test_undefine_helper( "multiple-parent", Expect::Pass, UUID, Some(PARENT.to_string()), false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_defined_device(UUID, PARENT2, "defined.json"); }, ); // if multiple devices with the same uuid exists and no parent is specified, they should // all be undefined test_undefine_helper( "multiple-noparent", Expect::Pass, UUID, None, false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_defined_device(UUID, PARENT2, "defined.json"); }, ); test_undefine_helper( "nonexistent", Expect::Fail(None), UUID, Some(PARENT.to_string()), false, |_| {}, ); // callout script always returns with RC=0 test_undefine_helper( "single-callout-all-pass", Expect::Pass, UUID, Some(PARENT.to_string()), false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_callout_script("rc0.sh"); }, ); // callout script rejects in pre event undefine with RC=1 test_undefine_helper( "single-callout-pre-fail", Expect::Fail(None), UUID, Some(PARENT.to_string()), false, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_callout_script("rc1.sh"); }, ); // force command even with callout script failure test_undefine_helper( "single-callout-pre-fail-force", Expect::Pass, UUID, Some(PARENT.to_string()), true, |test| { test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_callout_script("rc1.sh"); }, ); // test define with versioning callouts // uuid=11111111-1111-0000-0000-000000000000 has a supported version const UUID_VER: &str = "11111111-1111-0000-0000-000000000000"; test_undefine_helper( "undefine-single-with-version-callout-all-pass", Expect::Pass, UUID_VER, Some(PARENT.to_string()), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_undefine_helper( "undefine-single-with-version-callout-all-fail", Expect::Fail(None), UUID_VER, Some(PARENT.to_string()), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); test_undefine_helper( "define-with-version-callout-multiple-with-version-pass", Expect::Pass, UUID_VER, Some(PARENT.to_string()), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_undefine_helper( "define-with-version-callout-multiple-with-version-pass2", Expect::Pass, UUID_VER, Some(PARENT.to_string()), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("rc1.sh"); // no versioning error test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_undefine_helper( "define-with-version-callout-multiple-with-version-fail", Expect::Fail(None), UUID_VER, Some(PARENT.to_string()), false, |test| { test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); } fn test_start_command_callout( testname: &str, expect: Expect, uuid: Option, parent: Option, mdev_type: Option, force: bool, setupfn: F, ) where F: Fn(&TestEnvironment), { let test = TestEnvironment::new("start", testname); setupfn(&test); use crate::start_command; let res = start_command(&test, uuid, parent, mdev_type, None, force); let _ = test.assert_result(res, expect, None); } fn test_start_helper( testname: &str, expect_setup: Expect, expect_execute: Expect, uuid: Option, parent: Option, mdev_type: Option, jsonfile: Option, setupfn: F, ) where F: Fn(&TestEnvironment), { let test = TestEnvironment::new("start", testname); setupfn(&test); let uuid = uuid.map(|s| Uuid::parse_str(s.as_ref()).unwrap()); let result = crate::start_command_helper(&test, uuid, parent, mdev_type, jsonfile); if let Ok(mut dev) = test.assert_result(result, expect_setup, Some("setup command")) { let result = dev.start(); if test .assert_result(result, expect_execute, Some("execute command")) .is_err() { return; } let create_path = test .parent_base() .join(dev.parent.unwrap()) .join("mdev_supported_types") .join(dev.mdev_type.unwrap()) .join("create"); assert!(create_path.exists()); if uuid.is_some() { assert_eq!(uuid.unwrap(), dev.uuid); } let contents = fs::read_to_string(create_path).expect("Unable to read 'create' file"); assert_eq!(dev.uuid.hyphenated().to_string(), contents); } } #[test] fn test_start() { init(); const UUID: &str = "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9"; const PARENT: &str = "0000:00:03.0"; const PARENT2: &str = "0000:00:02.0"; const PARENT3: &str = "0000:2b:00.0"; const MDEV_TYPE: &str = "arbitrary_type"; test_start_helper( "uuid-type-parent", Expect::Pass, Expect::Pass, Some(UUID.to_string()), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); }, ); test_start_helper( "no-uuid", Expect::Pass, Expect::Pass, None, Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); }, ); test_start_helper( "no-uuid-no-parent", Expect::Fail(None), Expect::Fail(None), None, None, Some(MDEV_TYPE.to_string()), None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); }, ); test_start_helper( "no-uuid-no-type", Expect::Fail(None), Expect::Fail(None), None, Some(PARENT.to_string()), None, None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); }, ); test_start_helper( "no-parent", Expect::Fail(None), Expect::Fail(None), Some(UUID.to_string()), None, Some(MDEV_TYPE.to_string()), None, |_| {}, ); // should fail if there is no defined device with the given uuid test_start_helper( "no-type", Expect::Fail(None), Expect::Fail(None), Some(UUID.to_string()), Some(PARENT.to_string()), None, None, |_| {}, ); // should pass if there is a defined device with the given uuid test_start_helper( "no-type-defined", Expect::Pass, Expect::Pass, Some(UUID.to_string()), Some(PARENT.to_string()), None, None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_start_helper( "no-type-parent-defined", Expect::Pass, Expect::Pass, Some(UUID.to_string()), None, None, None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_start_helper( "defined-with-type", Expect::Pass, Expect::Pass, Some(UUID.to_string()), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_parent_device(PARENT2, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT2, "defined.json"); }, ); // if there are multiple defined devices with the same UUID, must disambiguate with parent test_start_helper( "defined-multiple-underspecified", Expect::Fail(None), Expect::Fail(None), Some(UUID.to_string()), None, None, None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_parent_device(PARENT2, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT2, "defined.json"); }, ); test_start_helper( "defined-multiple", Expect::Pass, Expect::Pass, Some(UUID.to_string()), Some(PARENT.to_string()), None, None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_parent_device(PARENT2, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT2, "defined.json"); }, ); // test specifying a uuid and a parent matching an existing defined device but with a different // type. See https://github.com/mdevctl/mdevctl/issues/38 test_start_helper( "defined-diff-type", Expect::Fail(None), Expect::Fail(None), Some(UUID.to_string()), Some(PARENT.to_string()), Some("wrong-type".to_string()), None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT, "defined.json"); }, ); test_start_helper( "already-running", Expect::Pass, Expect::Fail(None), Some(UUID.to_string()), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_active_device(UUID, PARENT, MDEV_TYPE); }, ); test_start_helper( "no-instances", Expect::Pass, Expect::Fail(None), Some(UUID.to_string()), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 0, "vfio-pci", "testdev", None); }, ); test_start_helper( "uuid-type-parent", Expect::Pass, Expect::Pass, Some(UUID.to_string()), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), None, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); }, ); test_start_command_callout( "defined-multiple-callout-success", Expect::Pass, Uuid::parse_str(UUID).ok(), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), false, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_parent_device(PARENT2, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT2, "defined.json"); test.populate_callout_script("rc0.sh"); }, ); test_start_command_callout( "defined-multiple-callout-fail", Expect::Fail(None), Uuid::parse_str(UUID).ok(), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), false, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_parent_device(PARENT2, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT2, "defined.json"); test.populate_callout_script("rc1.sh"); }, ); test_start_command_callout( "defined-multiple-callout-fail-force", Expect::Pass, Uuid::parse_str(UUID).ok(), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), true, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT, "defined.json"); test.populate_parent_device(PARENT2, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID, PARENT2, "defined.json"); test.populate_callout_script("rc1.sh"); }, ); test_start_helper( "missing-parent", Expect::Pass, Expect::Fail(Some( format!("Unable to find parent device '{}'", PARENT).as_str(), )), Some(UUID.to_string()), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), None, |_| {}, ); test_start_helper( "parent-case", Expect::Pass, Expect::Fail(Some( format!( "Unable to find parent device '{}'. Did you mean '{}'?", PARENT3.to_string().to_uppercase(), PARENT3.to_string() ) .as_str(), )), Some(UUID.to_string()), Some(PARENT3.to_string().to_uppercase()), Some(MDEV_TYPE.to_string()), None, |test| { test.populate_parent_device(PARENT3, MDEV_TYPE, 1, "vfio-pci", "test device", None); }, ); // TODO: test attributes -- difficult because executing the 'start' command by writing to // the 'create' file in sysfs does not automatically create the device file structure in // the temporary test environment, so writing the sysfs attribute files fails. // test start with versioning callouts // uuid=11111111-1111-0000-0000-000000000000 has a supported version const UUID_VER: &str = "11111111-1111-0000-0000-000000000000"; test_start_command_callout( "start-single-with-version-callout-pass", Expect::Pass, Uuid::parse_str(UUID_VER).ok(), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), false, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_start_command_callout( "start-single-with-version-callout-fail", Expect::Fail(None), Uuid::parse_str(UUID_VER).ok(), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), false, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); test_start_command_callout( "start-with-version-callout-multiple-with-version-pass", Expect::Pass, Uuid::parse_str(UUID_VER).ok(), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), false, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_start_command_callout( "start-with-version-callout-multiple-with-version-pass2", Expect::Pass, Uuid::parse_str(UUID_VER).ok(), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), false, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("rc1.sh"); // no versioning error test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_start_command_callout( "start-with-version-callout-multiple-with-version-fail", Expect::Fail(None), Uuid::parse_str(UUID_VER).ok(), Some(PARENT.to_string()), Some(MDEV_TYPE.to_string()), false, |test| { test.populate_parent_device(PARENT, MDEV_TYPE, 1, "vfio-pci", "test device", None); test.populate_defined_device(UUID_VER, PARENT, "defined.json"); test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); } fn test_stop_helper(testname: &str, expect: Expect, uuid: &str, force: bool, setupfn: F) where F: Fn(&TestEnvironment), { let test = TestEnvironment::new("stop", testname); setupfn(&test); let res = crate::stop_command(&test, Uuid::parse_str(uuid).unwrap(), force); if let Ok(_) = test.assert_result(res, expect, None) { let remove_path = test.mdev_base().join(uuid).join("remove"); assert!(remove_path.exists()); let contents = fs::read_to_string(remove_path).expect("Unable to read 'remove' file"); assert_eq!("1", contents); } } #[test] fn test_stop() { init(); const UUID: &str = "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9"; const PARENT: &str = "0000:00:03.0"; const MDEV_TYPE: &str = "arbitrary_type"; test_stop_helper("default", Expect::Pass, UUID, false, |t| { t.populate_active_device(UUID, PARENT, MDEV_TYPE) }); test_stop_helper("callout-success", Expect::Pass, UUID, false, |t| { t.populate_active_device(UUID, PARENT, MDEV_TYPE); t.populate_callout_script("rc0.sh") }); test_stop_helper("callout-fail", Expect::Fail(None), UUID, false, |t| { t.populate_active_device(UUID, PARENT, MDEV_TYPE); t.populate_callout_script("rc1.sh") }); test_stop_helper("callout-fail-force", Expect::Pass, UUID, true, |t| { t.populate_active_device(UUID, PARENT, MDEV_TYPE); t.populate_callout_script("rc1.sh") }); // test start with versioning callouts // uuid=11111111-1111-0000-0000-000000000000 has a supported version const UUID_VER: &str = "11111111-1111-0000-0000-000000000000"; test_stop_helper( "stop-single-callout-with-version-all-pass", Expect::Pass, UUID_VER, false, |test| { test.populate_active_device(UUID_VER, PARENT, MDEV_TYPE); test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_stop_helper( "stop-single-callout-with-version-all-fail", Expect::Fail(None), UUID_VER, false, |test| { test.populate_active_device(UUID_VER, PARENT, MDEV_TYPE); test.populate_callout_script("ver-rc1.sh"); // versioning }, ); test_stop_helper( "stop-single-callouts-mix-all-pass", Expect::Pass, UUID_VER, false, |test| { test.populate_active_device(UUID_VER, PARENT, MDEV_TYPE); test.populate_callout_script("rc1.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_stop_helper( "stop-single-callouts-mix-all-fail", Expect::Fail(None), UUID_VER, false, |test| { test.populate_active_device(UUID_VER, PARENT, MDEV_TYPE); test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc1.sh"); // versioning }, ); } #[test] fn test_invalid_files() { init(); const PARENT: &str = "0000:00:03.0"; const MDEV_TYPE: &str = "arbitrary_type"; // just make sure that the list command can deal with invalid files without panic-ing let test = TestEnvironment::new("invalid-files", "invalid-active"); test.populate_active_device("invalid-uuid-value", PARENT, MDEV_TYPE); let result = crate::list_command(&test, false, false, false, None, None); assert!(result.is_ok()); let test = TestEnvironment::new("invalid-files", "invalid-defined"); test.populate_defined_device("invalid-uuid-value", PARENT, "device.json"); let result = crate::list_command(&test, true, false, false, None, None); assert!(result.is_ok()); } fn test_list_helper( subtest: &str, expect: Expect, defined: bool, verbose: bool, uuid: Option, parent: Option, setupfn: F, ) where F: Fn(&TestEnvironment), { use crate::list_command_helper; let uuid = uuid.map(|s| Uuid::parse_str(s.as_ref()).unwrap()); let test = TestEnvironment::new("list", "default"); setupfn(&test); let res = list_command_helper(&test, defined, false, verbose, uuid, parent.clone()); if let Ok(output) = test.assert_result(res, expect, Some("json")) { test.compare_to_file(&format!("{}.text", subtest), &output); } let res = list_command_helper(&test, defined, true, verbose, uuid, parent.clone()); if let Ok(output) = test.assert_result(res, expect, Some("text")) { test.compare_to_file(&format!("{}.json", subtest), &output); } } #[test] fn test_list() { init(); const UUID: &[&str] = &[ "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9", "59e8b599-afdd-4766-a59e-415ef4f5a492", "4a0a190f-dcf3-4def-9342-c48768f0c940", "9f579710-6ffc-4201-987a-4ffa0fb1f3a5", "3eee6cd9-35ad-43bd-9be1-14ee2b7389c9", ]; const PARENT: &[&str] = &["0000:00:02.0", "0000:00:03.0"]; const MDEV_TYPE: &[&str] = &["arbitrary_type1", "arbitrary_type2"]; // first test with an empty environment -- nothing defined, nothing active test_list_helper( "active-none", Expect::Pass, false, false, None, None, |_| {}, ); test_list_helper( "defined-none", Expect::Pass, true, false, None, None, |_| {}, ); // now setup test environment with some active devices and some defined devices. Include // multiple parents, multiple types, some parents with multiple devices, some with same UUID on // different parents, etc let setup = |test: &TestEnvironment| { test.populate_active_device(UUID[0], PARENT[0], MDEV_TYPE[0]); test.populate_active_device(UUID[1], PARENT[1], MDEV_TYPE[1]); test.populate_defined_device(UUID[2], PARENT[0], "device2.json"); test.populate_defined_device(UUID[3], PARENT[1], "device1.json"); test.populate_defined_device(UUID[3], PARENT[0], "device1.json"); }; test_list_helper("active", Expect::Pass, false, false, None, None, setup); test_list_helper( "active-verbose", Expect::Pass, false, true, None, None, setup, ); test_list_helper( "active-parent", Expect::Pass, false, false, None, Some(PARENT[0].to_string()), setup, ); test_list_helper( "active-parent-verbose", Expect::Pass, false, true, None, Some(PARENT[0].to_string()), setup, ); test_list_helper( "active-uuid", Expect::Pass, false, false, Some(UUID[0].to_string()), None, setup, ); test_list_helper( "active-uuid-verbose", Expect::Pass, false, true, Some(UUID[0].to_string()), None, setup, ); test_list_helper( "active-uuid-parent", Expect::Pass, false, false, Some(UUID[0].to_string()), Some(PARENT[0].to_string()), setup, ); test_list_helper( "active-uuid-parent-verbose", Expect::Pass, false, true, Some(UUID[0].to_string()), Some(PARENT[0].to_string()), setup, ); test_list_helper("defined", Expect::Pass, true, false, None, None, setup); test_list_helper( "defined-verbose", Expect::Pass, true, true, None, None, setup, ); test_list_helper( "defined-parent", Expect::Pass, true, false, None, Some(PARENT[0].to_string()), setup, ); test_list_helper( "defined-parent-verbose", Expect::Pass, true, true, None, Some(PARENT[0].to_string()), setup, ); test_list_helper( "defined-uuid", Expect::Pass, true, false, Some(UUID[3].to_string()), None, setup, ); test_list_helper( "defined-uuid-verbose", Expect::Pass, true, true, Some(UUID[3].to_string()), None, setup, ); test_list_helper( "defined-uuid-parent", Expect::Pass, true, false, Some(UUID[3].to_string()), Some(PARENT[0].to_string()), setup, ); test_list_helper( "defined-uuid-parent-verbose", Expect::Pass, true, true, Some(UUID[3].to_string()), Some(PARENT[0].to_string()), setup, ); test_list_helper( "no-match-uuid", Expect::Pass, true, true, Some("466983a3-1240-4543-8d02-01c29a08fb0c".to_string()), None, setup, ); test_list_helper( "no-match-parent", Expect::Pass, true, true, None, Some("nonexistent".to_string()), setup, ); // test list with the Get Attributes callout test_list_helper( "active-callout", Expect::Pass, false, false, None, None, |test| { setup(test); test.populate_callout_script("good-json.sh"); }, ); // if a script returns an ill-formatted JSON, then then the output should be ignored test_list_helper( "active-callout-bad-json", Expect::Pass, false, false, None, None, |test| { setup(test); test.populate_callout_script("bad-json.sh"); }, ); } fn test_types_helper( test: &TestEnvironment, subtest: &str, expect: Expect, parent: Option, ) { use crate::types_command_helper; // test text output let res = types_command_helper(test, parent.clone(), false); if let Ok(output) = test.assert_result(res, expect, Some("text")) { test.compare_to_file(&format!("{}.text", subtest), &output); } // test JSON output let res = types_command_helper(test, parent.clone(), true); if let Ok(output) = test.assert_result(res, expect, Some("json")) { test.compare_to_file(&format!("{}.json", subtest), &output); } } #[test] fn test_types() { init(); let test = TestEnvironment::new("types", "default"); // test an empty environment without any devices that suppport mdevs test_types_helper(&test, "empty", Expect::Pass, None); // populate test environment with a variety of parent devices that support certain mdev types let mut parents = BTreeMap::new(); parents.insert( "0000:00:02.0", vec![ ("mdev_type1", 5, "vfio-pci", "name1", Some("description 1")), ("mdev_type2", 16, "vfio-pci", "name2", None), ("mdev_type3", 1, "vfio-pci", "name3", Some("description 3")), ], ); parents.insert( "0000:00:03.0", vec![ ("nvidia-155", 4, "vfio-pci", "GRID M10-2B", None), ("nvidia-36", 16, "vfio-pci", "GRID M10-0Q", None), ], ); parents.insert( "0.0.26ab", vec![("vfio_ccw-io", 4, "vfio_mdev", "name", Some("description"))], ); for (parent, types) in parents { for t in types { test.populate_parent_device(parent, t.0, t.1, t.2, t.3, t.4); } } test_types_helper(&test, "full", Expect::Pass, None); test_types_helper( &test, "parent-match-1", Expect::Pass, Some("0000:00:02.0".to_string()), ); test_types_helper( &test, "parent-match-2", Expect::Pass, Some("0000:00:03.0".to_string()), ); test_types_helper( &test, "parent-match-3", Expect::Pass, Some("0.0.26ab".to_string()), ); test_types_helper( &test, "parent-no-match", Expect::Pass, Some("missing".to_string()), ); } fn test_invoke_callout( testname: &str, expect: Expect, action: Action, uuid: Uuid, parent: &str, mdev_type: &str, setupfn: F, ) where F: Fn(&TestEnvironment), { let test = TestEnvironment::new("invoke-callout", testname); setupfn(&test); let mut empty_mdev = MDev::new(&test, uuid); empty_mdev.mdev_type = match mdev_type { "" => None, _ => Some(mdev_type.to_string()), }; empty_mdev.parent = Some(parent.to_string()); let mut callout = callout(&mut empty_mdev); let res = callout.invoke(action, false, |_| Ok(())); let try_force = res.is_err(); let _ = test.assert_result(res, expect, Some("non-forced")); // now force and ensure it succeeds if try_force { let res = callout.invoke(action, true, |_| Ok(())); let _ = test.assert_result(res, Expect::Pass, Some("forced")); } } fn test_get_callout( testname: &str, expect: Expect, uuid: Uuid, parent: &str, mdev_type: &str, setupfn: F, ) where F: Fn(&TestEnvironment), { let test = TestEnvironment::new("get-callout", testname); setupfn(&test); let mut empty_mdev = MDev::new(&test, uuid); empty_mdev.mdev_type = match mdev_type { "" => None, _ => Some(mdev_type.to_string()), }; empty_mdev.parent = Some(parent.to_string()); let res = callout(&mut empty_mdev).get_attributes(); let _ = test.assert_result(res, expect, None); } #[test] #[should_panic] fn test_invoke_callout_panic() { init(); const DEFAULT_UUID: &str = "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9"; const DEFAULT_PARENT: &str = "test_parent"; test_invoke_callout( "test_invoke_callout_create_panic", Expect::Pass, Action::Test, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, "", |test| { test.populate_callout_script("rc0.sh"); }, ); } #[test] #[should_panic] fn test_get_callout_panic() { init(); const DEFAULT_UUID: &str = "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9"; const DEFAULT_PARENT: &str = "test_parent"; test_get_callout( "test_get_callout_create_panic", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, "", |test| { test.populate_callout_script("rc0.sh"); }, ); } #[test] fn test_callouts() { init(); const DEFAULT_UUID: &str = "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9"; const DEFAULT_TYPE: &str = "test_type"; const DEFAULT_PARENT: &str = "test_parent"; test_invoke_callout( "test_callout_all_success", Expect::Pass, Action::Test, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc0.sh"); }, ); test_invoke_callout( "test_callout_all_fail", Expect::Fail(None), Action::Test, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc1.sh"); }, ); // Expected behavior: script will report that the requested device type / parent does not // match the script's type / parent. mdevctl will continue with regularly scheduled programming. test_invoke_callout( "test_callout_wrong_type", Expect::Pass, Action::Test, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc2.sh"); }, ); // This test is expected to fail. If the correct script is executed, then it will` // return error code 1. test_invoke_callout( "test_callout_type_c", Expect::Fail(None), Action::Test, Uuid::parse_str(DEFAULT_UUID).unwrap(), "parent_c", "type_c", |test| { test.populate_callout_script("type-a.sh"); test.populate_callout_script("type-b.sh"); test.populate_callout_script("type-c.sh"); }, ); test_invoke_callout( "test_callout_no_script", Expect::Pass, Action::Test, Uuid::parse_str(DEFAULT_UUID).unwrap(), "parent_d", "type_d", |test| { test.populate_callout_script("type-a.sh"); test.populate_callout_script("type-b.sh"); test.populate_callout_script("type-c.sh"); }, ); // Each pre/post function in the test script will check for // a device type and parent with the command name appended // to the end test_invoke_callout( "test_callout_params_define", Expect::Pass, Action::Define, Uuid::parse_str(DEFAULT_UUID).unwrap(), "test_parent_define", "test_type_define", |test| { test.populate_callout_script("params.sh"); }, ); test_invoke_callout( "test_callout_params_modify", Expect::Pass, Action::Modify, Uuid::parse_str(DEFAULT_UUID).unwrap(), "test_parent_modify", "test_type_modify", |test| { test.populate_callout_script("params.sh"); }, ); test_invoke_callout( "test_callout_params_start", Expect::Pass, Action::Start, Uuid::parse_str(DEFAULT_UUID).unwrap(), "test_parent_start", "test_type_start", |test| { test.populate_callout_script("params.sh"); }, ); test_invoke_callout( "test_callout_params_stop", Expect::Pass, Action::Stop, Uuid::parse_str(DEFAULT_UUID).unwrap(), "test_parent_stop", "test_type_stop", |test| { test.populate_callout_script("params.sh"); }, ); test_invoke_callout( "test_callout_params_undefine", Expect::Pass, Action::Undefine, Uuid::parse_str(DEFAULT_UUID).unwrap(), "test_parent_undefine", "test_type_undefine", |test| { test.populate_callout_script("params.sh"); }, ); // test the Get Attributes callouts test_get_callout( "test_callout_good_json", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("good-json.sh"); }, ); test_get_callout( "test_callout_bad_json", Expect::Fail(None), Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("bad-json.sh"); }, ); test_invoke_callout( "test_callout_order_fail", Expect::Fail(None), Action::Test, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script_full("rc1.sh", Some("00.sh"), true); test.populate_callout_script_full("rc0.sh", Some("99.sh"), true); }, ); test_invoke_callout( "test_callout_order_pass", Expect::Pass, Action::Test, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script_full("rc0.sh", Some("00.sh"), true); test.populate_callout_script_full("rc1.sh", Some("99.sh"), true); }, ); test_invoke_callout( "test_callout_location_priority_pass", Expect::Pass, Action::Start, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script_full("rc0.sh", None, true); test.populate_callout_script_full("rc1.sh", None, false); }, ); test_invoke_callout( "test_callout_location_priority_fail", Expect::Fail(None), Action::Start, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script_full("rc0.sh", None, false); test.populate_callout_script_full("rc1.sh", None, true); }, ); test_invoke_callout( "test_callout_location_priority_skip_fail", Expect::Fail(None), Action::Start, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script_full("rc2.sh", None, true); test.populate_callout_script_full("rc1.sh", None, false); }, ); test_invoke_callout( "test_callout_location_priority_skip_pass", Expect::Pass, Action::Start, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script_full("rc2.sh", None, true); test.populate_callout_script_full("rc0.sh", None, false); }, ); test_get_callout( "test_callout_good_json_null", Expect::Pass, Uuid::parse_str(DEFAULT_UUID).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("good-json-null-terminated.sh"); }, ); // test start with versioning callouts // uuid=11111111-1111-0000-0000-000000000000 has a supported version const UUID_VER: &str = "11111111-1111-0000-0000-000000000000"; const UUID_VER_RC1: &str = "11111111-1111-0000-0000-111111111111"; const UUID_VER_RC2: &str = "11111111-1111-0000-0000-222222222222"; const UUID_VER_BAD_JSON: &str = "11111111-1111-0000-0000-aaaaaaaaaaaa"; const UUID_VER_ACTION_DUMMY: &str = "11111111-1111-0000-0000-bbbbbbbbbbbb"; const UUID_VER_EVENT_DUMMY: &str = "11111111-1111-0000-0000-cccccccccccc"; const UUID_VER_MODIFY_MISSING: &str = "11111111-1111-0000-0000-dddddddddddd"; const UUID_VER_PROVIDES: &str = "11111111-1111-0000-0000-eeeeeeeeeeee"; const UUID_VER_INVALID_JSON: &str = "11111111-1111-0000-0000-ffffffffffff"; test_invoke_callout( "test_callout_with_version_pass", Expect::Pass, Action::Start, Uuid::parse_str(UUID_VER).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_with_version_fail", Expect::Fail(None), Action::Start, Uuid::parse_str(UUID_VER).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); test_invoke_callout( "test_callout_with_version_mix_pass", Expect::Pass, Action::Start, Uuid::parse_str(UUID_VER).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc1.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_with_version_mix_fail", Expect::Fail(None), Action::Start, Uuid::parse_str(UUID_VER).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc0.sh"); // no versioning test.populate_callout_script("ver-rc1.sh"); // versioning error }, ); test_get_callout( "test_callout_with_version_good_json", Expect::Pass, Uuid::parse_str(UUID_VER).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_get_callout( "test_callout_with_version_bad_json", Expect::Fail(None), Uuid::parse_str(UUID_VER).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("ver-rc0-get-attr-bad-json.sh"); // versioning }, ); test_invoke_callout( "test_callout_get_capabilities_rc1_run_with_version_pass", Expect::Pass, Action::Start, Uuid::parse_str(UUID_VER_RC1).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc1.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_get_capabilities_rc2_run_without_version_fail", Expect::Fail(None), Action::Start, Uuid::parse_str(UUID_VER_RC2).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc1.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_with_get_capabilities_bad_run_without_version_fail", Expect::Fail(None), Action::Start, Uuid::parse_str(UUID_VER_BAD_JSON).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc1.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_with_unknown_action_with_version_pass", Expect::Pass, Action::Start, Uuid::parse_str(UUID_VER_ACTION_DUMMY).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc1.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_with_unknown_event_with_verion_pass", Expect::Pass, Action::Start, Uuid::parse_str(UUID_VER_EVENT_DUMMY).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc1.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_with_version_missing_modify_run_start_pass", Expect::Pass, Action::Start, Uuid::parse_str(UUID_VER_MODIFY_MISSING).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_with_version_missing_modify_run_modify_fail", Expect::Fail(None), Action::Modify, Uuid::parse_str(UUID_VER_MODIFY_MISSING).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_with_version_json_provides_with_version_pass", Expect::Pass, Action::Start, Uuid::parse_str(UUID_VER_PROVIDES).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc1.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); test_invoke_callout( "test_callout_with_version_json_invalid_with_version_without_version_fail", Expect::Fail(None), Action::Start, Uuid::parse_str(UUID_VER_INVALID_JSON).unwrap(), DEFAULT_PARENT, DEFAULT_TYPE, |test| { test.populate_callout_script("rc1.sh"); // no versioning test.populate_callout_script("ver-rc0.sh"); // versioning }, ); } mdevctl-mdevctl-54db334/tests/000077500000000000000000000000001454705020100162765ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/callouts/000077500000000000000000000000001454705020100201245ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/callouts/bad-json.sh000077500000000000000000000000341454705020100221550ustar00rootroot00000000000000#!/bin/sh printf "not json" mdevctl-mdevctl-54db334/tests/callouts/good-json-null-terminated.sh000077500000000000000000000000631454705020100254630ustar00rootroot00000000000000#!/bin/sh printf "[{\"attribute0\": \"VALUE\"}]\0" mdevctl-mdevctl-54db334/tests/callouts/good-json.sh000077500000000000000000000000611454705020100223570ustar00rootroot00000000000000#!/bin/sh printf "[{\"attribute0\": \"VALUE\"}]" mdevctl-mdevctl-54db334/tests/callouts/live-rc0.sh000077500000000000000000000027161454705020100221120ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging notification call-out events # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) print_supported_version() { case "$1" in 11111111-1111-0000-0000-000000000000) # full version 2 and RC=0 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-1111-0000-000000000000) # valid version 3 and RC=0 echo "{\"supports\":{" echo "\"version\":3," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\",\"live\"]" echo "}}" exit 0 ;; *) exit 2 ;; esac } case "$event" in get) case "$action" in capabilities) print_supported_version $uuid ;; *) exit 0 ;; esac ;; live) exit 0 ;; *) exit 0 ;; esac mdevctl-mdevctl-54db334/tests/callouts/live-rc1.sh000077500000000000000000000027161454705020100221130ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging notification call-out events # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) print_supported_version() { case "$1" in 11111111-1111-0000-0000-000000000000) # full version 2 and RC=0 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-1111-0000-000000000000) # valid version 3 and RC=0 echo "{\"supports\":{" echo "\"version\":3," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\",\"live\"]" echo "}}" exit 0 ;; *) exit 2 ;; esac } case "$event" in get) case "$action" in capabilities) print_supported_version $uuid ;; *) exit 0 ;; esac ;; live) exit 1 ;; *) exit 0 ;; esac mdevctl-mdevctl-54db334/tests/callouts/modify-active.sh000077500000000000000000000044151454705020100232270ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging notification call-out events # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) tempfile="tmp_modify-live.json" print_supported_version() { case "$1" in 11111111-1111-0000-0000-000000000000) # full version 2 and RC=0 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-1111-0000-000000000000) # valid version 3 and RC=0 echo "{\"supports\":{" echo "\"version\":3," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\",\"live\"]" echo "}}" exit 0 ;; *) exit 2 ;; esac } case "$event" in pre) case "$action" in modify) exit 0 ;; *) exit 1 ;; esac ;; get) case "$action" in capabilities) print_supported_version "$uuid" ;; attributes) if [ -f "$tempfile" ]; then cat "$tempfile" rm "$tempfile" else echo "[]" fi exit 0 ;; *) exit 1 ;; esac ;; post) case "$action" in modify) exit 0 ;; *) exit 1 ;; esac ;; live) case "$action" in modify) echo "$json" | grep -oP '"attrs":+\K(\[.*\])' > "$tempfile" exit 0 ;; *) exit 1 ;; esac ;; *) exit 1 ;; esac mdevctl-mdevctl-54db334/tests/callouts/params.sh000077500000000000000000000037271454705020100217570ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging notification call-out events # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) test_params() { test_parent=$1 test_type=$2 test_state=$3 test_uuid="976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9" if [ "$parent" != "$test_parent" ]; then exit 1 fi if [ "$type" != "$test_type" ]; then exit 1 fi if [ "$state" != "$test_state" ]; then exit 1 fi if [ "$uuid" != "$test_uuid" ]; then exit 1 fi exit 0 } case "$event" in pre) case "$action" in define) test_params "test_parent_define" "test_type_define" "none" ;; undefine) test_params "test_parent_undefine" "test_type_undefine" "none" ;; start) test_params "test_parent_start" "test_type_start" "none" ;; stop) test_params "test_parent_stop" "test_type_stop" "none" ;; modify) test_params "test_parent_modify" "test_type_modify" "none" ;; *) exit 1 ;; esac ;; post) case "$action" in define) test_params "test_parent_define" "test_type_define" "success" ;; undefine) test_params "test_parent_undefine" "test_type_undefine" "success" ;; start) test_params "test_parent_start" "test_type_start" "success" ;; stop) test_params "test_parent_stop" "test_type_stop" "success" ;; modify) test_params "test_parent_modify" "test_type_modify" "success" ;; *) exit 1 ;; esac ;; *) exit 1 ;; esac mdevctl-mdevctl-54db334/tests/callouts/rc0.sh000077500000000000000000000000351454705020100211450ustar00rootroot00000000000000#!/bin/sh json=$(cat) exit 0 mdevctl-mdevctl-54db334/tests/callouts/rc1.sh000077500000000000000000000000351454705020100211460ustar00rootroot00000000000000#!/bin/sh json=$(cat) exit 1 mdevctl-mdevctl-54db334/tests/callouts/rc2.sh000077500000000000000000000000351454705020100211470ustar00rootroot00000000000000#!/bin/sh json=$(cat) exit 2 mdevctl-mdevctl-54db334/tests/callouts/template.sh000077500000000000000000000005121454705020100222740ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging notification call-out events # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) # do stuff here mdevctl-mdevctl-54db334/tests/callouts/type-a.sh000077500000000000000000000005551454705020100216670ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging notification call-out events # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) if [ "$type" = "type_a" ]; then exit 0 fi exit 2 mdevctl-mdevctl-54db334/tests/callouts/type-b.sh000077500000000000000000000005551454705020100216700ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging notification call-out events # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) if [ "$type" = "type_b" ]; then exit 0 fi exit 2 mdevctl-mdevctl-54db334/tests/callouts/type-c.sh000077500000000000000000000006111454705020100216620ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging notification call-out events # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) if [ "$type" = "type_c" ]; then exit 1 # this test expects to fail fi exit 2 mdevctl-mdevctl-54db334/tests/callouts/ver-rc0-get-attr-bad-json.sh000077500000000000000000000103121454705020100251560ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging versioning of call-out scripts # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) print_supported_version() { case "$1" in 11111111-1111-0000-0000-000000000000) # full version 2 and RC=0 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-111111111111) # valid json with RC=1 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 1 ;; 11111111-1111-0000-0000-222222222222) # valid json with RC=2 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 2 ;; 11111111-1111-0000-0000-aaaaaaaaaaaa) # no json output at all echo "This output is bad" exit 0 ;; 11111111-1111-0000-0000-bbbbbbbbbbbb) # extra action dummy echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\",\"dummy\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-cccccccccccc) # extra event dummy echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\",\"dummy\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-dddddddddddd) # action modify missing echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-eeeeeeeeeeee) # extra valid data contained echo "{\"provides\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "},\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-ffffffffffff) # invalid json echo "{\"supports\":{{{" echo "\"version\":\111111," echo "\"actors\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"inventors\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; *) exit 2 ;; esac } case "$event" in get) case "$action" in capabilities) print_supported_version $uuid ;; attributes) echo "not json" exit 0 ;; *) exit 1 ;; esac ;; *) exit 1 ;; esac mdevctl-mdevctl-54db334/tests/callouts/ver-rc0.sh000077500000000000000000000117711454705020100217500ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging versioning of call-out scripts # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) print_supported_version() { case "$1" in 11111111-1111-0000-0000-000000000000) # full version 2 and RC=0 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-111111111111) # valid json with RC=1 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 1 ;; 11111111-1111-0000-0000-222222222222) # valid json with RC=2 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 2 ;; 11111111-1111-0000-0000-aaaaaaaaaaaa) # no json output at all echo "This output is bad" exit 0 ;; 11111111-1111-0000-0000-bbbbbbbbbbbb) # extra action dummy echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\",\"dummy\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-cccccccccccc) # extra event dummy echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\",\"dummy\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-dddddddddddd) # action modify missing echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-eeeeeeeeeeee) # extra valid data contained echo "{\"provides\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "},\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-ffffffffffff) # invalid json echo "{\"supports\":{{{" echo "\"version\":111111," echo "\"actors\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"inventors\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; *) exit 1 ;; esac } case "$event" in get) case "$action" in capabilities) print_supported_version $uuid ;; attributes) echo "[{\"attribute0\": \"VALUE\"}]" exit 0 ;; *) exit 1 ;; esac ;; pre) case "$action" in define) exit 0 ;; undefine) exit 0 ;; start) exit 0 ;; stop) exit 0 ;; modify) exit 0 ;; *) exit 1 ;; esac ;; post) case "$action" in define) exit 0 ;; undefine) exit 0 ;; start) exit 0 ;; stop) exit 0 ;; modify) exit 0 ;; *) exit 1 ;; esac ;; *) exit 1 ;; esac mdevctl-mdevctl-54db334/tests/callouts/ver-rc1.sh000077500000000000000000000103361454705020100217450ustar00rootroot00000000000000#!/bin/sh # A basic utility script used for debugging versioning of call-out scripts # in mdevctl. Output can be observed via system logs. #stdin | -t type -e event -a action -s state -u uuid -p parent shift type=$1 shift 2 event=$1 shift 2 action=$1 shift 2 state=$1 shift 2 uuid=$1 shift 2 parent=$1 json=$(cat) print_supported_version() { case "$1" in 11111111-1111-0000-0000-000000000000) # full version 2 and RC=0 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-111111111111) # valid json with RC=1 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 1 ;; 11111111-1111-0000-0000-111111111111) # valid json with RC=2 echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 2 ;; 11111111-1111-0000-0000-aaaaaaaaaaaa) # no json output at all echo "This output is bad" exit 0 ;; 11111111-1111-0000-0000-bbbbbbbbbbbb) # extra action dummy echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\",\"dummy\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-cccccccccccc) # extra event dummy echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\",\"dummy\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-dddddddddddd) # action modify missing echo "{\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-eeeeeeeeeeee) # extra valid data contained echo "{\"provides\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "},\"supports\":{" echo "\"version\":2," echo "\"actions\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"events\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; 11111111-1111-0000-0000-ffffffffffff) # invalid json echo "{\"supports\":{{{" echo "\"version\":111111," echo "\"actors\":[\"start\",\"stop\",\"define\",\"undefine\",\"modify\",\"attributes\",\"capabilities\"]," echo "\"inventors\":[\"pre\",\"post\",\"notify\",\"get\"]" echo "}}" exit 0 ;; *) exit 1 ;; esac } case "$event" in get) case "$action" in capabilities) print_supported_version $uuid ;; attributes) echo "[{\"attribute0\": \"VALUE\"}]" exit 0 ;; *) exit 1 ;; esac ;; *) exit 1 ;; esac mdevctl-mdevctl-54db334/tests/define/000077500000000000000000000000001454705020100175305ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/define/defined.json000066400000000000000000000005271454705020100220250ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } mdevctl-mdevctl-54db334/tests/define/jsonfile.expected000066400000000000000000000005261454705020100230670ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/define/no-uuid.expected000066400000000000000000000001051454705020100226270ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_4", "start": "auto", "attrs": [] }mdevctl-mdevctl-54db334/tests/define/uuid-auto.expected000066400000000000000000000001051454705020100231630ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_4", "start": "auto", "attrs": [] }mdevctl-mdevctl-54db334/tests/define/uuid-manual.expected000066400000000000000000000001071454705020100234720ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_4", "start": "manual", "attrs": [] }mdevctl-mdevctl-54db334/tests/define/uuid-running-diff-parent.expected000066400000000000000000000001071454705020100260720ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_4", "start": "manual", "attrs": [] }mdevctl-mdevctl-54db334/tests/define/uuid-running-diff-type.expected000066400000000000000000000001071454705020100255620ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_4", "start": "manual", "attrs": [] }mdevctl-mdevctl-54db334/tests/define/uuid-running-no-type.expected000066400000000000000000000001071454705020100252660ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_4", "start": "manual", "attrs": [] }mdevctl-mdevctl-54db334/tests/invalid-files/000077500000000000000000000000001454705020100210245ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/invalid-files/device.json000066400000000000000000000005271454705020100231620ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } mdevctl-mdevctl-54db334/tests/list/000077500000000000000000000000001454705020100172515ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/list/active-callout-bad-json.json000066400000000000000000000006261454705020100245570ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9": { "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [] } } ], "0000:00:03.0": [ { "59e8b599-afdd-4766-a59e-415ef4f5a492": { "mdev_type": "arbitrary_type2", "start": "manual", "attrs": [] } } ] } ]mdevctl-mdevctl-54db334/tests/list/active-callout-bad-json.text000066400000000000000000000002221454705020100245620ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual 59e8b599-afdd-4766-a59e-415ef4f5a492 0000:00:03.0 arbitrary_type2 manual mdevctl-mdevctl-54db334/tests/list/active-callout.json000066400000000000000000000010541454705020100230600ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9": { "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [ { "attribute0": "VALUE" } ] } } ], "0000:00:03.0": [ { "59e8b599-afdd-4766-a59e-415ef4f5a492": { "mdev_type": "arbitrary_type2", "start": "manual", "attrs": [ { "attribute0": "VALUE" } ] } } ] } ]mdevctl-mdevctl-54db334/tests/list/active-callout.text000066400000000000000000000002221454705020100230670ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual 59e8b599-afdd-4766-a59e-415ef4f5a492 0000:00:03.0 arbitrary_type2 manual mdevctl-mdevctl-54db334/tests/list/active-none.json000066400000000000000000000000021454705020100223440ustar00rootroot00000000000000[]mdevctl-mdevctl-54db334/tests/list/active-none.text000066400000000000000000000000001454705020100223550ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/list/active-parent-verbose.json000066400000000000000000000003201454705020100243440ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9": { "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [] } } ] } ]mdevctl-mdevctl-54db334/tests/list/active-parent-verbose.text000066400000000000000000000001111454705020100243550ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual mdevctl-mdevctl-54db334/tests/list/active-parent.json000066400000000000000000000003201454705020100227010ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9": { "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [] } } ] } ]mdevctl-mdevctl-54db334/tests/list/active-parent.text000066400000000000000000000001111454705020100227120ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual mdevctl-mdevctl-54db334/tests/list/active-uuid-parent-verbose.json000066400000000000000000000001101454705020100253050ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [] }mdevctl-mdevctl-54db334/tests/list/active-uuid-parent-verbose.text000066400000000000000000000001111454705020100253210ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual mdevctl-mdevctl-54db334/tests/list/active-uuid-parent.json000066400000000000000000000001101454705020100236420ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [] }mdevctl-mdevctl-54db334/tests/list/active-uuid-parent.text000066400000000000000000000001111454705020100236560ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual mdevctl-mdevctl-54db334/tests/list/active-uuid-verbose.json000066400000000000000000000001101454705020100240160ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [] }mdevctl-mdevctl-54db334/tests/list/active-uuid-verbose.text000066400000000000000000000001111454705020100240320ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual mdevctl-mdevctl-54db334/tests/list/active-uuid.json000066400000000000000000000001101454705020100223530ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [] }mdevctl-mdevctl-54db334/tests/list/active-uuid.text000066400000000000000000000001111454705020100223670ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual mdevctl-mdevctl-54db334/tests/list/active-verbose.json000066400000000000000000000006261454705020100230660ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9": { "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [] } } ], "0000:00:03.0": [ { "59e8b599-afdd-4766-a59e-415ef4f5a492": { "mdev_type": "arbitrary_type2", "start": "manual", "attrs": [] } } ] } ]mdevctl-mdevctl-54db334/tests/list/active-verbose.text000066400000000000000000000002221454705020100230710ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual 59e8b599-afdd-4766-a59e-415ef4f5a492 0000:00:03.0 arbitrary_type2 manual mdevctl-mdevctl-54db334/tests/list/active.json000066400000000000000000000006261454705020100214230ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9": { "mdev_type": "arbitrary_type1", "start": "manual", "attrs": [] } } ], "0000:00:03.0": [ { "59e8b599-afdd-4766-a59e-415ef4f5a492": { "mdev_type": "arbitrary_type2", "start": "manual", "attrs": [] } } ] } ]mdevctl-mdevctl-54db334/tests/list/active.text000066400000000000000000000002221454705020100214260ustar00rootroot00000000000000976d8cc2-4bfc-43b9-b9f9-f4af2de91ab9 0000:00:02.0 arbitrary_type1 manual 59e8b599-afdd-4766-a59e-415ef4f5a492 0000:00:03.0 arbitrary_type2 manual mdevctl-mdevctl-54db334/tests/list/defined-none.json000066400000000000000000000000021454705020100224670ustar00rootroot00000000000000[]mdevctl-mdevctl-54db334/tests/list/defined-none.text000066400000000000000000000000001454705020100225000ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/list/defined-parent-verbose.json000066400000000000000000000014351454705020100244770ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "4a0a190f-dcf3-4def-9342-c48768f0c940": { "mdev_type": "i915-GVTg_V5_8", "start": "auto", "attrs": [] } }, { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ] } ]mdevctl-mdevctl-54db334/tests/list/defined-parent-verbose.text000066400000000000000000000005641454705020100245140ustar00rootroot000000000000004a0a190f-dcf3-4def-9342-c48768f0c940 0000:00:02.0 i915-GVTg_V5_8 auto 9f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:02.0 vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} @{4}: {"assign_domain":"4"} @{5}: {"assign_control_domain":"4"} mdevctl-mdevctl-54db334/tests/list/defined-parent.json000066400000000000000000000014351454705020100230340ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "4a0a190f-dcf3-4def-9342-c48768f0c940": { "mdev_type": "i915-GVTg_V5_8", "start": "auto", "attrs": [] } }, { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ] } ]mdevctl-mdevctl-54db334/tests/list/defined-parent.text000066400000000000000000000002231454705020100230410ustar00rootroot000000000000004a0a190f-dcf3-4def-9342-c48768f0c940 0000:00:02.0 i915-GVTg_V5_8 auto 9f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:02.0 vfio_ap-passthrough manual mdevctl-mdevctl-54db334/tests/list/defined-uuid-parent-verbose.json000066400000000000000000000005261454705020100254430ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/list/defined-uuid-parent-verbose.text000066400000000000000000000004561454705020100254600ustar00rootroot000000000000009f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:02.0 vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} @{4}: {"assign_domain":"4"} @{5}: {"assign_control_domain":"4"} mdevctl-mdevctl-54db334/tests/list/defined-uuid-parent.json000066400000000000000000000005261454705020100240000ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/list/defined-uuid-parent.text000066400000000000000000000001151454705020100240050ustar00rootroot000000000000009f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:02.0 vfio_ap-passthrough manual mdevctl-mdevctl-54db334/tests/list/defined-uuid-verbose.json000066400000000000000000000023421454705020100241520ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ], "0000:00:03.0": [ { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ] } ]mdevctl-mdevctl-54db334/tests/list/defined-uuid-verbose.text000066400000000000000000000011341454705020100241630ustar00rootroot000000000000009f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:02.0 vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} @{4}: {"assign_domain":"4"} @{5}: {"assign_control_domain":"4"} 9f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:03.0 vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} @{4}: {"assign_domain":"4"} @{5}: {"assign_control_domain":"4"} mdevctl-mdevctl-54db334/tests/list/defined-uuid.json000066400000000000000000000023421454705020100225070ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ], "0000:00:03.0": [ { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ] } ]mdevctl-mdevctl-54db334/tests/list/defined-uuid.text000066400000000000000000000002321454705020100225160ustar00rootroot000000000000009f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:02.0 vfio_ap-passthrough manual 9f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:03.0 vfio_ap-passthrough manual mdevctl-mdevctl-54db334/tests/list/defined-verbose.json000066400000000000000000000026111454705020100232050ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "4a0a190f-dcf3-4def-9342-c48768f0c940": { "mdev_type": "i915-GVTg_V5_8", "start": "auto", "attrs": [] } }, { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ], "0000:00:03.0": [ { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ] } ]mdevctl-mdevctl-54db334/tests/list/defined-verbose.text000066400000000000000000000012421454705020100232170ustar00rootroot000000000000004a0a190f-dcf3-4def-9342-c48768f0c940 0000:00:02.0 i915-GVTg_V5_8 auto 9f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:02.0 vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} @{4}: {"assign_domain":"4"} @{5}: {"assign_control_domain":"4"} 9f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:03.0 vfio_ap-passthrough manual Attrs: @{0}: {"assign_adapter":"5"} @{1}: {"assign_adapter":"6"} @{2}: {"assign_domain":"0xab"} @{3}: {"assign_control_domain":"0xab"} @{4}: {"assign_domain":"4"} @{5}: {"assign_control_domain":"4"} mdevctl-mdevctl-54db334/tests/list/defined.json000066400000000000000000000026111454705020100215420ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "4a0a190f-dcf3-4def-9342-c48768f0c940": { "mdev_type": "i915-GVTg_V5_8", "start": "auto", "attrs": [] } }, { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ], "0000:00:03.0": [ { "9f579710-6ffc-4201-987a-4ffa0fb1f3a5": { "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } } ] } ]mdevctl-mdevctl-54db334/tests/list/defined.text000066400000000000000000000003401454705020100215520ustar00rootroot000000000000004a0a190f-dcf3-4def-9342-c48768f0c940 0000:00:02.0 i915-GVTg_V5_8 auto 9f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:02.0 vfio_ap-passthrough manual 9f579710-6ffc-4201-987a-4ffa0fb1f3a5 0000:00:03.0 vfio_ap-passthrough manual mdevctl-mdevctl-54db334/tests/list/device1.json000066400000000000000000000005271454705020100214700ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } mdevctl-mdevctl-54db334/tests/list/device2.json000066400000000000000000000001151454705020100214620ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_8", "start": "auto", "attrs": [] } mdevctl-mdevctl-54db334/tests/list/no-match-parent.json000066400000000000000000000000021454705020100231310ustar00rootroot00000000000000[]mdevctl-mdevctl-54db334/tests/list/no-match-parent.text000066400000000000000000000000001454705020100231420ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/list/no-match-uuid.json000066400000000000000000000000021454705020100226060ustar00rootroot00000000000000[]mdevctl-mdevctl-54db334/tests/list/no-match-uuid.text000066400000000000000000000000001454705020100226170ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/load-json/000077500000000000000000000000001454705020100201645ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/load-json/5269fe7a-18d1-48ad-88e1-3fda4176f536.in000066400000000000000000000000731454705020100253210ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_8", "start": "auto" } mdevctl-mdevctl-54db334/tests/load-json/5269fe7a-18d1-48ad-88e1-3fda4176f536.out000066400000000000000000000001051454705020100255160ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_8", "start": "auto", "attrs": [] }mdevctl-mdevctl-54db334/tests/load-json/783e6dbb-ea0e-411f-94e2-717eaad438bf.in000066400000000000000000000005271454705020100256040ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } mdevctl-mdevctl-54db334/tests/load-json/783e6dbb-ea0e-411f-94e2-717eaad438bf.out000066400000000000000000000005261454705020100260040ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/load-json/c07ab7b2-8aa2-427a-91c6-ffc949bb77f9.in000066400000000000000000000006241454705020100255340ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_8", "start": "manual", "attrs": [ { "example-attribute": "attribute-value" }, { "foo": "bar" }, { "foo2": "bar2" }, { "example-attribute-2": "attribute-value-2" }, { "another-example-attribute": "zzz" } ] } mdevctl-mdevctl-54db334/tests/load-json/c07ab7b2-8aa2-427a-91c6-ffc949bb77f9.out000066400000000000000000000004711454705020100257350ustar00rootroot00000000000000{ "mdev_type": "i915-GVTg_V5_8", "start": "manual", "attrs": [ { "example-attribute": "attribute-value" }, { "foo": "bar" }, { "foo2": "bar2" }, { "example-attribute-2": "attribute-value-2" }, { "another-example-attribute": "zzz" } ] }mdevctl-mdevctl-54db334/tests/modify/000077500000000000000000000000001454705020100175655ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/modify/addattr-noindex.expected000066400000000000000000000006121454705020100243740ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" }, { "added-attr": "added-attr-value" } ] }mdevctl-mdevctl-54db334/tests/modify/addattr.expected000066400000000000000000000006121454705020100227320ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "added-attr": "added-attr-value" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/modify/auto.expected000066400000000000000000000005241454705020100222610ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/modify/callout-fail-force.expected000066400000000000000000000005241454705020100247610ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/modify/callout-pass.expected000066400000000000000000000005241454705020100237200ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/modify/defined-only.active.expected000066400000000000000000000001141454705020100251330ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [] }mdevctl-mdevctl-54db334/tests/modify/defined-only.defined.expected000066400000000000000000000006121454705020100252610ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" }, { "added-attr": "added-attr-value" } ] }mdevctl-mdevctl-54db334/tests/modify/defined.json000066400000000000000000000005271454705020100220620ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } mdevctl-mdevctl-54db334/tests/modify/delattr-noindex.expected000066400000000000000000000004461454705020100244150ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/modify/delattr.expected000066400000000000000000000004531454705020100227510ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/modify/jsonfile.expected000066400000000000000000000003321454705020100231170ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "0x04" }, { "assign_domain": "0x0005" }, { "assign_control_domain": "0x0005" } ] }mdevctl-mdevctl-54db334/tests/modify/live-defined-supported.active.expected000066400000000000000000000003321454705020100271360ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "0x04" }, { "assign_domain": "0x0005" }, { "assign_control_domain": "0x0005" } ] }mdevctl-mdevctl-54db334/tests/modify/live-defined-supported.defined.expected000066400000000000000000000003321454705020100272610ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "0x04" }, { "assign_domain": "0x0005" }, { "assign_control_domain": "0x0005" } ] }mdevctl-mdevctl-54db334/tests/modify/live-event-supported.expected000066400000000000000000000005271454705020100254150ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] } mdevctl-mdevctl-54db334/tests/modify/manual.expected000066400000000000000000000005261454705020100225700ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/modify/mdev_type.expected000066400000000000000000000005241454705020100233050ustar00rootroot00000000000000{ "mdev_type": "changed-mdev-type", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/modify/modified.json000066400000000000000000000003331454705020100222370ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "0x04" }, { "assign_domain": "0x0005" }, { "assign_control_domain": "0x0005" } ] } mdevctl-mdevctl-54db334/tests/modify/modify-jsonfile-with-version-callout-all-pass.expected000066400000000000000000000003321454705020100322130ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "0x04" }, { "assign_domain": "0x0005" }, { "assign_control_domain": "0x0005" } ] }modify-jsonfile-with-version-callout-multiple-with-version-pass.expected000066400000000000000000000003321454705020100356530ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/modify{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "0x04" }, { "assign_domain": "0x0005" }, { "assign_control_domain": "0x0005" } ] }modify-jsonfile-with-version-callout-multiple-with-version-pass2.expected000066400000000000000000000003321454705020100357350ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/modify{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "0x04" }, { "assign_domain": "0x0005" }, { "assign_control_domain": "0x0005" } ] }mdevctl-mdevctl-54db334/tests/modify/multiple-parent.expected000066400000000000000000000005241454705020100244330ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "auto", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }mdevctl-mdevctl-54db334/tests/start/000077500000000000000000000000001454705020100174335ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/start/defined-diff-type/000077500000000000000000000000001454705020100227165ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/start/defined-diff-type/defined.json000066400000000000000000000000711454705020100252050ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type", "start": "manual" } mdevctl-mdevctl-54db334/tests/start/defined-multiple-underspecified/000077500000000000000000000000001454705020100256515ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/start/defined-multiple-underspecified/defined.json000066400000000000000000000000711454705020100301400ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type", "start": "manual" } mdevctl-mdevctl-54db334/tests/start/defined-multiple-underspecified/defined/000077500000000000000000000000001454705020100272475ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/start/defined-multiple-underspecified/defined/defined.json000066400000000000000000000000711454705020100315360ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type", "start": "manual" } mdevctl-mdevctl-54db334/tests/start/defined-multiple/000077500000000000000000000000001454705020100226625ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/start/defined-multiple/defined.json000066400000000000000000000000711454705020100251510ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type", "start": "manual" } mdevctl-mdevctl-54db334/tests/start/defined-with-type/000077500000000000000000000000001454705020100227615ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/start/defined-with-type/defined.json000066400000000000000000000000711454705020100252500ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type", "start": "manual" } mdevctl-mdevctl-54db334/tests/start/defined.json000066400000000000000000000000711454705020100217220ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type", "start": "manual" } mdevctl-mdevctl-54db334/tests/start/no-type-parent-defined/000077500000000000000000000000001454705020100237115ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/start/no-type-parent-defined/defined.json000066400000000000000000000000711454705020100262000ustar00rootroot00000000000000{ "mdev_type": "arbitrary_type", "start": "manual" } mdevctl-mdevctl-54db334/tests/types/000077500000000000000000000000001454705020100174425ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/types/empty.json000066400000000000000000000000021454705020100214630ustar00rootroot00000000000000[]mdevctl-mdevctl-54db334/tests/types/empty.text000066400000000000000000000000001454705020100214740ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/types/full.json000066400000000000000000000021421454705020100212760ustar00rootroot00000000000000[ { "0.0.26ab": [ { "vfio_ccw-io": { "available_instances": 4, "device_api": "vfio_mdev", "name": "name", "description": "description" } } ], "0000:00:02.0": [ { "mdev_type1": { "available_instances": 5, "device_api": "vfio-pci", "name": "name1", "description": "description 1" } }, { "mdev_type2": { "available_instances": 16, "device_api": "vfio-pci", "name": "name2" } }, { "mdev_type3": { "available_instances": 1, "device_api": "vfio-pci", "name": "name3", "description": "description 3" } } ], "0000:00:03.0": [ { "nvidia-155": { "available_instances": 4, "device_api": "vfio-pci", "name": "GRID M10-2B" } }, { "nvidia-36": { "available_instances": 16, "device_api": "vfio-pci", "name": "GRID M10-0Q" } } ] } ]mdevctl-mdevctl-54db334/tests/types/full.text000066400000000000000000000011621454705020100213120ustar00rootroot000000000000000.0.26ab vfio_ccw-io Available instances: 4 Device API: vfio_mdev Name: name Description: description 0000:00:02.0 mdev_type1 Available instances: 5 Device API: vfio-pci Name: name1 Description: description 1 mdev_type2 Available instances: 16 Device API: vfio-pci Name: name2 mdev_type3 Available instances: 1 Device API: vfio-pci Name: name3 Description: description 3 0000:00:03.0 nvidia-155 Available instances: 4 Device API: vfio-pci Name: GRID M10-2B nvidia-36 Available instances: 16 Device API: vfio-pci Name: GRID M10-0Q mdevctl-mdevctl-54db334/tests/types/parent-match-1.json000066400000000000000000000010721454705020100230560ustar00rootroot00000000000000[ { "0000:00:02.0": [ { "mdev_type1": { "available_instances": 5, "device_api": "vfio-pci", "name": "name1", "description": "description 1" } }, { "mdev_type2": { "available_instances": 16, "device_api": "vfio-pci", "name": "name2" } }, { "mdev_type3": { "available_instances": 1, "device_api": "vfio-pci", "name": "name3", "description": "description 3" } } ] } ]mdevctl-mdevctl-54db334/tests/types/parent-match-1.text000066400000000000000000000004771454705020100231010ustar00rootroot000000000000000000:00:02.0 mdev_type1 Available instances: 5 Device API: vfio-pci Name: name1 Description: description 1 mdev_type2 Available instances: 16 Device API: vfio-pci Name: name2 mdev_type3 Available instances: 1 Device API: vfio-pci Name: name3 Description: description 3 mdevctl-mdevctl-54db334/tests/types/parent-match-2.json000066400000000000000000000005341454705020100230610ustar00rootroot00000000000000[ { "0000:00:03.0": [ { "nvidia-155": { "available_instances": 4, "device_api": "vfio-pci", "name": "GRID M10-2B" } }, { "nvidia-36": { "available_instances": 16, "device_api": "vfio-pci", "name": "GRID M10-0Q" } } ] } ]mdevctl-mdevctl-54db334/tests/types/parent-match-2.text000066400000000000000000000002731454705020100230740ustar00rootroot000000000000000000:00:03.0 nvidia-155 Available instances: 4 Device API: vfio-pci Name: GRID M10-2B nvidia-36 Available instances: 16 Device API: vfio-pci Name: GRID M10-0Q mdevctl-mdevctl-54db334/tests/types/parent-match-3.json000066400000000000000000000003401454705020100230550ustar00rootroot00000000000000[ { "0.0.26ab": [ { "vfio_ccw-io": { "available_instances": 4, "device_api": "vfio_mdev", "name": "name", "description": "description" } } ] } ]mdevctl-mdevctl-54db334/tests/types/parent-match-3.text000066400000000000000000000001701454705020100230710ustar00rootroot000000000000000.0.26ab vfio_ccw-io Available instances: 4 Device API: vfio_mdev Name: name Description: description mdevctl-mdevctl-54db334/tests/types/parent-no-match.json000066400000000000000000000000021454705020100233220ustar00rootroot00000000000000[]mdevctl-mdevctl-54db334/tests/types/parent-no-match.text000066400000000000000000000000001454705020100233330ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/undefine/000077500000000000000000000000001454705020100200735ustar00rootroot00000000000000mdevctl-mdevctl-54db334/tests/undefine/defined.json000066400000000000000000000005271454705020100223700ustar00rootroot00000000000000{ "mdev_type": "vfio_ap-passthrough", "start": "manual", "attrs": [ { "assign_adapter": "5" }, { "assign_adapter": "6" }, { "assign_domain": "0xab" }, { "assign_control_domain": "0xab" }, { "assign_domain": "4" }, { "assign_control_domain": "4" } ] }