Projects
Eulaceura:Mainline:GA
libvirt-python
_service:obs_scm:libvirt-python-1715562623.8e7d...
Sign Up
Log In
Username
Password
Overview
Repositories
Revisions
Requests
Users
Attributes
Meta
File _service:obs_scm:libvirt-python-1715562623.8e7da98.obscpio of Package libvirt-python
07070100000000000081A40000000000000000000000016641687F000D7000000000000000000000000000000000000000003F00000000libvirt-python-1715562623.8e7da98/libvirt-python-9.10.0.tar.gz./libvirt-python-9.10.0/0000755000000000000000000000000014555065003013431 5ustar rootroot./libvirt-python-9.10.0/.ctags0000644000000000000000000000003314555064067014540 0ustar rootroot--recurse --exclude=*.orig ./libvirt-python-9.10.0/.dir-locals.el0000644000000000000000000000025314555064067016073 0ustar rootroot( (c-mode . ( (c-file-style . "K&R") (indent-tabs-mode . nil) (c-indent-level . 4) (c-basic-offset . 4) )) ) ./libvirt-python-9.10.0/.mailmap0000644000000000000000000000105214555064067015061 0ustar rootroot# 'git shortlog --help' and look for mailmap for the format of each line # Email consolidation: # <Preferred address in AUTHORS> <other alias used by same author> <jdenemar@redhat.com> <Jiri.Denemark@gmail.com> <jfehlig@suse.com> <jfehlig@novell.com> <stefanb@us.ibm.com> <stefanb@linux.vnet.ibm.com> # Name consolidation: # Preferred author spelling <preferred email> Alex Jia <ajia@redhat.com> Ján Tomko <jtomko@redhat.com> MATSUDA Daiki <matsudadik@intellilink.co.jp> Serge E. Hallyn <serge.hallyn@canonical.com> Philipp Hahn <hahn@univention.de> ./libvirt-python-9.10.0/AUTHORS.in0000644000000000000000000000035414555064067015121 0ustar rootroot Libvirt Python Binding Authors ============================== The libvirt python binding is maintained by the libvirt development team, who can be contacted at libvir-list@redhat.com The individual contributors are @AUTHORS@ ./libvirt-python-9.10.0/CONTRIBUTING.rst0000644000000000000000000000177714555064067016117 0ustar rootroot============================== Contributing to libvirt-python ============================== The libvirt Python API binding accepts code contributions via merge requests on the GitLab project: https://gitlab.com/libvirt/libvirt-python/-/merge_requests It is required that automated CI pipelines succeed before a merge request will be accepted. The global pipeline status for the ``master`` branch is visible at: https://gitlab.com/libvirt/libvirt-python/pipelines CI pipeline results for merge requests will be visible via the contributors' own private repository fork: https://gitlab.com/yourusername/libvirt-python/pipelines Contributions submitted to the project must be in compliance with the Developer Certificate of Origin Version 1.1. This is documented at: https://developercertificate.org/ To indicate compliance, each commit in a series must have a "Signed-off-by" tag with the submitter's name and email address. This can be added by passing the ``-s`` flag to ``git commit`` when creating the patches. ./libvirt-python-9.10.0/COPYING0000644000000000000000000006363114555064067014506 0ustar rootroot 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. <one line to give the library's name and a brief idea of what it does.> Copyright (C) <year> <name of author> 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. <signature of Ty Coon>, 1 April 1990 Ty Coon, President of Vice That's all there is to it! ./libvirt-python-9.10.0/HACKING0000644000000000000000000000272314555064067014435 0ustar rootroot libvirt Python Bindings Hacking =============================== Most of the libvirt python binding code is automatically generated using the script generator.py, and the API description that the libvirt library installs at the location shown by pkg-config, with this command: $ pkg-config --variable libvirt_api libvirt /usr/share/libvirt/api/libvirt-api.xml Some of the API descriptions in the primary XML files are not directly usable by the code generator. Thus there are overrides in - libvirt-override-api.xml - libvirt-qemu-override-api.xml - libvirt-lxc-override-api.xml For stuff which the generator can't cope with at all there are some hand written source files - libvirt-override.c - low level binding to libvirt.so - libvirt-qemu-override.c - low level binding to libvirt-qemu.so - libvirt-lxc-override.c - low level binding to libvirt-lxc.so - libvirt-override.py - high level overrides in the global namespace - libvirt-override-virConnect.py - high level overrides in the virConnect class - libvirt-override-virDomain.py - high level overrides in the virDomain class - libvirt-override-virDomainCheckpoint.py - high level overrides in the virDomainCheckpoint class - libvirt-override-virDomainSnapshot.py - high level overrides in the virDomainSnapshot class - libvirt-override-virStoragePool.py - high level overrides in the virStoragePool class - libvirt-override-virStream.py - high level overrides in the virStream class ./libvirt-python-9.10.0/MANIFEST.in0000644000000000000000000000050614555064067015201 0ustar rootrootgraft tests graft examples include AUTHORS include COPYING include CONTRIBUTING.rst include HACKING include VERSION include requirements-test.txt include tox.ini include Makefile include ChangeLog include libvirt-python.spec include *.[ch] include *.xml include *.py global-exclude */__pycache__/* global-exclude *.py[cod] ./libvirt-python-9.10.0/Makefile0000644000000000000000000000046014555064067015102 0ustar rootroot# Shim wrapper around setup.py to allow for familiar build targets PYTHON ?= python all: $(PYTHON) -m build install: all $(PYTHON) -m pip install . clean: rm -rf build/ dist/ check: all tox -e py36 test: all tox rpm: all rpmbuild -ta dist/libvirt-python-$(shell tr -d '\n' < VERSION).tar.gz ./libvirt-python-9.10.0/README0000644000000000000000000000370414555064067014326 0ustar rootrootLibvirt Python Binding README ============================= This package provides a module that permits applications written in the Python 3.x programming language to call the interface supplied by the libvirt library, to manage the virtualization capabilities of recent versions of Linux (and other OSes). As such, the module exposes Python bindings to to the libvirt.so, libvirt-qemu.so and libvirt-lxc.so library APIs. It is written to build against any version of libvirt that is 0.9.11 or newer. This code is distributed under the terms of the LGPL version 2 or later. Requirements ------------ To build the libvirt python binary requires the GCC and pkg-config tools, and development headers for the libvirt and python libraries. Building and installing ----------------------- The module can be built by following the normal python module build process $ python3 -m build for testing and distributing purposes or it can be installed directly via pip as $ python3 -m pip install . without explicit building. In order to test the package, you'll need either tox or at least pytest, depending on whether you want to test an already installed package in which case the latter is sufficient or if you wish to test in a virtual environment you'd need tox. Depending on your preferred setup, you can run the tests either as $ python3 -m pytest or as $ tox A makefile shim is also provided for your convenience, so that you don't have to care about the exact operations mentioned above and instead you simply do $ make && make check As of libvirt 1.2.6, it is possible to develop against an uninstalled libvirt.git checkout, by setting PKG_CONFIG_PATH and LD_LIBRARY_PATH environment variables to point into that libvirt tree; you can even automate this by using libvirt's run script: /path/to/libvirt/run python3 -m build Patches for this code should be submitted as merge requests to the project page on gitlab. See CONTRIBUTING.rst for more information. ./libvirt-python-9.10.0/ci/0000755000000000000000000000000014555064757014043 5ustar rootroot./libvirt-python-9.10.0/ci/buildenv/0000755000000000000000000000000014555064757015653 5ustar rootroot./libvirt-python-9.10.0/ci/buildenv/centos-stream-8.sh0000644000000000000000000000266714555064757021153 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { dnf distro-sync -y dnf install 'dnf-command(config-manager)' -y dnf config-manager --set-enabled -y powertools dnf install -y centos-release-advanced-virtualization dnf install -y epel-release dnf install -y epel-next-release dnf install -y \ ca-certificates \ ccache \ cpp \ gcc \ gettext \ git \ glib2-devel \ glibc-devel \ glibc-langpack-en \ gnutls-devel \ libnl3-devel \ libtirpc-devel \ libvirt-devel \ libxml2 \ libxml2-devel \ libxslt \ make \ meson \ ninja-build \ perl \ pkgconfig \ python3 \ python3-devel \ python3-docutils \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-wheel \ rpcgen \ rpm-build rpm -qa | sort > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc /usr/bin/pip3 install build } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export MAKE="/usr/bin/make" export NINJA="/usr/bin/ninja" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/centos-stream-9.sh0000644000000000000000000000177514555064757021153 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { dnf distro-sync -y dnf install 'dnf-command(config-manager)' -y dnf config-manager --set-enabled -y crb dnf install -y epel-release dnf install -y epel-next-release dnf install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-langpack-en \ libvirt-devel \ pkgconfig \ python3 \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-wheel \ rpm-build rpm -qa | sort > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc /usr/bin/pip3 install build } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/debian-10.sh0000644000000000000000000000217114555064757017650 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { export DEBIAN_FRONTEND=noninteractive apt-get update apt-get dist-upgrade -y apt-get install --no-install-recommends -y \ ca-certificates \ ccache \ gcc \ git \ libvirt-dev \ locales \ pkgconf \ python3 \ python3-dev \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-venv \ python3-wheel sed -Ei 's,^# (en_US\.UTF-8 .*)$,\1,' /etc/locale.gen dpkg-reconfigure locales dpkg-query --showformat '${Package}_${Version}_${Architecture}\n' --show > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc /usr/bin/pip3 install build } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/debian-sid.sh0000644000000000000000000000213114555064757020203 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { export DEBIAN_FRONTEND=noninteractive apt-get update apt-get dist-upgrade -y apt-get install --no-install-recommends -y \ ca-certificates \ ccache \ gcc \ git \ libvirt-dev \ locales \ pkgconf \ python3 \ python3-build \ python3-dev \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-venv sed -Ei 's,^# (en_US\.UTF-8 .*)$,\1,' /etc/locale.gen dpkg-reconfigure locales dpkg-query --showformat '${Package}_${Version}_${Architecture}\n' --show > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/fedora-37.sh0000644000000000000000000000146614555064757017705 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { dnf update -y dnf install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-langpack-en \ libvirt-devel \ pkgconfig \ python3 \ python3-build \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ rpm-build rpm -qa | sort > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/fedora-38.sh0000644000000000000000000000146614555064757017706 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { dnf update -y dnf install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-langpack-en \ libvirt-devel \ pkgconfig \ python3 \ python3-build \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ rpm-build rpm -qa | sort > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/fedora-rawhide.sh0000644000000000000000000000155214555064757021073 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { dnf update -y --nogpgcheck fedora-gpg-keys dnf distro-sync -y dnf install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-langpack-en \ libvirt-devel \ pkgconfig \ python3 \ python3-build \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ rpm-build rpm -qa | sort > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/opensuse-leap-15.sh0000644000000000000000000000161114555064757021211 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { zypper update -y zypper install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-locale \ libvirt-devel \ pkgconfig \ python3-base \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-wheel \ rpm-build rpm -qa | sort > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc /usr/bin/pip3 install build } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/opensuse-tumbleweed.sh0000644000000000000000000000161714555064757022210 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { zypper dist-upgrade -y zypper install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-locale \ libvirt-devel \ pkgconfig \ python3-base \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-wheel \ rpm-build rpm -qa | sort > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc /usr/bin/pip3 install build } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/ubuntu-2004.sh0000644000000000000000000000217114555064757020115 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { export DEBIAN_FRONTEND=noninteractive apt-get update apt-get dist-upgrade -y apt-get install --no-install-recommends -y \ ca-certificates \ ccache \ gcc \ git \ libvirt-dev \ locales \ pkgconf \ python3 \ python3-dev \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-venv \ python3-wheel sed -Ei 's,^# (en_US\.UTF-8 .*)$,\1,' /etc/locale.gen dpkg-reconfigure locales dpkg-query --showformat '${Package}_${Version}_${Architecture}\n' --show > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc /usr/bin/pip3 install build } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/buildenv/ubuntu-2204.sh0000644000000000000000000000217114555064757020117 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci function install_buildenv() { export DEBIAN_FRONTEND=noninteractive apt-get update apt-get dist-upgrade -y apt-get install --no-install-recommends -y \ ca-certificates \ ccache \ gcc \ git \ libvirt-dev \ locales \ pkgconf \ python3 \ python3-dev \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-venv \ python3-wheel sed -Ei 's,^# (en_US\.UTF-8 .*)$,\1,' /etc/locale.gen dpkg-reconfigure locales dpkg-query --showformat '${Package}_${Version}_${Architecture}\n' --show > /packages.txt mkdir -p /usr/libexec/ccache-wrappers ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc /usr/bin/pip3 install build } export CCACHE_WRAPPERSDIR="/usr/libexec/ccache-wrappers" export LANG="en_US.UTF-8" export PYTHON="/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/0000755000000000000000000000000014555064757016210 5ustar rootroot./libvirt-python-9.10.0/ci/containers/centos-stream-8.Dockerfile0000644000000000000000000000302414555064757023131 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM quay.io/centos/centos:stream8 RUN dnf distro-sync -y && \ dnf install 'dnf-command(config-manager)' -y && \ dnf config-manager --set-enabled -y powertools && \ dnf install -y centos-release-advanced-virtualization && \ dnf install -y epel-release && \ dnf install -y epel-next-release && \ dnf install -y \ ca-certificates \ ccache \ cpp \ gcc \ gettext \ git \ glib2-devel \ glibc-devel \ glibc-langpack-en \ gnutls-devel \ libnl3-devel \ libtirpc-devel \ libvirt-devel \ libxml2 \ libxml2-devel \ libxslt \ make \ meson \ ninja-build \ perl \ pkgconfig \ python3 \ python3-devel \ python3-docutils \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-wheel \ rpcgen \ rpm-build && \ dnf autoremove -y && \ dnf clean all -y && \ rpm -qa | sort > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc RUN /usr/bin/pip3 install build ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV MAKE "/usr/bin/make" ENV NINJA "/usr/bin/ninja" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/centos-stream-9.Dockerfile0000644000000000000000000000213314555064757023132 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM quay.io/centos/centos:stream9 RUN dnf distro-sync -y && \ dnf install 'dnf-command(config-manager)' -y && \ dnf config-manager --set-enabled -y crb && \ dnf install -y epel-release && \ dnf install -y epel-next-release && \ dnf install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-langpack-en \ libvirt-devel \ pkgconfig \ python3 \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-wheel \ rpm-build && \ dnf autoremove -y && \ dnf clean all -y && \ rpm -qa | sort > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc RUN /usr/bin/pip3 install build ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/debian-10.Dockerfile0000644000000000000000000000270614555064757021646 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM docker.io/library/debian:10-slim RUN export DEBIAN_FRONTEND=noninteractive && \ apt-get update && \ apt-get install -y eatmydata && \ eatmydata apt-get dist-upgrade -y && \ eatmydata apt-get install --no-install-recommends -y \ ca-certificates \ ccache \ gcc \ git \ libvirt-dev \ locales \ pkgconf \ python3 \ python3-dev \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-venv \ python3-wheel && \ eatmydata apt-get autoremove -y && \ eatmydata apt-get autoclean -y && \ sed -Ei 's,^# (en_US\.UTF-8 .*)$,\1,' /etc/locale.gen && \ dpkg-reconfigure locales && \ dpkg-query --showformat '${Package}_${Version}_${Architecture}\n' --show > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc RUN /usr/bin/pip3 install build ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/debian-sid.Dockerfile0000644000000000000000000000264614555064757022210 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM docker.io/library/debian:sid-slim RUN export DEBIAN_FRONTEND=noninteractive && \ apt-get update && \ apt-get install -y eatmydata && \ eatmydata apt-get dist-upgrade -y && \ eatmydata apt-get install --no-install-recommends -y \ ca-certificates \ ccache \ gcc \ git \ libvirt-dev \ locales \ pkgconf \ python3 \ python3-build \ python3-dev \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-venv && \ eatmydata apt-get autoremove -y && \ eatmydata apt-get autoclean -y && \ sed -Ei 's,^# (en_US\.UTF-8 .*)$,\1,' /etc/locale.gen && \ dpkg-reconfigure locales && \ dpkg-query --showformat '${Package}_${Version}_${Architecture}\n' --show > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/fedora-37.Dockerfile0000644000000000000000000000244014555064757021670 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM registry.fedoraproject.org/fedora:37 RUN dnf install -y nosync && \ printf '#!/bin/sh\n\ if test -d /usr/lib64\n\ then\n\ export LD_PRELOAD=/usr/lib64/nosync/nosync.so\n\ else\n\ export LD_PRELOAD=/usr/lib/nosync/nosync.so\n\ fi\n\ exec "$@"\n' > /usr/bin/nosync && \ chmod +x /usr/bin/nosync && \ nosync dnf update -y && \ nosync dnf install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-langpack-en \ libvirt-devel \ pkgconfig \ python3 \ python3-build \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ rpm-build && \ nosync dnf autoremove -y && \ nosync dnf clean all -y && \ rpm -qa | sort > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/fedora-38.Dockerfile0000644000000000000000000000244014555064757021671 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM registry.fedoraproject.org/fedora:38 RUN dnf install -y nosync && \ printf '#!/bin/sh\n\ if test -d /usr/lib64\n\ then\n\ export LD_PRELOAD=/usr/lib64/nosync/nosync.so\n\ else\n\ export LD_PRELOAD=/usr/lib/nosync/nosync.so\n\ fi\n\ exec "$@"\n' > /usr/bin/nosync && \ chmod +x /usr/bin/nosync && \ nosync dnf update -y && \ nosync dnf install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-langpack-en \ libvirt-devel \ pkgconfig \ python3 \ python3-build \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ rpm-build && \ nosync dnf autoremove -y && \ nosync dnf clean all -y && \ rpm -qa | sort > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/fedora-rawhide.Dockerfile0000644000000000000000000000253614555064757023070 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM registry.fedoraproject.org/fedora:rawhide RUN dnf update -y --nogpgcheck fedora-gpg-keys && \ dnf install -y nosync && \ printf '#!/bin/sh\n\ if test -d /usr/lib64\n\ then\n\ export LD_PRELOAD=/usr/lib64/nosync/nosync.so\n\ else\n\ export LD_PRELOAD=/usr/lib/nosync/nosync.so\n\ fi\n\ exec "$@"\n' > /usr/bin/nosync && \ chmod +x /usr/bin/nosync && \ nosync dnf distro-sync -y && \ nosync dnf install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-langpack-en \ libvirt-devel \ pkgconfig \ python3 \ python3-build \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ rpm-build && \ nosync dnf autoremove -y && \ nosync dnf clean all -y && \ rpm -qa | sort > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/opensuse-leap-15.Dockerfile0000644000000000000000000000170514555064757023207 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM registry.opensuse.org/opensuse/leap:15.5 RUN zypper update -y && \ zypper install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-locale \ libvirt-devel \ pkgconfig \ python3-base \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-wheel \ rpm-build && \ zypper clean --all && \ rpm -qa | sort > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc RUN /usr/bin/pip3 install build ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/opensuse-tumbleweed.Dockerfile0000644000000000000000000000172314555064757024200 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM registry.opensuse.org/opensuse/tumbleweed:latest RUN zypper dist-upgrade -y && \ zypper install -y \ ca-certificates \ ccache \ gcc \ git \ glibc-locale \ libvirt-devel \ pkgconfig \ python3-base \ python3-devel \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-wheel \ rpm-build && \ zypper clean --all && \ rpm -qa | sort > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc RUN /usr/bin/pip3 install build ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/ubuntu-2004.Dockerfile0000644000000000000000000000270414555064757022111 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM docker.io/library/ubuntu:20.04 RUN export DEBIAN_FRONTEND=noninteractive && \ apt-get update && \ apt-get install -y eatmydata && \ eatmydata apt-get dist-upgrade -y && \ eatmydata apt-get install --no-install-recommends -y \ ca-certificates \ ccache \ gcc \ git \ libvirt-dev \ locales \ pkgconf \ python3 \ python3-dev \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-venv \ python3-wheel && \ eatmydata apt-get autoremove -y && \ eatmydata apt-get autoclean -y && \ sed -Ei 's,^# (en_US\.UTF-8 .*)$,\1,' /etc/locale.gen && \ dpkg-reconfigure locales && \ dpkg-query --showformat '${Package}_${Version}_${Architecture}\n' --show > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc RUN /usr/bin/pip3 install build ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/containers/ubuntu-2204.Dockerfile0000644000000000000000000000270414555064757022113 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci FROM docker.io/library/ubuntu:22.04 RUN export DEBIAN_FRONTEND=noninteractive && \ apt-get update && \ apt-get install -y eatmydata && \ eatmydata apt-get dist-upgrade -y && \ eatmydata apt-get install --no-install-recommends -y \ ca-certificates \ ccache \ gcc \ git \ libvirt-dev \ locales \ pkgconf \ python3 \ python3-dev \ python3-lxml \ python3-pip \ python3-pytest \ python3-setuptools \ python3-venv \ python3-wheel && \ eatmydata apt-get autoremove -y && \ eatmydata apt-get autoclean -y && \ sed -Ei 's,^# (en_US\.UTF-8 .*)$,\1,' /etc/locale.gen && \ dpkg-reconfigure locales && \ dpkg-query --showformat '${Package}_${Version}_${Architecture}\n' --show > /packages.txt && \ mkdir -p /usr/libexec/ccache-wrappers && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/cc && \ ln -s /usr/bin/ccache /usr/libexec/ccache-wrappers/gcc RUN /usr/bin/pip3 install build ENV CCACHE_WRAPPERSDIR "/usr/libexec/ccache-wrappers" ENV LANG "en_US.UTF-8" ENV PYTHON "/usr/bin/python3" ./libvirt-python-9.10.0/ci/gitlab.yml0000644000000000000000000000530214555064067016022 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci # Variables that can be set to control the behaviour of # pipelines that are run # # - RUN_PIPELINE - force creation of a CI pipeline when # pushing to a branch in a forked repository. Official # CI pipelines are triggered when merge requests are # created/updated. Setting this variable to a non-empty # value allows CI testing prior to opening a merge request. # # - RUN_PIPELINE_UPSTREAM_ENV - same semantics as RUN_PIPELINE, # but uses the CI environment (containers) from the upstream project # rather than creating and updating a throwaway environment # Should not be used if the pushed branch includes CI container # changes. # # - RUN_CONTAINER_BUILDS - CI pipelines in upstream only # publish containers if CI file changes are detected. # Setting this variable to a non-empty value will force # re-publishing, even when no file changes are detected. # Typically to use from a scheduled job once a month. # # - RUN_UPSTREAM_NAMESPACE - the upstream namespace is # configured to default to 'libvirt'. When testing # changes to CI it might be useful to use a different # upstream. Setting this variable will override the # namespace considered to be upstream. # # These can be set as git push options # # $ git push -o ci.variable=RUN_PIPELINE=1 # # Aliases can be set for common usage # # $ git config --local alias.push-ci "push -o ci.variable=RUN_PIPELINE=1" # # Allowing the less verbose invocation # # $ git push-ci # # Pipeline variables can also be set in the repository # pipeline config globally, or set against scheduled pipelines variables: RUN_UPSTREAM_NAMESPACE: libvirt FF_SCRIPT_SECTIONS: 1 workflow: rules: # upstream+forks: Avoid duplicate pipelines on pushes, if a MR is open - if: '$CI_PIPELINE_SOURCE == "push" && $CI_OPEN_MERGE_REQUESTS' when: never # upstream+forks: Avoid pipelines on tag pushes - if: '$CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_TAG' when: never # upstream+forks: Allow pipelines in scenarios we've figured out job rules - if: '$CI_PIPELINE_SOURCE =~ /^(push|merge_request_event|api|web|schedule)$/' when: always # upstream+forks: Avoid all other pipelines - when: never debug: image: docker.io/library/alpine:3 stage: sanity_checks interruptible: true needs: [] script: - printenv | sort rules: - if: '$RUN_DEBUG' when: always include: - local: '/ci/gitlab/container-templates.yml' - local: '/ci/gitlab/build-templates.yml' - local: '/ci/gitlab/sanity-checks.yml' - local: '/ci/gitlab/containers.yml' - local: '/ci/gitlab/builds.yml' ./libvirt-python-9.10.0/ci/gitlab/0000755000000000000000000000000014555064757015305 5ustar rootroot./libvirt-python-9.10.0/ci/gitlab/container-templates.yml0000644000000000000000000000304514555064067022002 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci # We want to publish containers with tag 'latest': # # - In upstream, for push to default branch with CI changes. # - In upstream, on request, for scheduled/manual pipelines # against default branch # # Note: never publish from merge requests since they have non-committed code # .container_job: image: docker:latest stage: containers interruptible: false needs: [] services: - docker:dind before_script: - export TAG="$CI_REGISTRY_IMAGE/ci-$NAME:latest" - docker info - docker login "$CI_REGISTRY" -u "$CI_REGISTRY_USER" -p "$CI_REGISTRY_PASSWORD" script: - docker build --tag "$TAG" -f "ci/containers/$NAME.Dockerfile" ci/containers ; - docker push "$TAG" after_script: - docker logout rules: # upstream: publish containers if there were CI changes on the default branch - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' when: on_success changes: - ci/gitlab/container-templates.yml - ci/containers/$NAME.Dockerfile # upstream: allow force re-publishing containers on default branch for web/api/scheduled pipelines - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE =~ /(web|api|schedule)/ && $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH && $RUN_CONTAINER_BUILDS == "1"' when: on_success # upstream+forks: that's all folks - when: never ./libvirt-python-9.10.0/ci/gitlab/sanity-checks.yml0000644000000000000000000000165214555064067020573 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci check-dco: stage: sanity_checks needs: [] image: registry.gitlab.com/libvirt/libvirt-ci/check-dco:latest interruptible: true script: - /check-dco "$RUN_UPSTREAM_NAMESPACE" rules: # upstream+forks: Run pipelines on MR - if: '$CI_PIPELINE_SOURCE =~ "merge_request_event"' when: on_success # forks: pushes to branches with pipeline requested (including upstream env pipelines) - if: '$CI_PROJECT_NAMESPACE != $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH && $RUN_PIPELINE' when: on_success - if: '$CI_PROJECT_NAMESPACE != $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH && $RUN_PIPELINE_UPSTREAM_ENV' when: on_success # upstream+forks: that's all folks - when: never variables: GIT_DEPTH: 1000 ./libvirt-python-9.10.0/ci/gitlab/build-templates.yml0000644000000000000000000001366714555064757021140 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci # # We use pre-built containers for any pipelines that are: # # - Validating code committed on default upstream branch # - Validating patches targeting default upstream branch # which do not have CI changes # # We use a local build env for any pipelines that are: # # - Validating code committed to a non-default upstream branch # - Validating patches targeting a non-default upstream branch # - Validating patches targeting default upstream branch which # include CI changes # - Validating code committed to a fork branch # # Note: the rules across the prebuilt_env and local_env templates # should be logical inverses, such that jobs are mutually exclusive # .gitlab_native_build_job_prebuilt_env: image: $CI_REGISTRY/$RUN_UPSTREAM_NAMESPACE/libvirt-python/ci-$NAME:latest stage: builds interruptible: true before_script: - cat /packages.txt rules: # upstream: pushes to the default branch - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH && $JOB_OPTIONAL' when: manual allow_failure: true - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH' when: on_success # forks: pushes to a branch when a pipeline run in upstream env is explicitly requested - if: '$CI_PROJECT_NAMESPACE != $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $RUN_PIPELINE_UPSTREAM_ENV && $JOB_OPTIONAL' when: manual allow_failure: true - if: '$CI_PROJECT_NAMESPACE != $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $RUN_PIPELINE_UPSTREAM_ENV' when: on_success # upstream: other web/api/scheduled pipelines targeting the default branch - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE =~ /(web|api|schedule)/ && $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH && $JOB_OPTIONAL' when: manual allow_failure: true - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE =~ /(web|api|schedule)/ && $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH' when: on_success # upstream+forks: merge requests targeting the default branch, without CI changes - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH' changes: - ci/gitlab/container-templates.yml - ci/containers/$NAME.Dockerfile when: never - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH && $JOB_OPTIONAL' when: manual allow_failure: true - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH' when: on_success # upstream+forks: that's all folks - when: never .gitlab_native_build_job_local_env: image: $IMAGE stage: builds interruptible: true before_script: - source ci/buildenv/$NAME.sh - install_buildenv - cat /packages.txt rules: # upstream: pushes to a non-default branch - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH && $JOB_OPTIONAL' when: manual allow_failure: true - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $CI_COMMIT_BRANCH != $CI_DEFAULT_BRANCH' when: on_success # forks: avoid build in local env when job requests run in upstream containers - if: '$CI_PROJECT_NAMESPACE != $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $RUN_PIPELINE_UPSTREAM_ENV' when: never # forks: pushes to branches with pipeline requested - if: '$CI_PROJECT_NAMESPACE != $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $RUN_PIPELINE && $JOB_OPTIONAL' when: manual allow_failure: true - if: '$CI_PROJECT_NAMESPACE != $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE == "push" && $RUN_PIPELINE' when: on_success # upstream: other web/api/scheduled pipelines targeting non-default branches - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE =~ /(web|api|schedule)/ && $CI_COMMIT_REF_NAME != $CI_DEFAULT_BRANCH && $JOB_OPTIONAL' when: manual allow_failure: true - if: '$CI_PROJECT_NAMESPACE == $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE =~ /(web|api|schedule)/ && $CI_COMMIT_REF_NAME != $CI_DEFAULT_BRANCH' when: on_success # forks: other web/api/scheduled pipelines - if: '$CI_PROJECT_NAMESPACE != $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE =~ /(web|api|schedule)/ && $JOB_OPTIONAL' when: manual allow_failure: true - if: '$CI_PROJECT_NAMESPACE != $RUN_UPSTREAM_NAMESPACE && $CI_PIPELINE_SOURCE =~ /(web|api|schedule)/' when: on_success # upstream+forks: merge requests targeting the default branch, with CI changes - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH && $JOB_OPTIONAL' changes: - ci/gitlab/container-templates.yml - ci/containers/$NAME.Dockerfile when: manual allow_failure: true - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == $CI_DEFAULT_BRANCH' changes: - ci/gitlab/container-templates.yml - ci/containers/$NAME.Dockerfile when: on_success # upstream+forks: merge requests targeting non-default branches - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME != $CI_DEFAULT_BRANCH && $JOB_OPTIONAL' when: manual allow_failure: true - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME != $CI_DEFAULT_BRANCH' when: on_success # upstream+forks: that's all folks - when: never ./libvirt-python-9.10.0/ci/gitlab/builds.yml0000644000000000000000000001332214555064757017313 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci # Native build jobs x86_64-centos-stream-8-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-centos-stream-8-container optional: true allow_failure: false variables: NAME: centos-stream-8 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms x86_64-centos-stream-8-local-env: extends: .native_build_job_local_env needs: [] allow_failure: false variables: IMAGE: quay.io/centos/centos:stream8 NAME: centos-stream-8 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms x86_64-centos-stream-8-git-prebuilt-env: extends: .native_git_build_job_prebuilt_env needs: - job: x86_64-centos-stream-8-container optional: true allow_failure: false variables: NAME: centos-stream-8 artifacts: expire_in: 2 days paths: - scratch - dist x86_64-centos-stream-8-git-local-env: extends: .native_git_build_job_local_env needs: [] allow_failure: false variables: IMAGE: quay.io/centos/centos:stream8 NAME: centos-stream-8 artifacts: expire_in: 2 days paths: - scratch - dist x86_64-centos-stream-9-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-centos-stream-9-container optional: true allow_failure: false variables: NAME: centos-stream-9 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms x86_64-centos-stream-9-local-env: extends: .native_build_job_local_env needs: [] allow_failure: false variables: IMAGE: quay.io/centos/centos:stream9 NAME: centos-stream-9 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms x86_64-debian-10-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-debian-10-container optional: true allow_failure: false variables: NAME: debian-10 x86_64-debian-10-local-env: extends: .native_build_job_local_env needs: [] allow_failure: false variables: IMAGE: docker.io/library/debian:10-slim NAME: debian-10 x86_64-debian-sid-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-debian-sid-container optional: true allow_failure: true variables: NAME: debian-sid PIP_INSTALL: install --break-system-packages x86_64-debian-sid-local-env: extends: .native_build_job_local_env needs: [] allow_failure: true variables: IMAGE: docker.io/library/debian:sid-slim NAME: debian-sid PIP_INSTALL: install --break-system-packages x86_64-fedora-37-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-fedora-37-container optional: true allow_failure: false variables: NAME: fedora-37 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms x86_64-fedora-37-local-env: extends: .native_build_job_local_env needs: [] allow_failure: false variables: IMAGE: registry.fedoraproject.org/fedora:37 NAME: fedora-37 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms x86_64-fedora-38-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-fedora-38-container optional: true allow_failure: false variables: NAME: fedora-38 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms x86_64-fedora-38-local-env: extends: .native_build_job_local_env needs: [] allow_failure: false variables: IMAGE: registry.fedoraproject.org/fedora:38 NAME: fedora-38 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms x86_64-fedora-rawhide-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-fedora-rawhide-container optional: true allow_failure: true variables: NAME: fedora-rawhide x86_64-fedora-rawhide-local-env: extends: .native_build_job_local_env needs: [] allow_failure: true variables: IMAGE: registry.fedoraproject.org/fedora:rawhide NAME: fedora-rawhide x86_64-opensuse-leap-15-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-opensuse-leap-15-container optional: true allow_failure: false variables: NAME: opensuse-leap-15 RPM: skip x86_64-opensuse-leap-15-local-env: extends: .native_build_job_local_env needs: [] allow_failure: false variables: IMAGE: registry.opensuse.org/opensuse/leap:15.5 NAME: opensuse-leap-15 RPM: skip x86_64-opensuse-tumbleweed-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-opensuse-tumbleweed-container optional: true allow_failure: true variables: NAME: opensuse-tumbleweed RPM: skip x86_64-opensuse-tumbleweed-local-env: extends: .native_build_job_local_env needs: [] allow_failure: true variables: IMAGE: registry.opensuse.org/opensuse/tumbleweed:latest NAME: opensuse-tumbleweed RPM: skip x86_64-ubuntu-2004-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-ubuntu-2004-container optional: true allow_failure: false variables: NAME: ubuntu-2004 x86_64-ubuntu-2004-local-env: extends: .native_build_job_local_env needs: [] allow_failure: false variables: IMAGE: docker.io/library/ubuntu:20.04 NAME: ubuntu-2004 x86_64-ubuntu-2204-prebuilt-env: extends: .native_build_job_prebuilt_env needs: - job: x86_64-ubuntu-2204-container optional: true allow_failure: false variables: NAME: ubuntu-2204 x86_64-ubuntu-2204-local-env: extends: .native_build_job_local_env needs: [] allow_failure: false variables: IMAGE: docker.io/library/ubuntu:22.04 NAME: ubuntu-2204 ./libvirt-python-9.10.0/ci/gitlab/containers.yml0000644000000000000000000000264514555064757020204 0ustar rootroot# THIS FILE WAS AUTO-GENERATED # # $ lcitool manifest ci/manifest.yml # # https://gitlab.com/libvirt/libvirt-ci # Native container jobs x86_64-centos-stream-8-container: extends: .container_job allow_failure: false variables: NAME: centos-stream-8 x86_64-centos-stream-9-container: extends: .container_job allow_failure: false variables: NAME: centos-stream-9 x86_64-debian-10-container: extends: .container_job allow_failure: false variables: NAME: debian-10 x86_64-debian-sid-container: extends: .container_job allow_failure: true variables: NAME: debian-sid x86_64-fedora-37-container: extends: .container_job allow_failure: false variables: NAME: fedora-37 x86_64-fedora-38-container: extends: .container_job allow_failure: false variables: NAME: fedora-38 x86_64-fedora-rawhide-container: extends: .container_job allow_failure: true variables: NAME: fedora-rawhide x86_64-opensuse-leap-15-container: extends: .container_job allow_failure: false variables: NAME: opensuse-leap-15 x86_64-opensuse-tumbleweed-container: extends: .container_job allow_failure: true variables: NAME: opensuse-tumbleweed x86_64-ubuntu-2004-container: extends: .container_job allow_failure: false variables: NAME: ubuntu-2004 x86_64-ubuntu-2204-container: extends: .container_job allow_failure: false variables: NAME: ubuntu-2204 ./libvirt-python-9.10.0/ci/lcitool/0000755000000000000000000000000014555064067015502 5ustar rootroot./libvirt-python-9.10.0/ci/lcitool/projects/0000755000000000000000000000000014555064067017333 5ustar rootroot./libvirt-python-9.10.0/ci/lcitool/projects/libvirt-python.yml0000644000000000000000000000031114555064067023043 0ustar rootroot--- packages: - ccache - gcc - pkg-config - python3 - python3-build - python3-devel - python3-lxml - python3-pip - python3-pytest - python3-setuptools - python3-venv - rpmbuild ./libvirt-python-9.10.0/ci/manifest.yml0000644000000000000000000000270114555064757016374 0ustar rootrootprojects: - libvirt-python - libvirt+dist gitlab: namespace: libvirt project: libvirt-python targets: centos-stream-8: projects: - libvirt-python - libvirt+minimal - libvirt+dist jobs: - arch: x86_64 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms - arch: x86_64 template: .native_git_build_job suffix: -git artifacts: expire_in: 2 days paths: - scratch - dist centos-stream-9: jobs: - arch: x86_64 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms debian-10: x86_64 debian-sid: jobs: - arch: x86_64 allow-failure: true variables: PIP_INSTALL: install --break-system-packages fedora-37: jobs: - arch: x86_64 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms fedora-38: jobs: - arch: x86_64 artifacts: expire_in: 1 hour paths: - libvirt-python-rpms fedora-rawhide: jobs: - arch: x86_64 allow-failure: true opensuse-leap-15: jobs: - arch: x86_64 variables: RPM: skip opensuse-tumbleweed: jobs: - arch: x86_64 allow-failure: true variables: RPM: skip ubuntu-2004: x86_64 ubuntu-2204: x86_64 ./libvirt-python-9.10.0/examples/0000755000000000000000000000000014555064067015260 5ustar rootroot./libvirt-python-9.10.0/examples/README0000644000000000000000000000307014555064067016140 0ustar rootrootSome simple examples on how to use the Python API for libvirt The examples are: dominfo.py - print information about a running domU based on the results of virDomainGetInfo and virDomainGetXMLDesc domstart.py - create a domU from an XML description if the domU isn't running yet domsave.py - save all running domU's into a directory domrestore.py - restore domU's from their saved files in a directory esxlist.py - list active domains of an VMware ESX host and print some info. also demonstrates how to use the libvirt.openAuth() method dhcpleases.py - list dhcp leases for a given virtual network domipaddrs.py - list IP addresses for guest domains guest-vcpus - two helpers to make the guest agent event useful with agent based vCPU state modification nodestats.py - print total memory and free memory for each host NUMA node and the memory strictly bound to certain host nodes for each running domain. Some additional notes for the esxlist.py example: You may see remote errors complaining about missing certificates: Cannot access CA certificate '/usr/local/etc/pki/CA/cacert.pem': No such file or directory This is expected, libvirt tries to find network and storage drivers for ESX, but those are not implemented yet (November 2009). While searching for this drivers, libvirt may try to start a local libvirtd instance, but fails because of the missing certificates. It'll warn about that: Failed to find the network: Is the daemon running? This is also expected and can be ignored. ./libvirt-python-9.10.0/examples/consolecallback.py0000644000000000000000000000634414555064067020760 0ustar rootroot#!/usr/bin/env python3 # consolecallback - provide a persistent console that survives guest reboots import os import logging import libvirt import tty import termios import atexit from argparse import ArgumentParser from typing import Optional # noqa F401 def reset_term() -> None: termios.tcsetattr(0, termios.TCSADRAIN, attrs) def error_handler(unused, error) -> None: # The console stream errors on VM shutdown; we don't care if error[0] == libvirt.VIR_ERR_RPC and error[1] == libvirt.VIR_FROM_STREAMS: return logging.warn(error) class Console(object): def __init__(self, uri: str, uuid: str) -> None: self.uri = uri self.uuid = uuid self.connection = libvirt.open(uri) self.domain = self.connection.lookupByUUIDString(uuid) self.state = self.domain.state(0) self.connection.domainEventRegister(lifecycle_callback, self) self.stream = None # type: Optional[libvirt.virStream] self.run_console = True self.stdin_watch = -1 logging.info("%s initial state %d, reason %d", self.uuid, self.state[0], self.state[1]) def check_console(console: Console) -> bool: if (console.state[0] == libvirt.VIR_DOMAIN_RUNNING or console.state[0] == libvirt.VIR_DOMAIN_PAUSED): if console.stream is None: console.stream = console.connection.newStream(libvirt.VIR_STREAM_NONBLOCK) console.domain.openConsole(None, console.stream, 0) console.stream.eventAddCallback(libvirt.VIR_STREAM_EVENT_READABLE, stream_callback, console) else: if console.stream: console.stream.eventRemoveCallback() console.stream = None return console.run_console def stdin_callback(watch: int, fd: int, events: int, console: Console) -> None: readbuf = os.read(fd, 1024) if readbuf.startswith(b""): console.run_console = False return if console.stream: console.stream.send(readbuf) def stream_callback(stream: libvirt.virStream, events: int, console: Console) -> None: try: assert console.stream received_data = console.stream.recv(1024) except Exception: return os.write(0, received_data) def lifecycle_callback(connection: libvirt.virConnect, domain: libvirt.virDomain, event: int, detail: int, console: Console) -> None: console.state = console.domain.state(0) logging.info("%s transitioned to state %d, reason %d", console.uuid, console.state[0], console.state[1]) # main parser = ArgumentParser(epilog="Example: %(prog)s 'qemu:///system' '32ad945f-7e78-c33a-e96d-39f25e025d81'") parser.add_argument("uri") parser.add_argument("uuid") args = parser.parse_args() print("Escape character is ^]") logging.basicConfig(filename='msg.log', level=logging.DEBUG) logging.info("URI: %s", args.uri) logging.info("UUID: %s", args.uuid) libvirt.virEventRegisterDefaultImpl() libvirt.registerErrorHandler(error_handler, None) atexit.register(reset_term) attrs = termios.tcgetattr(0) tty.setraw(0) console = Console(args.uri, args.uuid) console.stdin_watch = libvirt.virEventAddHandle(0, libvirt.VIR_EVENT_HANDLE_READABLE, stdin_callback, console) while check_console(console): libvirt.virEventRunDefaultImpl() ./libvirt-python-9.10.0/examples/dhcpleases.py0000755000000000000000000000317714555064067017760 0ustar rootroot#!/usr/bin/env python3 """ Print leases info for a given virtual network """ import libvirt import time from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("uri", nargs="?", default=None) parser.add_argument("network") args = parser.parse_args() try: conn = libvirt.open(args.uri) except libvirt.libvirtError: print("Unable to open connection to libvirt") exit(1) try: net = conn.networkLookupByName(args.network) except libvirt.libvirtError: print("Network %s not found" % args.network) exit(0) leases = net.DHCPLeases() if not leases: print("Failed to get leases for %s" % net.name()) exit(0) def toIPAddrType(addrType: int) -> str: if addrType == libvirt.VIR_IP_ADDR_TYPE_IPV4: return "ipv4" elif addrType == libvirt.VIR_IP_ADDR_TYPE_IPV6: return "ipv6" return "Unknown" print(" {0:20} {1:18} {2:9} {3:25} {4:15} {5}".format("Expiry Time", "MAC address", "Protocol", "IP address", "Hostname", "Client ID or DUID")) print("-" * 115) for lease in leases: print(" {0:20} {1:18} {2:9} {3:25} {4:15} {5}".format( time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(lease['expirytime'])), lease['mac'], toIPAddrType(lease['type']), "{}/{}".format(lease['ipaddr'], lease['prefix']), lease['hostname'], lease['clientid'] )) ./libvirt-python-9.10.0/examples/dominfo.py0000755000000000000000000000407314555064067017274 0ustar rootroot#!/usr/bin/env python3 """ Print information about the domain DOMAIN """ import libvirt import libxml2 from argparse import ArgumentParser from typing import Any parser = ArgumentParser(description=__doc__) parser.add_argument("domain") args = parser.parse_args() def print_section(title: str) -> None: print("\n%s" % title) print("=" * 60) def print_entry(key: str, value: Any) -> None: print("%-10s %-10s" % (key, value)) def print_xml(key: str, ctx, path: str) -> str: res = ctx.xpathEval(path) if res is None or len(res) == 0: value = "Unknown" else: value = res[0].content print_entry(key, value) return value # Connect to libvirt try: conn = libvirt.openReadOnly(None) except libvirt.libvirtError: print('Failed to open connection to the hypervisor') exit(1) try: dom = conn.lookupByName(args.domain) # Annoyiingly, libvirt prints its own error message here except libvirt.libvirtError: print("Domain %s is not running" % args.domain) exit(0) info = dom.info() print_section("Domain info") print_entry("State:", info[0]) print_entry("MaxMem:", info[1]) print_entry("UsedMem:", info[2]) print_entry("VCPUs:", info[3]) # Read some info from the XML desc xmldesc = dom.XMLDesc(0) doc = libxml2.parseDoc(xmldesc) ctx = doc.xpathNewContext() print_section("Kernel") print_xml("Type:", ctx, "/domain/os/type") print_xml("Kernel:", ctx, "/domain/os/kernel") print_xml("initrd:", ctx, "/domain/os/initrd") print_xml("cmdline:", ctx, "/domain/os/cmdline") print_section("Devices") devs = ctx.xpathEval("/domain/devices/*") for d in devs: ctx.setContextNode(d) # import pdb; pdb.set_trace() type = print_xml("Type:", ctx, "@type") if type == "file": print_xml("Source:", ctx, "source/@file") print_xml("Target:", ctx, "target/@dev") elif type == "block": print_xml("Source:", ctx, "source/@dev") print_xml("Target:", ctx, "target/@dev") elif type == "bridge": print_xml("Source:", ctx, "source/@bridge") print_xml("MAC Addr:", ctx, "mac/@address") ./libvirt-python-9.10.0/examples/domipaddrs.py0000755000000000000000000000304014555064067017760 0ustar rootroot#!/usr/bin/env python3 """ Print domain interfaces along with their MAC and IP addresses """ import libvirt from argparse import ArgumentParser IPTYPE = { libvirt.VIR_IP_ADDR_TYPE_IPV4: "ipv4", libvirt.VIR_IP_ADDR_TYPE_IPV6: "ipv6", } def print_dom_ifaces(dom: libvirt.virDomain) -> None: ifaces = dom.interfaceAddresses(libvirt.VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE) if ifaces is None: print("Failed to get domain interfaces") exit(0) print(" {0:10} {1:20} {2:12} {3}".format( "Interface", "MAC address", "Protocol", "Address")) for (name, val) in ifaces.items(): if val['addrs']: for addr in val['addrs']: print(" {0:10} {1:19} {2:12} {3}/{4}".format( name, val['hwaddr'], IPTYPE[addr['type']], addr['addr'], addr['prefix'])) else: print(" {0:10} {1:19} {2:12} {3}".format(name, val['hwaddr'], "N/A", "N/A")) if __name__ == "__main__": parser = ArgumentParser(description=__doc__) parser.add_argument("uri", nargs="?", default=None) parser.add_argument("domain") args = parser.parse_args() try: conn = libvirt.open(args.uri) except libvirt.libvirtError: raise SystemExit("Unable to open connection to libvirt") try: dom = conn.lookupByName(args.domain) except libvirt.libvirtError: print("Domain %s not found" % args.domain) exit(0) print_dom_ifaces(dom) conn.close() ./libvirt-python-9.10.0/examples/domrestore.py0000755000000000000000000000126214555064067020021 0ustar rootroot#!/usr/bin/env python3 """ Restore all the domains contained in DIR. It is assumed that all files in DIR are images of domU's previously created with save. """ import libvirt import os from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("dir") args = parser.parse_args() imgs = os.listdir(args.dir) try: conn = libvirt.open(None) except libvirt.libvirtError: print('Failed to open connection to the hypervisor') exit(1) for img in imgs: file = os.path.join(args.dir, img) print("Restoring %s ... " % img) ret = conn.restore(file) if ret == 0: print("done") else: print("error %d" % ret) ./libvirt-python-9.10.0/examples/domsave.py0000755000000000000000000000137214555064067017276 0ustar rootroot#!/usr/bin/env python3 """ Save all currently running domU's into DIR. DIR must exist and be writable by this process. """ import libvirt import os from argparse import ArgumentParser parser = ArgumentParser(description=__doc__) parser.add_argument("dir") args = parser.parse_args() try: conn = libvirt.open(None) except libvirt.libvirtError: print('Failed to open connection to the hypervisor') exit(1) doms = conn.listDomainsID() for id in doms: if id == 0: continue dom = conn.lookupByID(id) print("Saving %s[%d] ... " % (dom.name(), id)) path = os.path.join(args.dir, dom.name()) ret = dom.save(path) if ret == 0: print("done") else: print("error %d" % ret) # import pdb; pdb.set_trace() ./libvirt-python-9.10.0/examples/domstart.py0000755000000000000000000000232714555064067017476 0ustar rootroot#!/usr/bin/env python3 """ Check that the domain described by DOMAIN.XML is running. If the domain is not running, create it. """ import libvirt import libxml2 from argparse import ArgumentParser from typing import Tuple # Parse the XML description of domU from FNAME # and return a tuple (name, xmldesc) where NAME # is the name of the domain, and xmldesc is the contetn of FNAME def read_domain(fname: str) -> Tuple[str, str]: fp = open(fname, "r") xmldesc = fp.read() fp.close() doc = libxml2.parseDoc(xmldesc) name = doc.xpathNewContext().xpathEval("/domain/name")[0].content return (name, xmldesc) parser = ArgumentParser(description=__doc__) parser.add_argument("file", metavar="DOMAIN.XML", help="XML configuration of the domain in libvirt's XML format") args = parser.parse_args() (name, xmldesc) = read_domain(args.file) try: conn = libvirt.open(None) except libvirt.libvirtError: print('Failed to open connection to the hypervisor') exit(1) try: dom = conn.lookupByName(name) except libvirt.libvirtError: print("Starting domain %s ... " % name) dom = conn.createLinux(xmldesc, 0) if dom is None: print("failed") exit(1) else: print("done") ./libvirt-python-9.10.0/examples/esxlist.py0000755000000000000000000001171214555064067017332 0ustar rootroot#!/usr/bin/env python3 """ List active domains of an ESX host and print some info. """ # also demonstrates how to use the libvirt.openAuth() method import libvirt import libxml2 import getpass from argparse import ArgumentParser from typing import Any, List # This is the callback method passed to libvirt.openAuth() (see below). # # The credentials argument is a list of credentials that libvirt (actually # the ESX driver) would like to request. An element of this list is itself a # list containing 5 items (4 inputs, 1 output): # - the credential type, e.g. libvirt.VIR_CRED_AUTHNAME # - a prompt to be displayed to the user # - a challenge, the ESX driver sets this to the hostname to allow automatic # distinction between requests for ESX and vCenter credentials # - a default result for the request # - a place to store the actual result for the request # # The user_data argument is the user data item of the auth argument (see below) # passed to libvirt.openAuth(). def request_credentials(credentials: List[List], user_data: Any) -> int: for credential in credentials: if credential[0] == libvirt.VIR_CRED_AUTHNAME: # prompt the user to input a authname. display the provided message credential[4] = input(credential[1] + ": ") # if the user just hits enter raw_input() returns an empty string. # in this case return the default result through the last item of # the list if len(credential[4]) == 0: credential[4] = credential[3] elif credential[0] == libvirt.VIR_CRED_NOECHOPROMPT: # use the getpass module to prompt the user to input a password. # display the provided message and return the result through the # last item of the list credential[4] = getpass.getpass(credential[1] + ": ") else: return -1 return 0 def print_section(title: str) -> None: print("\n%s" % title) print("=" * 60) def print_entry(key: str, value: Any) -> None: print("%-10s %-10s" % (key, value)) def print_xml(key: str, ctx, path: str) -> str: res = ctx.xpathEval(path) if res is None or len(res) == 0: value = "Unknown" else: value = res[0].content print_entry(key, value) return value parser = ArgumentParser(description=__doc__) parser.add_argument("hostname") args = parser.parse_args() # Connect to libvirt uri = "esx://%s/?no_verify=1" % args.hostname # The auth argument is a list that contains 3 items: # - a list of supported credential types # - a callable that takes 2 arguments # - user data that will be passed to the callable as second argument # # In this example the supported credential types are VIR_CRED_AUTHNAME and # VIR_CRED_NOECHOPROMPT, the callable is the unbound method request_credentials # (see above) and the user data is None. # # libvirt (actually the ESX driver) will call the callable to request # credentials in order to log into the ESX host. The callable would also be # called if the connection URI would reference a vCenter to request credentials # in order to log into the vCenter auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT], request_credentials, None] try: conn = libvirt.openAuth(uri, auth, 0) except libvirt.libvirtError: print("Failed to open connection to %s" % args.hostname) exit(1) state_names = { libvirt.VIR_DOMAIN_RUNNING: "running", libvirt.VIR_DOMAIN_BLOCKED: "idle", libvirt.VIR_DOMAIN_PAUSED: "paused", libvirt.VIR_DOMAIN_SHUTDOWN: "in shutdown", libvirt.VIR_DOMAIN_SHUTOFF: "shut off", libvirt.VIR_DOMAIN_CRASHED: "crashed", libvirt.VIR_DOMAIN_NOSTATE: "no state", } for id in conn.listDomainsID(): domain = conn.lookupByID(id) info = domain.info() print_section("Domain " + domain.name()) print_entry("ID:", id) print_entry("UUID:", domain.UUIDString()) print_entry("State:", state_names[info[0]]) print_entry("MaxMem:", info[1]) print_entry("UsedMem:", info[2]) print_entry("VCPUs:", info[3]) # Read some info from the XML desc print_section("Devices of " + domain.name()) xmldesc = domain.XMLDesc(0) doc = libxml2.parseDoc(xmldesc) ctx = doc.xpathNewContext() devs = ctx.xpathEval("/domain/devices/*") first = True for d in devs: ctx.setContextNode(d) if not first: print("------------------------------------------------------------") else: first = False print_entry("Device", d.name) type = print_xml("Type:", ctx, "@type") if type == "file": print_xml("Source:", ctx, "source/@file") print_xml("Target:", ctx, "target/@dev") elif type == "block": print_xml("Source:", ctx, "source/@dev") print_xml("Target:", ctx, "target/@dev") elif type == "bridge": print_xml("Source:", ctx, "source/@bridge") print_xml("MAC Addr:", ctx, "mac/@address") ./libvirt-python-9.10.0/examples/event-test.py0000755000000000000000000010673514555064067017747 0ustar rootroot#!/usr/bin/env python3 # # # ############################################################################## # Start off by implementing a general purpose event loop for anyone's use ############################################################################## import atexit import os import libvirt import select import errno import time import threading from argparse import ArgumentParser from typing import Any, Callable, Dict, List, Optional, TypeVar # noqa F401 _T = TypeVar("_T") _EventCallback = Callable[[int, int, int, _T], None] _TimerCallback = Callable[[int, _T], None] # This example can use three different event loop impls. It defaults # to a portable pure-python impl based on poll that is implemented # in this file. # # When Python >= 3.4, it can optionally use an impl based on the # new asyncio module. # # Finally, it can also use the libvirt native event loop impl # # This setting thus allows 'poll', 'native' or 'asyncio' as valid # choices # event_impl = "poll" do_debug = False def debug(msg: str) -> None: if do_debug: print(msg) # # This general purpose event loop will support waiting for file handle # I/O and errors events, as well as scheduling repeatable timers with # a fixed interval. # # It is a pure python implementation based around the poll() API # class virEventLoopPoll: # This class contains the data we need to track for a # single file handle class virEventLoopPollHandle: def __init__(self, handle: int, fd: int, events: int, cb: _EventCallback, opaque: _T): self.handle = handle self.fd = fd self.events = events self.cb = cb self.opaque = opaque def get_id(self) -> int: return self.handle def get_fd(self) -> int: return self.fd def get_events(self) -> int: return self.events def set_events(self, events: int): self.events = events def dispatch(self, events: int): self.cb(self.handle, self.fd, events, self.opaque) # This class contains the data we need to track for a # single periodic timer class virEventLoopPollTimer: def __init__(self, timer: int, interval: int, cb: _TimerCallback, opaque: _T): self.timer = timer self.interval = interval self.cb = cb self.opaque = opaque self.lastfired = 0 def get_id(self) -> int: return self.timer def get_interval(self) -> int: return self.interval def set_interval(self, interval: int): self.interval = interval def get_last_fired(self) -> int: return self.lastfired def set_last_fired(self, now: int): self.lastfired = now def dispatch(self) -> None: self.cb(self.timer, self.opaque) def __init__(self): self.poll = select.poll() self.pipetrick = os.pipe() self.pendingWakeup = False self.runningPoll = False self.nextHandleID = 1 self.nextTimerID = 1 self.handles = [] # type: List[virEventLoopPollHandle] self.timers = [] # type: List[virEventLoopPollTimer] self.cleanup = [] self.quit = False # The event loop can be used from multiple threads at once. # Specifically while the main thread is sleeping in poll() # waiting for events to occur, another thread may come along # and add/update/remove a file handle, or timer. When this # happens we need to interrupt the poll() sleep in the other # thread, so that it'll see the file handle / timer changes. # # Using OS level signals for this is very unreliable and # hard to implement correctly. Thus we use the real classic # "self pipe" trick. A anonymous pipe, with one end registered # with the event loop for input events. When we need to force # the main thread out of a poll() sleep, we simple write a # single byte of data to the other end of the pipe. debug("Self pipe watch %d write %d" % (self.pipetrick[0], self.pipetrick[1])) self.poll.register(self.pipetrick[0], select.POLLIN) # Calculate when the next timeout is due to occur, returning # the absolute timestamp for the next timeout, or 0 if there is # no timeout due def next_timeout(self) -> int: next = 0 for t in self.timers: last = t.get_last_fired() interval = t.get_interval() if interval < 0: continue if next == 0 or (last + interval) < next: next = last + interval return next # Lookup a virEventLoopPollHandle object based on file descriptor def get_handle_by_fd(self, fd: int) -> Optional[virEventLoopPollHandle]: for h in self.handles: if h.get_fd() == fd: return h return None # Lookup a virEventLoopPollHandle object based on its event loop ID def get_handle_by_id(self, handleID: int) -> Optional[virEventLoopPollHandle]: for h in self.handles: if h.get_id() == handleID: return h return None # This is the heart of the event loop, performing one single # iteration. It asks when the next timeout is due, and then # calculates the maximum amount of time it is able to sleep # for in poll() pending file handle events. # # It then goes into the poll() sleep. # # When poll() returns, there will zero or more file handle # events which need to be dispatched to registered callbacks # It may also be time to fire some periodic timers. # # Due to the coarse granularity of scheduler timeslices, if # we ask for a sleep of 500ms in order to satisfy a timer, we # may return up to 1 scheduler timeslice early. So even though # our sleep timeout was reached, the registered timer may not # technically be at its expiry point. This leads to us going # back around the loop with a crazy 5ms sleep. So when checking # if timeouts are due, we allow a margin of 20ms, to avoid # these pointless repeated tiny sleeps. def run_once(self) -> None: sleep = -1 # type: float self.runningPoll = True for opaque in self.cleanup: libvirt.virEventInvokeFreeCallback(opaque) self.cleanup = [] try: next = self.next_timeout() debug("Next timeout due at %d" % next) if next > 0: now = int(time.time() * 1000) if now >= next: sleep = 0 else: sleep = (next - now) / 1000.0 debug("Poll with a sleep of %d" % sleep) events = self.poll.poll(sleep) # Dispatch any file handle events that occurred for (fd, revents) in events: # See if the events was from the self-pipe # telling us to wakup. if so, then discard # the data just continue if fd == self.pipetrick[0]: self.pendingWakeup = False os.read(fd, 1) continue h = self.get_handle_by_fd(fd) if h: debug("Dispatch fd %d handle %d events %d" % (fd, h.get_id(), revents)) h.dispatch(self.events_from_poll(revents)) now = int(time.time() * 1000) for t in self.timers: interval = t.get_interval() if interval < 0: continue want = t.get_last_fired() + interval # Deduct 20ms, since scheduler timeslice # means we could be ever so slightly early if now >= want - 20: debug("Dispatch timer %d now %s want %s" % (t.get_id(), str(now), str(want))) t.set_last_fired(now) t.dispatch() except (os.error, select.error) as e: if e.args[0] != errno.EINTR: raise finally: self.runningPoll = False # Actually run the event loop forever def run_loop(self) -> None: self.quit = False while not self.quit: self.run_once() def interrupt(self) -> None: if self.runningPoll and not self.pendingWakeup: self.pendingWakeup = True os.write(self.pipetrick[1], 'c'.encode("UTF-8")) # Registers a new file handle 'fd', monitoring for 'events' (libvirt # event constants), firing the callback cb() when an event occurs. # Returns a unique integer identier for this handle, that should be # used to later update/remove it def add_handle(self, fd: int, events: int, cb: _EventCallback, opaque: _T) -> int: handleID = self.nextHandleID + 1 self.nextHandleID = self.nextHandleID + 1 h = self.virEventLoopPollHandle(handleID, fd, events, cb, opaque) self.handles.append(h) self.poll.register(fd, self.events_to_poll(events)) self.interrupt() debug("Add handle %d fd %d events %d" % (handleID, fd, events)) return handleID # Registers a new timer with periodic expiry at 'interval' ms, # firing cb() each time the timer expires. If 'interval' is -1, # then the timer is registered, but not enabled # Returns a unique integer identier for this handle, that should be # used to later update/remove it def add_timer(self, interval: int, cb: _TimerCallback, opaque: _T) -> int: timerID = self.nextTimerID + 1 self.nextTimerID = self.nextTimerID + 1 h = self.virEventLoopPollTimer(timerID, interval, cb, opaque) self.timers.append(h) self.interrupt() debug("Add timer %d interval %d" % (timerID, interval)) return timerID # Change the set of events to be monitored on the file handle def update_handle(self, handleID: int, events: int) -> None: h = self.get_handle_by_id(handleID) if h: h.set_events(events) self.poll.unregister(h.get_fd()) self.poll.register(h.get_fd(), self.events_to_poll(events)) self.interrupt() debug("Update handle %d fd %d events %d" % (handleID, h.get_fd(), events)) # Change the periodic frequency of the timer def update_timer(self, timerID: int, interval: int) -> None: for h in self.timers: if h.get_id() == timerID: h.set_interval(interval) self.interrupt() debug("Update timer %d interval %d" % (timerID, interval)) break # Stop monitoring for events on the file handle def remove_handle(self, handleID: int) -> int: handles = [] for h in self.handles: if h.get_id() == handleID: debug("Remove handle %d fd %d" % (handleID, h.get_fd())) self.poll.unregister(h.get_fd()) self.cleanup.append(h.opaque) else: handles.append(h) self.handles = handles self.interrupt() return 0 # Stop firing the periodic timer def remove_timer(self, timerID: int) -> int: timers = [] for h in self.timers: if h.get_id() != timerID: timers.append(h) else: debug("Remove timer %d" % timerID) self.cleanup.append(h.opaque) self.timers = timers self.interrupt() return 0 # Convert from libvirt event constants, to poll() events constants def events_to_poll(self, events: int) -> int: ret = 0 if events & libvirt.VIR_EVENT_HANDLE_READABLE: ret |= select.POLLIN if events & libvirt.VIR_EVENT_HANDLE_WRITABLE: ret |= select.POLLOUT if events & libvirt.VIR_EVENT_HANDLE_ERROR: ret |= select.POLLERR if events & libvirt.VIR_EVENT_HANDLE_HANGUP: ret |= select.POLLHUP return ret # Convert from poll() event constants, to libvirt events constants def events_from_poll(self, events: int) -> int: ret = 0 if events & select.POLLIN: ret |= libvirt.VIR_EVENT_HANDLE_READABLE if events & select.POLLOUT: ret |= libvirt.VIR_EVENT_HANDLE_WRITABLE if events & select.POLLNVAL: ret |= libvirt.VIR_EVENT_HANDLE_ERROR if events & select.POLLERR: ret |= libvirt.VIR_EVENT_HANDLE_ERROR if events & select.POLLHUP: ret |= libvirt.VIR_EVENT_HANDLE_HANGUP return ret ########################################################################### # Now glue an instance of the general event loop into libvirt's event loop ########################################################################### # This single global instance of the event loop wil be used for # monitoring libvirt events eventLoop = virEventLoopPoll() # This keeps track of what thread is running the event loop, # (if it is run in a background thread) eventLoopThread = None # These next set of 6 methods are the glue between the official # libvirt events API, and our particular impl of the event loop # # There is no reason why the 'virEventLoopPoll' has to be used. # An application could easily may these 6 glue methods hook into # another event loop such as GLib's, or something like the python # Twisted event framework. def virEventAddHandleImpl(fd: int, events: int, cb: _EventCallback, opaque: _T) -> int: return eventLoop.add_handle(fd, events, cb, opaque) def virEventUpdateHandleImpl(handleID: int, events: int) -> None: return eventLoop.update_handle(handleID, events) def virEventRemoveHandleImpl(handleID: int) -> int: return eventLoop.remove_handle(handleID) def virEventAddTimerImpl(interval: int, cb: _TimerCallback, opaque: _T) -> int: return eventLoop.add_timer(interval, cb, opaque) def virEventUpdateTimerImpl(timerID: int, interval: int) -> None: return eventLoop.update_timer(timerID, interval) def virEventRemoveTimerImpl(timerID: int) -> int: return eventLoop.remove_timer(timerID) # This tells libvirt what event loop implementation it # should use def virEventLoopPollRegister() -> None: libvirt.virEventRegisterImpl(virEventAddHandleImpl, virEventUpdateHandleImpl, virEventRemoveHandleImpl, virEventAddTimerImpl, virEventUpdateTimerImpl, virEventRemoveTimerImpl) # Directly run the event loop in the current thread def virEventLoopPollRun() -> None: eventLoop.run_loop() def virEventLoopAIORun(loop) -> None: import asyncio asyncio.set_event_loop(loop) loop.run_forever() def virEventLoopNativeRun() -> None: while True: libvirt.virEventRunDefaultImpl() # Spawn a background thread to run the event loop def virEventLoopPollStart() -> None: global eventLoopThread virEventLoopPollRegister() eventLoopThread = threading.Thread(target=virEventLoopPollRun, name="libvirtEventLoop", daemon=True) eventLoopThread.start() def virEventLoopAIOStart() -> None: global eventLoopThread import libvirtaio import asyncio loop = asyncio.new_event_loop() libvirtaio.virEventRegisterAsyncIOImpl(loop=loop) eventLoopThread = threading.Thread(target=virEventLoopAIORun, args=(loop,), name="libvirtEventLoop", daemon=True) eventLoopThread.start() def virEventLoopNativeStart() -> None: global eventLoopThread libvirt.virEventRegisterDefaultImpl() eventLoopThread = threading.Thread(target=virEventLoopNativeRun, name="libvirtEventLoop", daemon=True) eventLoopThread.start() ########################################################################## # Everything that now follows is a simple demo of domain lifecycle events ########################################################################## class Description(object): __slots__ = ('desc', 'args') def __init__(self, *args, **kwargs) -> None: self.desc = kwargs.get('desc') self.args = args def __str__(self) -> str: return self.desc or '' def __getitem__(self, item: int) -> 'Description': try: data = self.args[item] except IndexError: return self.__class__(desc=str(item)) if isinstance(data, str): return self.__class__(desc=data) elif isinstance(data, (list, tuple)): desc, args = data return self.__class__(*args, desc=desc) raise TypeError(args) DOM_EVENTS = Description( ("Defined", ("Added", "Updated", "Renamed", "Snapshot")), ("Undefined", ("Removed", "Renamed")), ("Started", ("Booted", "Migrated", "Restored", "Snapshot", "Wakeup")), ("Suspended", ("Paused", "Migrated", "IOError", "Watchdog", "Restored", "Snapshot", "API error", "Postcopy", "Postcopy failed")), ("Resumed", ("Unpaused", "Migrated", "Snapshot", "Postcopy")), ("Stopped", ("Shutdown", "Destroyed", "Crashed", "Migrated", "Saved", "Failed", "Snapshot", "Daemon")), ("Shutdown", ("Finished", "On guest request", "On host request")), ("PMSuspended", ("Memory", "Disk")), ("Crashed", ("Panicked",)), ) BLOCK_JOB_TYPES = Description("unknown", "Pull", "Copy", "Commit", "ActiveCommit") BLOCK_JOB_STATUS = Description("Completed", "Failed", "Canceled", "Ready") WATCHDOG_ACTIONS = Description("none", "Pause", "Reset", "Poweroff", "Shutdown", "Debug", "Inject NMI") ERROR_EVENTS = Description("None", "Pause", "Report") AGENT_STATES = Description("unknown", "connected", "disconnected") AGENT_REASONS = Description("unknown", "domain started", "channel event") GRAPHICS_PHASES = Description("Connect", "Initialize", "Disconnect") DISK_EVENTS = Description("Change missing on start", "Drop missing on start") TRAY_EVENTS = Description("Opened", "Closed") def myDomainEventCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, event: int, detail: int, opaque: _T) -> None: print("myDomainEventCallback%s EVENT: Domain %s(%s) %s %s" % ( opaque, dom.name(), dom.ID(), DOM_EVENTS[event], DOM_EVENTS[event][detail])) def myDomainEventRebootCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, opaque: _T) -> None: print("myDomainEventRebootCallback: Domain %s(%s)" % ( dom.name(), dom.ID())) def myDomainEventRTCChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, utcoffset: int, opaque: _T) -> None: print("myDomainEventRTCChangeCallback: Domain %s(%s) %d" % ( dom.name(), dom.ID(), utcoffset)) def myDomainEventWatchdogCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, action: int, opaque: _T) -> None: print("myDomainEventWatchdogCallback: Domain %s(%s) %s" % ( dom.name(), dom.ID(), WATCHDOG_ACTIONS[action])) def myDomainEventIOErrorCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, srcpath: str, devalias: str, action: int, opaque: _T) -> None: print("myDomainEventIOErrorCallback: Domain %s(%s) %s %s %s" % ( dom.name(), dom.ID(), srcpath, devalias, ERROR_EVENTS[action])) def myDomainEventIOErrorReasonCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, srcpath: str, devalias: str, action: int, reason: int, opaque: _T) -> None: print("myDomainEventIOErrorReasonCallback: Domain %s(%s) %s %s %s %s" % ( dom.name(), dom.ID(), srcpath, devalias, ERROR_EVENTS[action], reason)) def myDomainEventGraphicsCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, phase: int, localAddr: str, remoteAddr: str, authScheme: str, subject: str, opaque: _T) -> None: print("myDomainEventGraphicsCallback: Domain %s(%s) %s %s" % ( dom.name(), dom.ID(), GRAPHICS_PHASES[phase], authScheme)) def myDomainEventControlErrorCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, opaque: _T) -> None: print("myDomainEventControlErrorCallback: Domain %s(%s)" % ( dom.name(), dom.ID())) def myDomainEventBlockJobCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, disk, type: int, status: int, opaque: _T) -> None: print("myDomainEventBlockJobCallback: Domain %s(%s) %s on disk %s %s" % ( dom.name(), dom.ID(), BLOCK_JOB_TYPES[type], disk, BLOCK_JOB_STATUS[status])) def myDomainEventDiskChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, oldSrcPath: str, newSrcPath: str, devAlias: str, reason: int, opaque: _T) -> None: print("myDomainEventDiskChangeCallback: Domain %s(%s) disk change oldSrcPath: %s newSrcPath: %s devAlias: %s reason: %s" % ( dom.name(), dom.ID(), oldSrcPath, newSrcPath, devAlias, DISK_EVENTS[reason])) def myDomainEventTrayChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, devAlias: str, reason: int, opaque: _T) -> None: print("myDomainEventTrayChangeCallback: Domain %s(%s) tray change devAlias: %s reason: %s" % ( dom.name(), dom.ID(), devAlias, TRAY_EVENTS[reason])) def myDomainEventPMWakeupCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, reason: int, opaque: _T) -> None: print("myDomainEventPMWakeupCallback: Domain %s(%s) system pmwakeup" % ( dom.name(), dom.ID())) def myDomainEventPMSuspendCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, reason: int, opaque: _T) -> None: print("myDomainEventPMSuspendCallback: Domain %s(%s) system pmsuspend" % ( dom.name(), dom.ID())) def myDomainEventBalloonChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, actual: int, opaque: _T) -> None: print("myDomainEventBalloonChangeCallback: Domain %s(%s) %d" % ( dom.name(), dom.ID(), actual)) def myDomainEventPMSuspendDiskCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, reason: int, opaque: _T) -> None: print("myDomainEventPMSuspendDiskCallback: Domain %s(%s) system pmsuspend_disk" % ( dom.name(), dom.ID())) def myDomainEventDeviceRemovedCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, dev: str, opaque: _T) -> None: print("myDomainEventDeviceRemovedCallback: Domain %s(%s) device removed: %s" % ( dom.name(), dom.ID(), dev)) def myDomainEventBlockJob2Callback(conn: libvirt.virConnect, dom: libvirt.virDomain, disk: str, type: int, status: int, opaque: _T) -> None: print("myDomainEventBlockJob2Callback: Domain %s(%s) %s on disk %s %s" % ( dom.name(), dom.ID(), BLOCK_JOB_TYPES[type], disk, BLOCK_JOB_STATUS[status])) def myDomainEventTunableCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, params: Dict[str, Any], opaque: _T) -> None: print("myDomainEventTunableCallback: Domain %s(%s) %s" % ( dom.name(), dom.ID(), params)) def myDomainEventAgentLifecycleCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, state: int, reason: int, opaque: _T) -> None: print("myDomainEventAgentLifecycleCallback: Domain %s(%s) %s %s" % ( dom.name(), dom.ID(), AGENT_STATES[state], AGENT_REASONS[reason])) def myDomainEventDeviceAddedCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, dev: str, opaque: _T) -> None: print("myDomainEventDeviceAddedCallback: Domain %s(%s) device added: %s" % ( dom.name(), dom.ID(), dev)) def myDomainEventMigrationIteration(conn: libvirt.virConnect, dom: libvirt.virDomain, iteration: int, opaque: _T) -> None: print("myDomainEventMigrationIteration: Domain %s(%s) started migration iteration %d" % ( dom.name(), dom.ID(), iteration)) def myDomainEventJobCompletedCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, params: Dict[str, Any], opaque: _T) -> None: print("myDomainEventJobCompletedCallback: Domain %s(%s) %s" % ( dom.name(), dom.ID(), params)) def myDomainEventDeviceRemovalFailedCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, dev: str, opaque: _T) -> None: print("myDomainEventDeviceRemovalFailedCallback: Domain %s(%s) failed to remove device: %s" % ( dom.name(), dom.ID(), dev)) def myDomainEventMetadataChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, mtype: int, nsuri: str, opaque: _T) -> None: print("myDomainEventMetadataChangeCallback: Domain %s(%s) changed metadata mtype=%d nsuri=%s" % ( dom.name(), dom.ID(), mtype, nsuri)) def myDomainEventBlockThresholdCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, dev: str, path: str, threshold: int, excess: int, opaque: _T) -> None: print("myDomainEventBlockThresholdCallback: Domain %s(%s) block device %s(%s) threshold %d exceeded by %d" % ( dom.name(), dom.ID(), dev, path, threshold, excess)) def myDomainEventMemoryFailureCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, recipient: int, action: int, flags: int, opaque: _T) -> None: print("myDomainEventMemoryFailureCallback: Domain %s(%s) memory failure recipient %d action %d flags %d" % ( dom.name(), dom.ID(), recipient, action, flags)) def myDomainEventMemoryDeviceSizeChangeCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, recipient: int, action: int, flags: int, opaque: _T) -> None: print("myDomainEventMemoryDeviceSizeChangeCallback: Domain %s(%s) memory device size change alias %s size %d" % ( dom.name(), dom.ID(), alias, size)) ########################################################################## # Network events ########################################################################## NET_EVENTS = Description( ("Defined", ("Added",)), ("Undefined", ("Removed",)), ("Started", ("Started",)), ("Stopped", ("Stopped",)), ) def myNetworkEventLifecycleCallback(conn: libvirt.virConnect, net: libvirt.virNetwork, event: int, detail: int, opaque: _T) -> None: print("myNetworkEventLifecycleCallback: Network %s %s %s" % ( net.name(), NET_EVENTS[event], NET_EVENTS[event][detail])) def myNetworkEventMetadataChangeCallback(conn: libvirt.virConnect, dom: libvirt.virNetwork, mtype: int, nsuri: str, opaque: _T) -> None: print("myNetworkEventMetadataChangeCallback: Network %s(%s) changed metadata mtype=%d nsuri=%s" % ( dom.name(), dom.ID(), mtype, nsuri)) ########################################################################## # Storage pool events ########################################################################## STORAGE_EVENTS = Description( ("Defined", ()), ("Undefined", ()), ("Started", ()), ("Stopped", ()), ("Created", ()), ("Deleted", ()), ) def myStoragePoolEventLifecycleCallback(conn: libvirt.virConnect, pool: libvirt.virStoragePool, event: int, detail: int, opaque: _T) -> None: print("myStoragePoolEventLifecycleCallback: Storage pool %s %s %s" % ( pool.name(), STORAGE_EVENTS[event], STORAGE_EVENTS[event][detail])) def myStoragePoolEventRefreshCallback(conn: libvirt.virConnect, pool: libvirt.virStoragePool, opaque: _T) -> None: print("myStoragePoolEventRefreshCallback: Storage pool %s" % pool.name()) ########################################################################## # Node device events ########################################################################## DEVICE_EVENTS = Description( ("Created", ()), ("Deleted", ()), ) def myNodeDeviceEventLifecycleCallback(conn: libvirt.virConnect, dev: libvirt.virNodeDevice, event: int, detail: int, opaque: _T) -> None: print("myNodeDeviceEventLifecycleCallback: Node device %s %s %s" % ( dev.name(), DEVICE_EVENTS[event], DEVICE_EVENTS[event][detail])) def myNodeDeviceEventUpdateCallback(conn: libvirt.virConnect, dev: libvirt.virNodeDevice, opaque: _T) -> None: print("myNodeDeviceEventUpdateCallback: Node device %s" % dev.name()) ########################################################################## # Secret events ########################################################################## SECRET_EVENTS = Description( ("Defined", ()), ("Undefined", ()), ) def mySecretEventLifecycleCallback(conn: libvirt.virConnect, secret: libvirt.virSecret, event: int, detail: int, opaque: _T) -> None: print("mySecretEventLifecycleCallback: Secret %s %s %s" % ( secret.UUIDString(), SECRET_EVENTS[event], SECRET_EVENTS[event][detail])) def mySecretEventValueChanged(conn: libvirt.virConnect, secret: libvirt.virSecret, opaque: _T) -> None: print("mySecretEventValueChanged: Secret %s" % secret.UUIDString()) ########################################################################## # Set up and run the program ########################################################################## run = True CONNECTION_EVENTS = Description("Error", "End-of-file", "Keepalive", "Client") def myConnectionCloseCallback(conn: libvirt.virConnect, reason: int, opaque: _T) -> None: print("myConnectionCloseCallback: %s: %s" % ( conn.getURI(), CONNECTION_EVENTS[reason])) global run run = False def main() -> None: parser = ArgumentParser() parser.add_argument("--debug", "-d", action="store_true", help="Print debug output") parser.add_argument("--loop", "-l", choices=("native", "poll", "asyncio"), default=event_impl, help="Choose event-loop-implementation") parser.add_argument("--timeout", type=int, default=None, help="Quit after SECS seconds running") parser.add_argument("uri", nargs="?", default="qemu:///system") args = parser.parse_args() if args.debug: global do_debug do_debug = True print("Using uri '%s' and event loop '%s'" % (args.uri, args.loop)) # Run a background thread with the event loop if args.loop == "poll": virEventLoopPollStart() elif args.loop == "asyncio": virEventLoopAIOStart() else: virEventLoopNativeStart() vc = libvirt.openReadOnly(args.uri) # Close connection on exit (to test cleanup paths) def exit() -> None: print("Closing " + vc.getURI()) if run: vc.close() atexit.register(exit) vc.registerCloseCallback(myConnectionCloseCallback, None) # Add 2 lifecycle callbacks to prove this works with more than just one vc.domainEventRegister(myDomainEventCallback, 1) domcallbacks = [ vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, myDomainEventCallback, 2), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_REBOOT, myDomainEventRebootCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_RTC_CHANGE, myDomainEventRTCChangeCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_WATCHDOG, myDomainEventWatchdogCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_IO_ERROR, myDomainEventIOErrorCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_GRAPHICS, myDomainEventGraphicsCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON, myDomainEventIOErrorReasonCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_CONTROL_ERROR, myDomainEventControlErrorCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_BLOCK_JOB, myDomainEventBlockJobCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DISK_CHANGE, myDomainEventDiskChangeCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_TRAY_CHANGE, myDomainEventTrayChangeCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_PMWAKEUP, myDomainEventPMWakeupCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_PMSUSPEND, myDomainEventPMSuspendCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE, myDomainEventBalloonChangeCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_PMSUSPEND_DISK, myDomainEventPMSuspendDiskCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED, myDomainEventDeviceRemovedCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2, myDomainEventBlockJob2Callback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_TUNABLE, myDomainEventTunableCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE, myDomainEventAgentLifecycleCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_ADDED, myDomainEventDeviceAddedCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_MIGRATION_ITERATION, myDomainEventMigrationIteration, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_JOB_COMPLETED, myDomainEventJobCompletedCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_DEVICE_REMOVAL_FAILED, myDomainEventDeviceRemovalFailedCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_METADATA_CHANGE, myDomainEventMetadataChangeCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD, myDomainEventBlockThresholdCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_MEMORY_FAILURE, myDomainEventMemoryFailureCallback, None), vc.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_MEMORY_DEVICE_SIZE_CHANGE, myDomainEventMemoryDeviceSizeChangeCallback, None), ] netcallbacks = [ vc.networkEventRegisterAny(None, libvirt.VIR_NETWORK_EVENT_ID_LIFECYCLE, myNetworkEventLifecycleCallback, None), vc.networkEventRegisterAny(None, libvirt.VIR_NETWORK_EVENT_ID_METADATA_CHANGE, myNetworkEventMetadataChangeCallback, None), ] poolcallbacks = [ vc.storagePoolEventRegisterAny(None, libvirt.VIR_STORAGE_POOL_EVENT_ID_LIFECYCLE, myStoragePoolEventLifecycleCallback, None), vc.storagePoolEventRegisterAny(None, libvirt.VIR_STORAGE_POOL_EVENT_ID_REFRESH, myStoragePoolEventRefreshCallback, None), ] devcallbacks = [ vc.nodeDeviceEventRegisterAny(None, libvirt.VIR_NODE_DEVICE_EVENT_ID_LIFECYCLE, myNodeDeviceEventLifecycleCallback, None), vc.nodeDeviceEventRegisterAny(None, libvirt.VIR_NODE_DEVICE_EVENT_ID_UPDATE, myNodeDeviceEventUpdateCallback, None), ] seccallbacks = [ vc.secretEventRegisterAny(None, libvirt.VIR_SECRET_EVENT_ID_LIFECYCLE, mySecretEventLifecycleCallback, None), vc.secretEventRegisterAny(None, libvirt.VIR_SECRET_EVENT_ID_VALUE_CHANGED, mySecretEventValueChanged, None), ] vc.setKeepAlive(5, 3) # The rest of your app would go here normally, but for sake # of demo we'll just go to sleep. The other option is to # run the event loop in your main thread if your app is # totally event based. count = 0 while run and (args.timeout is None or count < args.timeout): count = count + 1 time.sleep(1) # If the connection was closed, we cannot unregister anything. # Just abort now. if not run: return vc.domainEventDeregister(myDomainEventCallback) for id in seccallbacks: vc.secretEventDeregisterAny(id) for id in devcallbacks: vc.nodeDeviceEventDeregisterAny(id) for id in poolcallbacks: vc.storagePoolEventDeregisterAny(id) for id in netcallbacks: vc.networkEventDeregisterAny(id) for id in domcallbacks: vc.domainEventDeregisterAny(id) vc.unregisterCloseCallback() vc.close() # Allow delayed event loop cleanup to run, just for sake of testing time.sleep(2) if __name__ == "__main__": main() ./libvirt-python-9.10.0/examples/guest-vcpus/0000755000000000000000000000000014555064067017545 5ustar rootroot./libvirt-python-9.10.0/examples/guest-vcpus/guest-vcpu-daemon.py0000755000000000000000000000745014555064067023473 0ustar rootroot#!/usr/bin/env python3 """ This service waits for the guest agent lifecycle event and reissues guest agent calls to modify the cpu count according to the metadata set by guest-vcpu.py example """ import libvirt import threading from xml.dom import minidom import time from argparse import ArgumentParser uri = "qemu:///system" customXMLuri = "guest-cpu.python.libvirt.org" connectRetryTimeout = 5 class workerData: def __init__(self): self.doms = list() self.conn = None self.cond = threading.Condition() def notify(self): self.cond.acquire() self.cond.notify() self.cond.release() def waitNotify(self): self.cond.acquire() self.cond.wait() self.cond.release() def addDomainNotify(self, dom): self.doms.append(dom) self.notify() def closeConnectNotify(self): conn = self.conn self.conn = None conn.close() self.notify() def setConnect(self, conn): self.conn = conn def hasConn(self): return self.conn is not None def hasDom(self): return len(self.doms) > 0 def getDom(self): return self.doms.pop() def setDoms(self, doms): self.doms = doms def virEventLoopNativeRun(): while True: libvirt.virEventRunDefaultImpl() def handleAgentLifecycleEvent(conn, dom, state, reason, opaque): if state == libvirt.VIR_CONNECT_DOMAIN_EVENT_AGENT_LIFECYCLE_STATE_CONNECTED: opaque.addDomainNotify(dom) def handleConnectClose(conn, reason, opaque): print('Disconnected from ' + uri) opaque.closeConnectNotify() def handleLibvirtLibraryError(opaque, error): pass def processAgentConnect(dom): try: cpus = dom.metadata(libvirt.VIR_DOMAIN_METADATA_ELEMENT, customXMLuri, libvirt.VIR_DOMAIN_AFFECT_LIVE) doc = minidom.parseString(cpus) ncpus = int(doc.getElementsByTagName('ncpus')[0].getAttribute('count')) except Exception: return try: dom.setVcpusFlags(ncpus, libvirt.VIR_DOMAIN_AFFECT_LIVE | libvirt.VIR_DOMAIN_VCPU_GUEST) print("set vcpu count for domain " + dom.name() + " to " + str(ncpus)) except Exception: print("failed to set vcpu count for domain " + dom.name()) def work(): data = workerData() print("Using uri: " + uri) while True: if not data.hasConn(): try: conn = libvirt.open(uri) except libvirt.libvirtError: print('Failed to connect to ' + uri + ', retry in ' + str(connectRetryTimeout)) + ' seconds' time.sleep(connectRetryTimeout) continue print('Connected to ' + uri) data.setConnect(conn) conn.registerCloseCallback(handleConnectClose, data) conn.setKeepAlive(5, 3) conn.domainEventRegisterAny(None, libvirt.VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE, handleAgentLifecycleEvent, data) data.setDoms(conn.listAllDomains(libvirt.VIR_CONNECT_LIST_DOMAINS_ACTIVE)) while data.hasConn() and data.hasDom(): processAgentConnect(data.getDom()) data.waitNotify() def main(): libvirt.virEventRegisterDefaultImpl() libvirt.registerErrorHandler(handleLibvirtLibraryError, None) worker = threading.Thread(target=work) worker.setDaemon(True) worker.start() eventLoop = threading.Thread(target=virEventLoopNativeRun) eventLoop.setDaemon(True) eventLoop.start() while True: time.sleep(1) if __name__ == "__main__": parser = ArgumentParser(description=__doc__) parser.add_argument("uri", nargs="?", default=uri) args = parser.parse_args() uri = args.uri main() ./libvirt-python-9.10.0/examples/guest-vcpus/guest-vcpu.py0000755000000000000000000000306414555064067022227 0ustar rootroot#!/usr/bin/env python3 """ Sets the vCPU count via the guest agent and sets the metadata element used by guest-vcpu-daemon.py example """ import libvirt from argparse import ArgumentParser customXMLuri = "guest-cpu.python.libvirt.org" parser = ArgumentParser(description=__doc__) parser.add_argument("--config", "-c", action="store_true", help="Modify persistent domain configuration") parser.add_argument("--live", "-l", action="store_true", help="Modify live domain configuration") parser.add_argument("domain") parser.add_argument("count", type=int) parser.add_argument("uri", nargs="?", default="qemu:///system") args = parser.parse_args() flags = (libvirt.VIR_DOMAIN_AFFECT_CONFIG if args.config else 0) | (libvirt.VIR_DOMAIN_AFFECT_LIVE if args.live else 0) conn = libvirt.open(args.uri) dom = conn.lookupByName(args.domain) if flags == 0 or args.config: confvcpus = dom.vcpusFlags(libvirt.VIR_DOMAIN_AFFECT_CONFIG) if confvcpus < args.count: print("Persistent domain configuration has only " + str(confvcpus) + " vcpus configured") exit(1) if flags == 0 or args.live: livevcpus = dom.vcpusFlags(libvirt.VIR_DOMAIN_AFFECT_LIVE) if livevcpus < args.count: print("Live domain configuration has only " + str(livevcpus) + " vcpus configured") exit(1) if flags == 0 or args.live: dom.setVcpusFlags(args.count, libvirt.VIR_DOMAIN_AFFECT_LIVE | libvirt.VIR_DOMAIN_VCPU_GUEST) meta = "<ncpus count='" + str(args.count) + "'/>" dom.setMetadata(libvirt.VIR_DOMAIN_METADATA_ELEMENT, meta, "guestvcpudaemon", customXMLuri, flags) ./libvirt-python-9.10.0/examples/nodestats.py0000755000000000000000000000533614555064067017650 0ustar rootroot#!/usr/bin/env python3 # Print some host NUMA node statistics # # Authors: # Michal Privoznik <mprivozn@redhat.com> import libvirt from xml.dom import minidom import libxml2 from typing import Any, Dict # noqa F401 def xpath_eval(ctxt, path: str) -> str: res = ctxt.xpathEval(path) if res is None or len(res) == 0: value = '' else: value = res[0].content return value try: conn = libvirt.openReadOnly(None) except libvirt.libvirtError: print("Failed to connect to the hypervisor") exit(1) try: capsXML = conn.getCapabilities() except libvirt.libvirtError: print("Failed to request capabilities") exit(1) caps = minidom.parseString(capsXML) cells = caps.getElementsByTagName("cells")[0] nodesIDs = [ int(proc.getAttribute("id")) for proc in cells.getElementsByTagName("cell") ] nodesMem = [ conn.getMemoryStats(int(proc)) for proc in nodesIDs ] doms = conn.listAllDomains(libvirt.VIR_CONNECT_LIST_DOMAINS_ACTIVE) domsStrict = [ proc for proc in doms if proc.numaParameters()["numa_mode"] == libvirt.VIR_DOMAIN_NUMATUNE_MEM_STRICT ] domsStrictCfg = {} # type: Dict[libvirt.virDomain, Dict[str, Dict[str, Any]]] for dom in domsStrict: xmlStr = dom.XMLDesc() doc = libxml2.parseDoc(xmlStr) ctxt = doc.xpathNewContext() domsStrictCfg[dom] = {} pin = ctxt.xpathEval("string(/domain/numatune/memory/@nodeset)") memsize = ctxt.xpathEval("string(/domain/memory)") domsStrictCfg[dom]["memory"] = {"size": int(memsize), "pin": pin} for memnode in ctxt.xpathEval("/domain/numatune/memnode"): ctxt.setContextNode(memnode) cellid = xpath_eval(ctxt, "@cellid") nodeset = xpath_eval(ctxt, "@nodeset") nodesize = xpath_eval(ctxt, "/domain/cpu/numa/cell[@id='%s']/@memory" % cellid) domsStrictCfg[dom][cellid] = {"size": int(nodesize), "pin": nodeset} print("NUMA stats") print("NUMA nodes:\t" + "\t".join(str(node) for node in nodesIDs)) print("MemTotal:\t" + "\t".join(str(i.get("total") // 1024) for i in nodesMem)) # type: ignore print("MemFree:\t" + "\t".join(str(i.get("free") // 1024) for i in nodesMem)) # type: ignore for dom, v in domsStrictCfg.items(): print("Domain '%s':\t" % dom.name()) toPrint = "\tOverall memory: %d MiB" % (v["memory"]["size"] // 1024) if v["memory"]["pin"] is not None and v["memory"]["pin"] != "": toPrint = toPrint + " nodes %s" % v["memory"]["pin"] print(toPrint) for k, node in sorted(v.items()): if k == "memory": continue toPrint = "\tNode %s:\t%d MiB" % (k, node["size"] // 1024) if node["pin"] is not None and node["pin"] == "": toPrint = toPrint + " nodes %s" % node["pin"] print(toPrint) ./libvirt-python-9.10.0/examples/sparsestream.py0000755000000000000000000000742114555064067020352 0ustar rootroot#!/usr/bin/env python3 """ Either uploads local FILE to libvirt VOLUME, or downloads libvirt VOLUME into local FILE while preserving FILE/VOLUME sparseness """ # Example of sparse streams usage # # Authors: # Michal Privoznik <mprivozn@redhat.com> import libvirt import os from argparse import ArgumentParser def bytesWriteHandler(stream: libvirt.virStream, buf: bytes, opaque: int) -> int: fd = opaque return os.write(fd, buf) def bytesReadHandler(stream: libvirt.virStream, nbytes: int, opaque: int) -> bytes: fd = opaque return os.read(fd, nbytes) def recvSkipHandler(stream: libvirt.virStream, length: int, opaque: int) -> None: fd = opaque cur = os.lseek(fd, length, os.SEEK_CUR) return os.ftruncate(fd, cur) def sendSkipHandler(stream: libvirt.virStream, length: int, opaque: int) -> int: fd = opaque return os.lseek(fd, length, os.SEEK_CUR) def holeHandler(stream: libvirt.virStream, opaque: int): fd = opaque cur = os.lseek(fd, 0, os.SEEK_CUR) try: data = os.lseek(fd, cur, os.SEEK_DATA) except OSError as e: if e.errno != 6: raise e else: data = -1 # There are three options: # 1) data == cur; @cur is in data # 2) data > cur; @cur is in a hole, next data at @data # 3) data < 0; either @cur is in trailing hole, or @cur is beyond EOF. if data < 0: # case 3 inData = False eof = os.lseek(fd, 0, os.SEEK_END) if (eof < cur): raise RuntimeError("Current position in file after EOF: %d" % cur) sectionLen = eof - cur else: if (data > cur): # case 2 inData = False sectionLen = data - cur else: # case 1 inData = True # We don't know where does the next hole start. Let's find out. # Here we get the same options as above hole = os.lseek(fd, data, os.SEEK_HOLE) if hole < 0: # case 3. But wait a second. There is always a trailing hole. # Do the best what we can here raise RuntimeError("No trailing hole") if (hole == data): # case 1. Again, this is suspicious. The reason we are here is # because we are in data. But at the same time we are in a # hole. WAT? raise RuntimeError("Impossible happened") else: # case 2 sectionLen = hole - data os.lseek(fd, cur, os.SEEK_SET) return [inData, sectionLen] def download(vol: libvirt.virStorageVol, st: libvirt.virStream, filename: str) -> None: offset = 0 length = 0 fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode=0o0660) vol.download(st, offset, length, libvirt.VIR_STORAGE_VOL_DOWNLOAD_SPARSE_STREAM) st.sparseRecvAll(bytesWriteHandler, recvSkipHandler, fd) os.close(fd) def upload(vol: libvirt.virStorageVol, st: libvirt.virStream, filename: str) -> None: offset = 0 length = 0 fd = os.open(filename, os.O_RDONLY) vol.upload(st, offset, length, libvirt.VIR_STORAGE_VOL_UPLOAD_SPARSE_STREAM) st.sparseSendAll(bytesReadHandler, holeHandler, sendSkipHandler, fd) os.close(fd) # main parser = ArgumentParser(description=__doc__) parser.add_argument("uri") group = parser.add_mutually_exclusive_group(required=True) group.add_argument("--upload", action="store_const", const=upload, dest="operation") group.add_argument("--download", action="store_const", const=download, dest="operation") parser.add_argument("volume") parser.add_argument("file") args = parser.parse_args() conn = libvirt.open(args.uri) vol = conn.storageVolLookupByKey(args.volume) st = conn.newStream() args.operation(vol, st, args.file) st.finish() conn.close() ./libvirt-python-9.10.0/examples/topology.py0000755000000000000000000000232314555064067017511 0ustar rootroot#!/usr/bin/env python3 # Parse topology information from the capabilities XML and use # them to calculate host topology # # Authors: # Amador Pahim <apahim@redhat.com> # Peter Krempa <pkrempa@redhat.com> import libvirt from xml.dom import minidom try: conn = libvirt.openReadOnly(None) except libvirt.libvirtError: print('Failed to connect to the hypervisor') exit(1) try: capsXML = conn.getCapabilities() except libvirt.libvirtError: print('Failed to request capabilities') exit(1) caps = minidom.parseString(capsXML) host = caps.getElementsByTagName('host')[0] cells = host.getElementsByTagName('cells')[0] total_cpus = cells.getElementsByTagName('cpu').length socketIds = [] siblingsIds = [] socketIds = [ proc.getAttribute('socket_id') for proc in cells.getElementsByTagName('cpu') if proc.getAttribute('socket_id') not in socketIds ] siblingsIds = [ proc.getAttribute('siblings') for proc in cells.getElementsByTagName('cpu') if proc.getAttribute('siblings') not in siblingsIds ] print("Host topology") print("NUMA nodes:", cells.getAttribute('num')) print(" Sockets:", len(set(socketIds))) print(" Cores:", len(set(siblingsIds))) print(" Threads:", total_cpus) ./libvirt-python-9.10.0/generator.py0000755000000000000000000021070014555064067016005 0ustar rootroot#!/usr/bin/env python3 # # generate python wrappers from the XML API description # import os import re import sys import xml.sax from contextlib import closing from collections import defaultdict from typing import Dict, IO, List, Optional, Set, Tuple, Union # noqa F401 ArgumentType = Tuple[str, str, str] FunctionType = Tuple[str, ArgumentType, List[ArgumentType], str, str, str] EnumValue = Union[str, int] EnumType = Dict[str, EnumValue] functions = {} # type: Dict[str, FunctionType] enums = defaultdict(dict) # type: Dict[str, EnumType] # { enumType: { enumConstant: enumValue } } event_ids = [] # type: List[str] params = [] # type: List[Tuple[str, str]] # [ (paramName, paramValue)... ] quiet = True ####################################################################### # # That part if purely the API acquisition phase from the # libvirt API description # ####################################################################### debug = 0 onlyOverrides = False libvirt_headers = [ "libvirt", "libvirt-common", "libvirt-domain", "libvirt-domain-checkpoint", "libvirt-domain-snapshot", "libvirt-event", "libvirt-host", "libvirt-interface", "libvirt-network", "libvirt-nodedev", "libvirt-nwfilter", "libvirt-secret", "libvirt-storage", "libvirt-stream", ] def parse(data: IO[str]) -> None: target = docParser() with closing(xml.sax.make_parser()) as parser: parser.setContentHandler(target) parser.parse(data) class docParser(xml.sax.handler.ContentHandler): def __init__(self) -> None: self._data = [] # type: List[str] self.in_function = False def characters(self, text: str) -> None: if debug: print("data %s" % text) self._data.append(text) def startElement(self, tag: str, attrs: Dict[str, str]) -> None: if debug: print("start %s, %s" % (tag, attrs)) if tag == 'function': self._data = [] self.in_function = True self.function_cond = '' self.function_args = [] # type: List[ArgumentType] self.function_descr = '' self.function_return = None # type: Optional[ArgumentType] self.function = attrs.get('name', '') self.function_file = attrs.get('file', '') self.function_module = attrs.get('module', '') elif tag == 'cond': self._data = [] elif tag == 'info': self._data = [] elif tag == 'arg': if self.in_function: self.function_arg_name = attrs.get('name', '') if self.function_arg_name == 'from': self.function_arg_name = 'frm' self.function_arg_type = attrs.get('type', '') self.function_arg_info = attrs.get('info', '') elif tag == 'return': if self.in_function: self.function_return_type = attrs.get('type', '') self.function_return_info = attrs.get('info', '') self.function_return_field = attrs.get('field', '') elif tag == 'enum': # enums come from header files, hence virterror.h files = libvirt_headers + ["virerror", "virterror", "libvirt-lxc", "libvirt-qemu"] if attrs['file'] in files: enum(attrs['type'], attrs['name'], attrs['value']) elif tag == "macro": if "string" in attrs: params.append((attrs['name'], attrs['string'])) def endElement(self, tag: str) -> None: if debug: print("end %s" % tag) if tag == 'function': # functions come from source files, hence 'virerror.c' if self.function: assert self.function_return modules = libvirt_headers + ["event", "virevent", "virerror", "virterror", "libvirt-lxc", "libvirt-qemu"] files = ["python", "python-lxc", "python-qemu"] if (self.function_module in modules or self.function_file in files): function(self.function, self.function_descr, self.function_return, self.function_args, self.function_file, self.function_module, self.function_cond) self.in_function = False elif tag == 'arg': if self.in_function: self.function_args.append((self.function_arg_name, self.function_arg_type, self.function_arg_info)) elif tag == 'return': if self.in_function: self.function_return = (self.function_return_type, self.function_return_info, self.function_return_field) elif tag == 'info': str = ''.join(self._data) if self.in_function: self.function_descr = str elif tag == 'cond': str = ''.join(self._data) if self.in_function: self.function_cond = str def function(name: str, desc: str, ret: ArgumentType, args: List[ArgumentType], file: str, module: str, cond: str) -> None: if onlyOverrides and name not in functions: return if name == "virConnectListDomains": name = "virConnectListDomainsID" functions[name] = (desc, ret, args, file, module, cond) def enum(type: str, name: str, value: EnumValue) -> None: if (name.startswith('VIR_DOMAIN_EVENT_ID_') or name.startswith('VIR_NETWORK_EVENT_ID_')): event_ids.append(name) if value == 'VIR_TYPED_PARAM_INT': value = 1 elif value == 'VIR_TYPED_PARAM_UINT': value = 2 elif value == 'VIR_TYPED_PARAM_LLONG': value = 3 elif value == 'VIR_TYPED_PARAM_ULLONG': value = 4 elif value == 'VIR_TYPED_PARAM_DOUBLE': value = 5 elif value == 'VIR_TYPED_PARAM_BOOLEAN': value = 6 elif value == 'VIR_DOMAIN_AFFECT_CURRENT': value = 0 elif value == 'VIR_DOMAIN_AFFECT_LIVE': value = 1 elif value == 'VIR_DOMAIN_AFFECT_CONFIG': value = 2 elif value == 'VIR_DOMAIN_AGENT_RESPONSE_TIMEOUT_BLOCK': value = -2 elif value == 'VIR_DOMAIN_AGENT_RESPONSE_TIMEOUT_DEFAULT': value = -1 elif value == 'VIR_DOMAIN_AGENT_RESPONSE_TIMEOUT_NOWAIT': value = 0 if onlyOverrides and name not in enums[type]: return enums[type][name] = value ####################################################################### # # Some filtering rules to drop functions/types which should not # be exposed as-is on the Python interface # ####################################################################### skipped_types = { # 'int *': "usually a return type", 'virConnectDomainEventCallback': "No function types in python", 'virConnectDomainEventGenericCallback': "No function types in python", 'virConnectDomainEventRTCChangeCallback': "No function types in python", 'virConnectDomainEventWatchdogCallback': "No function types in python", 'virConnectDomainEventIOErrorCallback': "No function types in python", 'virConnectDomainEventGraphicsCallback': "No function types in python", 'virConnectDomainQemuMonitorEventCallback': "No function types in python", 'virStreamEventCallback': "No function types in python", 'virEventHandleCallback': "No function types in python", 'virEventTimeoutCallback': "No function types in python", 'virDomainBlockJobInfoPtr': "Not implemented yet", } ####################################################################### # # Table of remapping to/from the python type or class to the C # counterpart. # ####################################################################### py_types = { 'void': ('', '', '', ''), 'int': ('i', '', "int", "int"), 'long': ('l', '', "long", "long"), 'double': ('d', '', "double", "double"), 'unsigned int': ('I', '', "int", "int"), 'unsigned long': ('l', '', "long", "long"), 'long long': ('L', '', "longlong", "long long"), 'unsigned long long': ('L', '', "longlong", "long long"), 'unsigned char *': ('z', '', "charPtr", "char *"), 'char *': ('z', '', "charPtr", "char *"), 'const char *': ('z', '', "constcharPtr", "const char *"), 'size_t': ('n', '', "size_t", "size_t"), 'virDomainPtr': ('O', "virDomain", "virDomainPtr", "virDomainPtr"), 'virDomain *': ('O', "virDomain", "virDomainPtr", "virDomainPtr"), 'const virDomain *': ('O', "virDomain", "virDomainPtr", "virDomainPtr"), 'virNetworkPtr': ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"), 'virNetwork *': ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"), 'const virNetwork *': ('O', "virNetwork", "virNetworkPtr", "virNetworkPtr"), 'virNetworkPortPtr': ('O', "virNetworkPort", "virNetworkPortPtr", "virNetworkPortPtr"), 'virNetworkPort *': ('O', "virNetworkPort", "virNetworkPortPtr", "virNetworkPortPtr"), 'const virNetworkPort *': ('O', "virNetworkPort", "virNetworkPortPtr", "virNetworkPortPtr"), 'virInterfacePtr': ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"), 'virInterface *': ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"), 'const virInterface *': ('O', "virInterface", "virInterfacePtr", "virInterfacePtr"), 'virStoragePoolPtr': ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"), 'virStoragePool *': ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"), 'const virStoragePool *': ('O', "virStoragePool", "virStoragePoolPtr", "virStoragePoolPtr"), 'virStorageVolPtr': ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"), 'virStorageVol *': ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"), 'const virStorageVol *': ('O', "virStorageVol", "virStorageVolPtr", "virStorageVolPtr"), 'virConnectPtr': ('O', "virConnect", "virConnectPtr", "virConnectPtr"), 'virConnect *': ('O', "virConnect", "virConnectPtr", "virConnectPtr"), 'const virConnect *': ('O', "virConnect", "virConnectPtr", "virConnectPtr"), 'virNodeDevicePtr': ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"), 'virNodeDevice *': ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"), 'const virNodeDevice *': ('O', "virNodeDevice", "virNodeDevicePtr", "virNodeDevicePtr"), 'virSecretPtr': ('O', "virSecret", "virSecretPtr", "virSecretPtr"), 'virSecret *': ('O', "virSecret", "virSecretPtr", "virSecretPtr"), 'const virSecret *': ('O', "virSecret", "virSecretPtr", "virSecretPtr"), 'virNWFilterPtr': ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"), 'virNWFilter *': ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"), 'const virNWFilter *': ('O', "virNWFilter", "virNWFilterPtr", "virNWFilterPtr"), 'virNWFilterBindingPtr': ('O', "virNWFilterBinding", "virNWFilterBindingPtr", "virNWFilterBindingPtr"), 'virNWFilterBinding *': ('O', "virNWFilterBinding", "virNWFilterBindingPtr", "virNWFilterBindingPtr"), 'const virNWFilterBinding *': ('O', "virNWFilterBinding", "virNWFilterBindingPtr", "virNWFilterBindingPtr"), 'virStreamPtr': ('O', "virStream", "virStreamPtr", "virStreamPtr"), 'virStream *': ('O', "virStream", "virStreamPtr", "virStreamPtr"), 'const virStream *': ('O', "virStream", "virStreamPtr", "virStreamPtr"), 'virDomainCheckpointPtr': ('O', "virDomainCheckpoint", "virDomainCheckpointPtr", "virDomainCheckpointPtr"), 'virDomainCheckpoint *': ('O', "virDomainCheckpoint", "virDomainCheckpointPtr", "virDomainCheckpointPtr"), 'const virDomainCheckpoint *': ('O', "virDomainCheckpoint", "virDomainCheckpointPtr", "virDomainCheckpointPtr"), 'virDomainSnapshotPtr': ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"), 'virDomainSnapshot *': ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"), 'const virDomainSnapshot *': ('O', "virDomainSnapshot", "virDomainSnapshotPtr", "virDomainSnapshotPtr"), } # type: Dict[str, Tuple[str, str, str, str]] ####################################################################### # # This part writes the C <-> Python stubs libvirt.[ch] and # the table libvirt-export.c to add when registering the Python module # ####################################################################### # Class methods which are written by hand in libvirt.c but the Python-level # code is still automatically generated (so they are not in skip_function()). skip_impl = { 'virConnectGetVersion', 'virConnectGetLibVersion', 'virConnectListDomainsID', 'virConnectListDefinedDomains', 'virConnectListNetworks', 'virConnectListDefinedNetworks', 'virConnectListSecrets', 'virConnectListInterfaces', 'virConnectListStoragePools', 'virConnectListDefinedStoragePools', 'virConnectListStorageVols', 'virConnectListDefinedStorageVols', 'virConnectListDefinedInterfaces', 'virConnectListNWFilters', 'virDomainSnapshotListNames', 'virDomainSnapshotListChildrenNames', 'virConnGetLastError', 'virGetLastError', 'virDomainGetInfo', 'virDomainGetState', 'virDomainGetControlInfo', 'virDomainGetBlockInfo', 'virDomainGetJobInfo', 'virDomainGetJobStats', 'virNodeGetInfo', 'virNodeGetSecurityModel', 'virDomainGetSecurityLabel', 'virDomainGetSecurityLabelList', 'virDomainGetUUID', 'virDomainGetUUIDString', 'virDomainLookupByUUID', 'virNetworkGetUUID', 'virNetworkGetUUIDString', 'virNetworkLookupByUUID', 'virNetworkPortGetUUID', 'virNetworkPortGetUUIDString', 'virNetworkPortLookupByUUID', 'virDomainGetAutostart', 'virNetworkGetAutostart', 'virDomainBlockStats', 'virDomainInterfaceStats', 'virDomainMemoryStats', 'virNodeGetCellsFreeMemory', 'virDomainGetSchedulerType', 'virDomainGetSchedulerParameters', 'virDomainGetSchedulerParametersFlags', 'virDomainSetSchedulerParameters', 'virDomainSetSchedulerParametersFlags', 'virDomainSetBlkioParameters', 'virDomainGetBlkioParameters', 'virDomainSetMemoryParameters', 'virDomainGetMemoryParameters', 'virDomainSetNumaParameters', 'virDomainGetNumaParameters', 'virDomainGetVcpus', 'virDomainPinVcpu', 'virDomainPinVcpuFlags', 'virDomainGetVcpuPinInfo', 'virDomainGetEmulatorPinInfo', 'virDomainPinEmulator', 'virDomainGetIOThreadInfo', 'virDomainPinIOThread', 'virDomainSetIOThreadParams', 'virSecretGetValue', 'virSecretSetValue', 'virSecretGetUUID', 'virSecretGetUUIDString', 'virSecretLookupByUUID', 'virNWFilterGetUUID', 'virNWFilterGetUUIDString', 'virNWFilterLookupByUUID', 'virStoragePoolGetUUID', 'virStoragePoolGetUUIDString', 'virStoragePoolLookupByUUID', 'virStoragePoolGetInfo', 'virStorageVolGetInfo', 'virStorageVolGetInfoFlags', 'virStoragePoolGetAutostart', 'virStoragePoolListVolumes', 'virDomainBlockPeek', 'virDomainMemoryPeek', 'virEventRegisterImpl', 'virNodeListDevices', 'virNodeDeviceListCaps', 'virConnectBaselineCPU', 'virDomainRevertToSnapshot', 'virDomainSendKey', 'virNodeGetCPUStats', 'virNodeGetMemoryStats', 'virDomainGetBlockJobInfo', 'virDomainMigrateGetCompressionCache', 'virDomainMigrateGetMaxSpeed', 'virDomainMigrateGetMaxDowntime', 'virDomainBlockStatsFlags', 'virDomainSetBlockIoTune', 'virDomainGetBlockIoTune', 'virDomainSetInterfaceParameters', 'virDomainGetInterfaceParameters', 'virDomainGetCPUStats', 'virDomainGetDiskErrors', 'virNodeGetMemoryParameters', 'virNodeSetMemoryParameters', 'virConnectSetIdentity', 'virNodeGetCPUMap', 'virDomainMigrate3', 'virDomainMigrateToURI3', 'virConnectGetCPUModelNames', 'virNodeGetFreePages', 'virNetworkGetDHCPLeases', 'virDomainBlockCopy', 'virNodeAllocPages', 'virDomainGetFSInfo', 'virDomainInterfaceAddresses', 'virDomainGetPerfEvents', 'virDomainSetPerfEvents', 'virDomainGetGuestVcpus', 'virConnectBaselineHypervisorCPU', 'virDomainGetLaunchSecurityInfo', 'virDomainSetLaunchSecurityState', 'virNodeGetSEVInfo', 'virNetworkPortGetParameters', 'virNetworkPortSetParameters', 'virDomainGetGuestInfo', 'virDomainAuthorizedSSHKeysGet', 'virDomainAuthorizedSSHKeysSet', 'virDomainGetMessages', 'virNodeDeviceGetAutostart', 'virDomainSaveParams', 'virDomainRestoreParams', 'virDomainLxcOpenNamespace', 'virDomainQemuMonitorCommand', 'virDomainQemuAgentCommand', } # These are functions which the generator skips completely - no python # or C code is generated. Generally should not be used for any more # functions than those already listed skip_function = { 'virConnectListDomains', # Python API is called virConnectListDomainsID for unknown reasons 'virConnSetErrorFunc', # Not used in Python API XXX is this a bug ? 'virResetError', # Not used in Python API XXX is this a bug ? 'virGetVersion', # Python C code is manually written 'virSetErrorFunc', # Python API is called virRegisterErrorHandler for unknown reasons 'virConnCopyLastError', # Python API is called virConnGetLastError instead 'virCopyLastError', # Python API is called virGetLastError instead 'virConnectOpenAuth', # Python C code is manually written 'virDefaultErrorFunc', # Python virErrorFuncHandler impl calls this from C 'virConnectDomainEventRegister', # overridden in virConnect.py 'virConnectDomainEventDeregister', # overridden in virConnect.py 'virConnectDomainEventRegisterAny', # overridden in virConnect.py 'virConnectDomainEventDeregisterAny', # overridden in virConnect.py 'virConnectNetworkEventRegisterAny', # overridden in virConnect.py 'virConnectNetworkEventDeregisterAny', # overridden in virConnect.py 'virConnectStoragePoolEventRegisterAny', # overridden in virConnect.py 'virConnectStoragePoolEventDeregisterAny', # overridden in virConnect.py 'virConnectNodeDeviceEventRegisterAny', # overridden in virConnect.py 'virConnectNodeDeviceEventDeregisterAny', # overridden in virConnect.py 'virConnectSecretEventRegisterAny', # overridden in virConnect.py 'virConnectSecretEventDeregisterAny', # overridden in virConnect.py 'virSaveLastError', # We have our own python error wrapper 'virFreeError', # Only needed if we use virSaveLastError 'virConnectListAllDomains', # overridden in virConnect.py 'virDomainListAllCheckpoints', # overridden in virDomain.py 'virDomainCheckpointListAllChildren', # overridden in virDomainCheckpoint.py 'virDomainListAllSnapshots', # overridden in virDomain.py 'virDomainSnapshotListAllChildren', # overridden in virDomainSnapshot.py 'virConnectListAllStoragePools', # overridden in virConnect.py 'virStoragePoolListAllVolumes', # overridden in virStoragePool.py 'virConnectListAllNetworks', # overridden in virConnect.py 'virNetworkListAllPorts', # overridden in virConnect.py 'virConnectListAllInterfaces', # overridden in virConnect.py 'virConnectListAllNodeDevices', # overridden in virConnect.py 'virConnectListAllNWFilters', # overridden in virConnect.py 'virConnectListAllNWFilterBindings', # overridden in virConnect.py 'virConnectListAllSecrets', # overridden in virConnect.py 'virConnectGetAllDomainStats', # overridden in virConnect.py 'virDomainListGetStats', # overridden in virConnect.py 'virDomainFDAssociate', # overridden in virDomain.py 'virStreamRecvAll', # Pure python libvirt-override-virStream.py 'virStreamSendAll', # Pure python libvirt-override-virStream.py 'virStreamRecv', # overridden in libvirt-override-virStream.py 'virStreamSend', # overridden in libvirt-override-virStream.py 'virStreamRecvHole', # overridden in libvirt-override-virStream.py 'virStreamSendHole', # overridden in libvirt-override-virStream.py 'virStreamRecvFlags', # overridden in libvirt-override-virStream.py 'virStreamSparseRecvAll', # overridden in libvirt-override-virStream.py 'virStreamSparseSendAll', # overridden in libvirt-override-virStream.py 'virConnectUnregisterCloseCallback', # overridden in virConnect.py 'virConnectRegisterCloseCallback', # overridden in virConnect.py 'virDomainCreateXMLWithFiles', # overridden in virConnect.py 'virDomainCreateWithFiles', # overridden in virDomain.py 'virDomainFSFreeze', # overridden in virDomain.py 'virDomainFSThaw', # overridden in virDomain.py 'virDomainGetTime', # overridden in virDomain.py 'virDomainSetTime', # overridden in virDomain.py # 'Ref' functions have no use for bindings users. "virConnectRef", "virDomainRef", "virInterfaceRef", "virNetworkRef", "virNetworkPortRef", "virNodeDeviceRef", "virSecretRef", "virNWFilterRef", "virNWFilterBindingRef", "virStoragePoolRef", "virStorageVolRef", "virStreamRef", "virDomainCheckpointRef", "virDomainSnapshotRef", # This functions shouldn't be called via the bindings (and even the docs # contain an explicit warning to that effect). The equivalent should be # implemented in pure python for each class "virDomainGetConnect", "virInterfaceGetConnect", "virNetworkGetConnect", "virNetworkPortGetNetwork", "virSecretGetConnect", "virNWFilterGetConnect", "virStoragePoolGetConnect", "virStorageVolGetConnect", "virDomainCheckpointGetConnect", "virDomainCheckpointGetDomain", "virDomainSnapshotGetConnect", "virDomainSnapshotGetDomain", # only useful in C code, python code uses dict for typed parameters "virTypedParamsAddBoolean", "virTypedParamsAddDouble", "virTypedParamsAddFromString", "virTypedParamsAddInt", "virTypedParamsAddLLong", "virTypedParamsAddString", "virTypedParamsAddUInt", "virTypedParamsAddULLong", "virTypedParamsClear", "virTypedParamsFree", "virTypedParamsGet", "virTypedParamsGetBoolean", "virTypedParamsGetDouble", "virTypedParamsGetInt", "virTypedParamsGetLLong", "virTypedParamsGetString", "virTypedParamsGetUInt", "virTypedParamsGetULLong", 'virNetworkDHCPLeaseFree', # only useful in C, python code uses list 'virDomainStatsRecordListFree', # only useful in C, python uses dict 'virDomainFSInfoFree', # only useful in C, python code uses list 'virDomainIOThreadInfoFree', # only useful in C, python code uses list 'virDomainInterfaceFree', # only useful in C, python code uses list "virDomainLxcEnterNamespace", "virDomainLxcEnterSecurityLabel", # "virDomainQemuAttach", 'virConnectDomainQemuMonitorEventRegister', # overridden in -qemu.py 'virConnectDomainQemuMonitorEventDeregister', # overridden in -qemu.py 'virDomainQemuMonitorCommandWithFiles', # overridden in -qemu.py } # Generate C code, but skip python impl function_skip_python_impl = { "virStreamFree", # Needed in custom virStream __del__, but free shouldn't # be exposed in bindings } function_skip_index_one = { "virDomainRevertToSnapshot", } def validate_function(name): (desc, ret, args, file, mod, cond) = functions[name] if name in skip_function: return [] if name in skip_impl: return [] failed = False unknown = [] for a_name, a_type, a_info in args: # This should be correct if a_type[0:6] == "const ": a_type = a_type[6:] if a_type in skipped_types: return [] if a_type not in py_types: unknown.append(a_type) r_type, r_info, r_field = ret if r_type in skipped_types: return [] if r_type != 'void' and r_type not in py_types: unknown.append(r_type) return unknown def validate_functions(): unknown_types = defaultdict(list) # type: Dict[str, List[str]] funcs_failed = [] # type: List[str] for name in sorted(functions): unknown = validate_function(name) if unknown: funcs_failed.append(name) for thetype in unknown: unknown_types[thetype].append(name) if unknown_types: print("Missing type converters: ") for type, count in unknown_types.items(): print("%s:%d " % (type, len(count))) for f in funcs_failed: print("ERROR: failed %s" % f) if funcs_failed: return -1 return 0 def skip_both_impl(name: str) -> bool: if name in skip_function: return True (desc, ret, args, file, mod, cond) = functions[name] for a_name, a_type, a_info in args: # This should be correct if a_type[0:6] == "const ": a_type = a_type[6:] if a_type in skipped_types: return True r_type, r_info, r_field = ret if r_type in skipped_types: return True return False def skip_c_impl(name: str) -> bool: if skip_both_impl(name): return True if name in skip_impl: return True return False def skip_py_impl(name: str) -> bool: if skip_both_impl(name): return True if name in function_skip_python_impl: return True return False def print_function_wrapper(package: str, name: str, output: IO[str], export: IO[str], include: IO[str]) -> bool: """ :returns: True if generated, False if skipped """ (desc, ret, args, file, mod, cond) = functions[name] if skip_c_impl(name): return False c_call = "" format = "" format_args = "" c_args = "" c_return = "" c_convert = "" num_bufs = 0 for a_name, a_type, a_info in args: # This should be correct if a_type[0:6] == "const ": a_type = a_type[6:] c_args += " %s %s;\n" % (a_type, a_name) if a_type in py_types: (f, t, n, c) = py_types[a_type] if f: format += f if t: format_args += ", &pyobj_%s" % (a_name) c_args += " PyObject *pyobj_%s;\n" % (a_name) c_convert += \ " %s = (%s) Py%s_Get(pyobj_%s);\n" % ( a_name, a_type, t, a_name) else: format_args += ", &%s" % (a_name) if f == 't#': format_args += ", &py_buffsize%d" % num_bufs c_args += " int py_buffsize%d;\n" % num_bufs num_bufs += 1 if c_call: c_call += ", " c_call += "%s" % (a_name) else: raise Exception("Unexpected type %s in function %s" % (a_type, name)) if format: format += ":%s" % (name) r_type, r_info, r_field = ret if r_type == 'void': if file == "python_accessor": if args[1][1] == "char *": c_call = "\n VIR_FREE(%s->%s);\n" % ( args[0][0], args[1][0]) c_call += " %s->%s = (%s)strdup((const xmlChar *)%s);\n" % ( args[0][0], args[1][0], args[1][1], args[1][0]) else: c_call = "\n %s->%s = %s;\n" % (args[0][0], args[1][0], args[1][0]) else: c_call = "\n %s(%s);\n" % (name, c_call) ret_convert = " Py_INCREF(Py_None);\n return Py_None;\n" elif r_type in py_types: (f, t, n, c) = py_types[r_type] c_return = " %s c_retval;\n" % (r_type) if file == "python_accessor" and r_field: c_call = "\n c_retval = %s->%s;\n" % (args[0][0], r_field) else: c_call = "\n c_retval = %s(%s);\n" % (name, c_call) ret_convert = " py_retval = libvirt_%sWrap((%s) c_retval);\n" % (n, c) if n == "charPtr": ret_convert += " free(c_retval);\n" ret_convert += " return py_retval;\n" else: raise Exception("Unexpected type %s in function %s" % (r_type, name)) if cond: include.write("#if %s\n" % cond) export.write("#if %s\n" % cond) output.write("#if %s\n" % cond) include.write("PyObject * ") include.write("%s_%s(PyObject *self, PyObject *args);\n" % (package, name)) export.write(" { (char *)\"%s\", %s_%s, METH_VARARGS, NULL },\n" % (name, package, name)) if file == "python": # Those have been manually generated if cond: include.write("#endif\n") export.write("#endif\n") output.write("#endif\n") return True if file == "python_accessor" and r_type != "void" and not r_field: # Those have been manually generated if cond: include.write("#endif\n") export.write("#endif\n") output.write("#endif\n") return True output.write("PyObject *\n") output.write("%s_%s(PyObject *self ATTRIBUTE_UNUSED," % (package, name)) output.write(" PyObject *args") if format == "": output.write(" ATTRIBUTE_UNUSED") output.write(") {\n") if r_type != 'void': output.write(" PyObject *py_retval;\n") if c_return: output.write(c_return) if c_args: output.write(c_args) if format: output.write("\n if (!PyArg_ParseTuple(args, (char *)\"%s\"%s))\n" % (format, format_args)) output.write(" return NULL;\n") if c_convert: output.write(c_convert + "\n") output.write(" LIBVIRT_BEGIN_ALLOW_THREADS;") output.write(c_call) output.write(" LIBVIRT_END_ALLOW_THREADS;\n") output.write(ret_convert) output.write("}\n\n") if cond: include.write("#endif /* %s */\n" % cond) export.write("#endif /* %s */\n" % cond) output.write("#endif /* %s */\n" % cond) return True def print_c_pointer(classname: str, output: IO[str], export: IO[str], include: IO[str]) -> None: output.write("PyObject *\n") output.write("libvirt_%s_pointer(PyObject *self ATTRIBUTE_UNUSED, PyObject *args)\n" % classname) output.write("{\n") output.write(" %sPtr ptr;\n" % classname) output.write(" PyObject *pyptr;\n") output.write(" PyObject *pylong;\n") output.write("\n") output.write(" if (!PyArg_ParseTuple(args, (char *) \"O\", &pyptr))\n") output.write(" return NULL;\n") output.write(" ptr = (%sPtr) Py%s_Get(pyptr);\n" % (classname, classname)) output.write(" pylong = PyLong_FromVoidPtr(ptr);\n") output.write(" return pylong;\n") output.write("}\n") output.write("\n") include.write("PyObject *libvirt_%s_pointer(PyObject *self, PyObject *args);\n" % classname) export.write(" { (char *)\"%s_pointer\", libvirt_%s_pointer, METH_VARARGS, NULL },\n" % (classname, classname)) def load_apis(module: str, api_xml: str): global onlyOverrides try: onlyOverrides = False with open(api_xml) as stream: parse(stream) except IOError as msg: print(api_xml, ":", msg) sys.exit(1) n = len(functions) if not quiet: print("Found %d functions in %s" % ((n), api_xml)) override_api_xml = "%s-override-api.xml" % module py_types['pythonObject'] = ('O', "pythonObject", "pythonObject", "pythonObject") try: onlyOverrides = True with open(override_api_xml) as stream: parse(stream) except IOError as msg: print(override_api_xml, ":", msg) if not quiet: # XXX: This is not right, same function already in @functions # will be overwritten. print("Found %d functions in %s" % (len(functions) - n, override_api_xml)) def emit_c_code(module: str) -> None: package = module.replace('-', '_') nb_wrap = 0 header_file = "build/%s.h" % module export_file = "build/%s-export.c" % module wrapper_file = "build/%s.c" % module include = open(header_file, "w") include.write("/* Generated by generator.py */\n\n") export = open(export_file, "w") export.write("/* Generated by generator.py */\n\n") wrapper = open(wrapper_file, "w") wrapper.write("/* Generated by generator.py */\n\n") wrapper.write("#include <stdlib.h>\n") wrapper.write("#include <Python.h>\n") wrapper.write("#include <libvirt/%s.h>\n" % (module,)) wrapper.write("#include \"typewrappers.h\"\n") wrapper.write("#include \"build/%s.h\"\n\n" % (module,)) for function in sorted(functions): if print_function_wrapper(package, function, wrapper, export, include): nb_wrap += 1 if module == "libvirt": # Write C pointer conversion functions. for classname in primary_classes: print_c_pointer(classname, wrapper, export, include) # Write define wrappers around event id enums, so that the # preprocessor can see which enums were available. for event_id in event_ids: include.write("#define %s %s\n" % (event_id, event_id)) include.close() export.close() wrapper.close() if not quiet: print("Generated %d wrapper functions" % nb_wrap) ####################################################################### # # This part writes part of the Python front-end classes based on # mapping rules between types and classes and also based on function # renaming to get consistent function names at the Python level # ####################################################################### # # The type automatically remapped to generated classes # "C-type" -> (accessor, create, class, parent-class) # classes_type = { "virDomainPtr": ("._o", "virDomain(%(p)s, _obj=%(o)s)", "virDomain", "virConnect"), "virDomain *": ("._o", "virDomain(%(p)s, _obj=%(o)s)", "virDomain", "virConnect"), "virNetworkPtr": ("._o", "virNetwork(%(p)s, _obj=%(o)s)", "virNetwork", "virConnect"), "virNetwork *": ("._o", "virNetwork(%(p)s, _obj=%(o)s)", "virNetwork", "virConnect"), "virNetworkPortPtr": ("._o", "virNetworkPort(%(p)s, _obj=%(o)s)", "virNetworkPort", "virNetwork"), "virNetworkPort *": ("._o", "virNetworkPort(%(p)s, _obj=%(o)s)", "virNetworkPort", "virNetwork"), "virInterfacePtr": ("._o", "virInterface(%(p)s, _obj=%(o)s)", "virInterface", "virConnect"), "virInterface *": ("._o", "virInterface(%(p)s, _obj=%(o)s)", "virInterface", "virConnect"), "virStoragePoolPtr": ("._o", "virStoragePool(%(p)s, _obj=%(o)s)", "virStoragePool", "virConnect"), "virStoragePool *": ("._o", "virStoragePool(%(p)s, _obj=%(o)s)", "virStoragePool", "virConnect"), "virStorageVolPtr": ("._o", "virStorageVol(%(p)s, _obj=%(o)s)", "virStorageVol", "virConnect"), "virStorageVol *": ("._o", "virStorageVol(%(p)s, _obj=%(o)s)", "virStorageVol", "virConnect"), "virNodeDevicePtr": ("._o", "virNodeDevice(%(p)s, _obj=%(o)s)", "virNodeDevice", "virConnect"), "virNodeDevice *": ("._o", "virNodeDevice(%(p)s, _obj=%(o)s)", "virNodeDevice", "virConnect"), "virSecretPtr": ("._o", "virSecret(%(p)s, _obj=%(o)s)", "virSecret", "virConnect"), "virSecret *": ("._o", "virSecret(%(p)s, _obj=%(o)s)", "virSecret", "virConnect"), "virNWFilterPtr": ("._o", "virNWFilter(%(p)s, _obj=%(o)s)", "virNWFilter", "virConnect"), "virNWFilter *": ("._o", "virNWFilter(%(p)s, _obj=%(o)s)", "virNWFilter", "virConnect"), "virNWFilterBindingPtr": ("._o", "virNWFilterBinding(%(p)s, _obj=%(o)s)", "virNWFilterBinding", "virConnect"), "virNWFilterBinding *": ("._o", "virNWFilterBinding(%(p)s, _obj=%(o)s)", "virNWFilterBinding", "virConnect"), "virStreamPtr": ("._o", "virStream(%(p)s, _obj=%(o)s)", "virStream", "virConnect"), "virStream *": ("._o", "virStream(%(p)s, _obj=%(o)s)", "virStream", "virConnect"), "virConnectPtr": ("._o", "virConnect(_obj=%(o)s)", "virConnect", ""), "virConnect *": ("._o", "virConnect(_obj=%(o)s)", "virConnect", ""), "virDomainCheckpointPtr": ("._o", "virDomainCheckpoint(%(p)s, _obj=%(o)s)", "virDomainCheckpoint", "virDomain"), "virDomainCheckpoint *": ("._o", "virDomainCheckpoint(%(p)s, _obj=%(o)s)", "virDomainCheckpoint", "virDomain"), "virDomainSnapshotPtr": ("._o", "virDomainSnapshot(%(p)s, _obj=%(o)s)", "virDomainSnapshot", "virDomain"), "virDomainSnapshot *": ("._o", "virDomainSnapshot(%(p)s, _obj=%(o)s)", "virDomainSnapshot", "virDomain"), } primary_classes = ["virDomain", "virNetwork", "virNetworkPort", "virInterface", "virStoragePool", "virStorageVol", "virConnect", "virNodeDevice", "virSecret", "virNWFilter", "virNWFilterBinding", "virStream", "virDomainCheckpoint", "virDomainSnapshot"] classes_destructors = { "virDomain": "virDomainFree", "virNetwork": "virNetworkFree", "virNetworkPort": "virNetworkPortFree", "virInterface": "virInterfaceFree", "virStoragePool": "virStoragePoolFree", "virStorageVol": "virStorageVolFree", "virNodeDevice": "virNodeDeviceFree", "virSecret": "virSecretFree", "virNWFilter": "virNWFilterFree", "virNWFilterBinding": "virNWFilterBindingFree", "virDomainCheckpoint": "virDomainCheckpointFree", "virDomainSnapshot": "virDomainSnapshotFree", # We hand-craft __del__ for this one # "virStream": "virStreamFree", } class_skip_connect_impl = { "virConnect", } class_domain_impl = { "virDomainCheckpoint", "virDomainSnapshot", } class_network_impl = { "virNetworkPort", } functions_noexcept = { 'virDomainGetID', 'virDomainGetName', 'virNetworkGetName', 'virInterfaceGetName', 'virStoragePoolGetName', 'virStorageVolGetName', 'virStorageVolGetkey', 'virNodeDeviceGetName', 'virNodeDeviceGetParent', 'virSecretGetUsageType', 'virSecretGetUsageID', 'virNWFilterGetName', 'virNWFilterBindingGetFilterName', 'virNWFilterBindingGetPortDev', } function_classes = { "None": [] } # type: Dict[str, List[Tuple[int, str, str, ArgumentType, List[ArgumentType], str, str]]] # Functions returning an integral type which need special rules to # check for errors and raise exceptions. functions_int_exception_test = { 'virDomainGetMaxMemory': "%s == 0", } functions_int_default_test = "%s == -1" def is_integral_type(name: str) -> bool: return re.search("^(unsigned)? ?(int|long)$", name) is not None def is_optional_arg(info: str) -> bool: return re.search(r"^\(?optional\)?", info) is not None def is_python_noninteger_type(name: str) -> bool: return name[-1:] == "*" def nameFixup(name: str, classe: str, type: str, file: str) -> str: # avoid a disastrous clash listname = classe + "List" l = len(classe) if name[0:l] == listname: func = name[l:] func = func[0:1].lower() + func[1:] elif name[0:16] == "virNetworkDefine": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:19] == "virNetworkCreateXML": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:16] == "virNetworkLookup": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:23] == "virNetworkPortCreateXML": func = name[10:] func = func[0:1].lower() + func[1:] elif name[0:20] == "virNetworkPortLookup": func = name[10:] func = func[0:1].lower() + func[1:] elif name[0:18] == "virInterfaceDefine": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:21] == "virInterfaceCreateXML": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:18] == "virInterfaceLookup": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:15] == "virSecretDefine": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:15] == "virSecretLookup": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:27] == "virNWFilterBindingCreateXML": func = name[3:] func = func[0:3].lower() + func[3:] elif name[0:24] == "virNWFilterBindingLookup": func = name[3:] func = func[0:3].lower() + func[3:] elif name[0:24] == "virNWFilterBindingDefine": func = name[3:] func = func[0:3].lower() + func[3:] elif name[0:24] == "virNWFilterBindingLookup": func = name[3:] func = func[0:3].lower() + func[3:] elif name[0:17] == "virNWFilterDefine": func = name[3:] func = func[0:3].lower() + func[3:] elif name[0:17] == "virNWFilterLookup": func = name[3:] func = func[0:3].lower() + func[3:] elif name[0:20] == "virStoragePoolDefine": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:23] == "virStoragePoolCreateXML": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:20] == "virStoragePoolLookup": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:19] == "virStorageVolDefine": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:19] == "virStorageVolLookup": func = name[3:] func = func[0:1].lower() + func[1:] elif name[0:20] == "virDomainGetCPUStats": func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:24] == "virDomainGetIOThreadInfo": func = name[12:] func = func[0:2].lower() + func[2:] elif name[0:18] == "virDomainGetFSInfo": func = name[12:] func = func[0:2].lower() + func[2:] elif name[0:12] == "virDomainGet": func = name[12:] func = func[0:1].lower() + func[1:] elif name[0:31] == "virDomainCheckpointLookupByName": func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:28] == "virDomainCheckpointCreateXML": func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:19] == "virDomainCheckpoint": func = name[19:] func = func[0:1].lower() + func[1:] elif name[0:29] == "virDomainSnapshotLookupByName": func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:26] == "virDomainSnapshotListNames": func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:28] == "virDomainSnapshotNumChildren": func = name[17:] func = func[0:1].lower() + func[1:] elif name[0:20] == "virDomainSnapshotNum": func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:26] == "virDomainSnapshotCreateXML": func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:24] == "virDomainSnapshotCurrent": func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:17] == "virDomainSnapshot": func = name[17:] func = func[0:1].lower() + func[1:] elif name[0:9] == "virDomain": func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:17] == "virNetworkPortGet": func = name[17:] func = func[0:1].lower() + func[1:] elif name[0:13] == "virNetworkGet": func = name[13:] func = func[0:1].lower() + func[1:] func = func.replace("dHCP", "DHCP") elif name[0:14] == "virNetworkPort": func = name[14:] func = func[0:1].lower() + func[1:] elif name[0:10] == "virNetwork": func = name[10:] func = func[0:1].lower() + func[1:] elif name[0:15] == "virInterfaceGet": func = name[15:] func = func[0:1].lower() + func[1:] elif name[0:12] == "virInterface": func = name[12:] func = func[0:1].lower() + func[1:] elif name[0:12] == 'virSecretGet': func = name[12:] func = func[0:1].lower() + func[1:] elif name[0:9] == 'virSecret': func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:21] == 'virNWFilterBindingGet': func = name[21:] func = func[0:1].lower() + func[1:] elif name[0:18] == 'virNWFilterBinding': func = name[18:] func = func[0:1].lower() + func[1:] elif name[0:14] == 'virNWFilterGet': func = name[14:] func = func[0:1].lower() + func[1:] elif name[0:11] == 'virNWFilter': func = name[11:] func = func[0:1].lower() + func[1:] elif name[0:12] == 'virStreamNew': func = "newStream" elif name[0:9] == 'virStream': func = name[9:] func = func[0:1].lower() + func[1:] elif name[0:17] == "virStoragePoolGet": func = name[17:] func = func[0:1].lower() + func[1:] elif name[0:14] == "virStoragePool": func = name[14:] func = func[0:1].lower() + func[1:] elif name[0:16] == "virStorageVolGet": func = name[16:] func = func[0:1].lower() + func[1:] elif name[0:13] == "virStorageVol": func = name[13:] func = func[0:1].lower() + func[1:] elif name[0:16] == "virNodeDeviceGet": func = name[16].lower() + name[17:] elif name[0:19] == "virNodeDeviceLookup": func = name[3].lower() + name[4:] elif name[0:22] == "virNodeDeviceCreateXML": func = name[3].lower() + name[4:] elif name[0:19] == "virNodeDeviceDefine": func = name[3].lower() + name[4:] elif name[0:13] == "virNodeDevice": func = name[13].lower() + name[14:] elif name[0:7] == "virNode": func = name[7:] func = func[0:1].lower() + func[1:] elif name[0:10] == "virConnect": func = name[10:] func = func[0:1].lower() + func[1:] elif name[0:3] == "xml": func = name[3:] func = func[0:1].lower() + func[1:] else: func = name if func == "iD": func = "ID" if func == "uUID": func = "UUID" if func == "uUIDString": func = "UUIDString" if func == "oSType": func = "OSType" if func == "xMLDesc": func = "XMLDesc" if func == "mACString": func = "MACString" return func def functionSortKey(info: Tuple) -> Tuple[str, str]: (index, func, name, ret, args, filename, mod) = info return func, filename def writeDoc(module: str, name: str, args: List[ArgumentType], indent: str, output: IO) -> None: if not functions[name][0]: return val = functions[name][0] val = val.replace("NULL", "None") sep = '\n%s' % (indent,) output.write('%s"""%s """\n' % (indent, sep.join(val.splitlines()))) def emit_py_code(module: str) -> None: package = module.replace('-', '_') if module == "libvirt": pymod = "libvirtmod" cygmod = "cygvirtmod" elif module == "libvirt-lxc": pymod = "libvirtmod_lxc" cygmod = "cygvirtmod_lxc" elif module == "libvirt-qemu": pymod = "libvirtmod_qemu" cygmod = "cygvirtmod_qemu" else: raise Exception("Unknown module '%s'" % module) for tinfo in classes_type.values(): function_classes[tinfo[2]] = [] # # Build the list of C types to look for ordered to start # with primary classes # ctypes = [] # type: List[str] classes_list = [] # type: List[str] ctypes_processed = set() # type: Set[str] classes_processed = set() # type: Set[str] for classe in primary_classes: classes_list.append(classe) classes_processed.add(classe) for type, tinfo in classes_type.items(): if tinfo[2] == classe: ctypes.append(type) ctypes_processed.add(type) for type, tinfo in classes_type.items(): if type in ctypes_processed: continue if tinfo[2] not in classes_processed: classes_list.append(tinfo[2]) classes_processed.add(tinfo[2]) ctypes.append(type) ctypes_processed.add(type) for name, (desc, ret, args, file, mod, cond) in functions.items(): if skip_py_impl(name): continue for type in ctypes: classe = classes_type[type][2] if name[0:3] == "vir" and len(args) >= 1 and args[0][1] == type: func = nameFixup(name, classe, type, file) info = (0, func, name, ret, args, file, mod) function_classes[classe].append(info) break elif name[0:3] == "vir" and len(args) >= 2 and args[1][1] == type \ and file != "python_accessor" and name not in function_skip_index_one: func = nameFixup(name, classe, type, file) info = (1, func, name, ret, args, file, mod) function_classes[classe].append(info) break else: func = nameFixup(name, "None", file, file) info = (0, func, name, ret, args, file, mod) function_classes['None'].append(info) classes_file = "build/%s.py" % package extra_file = "%s-override.py" % module extra = None classes = open(classes_file, "w") if os.path.exists(extra_file): extra = open(extra_file, "r") classes.write("#\n") classes.write("# WARNING WARNING WARNING WARNING\n") classes.write("#\n") classes.write("# This file is automatically written by generator.py. Any changes\n") classes.write("# made here will be lost.\n") classes.write("#\n") classes.write("# To change the manually written methods edit %s-override.py\n" % (module,)) classes.write("# To change the automatically written methods edit generator.py\n") classes.write("#\n") classes.write("# WARNING WARNING WARNING WARNING\n") classes.write("#\n") classes.write("try:\n") classes.write(" import %s # type: ignore\n" % pymod) classes.write("except ImportError as lib_e:\n") classes.write(" try:\n") classes.write(" import %s as %s # type: ignore\n" % (cygmod, pymod)) classes.write(" except ImportError as cyg_e:\n") classes.write(" if \"No module named\" in str(cyg_e):\n") classes.write(" raise lib_e\n\n") if module != "libvirt": classes.write("import libvirt\n") classes.write("\n") if extra: classes.write("# WARNING WARNING WARNING WARNING\n") classes.write("#\n") classes.write("# Manually written part of python bindings for %s\n" % module) classes.writelines(extra.readlines()) classes.write("#\n") classes.write("# WARNING WARNING WARNING WARNING\n") classes.write("#\n") classes.write("# Automatically written part of python bindings for %s\n" % module) classes.write("#\n") classes.write("# WARNING WARNING WARNING WARNING\n") if extra: extra.close() if "None" in function_classes: flist = function_classes["None"] oldfile = "" for (index, func, name, ret, args, file, mod) in sorted(flist, key=functionSortKey): if file != oldfile: classes.write("#\n# Functions from module %s\n#\n\n" % file) oldfile = file classes.write("def %s(" % func) for n, (a_name, a_type, a_info) in enumerate(args): if n != 0: classes.write(", ") classes.write("%s" % a_name) if a_name == "flags" or is_optional_arg(a_info): if is_integral_type(a_type): classes.write("=0") else: classes.write("=None") classes.write("):\n") writeDoc(module, name, args, ' ', classes) for a_name, a_type, a_info in args: if a_type in classes_type: classes.write(" if %s is None:\n" " %s__o = None\n" % (a_name, a_name)) classes.write(" else:\n" " %s__o = %s%s\n" % (a_name, a_name, classes_type[a_type][0])) r_type, r_info, r_field = ret if r_type != "void": classes.write(" ret = ") else: classes.write(" ") classes.write("%s.%s(" % (pymod, name)) for n, (a_name, a_type, a_info) in enumerate(args): if n != 0: classes.write(", ") classes.write("%s" % a_name) if a_type in classes_type: classes.write("__o") classes.write(")\n") if r_type != "void": if r_type in classes_type: # # Raise an exception # if name in functions_noexcept: classes.write(" if ret is None:\n" " return None\n") else: classes.write( " if ret is None:\n" " raise libvirtError('%s() failed')\n" % (name)) tinfo = classes_type[r_type] classes.write(" return ") classes.write(tinfo[1] % {"o": "ret"}) classes.write("\n") # For functions returning an integral type there are # several things that we can do, depending on the # contents of functions_int_*: elif is_integral_type(r_type): if name not in functions_noexcept: test = functions_int_exception_test.get(name, functions_int_default_test) % ("ret",) classes.write( " if %s:\n" " raise libvirtError('%s() failed')\n" % (test, name)) classes.write(" return ret\n") elif is_python_noninteger_type(r_type): if name not in functions_noexcept: classes.write( " if ret is None:\n" " raise libvirtError('%s() failed')\n" % (name,)) classes.write(" return ret\n") else: classes.write(" return ret\n") classes.write("\n") modclasses = [] if module == "libvirt": modclasses = classes_list for classname in modclasses: PARENTS = { "virConnect": "self._conn", "virDomain": "self._dom", "virNetwork": "self._net", classname: "self", } if classname == "None": pass else: classes.write("class %s(object):\n" % (classname)) if classname == "virStorageVol": classes.write(" # The size (in bytes) of buffer used in sendAll(),\n") classes.write(" # recvAll(), sparseSendAll() and sparseRecvAll()\n") classes.write(" # methods. This corresponds to the size of payload\n") classes.write(" # of a stream packet.\n") classes.write(" streamBufSize = 262120\n\n") if classname in ["virDomain", "virNetwork", "virInterface", "virStoragePool", "virStorageVol", "virNodeDevice", "virSecret", "virStream", "virNWFilter", "virNWFilterBinding"]: classes.write(" def __init__(self, conn, _obj=None):\n") classes.write(" self._conn = conn\n") elif classname in ["virDomainCheckpoint", "virDomainSnapshot"]: classes.write(" def __init__(self, dom, _obj=None):\n") classes.write(" self._dom = dom\n") classes.write(" self._conn = dom.connect()\n") elif classname in ["virNetworkPort"]: classes.write(" def __init__(self, net, _obj=None) -> None:\n") classes.write(" self._net = net\n") classes.write(" self._conn = net.connect()\n") else: classes.write(" def __init__(self, _obj=None):\n") classes.write(" if type(_obj).__name__ not in [\"PyCapsule\", \"PyCObject\"]:\n") classes.write(" raise Exception(\"Expected a wrapped C Object but got %s\" % type(_obj))\n") classes.write(" self._o = _obj\n\n") destruct = None if classname in classes_destructors: classes.write(" def __del__(self):\n") classes.write(" if self._o is not None:\n") classes.write(" %s.%s(self._o)\n" % (pymod, classes_destructors[classname])) classes.write(" self._o = None\n\n") destruct = classes_destructors[classname] if classname not in class_skip_connect_impl: # Build python safe 'connect' method classes.write(" def connect(self):\n") classes.write(" return self._conn\n\n") if classname in class_domain_impl: classes.write(" def domain(self):\n") classes.write(" return self._dom\n\n") if classname in class_network_impl: classes.write(" def network(self):\n") classes.write(" return self._net\n\n") classes.write(" def c_pointer(self):\n") classes.write(" \"\"\"Get C pointer to underlying object\"\"\"\n") classes.write(" return %s.%s_pointer(self._o)\n\n" % (pymod, classname)) flist = function_classes[classname] oldfile = "" for (index, func, name, ret, args, file, mod) in sorted(flist, key=functionSortKey): # # Do not provide as method the destructors for the class # to avoid double free # if name == destruct: continue if file != oldfile: if file == "python_accessor": classes.write(" # accessors for %s\n" % (classname)) else: classes.write(" #\n") classes.write(" # %s functions from module %s\n" % ( classname, file)) classes.write(" #\n\n") oldfile = file classes.write(" def %s(self" % func) for n, (a_name, a_type, a_info) in enumerate(args): if n != index: classes.write(", %s" % a_name) if a_name == "flags" or is_optional_arg(a_info): if is_integral_type(a_type): classes.write("=0") else: classes.write("=None") classes.write("):\n") writeDoc(module, name, args, ' ', classes) for n, (a_name, a_type, a_info) in enumerate(args): if a_type in classes_type: if n != index: classes.write(" if %s is None:\n" " %s__o = None\n" % (a_name, a_name)) classes.write(" else:\n" " %s__o = %s%s\n" % (a_name, a_name, classes_type[a_type][0])) r_type, r_info, r_field = ret if r_type != "void": classes.write(" ret = ") else: classes.write(" ") classes.write("%s.%s(" % (pymod, name)) for n, (a_name, a_type, a_info) in enumerate(args): if n != 0: classes.write(", ") if n != index: classes.write("%s" % a_name) if a_type in classes_type: classes.write("__o") else: classes.write("self") if a_type in classes_type: classes.write(classes_type[a_type][0]) classes.write(")\n") if name == "virConnectClose": classes.write(" self._o = None\n") # For functions returning object types: if r_type != "void": if r_type in classes_type: # # Raise an exception # if name in functions_noexcept: classes.write( " if ret is None:\n" " return None\n") else: classes.write( " if ret is None:\n" " raise libvirtError('%s() failed')\n" % (name,)) # # generate the returned class wrapper for the object # tinfo = classes_type[r_type] classes.write(" __tmp = ") classes.write(tinfo[1] % {"o": "ret", "p": PARENTS[tinfo[3]]}) classes.write("\n") # # return the class # classes.write(" return __tmp\n") # For functions returning an integral type there # are several things that we can do, depending on # the contents of functions_int_*: elif is_integral_type(r_type): if name not in functions_noexcept: test = functions_int_exception_test.get(name, functions_int_default_test) % ("ret",) classes.write( " if %s:\n" " raise libvirtError('%s() failed')\n" % (test, name)) classes.write(" return ret\n") elif is_python_noninteger_type(r_type): if name not in functions_noexcept: classes.write( " if ret is None:\n" " raise libvirtError('%s() failed')\n" % (name,)) classes.write(" return ret\n") else: classes.write(" return ret\n") classes.write("\n") # Append "<classname>.py" to class def, iff it exists class_override = "%s-override-%s.py" % (module, classname) if os.path.exists(class_override): extra = open(class_override, "r") classes.write(" #\n") classes.write(" # %s methods from %s.py (hand coded)\n" % (classname, classname)) classes.write(" #\n") cached = None # Since we compile with older libvirt, we don't want to pull # in manually written python methods which call C methods # that don't exist. This code attempts to detect which # methods to skip by looking at the libvirtmod.XXXX calls def shouldSkip(lines: List[str]) -> bool: for line in lines: offset = line.find(pymod + ".") if offset != -1: func = line[offset + 11:] offset = func.find("(") func = func[0:offset] if not skip_c_impl(func) and func != "virConnectListDomains": return True return False for line in extra.readlines(): offset = line.find(" def ") if offset != -1: name = line[offset + 5:] offset = name.find("(") name = name[0:offset] if cached: if not shouldSkip(cached): classes.writelines(cached) if name == "__del__": cached = None classes.write(line) else: cached = [line] else: if cached: cached.append(line) else: classes.write(line) if cached is not None and not shouldSkip(cached): classes.writelines(cached) classes.write("\n") extra.close() direct_functions = {} if module != "libvirt": direct_functions = functions classes.write("#\n# Functions from module %s\n#\n\n" % module) # # Generate functions directly, no classes # for name, (desc, ret, args, file, mod, cond) in sorted(direct_functions.items()): if skip_py_impl(name): continue func = nameFixup(name, 'None', '', '') classes.write("def %s(" % func) for n, (a_name, a_type, a_info) in enumerate(args): if n != 0: classes.write(", ") classes.write("%s" % a_name) classes.write("):\n") writeDoc(module, name, args, ' ', classes) r_type, r_info, r_field = ret if r_type != "void": classes.write(" ret = ") else: classes.write(" ") classes.write("%s.%s(" % (pymod, name)) conn = None for n, (a_name, a_type, a_info) in enumerate(args): if a_type == "virConnectPtr": conn = a_name if n != 0: classes.write(", ") if a_type in ["virDomainPtr", "virConnectPtr"]: # FIXME: This might have problem if the function # has multiple args which are objects. classes.write("%s.%s" % (a_name, "_o")) else: classes.write("%s" % a_name) classes.write(")\n") if r_type != "void": classes.write(" if ret is None:\n" " raise libvirt.libvirtError('%s() failed')\n" % (name,)) if r_type == "virDomainPtr": classes.write(" __tmp = libvirt.virDomain(%s, _obj=ret)\n" % (conn,)) classes.write(" return __tmp\n") else: classes.write(" return ret\n") classes.write("\n") # # Generate enum constants # def enumsSortKey(data: Tuple[str, EnumValue]) -> Tuple[Union[int, float], str]: try: value = int(data[1]) # type: Union[int, float] except ValueError: value = float('inf') return value, data[0] # Resolve only one level of reference def resolveEnum(enum: EnumType, data: EnumType) -> EnumType: for name, val in enum.items(): try: int(val) except ValueError: enum[name] = data[val] # type: ignore return enum enumvals = list(enums.items()) # convert list of dicts to one dict enumData = {} # type: EnumType for type, enum in enumvals: enumData.update(enum) for type, enum in sorted(enumvals): classes.write("# %s\n" % type) items = sorted(resolveEnum(enum, enumData).items(), key=enumsSortKey) if items[-1][0].endswith('_LAST'): del items[-1] for name, value in items: classes.write("%s = %s\n" % (name, value)) classes.write("\n") if params: classes.write("# typed parameter names\n") for name, value in params: classes.write("%s = \"%s\"\n" % (name, value)) classes.close() if sys.argv[1] not in ["libvirt", "libvirt-lxc", "libvirt-qemu"]: print("ERROR: unknown module %s" % sys.argv[1]) sys.exit(1) load_apis(sys.argv[1], sys.argv[2]) if validate_functions() < 0: sys.exit(1) quiet = False if not os.path.exists("build"): os.mkdir("build") output = None if len(sys.argv) == 4: output = sys.argv[3] if output == "c" or output is None: emit_c_code(sys.argv[1]) if output == "py" or output is None: emit_py_code(sys.argv[1]) sys.exit(0) ./libvirt-python-9.10.0/libvirt-lxc-override-api.xml0000644000000000000000000000134114555064067021006 0ustar rootroot<?xml version="1.0"?> <api name='libvir-lxc-python'> <symbols> <function name='virDomainLxcOpenNamespace' file='python-lxc'> <info><![CDATA[This API is LXC specific, so it will only work with hypervisor connections to the LXC driver. Open the namespaces associated with the container @domain and return a list of file descriptors associated with the container. The returned file descriptors are intended to be used with the setns() system call.]]></info> <return type='int' info='the list of open file descriptors, or -1 on error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='flags' type='unsigned int' info='currently unused, pass 0'/> </function> </symbols> </api> ./libvirt-python-9.10.0/libvirt-lxc-override.c0000644000000000000000000000631414555064067017666 0ustar rootroot/* * libvir.c: this modules implements the main part of the glue of the * libvir library and the Python interpreter. It provides the * entry points where an automatically generated stub is * unpractical * * Copyright (C) 2012-2019 Red Hat, Inc. * * Daniel Veillard <veillard@redhat.com> */ /* Horrible kludge to work around even more horrible name-space pollution via Python.h. That file includes /usr/include/python3.x/pyconfig*.h, which has over 180 autoconf-style HAVE_* definitions. Shame on them. */ #undef HAVE_PTHREAD_H #include <Python.h> #include <libvirt/libvirt-lxc.h> #include <libvirt/virterror.h> #include "typewrappers.h" #include "libvirt-utils.h" #include "build/libvirt-lxc.h" #ifndef __CYGWIN__ extern PyObject *PyInit_libvirtmod_lxc(void); #else extern PyObject *PyInit_cygvirtmod_lxc(void); #endif #if 0 # define DEBUG_ERROR 1 #endif #if DEBUG_ERROR # define DEBUG(fmt, ...) \ printf(fmt, __VA_ARGS__) #else # define DEBUG(fmt, ...) \ while (0) {printf(fmt, __VA_ARGS__);} #endif /************************************************************************ * * * Statistics * * * ************************************************************************/ static PyObject * libvirt_lxc_virDomainLxcOpenNamespace(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; virDomainPtr domain; PyObject *pyobj_domain; unsigned int flags; int c_retval; int *fdlist = NULL; ssize_t i; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainLxcOpenNamespace", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (domain == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainLxcOpenNamespace(domain, &fdlist, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(0)) == NULL) goto error; for (i = 0; i < c_retval; i++) VIR_PY_LIST_APPEND_GOTO(py_retval, libvirt_intWrap(fdlist[i]), error); cleanup: VIR_FREE(fdlist); return py_retval; error: for (i = 0; i < c_retval; i++) { VIR_FORCE_CLOSE(fdlist[i]); } Py_CLEAR(py_retval); goto cleanup; } /************************************************************************ * * * The registration stuff * * * ************************************************************************/ static PyMethodDef libvirtLxcMethods[] = { #include "build/libvirt-lxc-export.c" {(char *) "virDomainLxcOpenNamespace", libvirt_lxc_virDomainLxcOpenNamespace, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, #ifndef __CYGWIN__ "libvirtmod_lxc", #else "cygvirtmod_lxc", #endif NULL, -1, libvirtLxcMethods, NULL, NULL, NULL, NULL }; PyObject * #ifndef __CYGWIN__ PyInit_libvirtmod_lxc #else PyInit_cygvirtmod_lxc #endif (void) { PyObject *module; if (virInitialize() < 0) return NULL; module = PyModule_Create(&moduledef); return module; } ./libvirt-python-9.10.0/libvirt-override-api.xml0000644000000000000000000016353514555064067020240 0ustar rootroot<?xml version="1.0"?> <api name='libvir-python'> <!-- This file lists libvirt API functions whose Python stubs are written by hand in libvirt-override.c, but the Python-level code are still automatically generated by the generator.py script. The type of return value is supposed to be C type. If a function's stub will return a python non-integer data type like string, list, tuple, dictionary, etc, please use "char *" as the type of its return value. --> <symbols> <function name="virConnectGetVersion" file='python'> <info>Returns the running hypervisor version of the connection host</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='int' info="0 on success, -1 on error"/> </function> <function name="virConnectGetLibVersion" file='python'> <info>Returns the libvirt version of the connection host</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='int' info="0 on success, -1 on error"/> </function> <function name="virConnectListDomainsID" file='python'> <info>Returns the list of the ID of the domains on the hypervisor</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='char *' info="the list of ID or None in case of error"/> </function> <function name='virConnectListDefinedDomains' file='python'> <info>list the defined domains, stores the pointers to the names in @names</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='char *' info='the list of Names or None in case of error'/> </function> <function name='virConnectListAllDomains' file='python'> <info>returns list of all defined domains</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='unsigned int' info='optional flags'/> <return type='char *' info='the list of domains or None in case of error'/> </function> <function name='virConnectListNetworks' file='python'> <info>list the networks, stores the pointers to the names in @names</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='char *' info='the list of Names or None in case of error'/> </function> <function name='virConnectListDefinedNetworks' file='python'> <info>list the defined networks, stores the pointers to the names in @names</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='char *' info='the list of Names or None in case of error'/> </function> <function name='virConnectListAllNetworks' file='python'> <info>returns list of all networks</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='unsigned int' info='optional flags'/> <return type='char *' info='the list of networks or None in case of error'/> </function> <function name='virDomainLookupByUUID' file='python'> <info>Try to lookup a domain on the given hypervisor based on its UUID.</info> <return type='virDomainPtr' info='a new domain object or NULL in case of failure'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='uuid' type='const unsigned char *' info='the UUID string for the domain, must be 16 bytes'/> </function> <function name='virNetworkLookupByUUID' file='python'> <info>Try to lookup a network on the given hypervisor based on its UUID.</info> <return type='virNetworkPtr' info='a new network object or NULL in case of failure'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='uuid' type='const unsigned char *' info='the UUID string for the network, must be 16 bytes'/> </function> <function name='virNetworkPortLookupByUUID' file='python'> <info>Try to lookup a port on the given network based on its UUID.</info> <return type='virNetworkPortPtr' info='a new network port object or NULL in case of failure'/> <arg name='net' type='virNetworkPtr' info='pointer to the network object'/> <arg name='uuid' type='const unsigned char *' info='the UUID string for the network port, must be 16 bytes'/> </function> <function name='virDomainGetInfo' file='python'> <info>Extract information about a domain. Note that if the connection used to get the domain is limited only a partial set of the information can be extracted.</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> </function> <function name='virDomainGetState' file='python'> <info>Extract domain state.</info> <return type='char *' info='the list containing state and reason or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='flags' type='unsigned int' info='additional flags'/> </function> <function name='virDomainGetControlInfo' file='python'> <info>Extract details about current state of control interface to a domain.</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='flags' type='unsigned int' info='additional flags'/> </function> <function name='virDomainGetBlockInfo' file='python'> <info>Extract information about a domain block device size</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='path' type='const char *' info='path to the block device or file'/> <arg name='flags' type='unsigned int' info='currently unused'/> </function> <function name='virDomainGetJobInfo' file='python'> <info>Extract information about an active job being processed for a domain.</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> </function> <function name='virDomainGetJobStats' file='python'> <info>Extract information about an active job being processed for a domain.</info> <return type='char *' info='dictionary mapping field names to values or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='flags' type='unsigned int' info='flags, currently unused, pass 0.'/> </function> <function name='virNodeGetInfo' file='python'> <info>Extract hardware information about the Node. Note that the memory size is reported in MiB instead of KiB.</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> </function> <function name='virNodeGetSecurityModel' file='python'> <info>Extract information about the hypervisor security model</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> </function> <function name='virDomainGetSecurityLabel' file='python'> <info>Extract information about the domain security label. Only the first label will be returned.</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> </function> <function name='virDomainGetSecurityLabelList' file='python'> <info>Extract information about the domain security label. A list of all labels will be returned.</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> </function> <function name='virNodeGetCPUStats' file='python'> <info>Extract node's CPU statistics.</info> <return type='char *' info='dictionary mapping field names to values or None in case of error'/> <arg name='conn' type='virConnectPtr' info='pointer to hypervisor connection'/> <arg name='cpuNum' type='int' info='number of node cpu. (VIR_NODE_CPU_STATS_ALL_CPUS means total cpu statistics)'/> <arg name='flags' type='unsigned int' info='additional flags'/> </function> <function name='virNodeGetMemoryStats' file='python'> <info>Extract node's memory statistics.</info> <return type='char *' info='dictionary mapping field names to values or None in case of error'/> <arg name='conn' type='virConnectPtr' info='pointer to hypervisor connection'/> <arg name='cellNum' type='int' info='number of node cell. (VIR_NODE_MEMORY_STATS_ALL_CELLS means total cell statistics)'/> <arg name='flags' type='unsigned int' info='additional flags'/> </function> <function name='virDomainGetUUID' file='python'> <info>Extract the UUID unique Identifier of a domain.</info> <return type='char *' info='the 16 bytes string or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> </function> <function name='virDomainGetUUIDString' file='python'> <info>Fetch globally unique ID of the domain as a string.</info> <return type='char *' info='the UUID string or None in case of error'/> <arg name='pool' type='virDomainPtr' info='a domain object'/> </function> <function name='virNetworkGetUUID' file='python'> <info>Extract the UUID unique Identifier of a network.</info> <return type='char *' info='the 16 bytes string or None in case of error'/> <arg name='domain' type='virNetworkPtr' info='a network object'/> </function> <function name='virNetworkGetUUIDString' file='python'> <info>Fetch globally unique ID of the network as a string.</info> <return type='char *' info='the UUID string or None in case of error'/> <arg name='net' type='virNetworkPtr' info='a network object'/> </function> <function name='virNetworkPortGetUUID' file='python'> <info>Extract the UUID unique Identifier of a network port.</info> <return type='char *' info='the 16 bytes string or None in case of error'/> <arg name='domain' type='virNetworkPortPtr' info='a network port object'/> </function> <function name='virNetworkPortGetUUIDString' file='python'> <info>Fetch globally unique ID of the network port as a string.</info> <return type='char *' info='the UUID string or None in case of error'/> <arg name='net' type='virNetworkPortPtr' info='a network port object'/> </function> <function name='virStoragePoolGetUUID' file='python'> <info>Extract the UUID unique Identifier of a storage pool.</info> <return type='char *' info='the 16 bytes string or None in case of error'/> <arg name='pool' type='virStoragePoolPtr' info='a storage pool object'/> </function> <function name='virStoragePoolGetUUIDString' file='python'> <info>Fetch globally unique ID of the storage pool as a string.</info> <return type='char *' info='the UUID string or None in case of error'/> <arg name='pool' type='virStoragePoolPtr' info='a storage pool object'/> </function> <function name='virNetworkGetAutostart' file='python'> <info>Extract the autostart flag for a network.</info> <return type='int' info='the autostart flag, or None in case of error'/> <arg name='domain' type='virNetworkPtr' info='a network object'/> </function> <function name='virDomainGetAutostart' file='python'> <info>Extract the autostart flag for a domain</info> <return type='int' info='the autostart flag, or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a network object'/> </function> <function name='virStoragePoolGetAutostart' file='python'> <info>Extract the autostart flag for a storage pool</info> <return type='int' info='the autostart flag, or None in case of error'/> <arg name='pool' type='virStoragePoolPtr' info='a storage pool object'/> </function> <function name='virNodeDeviceGetAutostart' file='python'> <info>Extract the autostart flag for a node device.</info> <return type='int' info='the autostart flag, or None in case of error'/> <arg name='dev' type='virNodeDevicePtr' info='a node device object'/> </function> <function name='virDomainBlockStats' file='python'> <info>Extracts block device statistics for a domain</info> <return type='char *' info='a tuple of statistics'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='path' type='char *' info='the path for the block device'/> </function> <function name='virDomainBlockStatsFlags' file='python'> <info>Extracts block device statistics parameters of a running domain</info> <return type='char *' info='None in case of error, returns a dictionary of params'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='path' type='char *' info='the path for the block device'/> <arg name='flags' type='int' info='flags (unused; pass 0)'/> </function> <function name='virDomainGetCPUStats' file='python'> <info>Extracts CPU statistics for a running domain. On success it will return a list of data of dictionary type. If boolean total is False or 0, the first element of the list refers to CPU0 on the host, second element is CPU1, and so on. The format of data struct is as follows: [{cpu_time:xxx}, {cpu_time:xxx}, ...] If it is True or 1, it returns total domain CPU statistics in the format of [{cpu_time:xxx, user_time:xxx, system_time:xxx}]</info> <return type='char *' info='returns a list of dictionary in case of success, None in case of error'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='total' type='bool' info='on true, return total domain CPU statistics, false return per-cpu info'/> <arg name='flags' type='int' info='flags (unused; pass 0)'/> </function> <function name='virDomainInterfaceStats' file='python'> <info>Extracts interface device statistics for a domain</info> <return type='char *' info='a tuple of statistics'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='path' type='char *' info='the path for the interface device'/> </function> <function name='virDomainMemoryStats' file='python'> <info>Extracts memory statistics for a domain</info> <return type='char *' info='a dictionary of statistics'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> </function> <function name="virNodeGetCellsFreeMemory" file='python'> <info>Returns the available memory for a list of cells</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='startCell' type='int' info='first cell in the list'/> <arg name='maxCells' type='int' info='number of cell in the list'/> <return type='char *' info="the list available memory in the cells"/> </function> <function name='virDomainGetSchedulerParameters' file='python'> <info>Get the scheduler parameters, the @params array will be filled with the values.</info> <return type='char *' info='None in case of error, returns a dictionary of params.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> </function> <function name='virDomainGetSchedulerParametersFlags' file='python'> <info>Get the scheduler parameters</info> <return type='char *' info='None in case of error, returns a dictionary of params'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainGetSchedulerType' file='python'> <info>Get the scheduler type.</info> <return type='char *' info='NULL in case of error. The caller must free the returned string.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> </function> <function name='virDomainGetVcpus' file='python'> <info>Extract information about virtual CPUs of domain, store it in info array and also in cpumaps.</info> <return type='char *' info='None in case of error, returns a tuple of vcpu info and vcpu map.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object, or NULL for Domain0'/> </function> <function name='virDomainPinVcpu' file='python'> <info>Dynamically change the real CPUs which can be allocated to a virtual CPU. This function requires privileged access to the hypervisor.</info> <return type='int' info='0 in case of success, -1 in case of failure.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object, or NULL for Domain0'/> <arg name='vcpu' type='unsigned int' info='virtual CPU number'/> <arg name='cpumap' type='unsigned char *' info='pointer to a bit map of real CPUs (in 8-bit bytes) (IN) Each bit set to 1 means that corresponding CPU is usable. Bytes are stored in little-endian order: CPU0-7, 8-15... In each byte, lowest CPU number is least significant bit.'/> </function> <function name='virDomainPinVcpuFlags' file='python'> <info>Dynamically change the real CPUs which can be allocated to a virtual CPU. This function requires privileged access to the hypervisor.</info> <return type='int' info='0 in case of success, -1 in case of failure.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object, or NULL for Domain0'/> <arg name='vcpu' type='unsigned int' info='virtual CPU number'/> <arg name='cpumap' type='unsigned char *' info='pointer to a bit map of real CPUs (in 8-bit bytes) (IN) Each bit set to 1 means that corresponding CPU is usable. Bytes are stored in little-endian order: CPU0-7, 8-15... In each byte, lowest CPU number is least significant bit.'/> <arg name='flags' type='int' info='flags to specify'/> </function> <function name='virDomainGetVcpuPinInfo' file='python'> <info>Query the CPU affinity setting of all virtual CPUs of domain</info> <return type='char *' info='the array of cpumap'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object, or NULL for Domain0'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainGetEmulatorPinInfo' file='python'> <info>Query the CPU affinity setting of the emulator process of domain</info> <return type='char *' info='the array of cpumap'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainPinEmulator' file='python'> <info>Dynamically change the real CPUs which can be allocated to the emulator process of a domain. This function requires privileged access to the hypervisor.</info> <return type='int' info='0 in case of success, -1 in case of failure.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object, or NULL for Domain0'/> <arg name='cpumap' type='unsigned char *' info='pointer to a bit map of real CPUs (in 8-bit bytes) (IN) Each bit set to 1 means that corresponding CPU is usable. Bytes are stored in little-endian order: CPU0-7, 8-15... In each byte, lowest CPU number is least significant bit.'/> <arg name='flags' type='int' info='flags to specify'/> </function> <function name='virDomainGetIOThreadInfo' file='python'> <info>Query the CPU affinity setting of the IOThreads of the domain</info> <arg name='domain' type='virDomainPtr' info='pointer to domain object, or NULL for Domain0'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> <return type='char *' info="list of IOThreads information including the iothread_id, the cpumap, and the cpumap length for each iothread_id."/> </function> <function name='virDomainPinIOThread' file='python'> <info>Dynamically change the real CPUs which can be allocated to an IOThread. This function requires privileged access to the hypervisor.</info> <return type='int' info='0 in case of success, -1 in case of failure.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='iothread_val' type='unsigned int' info='iothread_id number'/> <arg name='cpumap' type='unsigned char *' info='pointer to a bit map of real CPUs (in 8-bit bytes) (IN) Each bit set to 1 means that corresponding CPU is usable. Bytes are stored in little-endian order: CPU0-7, 8-15... In each byte, lowest CPU number is least significant bit.'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainSetIOThreadParams' file='python'> <info>Dynamically allow changing the IOThread polling related parameters. This function requires privileged access to the hypervisor.</info> <return type='int' info='0 in case of success, -1 in case of failure.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='iothread_val' type='unsigned int' info='iothread_id number'/> <arg name='params' type='virTypedParameterPtr' info='pointer to IOThread polling parameter objects'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainSetSchedulerParameters' file='python'> <info>Change the scheduler parameters</info> <return type='int' info='-1 in case of error, 0 in case of success.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='params' type='virSchedParameterPtr' info='pointer to scheduler parameter objects'/> </function> <function name='virDomainSetSchedulerParametersFlags' file='python'> <info>Change the scheduler parameters</info> <return type='int' info='-1 in case of error, 0 in case of success.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='params' type='virSchedParameterPtr' info='pointer to scheduler parameter objects'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainSetBlkioParameters' file='python'> <info>Change the blkio tunables</info> <return type='int' info='-1 in case of error, 0 in case of success.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='params' type='virBlkioParameterPtr' info='pointer to blkio tunable objects'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainGetBlkioParameters' file='python'> <info>Get the blkio parameters</info> <return type='char *' info='None in case of error, returns a dictionary of params'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainSetMemoryParameters' file='python'> <info>Change the memory tunables</info> <return type='int' info='-1 in case of error, 0 in case of success.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='params' type='virMemoryParameterPtr' info='pointer to memory tunable objects'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainGetMemoryParameters' file='python'> <info>Get the memory parameters</info> <return type='char *' info='None in case of error, returns a dictionary of params'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainSetNumaParameters' file='python'> <info>Change the NUMA tunables</info> <return type='int' info='-1 in case of error, 0 in case of success.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='params' type='virTypedParameterPtr' info='pointer to numa tunable objects'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainGetNumaParameters' file='python'> <info>Get the NUMA parameters</info> <return type='char *' info='returns a dictionary of params in case of success, None in case of error'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainGetPerfEvents' file='python'> <info>Get all perf events setting.</info> <return type='char *' info='returns a dictionary of params in case of success, None in case of error'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainSetPerfEvents' file='python'> <info>Enable or disable the particular list of perf events</info> <return type='int' info='-1 in case of error, 0 in case of success.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='params' type='virTypedParameterPtr' info='pointer to perf events parameter object'/> <arg name='flags' type='int' info='an OR'ed set of virDomainModificationImpact'/> </function> <function name='virDomainSetInterfaceParameters' file='python'> <info>Change the bandwidth tunables for a interface device</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='device' type='const char *' info='interface name'/> <arg name='params' type='virTypedParameterPtr' info='Pointer to bandwidth tuning params object'/> <arg name='flags' type='unsigned int' info='an OR'ed set of virDomainModificationImpact'/> <return type='int' info='0 in case of success, -1 in case of failure'/> </function> <function name='virDomainGetInterfaceParameters' file='python'> <info>Get the bandwidth tunables for a interface device</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='device' type='const char *' info='interface name'/> <arg name='flags' type='unsigned int' info='an OR'ed set of virDomainModificationImpact'/> <return type='char *' info='the bandwidth tunables value or None in case of error'/> </function> <function name='virConnectListStoragePools' file='python'> <info>list the storage pools, stores the pointers to the names in @names</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='char *' info='the list of Names of None in case of error'/> </function> <function name='virConnectListDefinedStoragePools' file='python'> <info>list the defined storage pool, stores the pointers to the names in @names</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='char *' info='the list of Names of None in case of error'/> </function> <function name='virConnectListAllStoragePools' file='python'> <info>returns list of all storage pools</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='unsigned int' info='optional flags'/> <return type='char *' info='the list of pools or None in case of error'/> </function> <function name='virStoragePoolListVolumes' file='python'> <info>list the storage volumes, stores the pointers to the names in @names</info> <arg name='pool' type='virStoragePoolPtr' info='pointer to the storage pool'/> <return type='char *' info='the list of Names or None in case of error'/> </function> <function name='virStoragePoolListAllVolumes' file='python'> <info>return list of storage volume objects</info> <arg name='pool' type='virStoragePoolPtr' info='pointer to the storage pool'/> <arg name='flags' type='unsigned int' info='optional flags'/> <return type='char *' info='the list of volumes or None in case of error'/> </function> <function name='virStoragePoolGetInfo' file='python'> <info>Extract information about a storage pool. Note that if the connection used to get the domain is limited only a partial set of the information can be extracted.</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='pool' type='virStoragePoolPtr' info='a storage pool object'/> </function> <function name='virStorageVolGetInfo' file='python'> <info>Extract information about a storage volume. Note that if the connection used to get the domain is limited only a partial set of the information can be extracted.</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='vol' type='virStorageVolPtr' info='a storage vol object'/> </function> <function name='virStorageVolGetInfoFlags' file='python'> <info>Extract information about a storage volume. Note that if the connection used to get the domain is limited only a partial set of the information can be extracted.</info> <return type='char *' info='the list of information or None in case of error'/> <arg name='vol' type='virStorageVolPtr' info='a storage vol object'/> <arg name='flags' type='unsigned int' info='bitwise-OR of virStorageVolInfoFlags'/> </function> <function name='virNodeListDevices' file='python'> <info>list the node devices</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='cap' type='const unsigned char *' info='capability name'/> <arg name='flags' type='unsigned int' info='flags (unused; pass 0)'/> <return type='char *' info='the list of Names or None in case of error'/> </function> <function name='virConnectListAllNodeDevices' file='python'> <info>returns list of all host node devices</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='unsigned int' info='optional flags'/> <return type='char *' info='the list of host node device or None in case of error'/> </function> <function name='virNodeDeviceListCaps' file='python'> <info>list the node device's capabilities</info> <arg name='dev' type='virNodeDevicePtr' info='pointer to the node device'/> <return type='char *' info='the list of Names or None in case of error'/> </function> <function name='virSecretGetValue' file='libvirt' module='libvirt'> <info>Fetches the value associated with a secret.</info> <return type='char *' info='the secret value or None in case of error'/> <arg name='secret' type='virSecretPtr' info='virSecret secret'/> <arg name='flags' type='unsigned int' info='flags (unused; pass 0)'/> </function> <function name='virConnectListSecrets' file='libvirt' module='libvirt'> <info>List the defined secret IDs</info> <arg name='conn' type='virConnectPtr' info='virConnect connection'/> <return type='char *' info='the list of secret IDs or None in case of error'/> </function> <function name='virConnectListAllSecrets' file='python'> <info>returns list of all interfaces</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='unsigned int' info='optional flags'/> <return type='char *' info='the list of secrets or None in case of error'/> </function> <function name='virSecretSetValue' file='libvirt' module='libvirt'> <info>Associates a value with a secret.</info> <return type='int' info='0 on success, -1 on failure.'/> <arg name='secret' type='virSecretPtr' info='virSecret secret'/> <arg name='value' type='const char *' info='The secret value'/> <arg name='flags' type='unsigned int' info='flags (unused; pass 0)'/> </function> <function name='virSecretLookupByUUID' file='python'> <info>Try to lookup a secret on the given hypervisor based on its UUID.</info> <return type='virSecretPtr' info='a new secret object or NULL in case of failure'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='uuid' type='const unsigned char *' info='the UUID string for the secret, must be 16 bytes'/> </function> <function name='virSecretGetUUID' file='python'> <info>Extract the UUID unique Identifier of a secret.</info> <return type='char *' info='the 16 bytes string or None in case of error'/> <arg name='secret' type='virSecretPtr' info='a secret object'/> </function> <function name='virSecretGetUUIDString' file='python'> <info>Fetch globally unique ID of the secret as a string.</info> <return type='char *' info='the UUID string or None in case of error'/> <arg name='secret' type='virSecretPtr' info='a secret object'/> </function> <function name='virConnectListNWFilters' file='libvirt' module='libvirt'> <info>List the defined network filters</info> <arg name='conn' type='virConnectPtr' info='virConnect connection'/> <return type='char *' info='the list of network filter IDs or None in case of error'/> </function> <function name='virConnectListAllNWFilters' file='python'> <info>returns list of all network fitlers</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='unsigned int' info='optional flags'/> <return type='char *' info='the list of network filters or None in case of error'/> </function> <function name='virConnectListAllNWFilterBindings' file='python'> <info>returns list of all network fitler bindings</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='unsigned int' info='optional flags'/> <return type='char *' info='the list of network filter bindings or None in case of error'/> </function> <function name='virNWFilterLookupByUUID' file='python'> <info>Try to lookup a network filter on the given hypervisor based on its UUID.</info> <return type='virNWFilterPtr' info='a new network filter object or NULL in case of failure'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='uuid' type='const unsigned char *' info='the UUID string for the secret, must be 16 bytes'/> </function> <function name='virNWFilterGetUUID' file='python'> <info>Extract the UUID unique Identifier of a network filter.</info> <return type='char *' info='the 16 bytes string or None in case of error'/> <arg name='nwfilter' type='virNWFilterPtr' info='a network filter object'/> </function> <function name='virNWFilterGetUUIDString' file='python'> <info>Fetch globally unique ID of the network filter as a string.</info> <return type='char *' info='the UUID string or None in case of error'/> <arg name='nwfilter' type='virNWFilterPtr' info='a network filter object'/> </function> <function name='virConnectListInterfaces' file='python'> <info>list the running interfaces, stores the pointers to the names in @names</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='char *' info='the list of Names of None in case of error'/> </function> <function name='virConnectListDefinedInterfaces' file='python'> <info>list the defined interfaces, stores the pointers to the names in @names</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <return type='char *' info='the list of Names of None in case of error'/> </function> <function name='virConnectListAllInterfaces' file='python'> <info>returns list of all interfaces</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='unsigned int' info='optional flags'/> <return type='char *' info='the list of interfaces or None in case of error'/> </function> <function name='virConnectBaselineCPU' file='python'> <info>Computes the most feature-rich CPU which is compatible with all given host CPUs.</info> <return type='char *' info='XML description of the computed CPU or NULL on error.'/> <arg name='conn' type='virConnectPtr' info='virConnect connection'/> <arg name='xmlCPUs' type='const char **' info='array of XML descriptions of host CPUs'/> <arg name='flags' type='unsigned int' info='fine-tuning flags, currently unused, pass 0.'/> </function> <function name='virConnectGetCPUModelNames' file='python'> <info>Get the list of supported CPU models.</info> <return type='char *' info='list of supported CPU models'/> <arg name='conn' type='virConnectPtr' info='virConnect connection'/> <arg name='arch' type='const char *' info='arch'/> <arg name='flags' type='unsigned int' info='fine-tuning flags, currently unused, pass 0.'/> </function> <function name='virDomainSnapshotListNames' file='python'> <info>collect the list of snapshot names for the given domain</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='flags' type='unsigned int' info='flags'/> <return type='char *' info='the list of Names or None in case of error'/> </function> <function name='virDomainListAllSnapshots' file='python'> <info>returns the list of snapshots for the given domain</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='flags' type='unsigned int' info='flags'/> <return type='char *' info='the list of snapshots or None in case of error'/> </function> <function name='virDomainSnapshotListChildrenNames' file='python'> <info>collect the list of child snapshot names for the given snapshot</info> <arg name='snapshot' type='virDomainSnapshotPtr' info='pointer to the snapshot'/> <arg name='flags' type='unsigned int' info='flags'/> <return type='char *' info='the list of Names or None in case of error'/> </function> <function name='virDomainSnapshotListAllChildren' file='python'> <info>returns the list of child snapshots for the given snapshot</info> <arg name='snapshot' type='virDomainSnapshotPtr' info='pointer to the snapshot'/> <arg name='flags' type='unsigned int' info='flags'/> <return type='char *' info='the list of snapshots or None in case of error'/> </function> <function name='virDomainRevertToSnapshot' file='python'> <info>revert the domain to the given snapshot</info> <arg name='dom' type='virDomainPtr' info='dummy domain pointer'/> <arg name='snap' type='virDomainSnapshotPtr' info='pointer to the snapshot'/> <arg name='flags' type='unsigned int' info='flags'/> <return type='int' info="0 on success, -1 on error"/> </function> <function name='virDomainListAllCheckpoints' file='python'> <info>returns the list of checkpoints for the given domain</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='flags' type='unsigned int' info='flags'/> <return type='char *' info='the list of checkpoints or None in case of error'/> </function> <function name='virDomainCheckpointListAllChildren' file='python'> <info>collect the list of child checkpoint names for the given checkpoint</info> <arg name='checkpoint' type='virDomainCheckpointPtr' info='pointer to the checkpoint'/> <arg name='flags' type='unsigned int' info='flags'/> <return type='char *' info='the list of checkpoints or None in case of error'/> </function> <function name='virDomainGetBlockJobInfo' file='python'> <info>Get progress information for a block job</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='path' type='const char *' info='Fully-qualified filename of disk'/> <arg name='flags' type='unsigned int' info='fine-tuning flags, currently unused, pass 0.'/> <return type='char *' info='A dictionary containing job information.' /> </function> <function name='virDomainMigrateGetCompressionCache' file='python'> <info>Get current size of the cache (in bytes) used for compressing repeatedly transferred memory pages during live migration.</info> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='flags' type='unsigned int' info='flags, currently unused, pass 0.'/> <return type='unsigned long long' info='current cache size, or None in case of error'/> </function> <function name='virDomainMigrateGetMaxSpeed' file='python'> <info>Get currently configured maximum migration speed for a domain</info> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='flags' type='unsigned int' info='flags, currently unused, pass 0.'/> <return type='unsigned long' info='current max migration speed, or None in case of error'/> </function> <function name='virDomainMigrateGetMaxDowntime' file='python'> <info>Get the current value of the maximum downtime (in milliseconds) allowed during a migration of a guest.</info> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='flags' type='unsigned int' info='flags, currently unused, pass 0.'/> <return type='unsigned long long' info='current downtime or None in case of error'/> </function> <function name='virDomainMigrate3' file='python'> <info>Migrate the domain object from its current host to the destination host given by dconn (a connection to the destination host).</info> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='dconn' type='virConnectPtr' info='pointer to the destination host connection'/> <arg name='params' type='char *' info='dictionary with migration parameters'/> <arg name='flags' type='unsigned int' info='an OR'ed set of virDomainMigrateFlags'/> <return type='virDomainPtr' info='a new domain object or NULL in case of failure'/> </function> <function name='virDomainMigrateToURI3' file='python'> <info>Migrate the domain object from its current host to the destination host given by URI.</info> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='dconnuri' type='char *' info='URI for target libvirtd if @flags includes VIR_MIGRATE_PEER2PEER'/> <arg name='params' type='char *' info='dictionary with migration parameters'/> <arg name='flags' type='unsigned int' info='an OR'ed set of virDomainMigrateFlags'/> <return type='int' info='0 in case of success, -1 in case of failure.'/> </function> <function name='virDomainSetBlockIoTune' file='python'> <info>Change the I/O tunables for a block device</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='disk' type='const char *' info='disk name'/> <arg name='params' type='virTypedParameterPtr' info='Pointer to blkio tuning params object'/> <arg name='flags' type='unsigned int' info='an OR'ed set of virDomainModificationImpact'/> <return type='int' info='0 in case of success, -1 in case of failure'/> </function> <function name='virDomainGetBlockIoTune' file='python'> <info>Get the I/O tunables for a block device</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='disk' type='const char *' info='disk name'/> <arg name='flags' type='unsigned int' info='an OR'ed set of virDomainModificationImpact'/> <return type='char *' info='the I/O tunables value or None in case of error'/> </function> <function name='virDomainBlockPeek' file='python'> <info>Read the contents of domain's disk device</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='disk' type='const char *' info='disk name'/> <arg name='offset' type='unsigned long long' info='offset within block device'/> <arg name='size' type='size_t' info='size to read'/> <arg name='flags' type='unsigned int' info='unused, always pass 0'/> <return type='char *' info='the returned buffer or None in case of error'/> </function> <function name='virDomainMemoryPeek' file='python'> <info>Read the contents of domain's memory</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='start' type='unsigned long long' info='start of memory to peek'/> <arg name='size' type='size_t' info='size of memory to peek'/> <arg name='flags' type='unsigned int' info='an OR'ed set of virDomainMemoryFlags'/> <return type='char *' info='the returned buffer or None in case of error'/> </function> <function name='virDomainGetDiskErrors' file='python'> <info>Extract errors on disk devices.</info> <return type='char *' info='dictionary of disks and their errors or None in case of error'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='flags' type='unsigned int' info='unused, always pass 0'/> </function> <function name='virNodeSetMemoryParameters' file='python'> <info>Change the node memory tunables</info> <return type='int' info='-1 in case of error, 0 in case of success.'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='params' type='virTypedParameterPtr' info='pointer to the memory tunable objects'/> <arg name='flags' type='int' info='unused, always pass 0'/> </function> <function name='virNodeGetMemoryParameters' file='python'> <info>Get the node memory parameters</info> <return type='char *' info='None in case of error, returns a dictionary of params'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='int' info='unused, always pass 0'/> </function> <function name='virNodeGetCPUMap' file='python'> <info>Get node CPU information</info> <return type='char *' info='(cpunum, cpumap, online) on success, None on error'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='flags' type='int' info='unused, pass 0'/> </function> <function name="virNodeGetFreePages" file='python'> <info>Returns the number of available pages for a list of cells and page sizes</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='pages' type='char *' info='list of desired page sizes'/> <arg name='startCell' type='int' info='first cell in the list'/> <arg name='maxCells' type='int' info='number of cell in the list'/> <arg name='flags' type='int' info='unused, pass 0'/> <return type='char *' info='the list available memory in the cells'/> </function> <function name="virNetworkGetDHCPLeases" file='python'> <info>Returns a list of dhcp leases for interfaces connected to the given virtual network</info> <arg name='network' type='virNetworkPtr' info='a network object'/> <arg name='mac' type='const char *' info='optional mac address'/> <arg name='flags' type='unsigned int' info='unused, pass 0'/> <return type='char *' info="list of leases"/> </function> <function name="virDomainBlockCopy" file="python"> <info>Copy the guest-visible contents of a disk image to a new file described by destxml</info> <arg name='dom' type='virDomainPtr' info='pointer to domain object'/> <arg name='disk' type='const char *' info='path to the block device, or device shorthand'/> <arg name='destxml' type='const char *' info='XML description of the copy destination'/> <arg name='params' type='virTypedParameterPtr' info='optional pointer to block copy parameter object, or NULL'/> <arg name='flags' type='unsigned int' info='bitwise-OR of virDomainBlockCopyFlags'/> <return type='int' info='0 if the operation has started, -1 on failure'/> </function> <function name="virNodeAllocPages" file='python'> <info>Allocate or free some pages in the huge pages pool</info> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='pages' type='char *' info='dictionary of desired page sizes, key is page size, value is page count'/> <arg name='startCell' type='int' info='optional first cell in the list'/> <arg name='cellCount' type='int' info='optional number of cell in the list'/> <arg name='flags' type='unsigned int' info='an OR'ed set of virNodeAllocPagesFlags'/> <return type='int' info='the number of nodes successfully adjusted or -1 in case of an error'/> </function> <function name="virDomainGetFSInfo" file='python'> <info>Get a list of mapping information for each mounted file systems within the specified guest and the disks.</info> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='flags' type='unsigned int' info='unused, pass 0'/> <return type='char *' info="list of mounted filesystems information"/> </function> <function name='virDomainInterfaceAddresses' file='python'> <info>returns a dictionary of domain interfaces along with their MAC and IP addresses</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='source' type='unsigned int' info='the data source'/> <arg name='flags' type='unsigned int' info='extra flags; not used yet, so callers should always pass 0'/> <return type='char *' info="dictionary of domain interfaces along with their MAC and IP addresses"/> </function> <function name='virDomainGetGuestVcpus' file='python'> <info>returns a dictionary containing information regarding guest vcpus</info> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='flags' type='unsigned int' info='extra flags; not used yet, so callers should always pass 0'/> <return type='int' info="dictionary of vcpu data returned by the guest agent"/> </function> <function name='virConnectBaselineHypervisorCPU' file='python'> <info>Computes the most feature-rich CPU which is compatible with all given CPUs and can be provided by the specified hypervisor.</info> <return type='char *' info='XML description of the computed CPU or NULL on error.'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='emulator' type='const char *' info='path to the emulator binary'/> <arg name='arch' type='const char *' info='CPU architecture'/> <arg name='machine' type='const char *' info='machine type'/> <arg name='virttype' type='const char *' info='virtualization type'/> <arg name='xmlCPUs' type='const char **' info='array of XML descriptions of CPUs'/> <arg name='flags' type='unsigned int' info='bitwise-OR of virConnectBaselineCPUFlags'/> </function> <function name='virDomainGetLaunchSecurityInfo' file='python'> <info>Get launch security info for a domain</info> <return type='char *' info='None in case of error, returns a dictionary of params'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='flags' type='int' info='unused, always pass 0'/> </function> <function name='virNodeGetSEVInfo' file='python'> <info>Get platform specific information from the SEV firmware</info> <return type='char *' info='None in case of error, returns a dictionary of params'/> <arg name='conn' type='virConnectPtr' info='pointer to hypervisor connection'/> <arg name='flags' type='int' info='unused, always pass 0'/> </function> <function name='virConnectGetDomainCapabilities' file='libvirt-domain' module='libvirt-domain'> <info>Query domain capabilities</info> <return type='char *' info='NULL in case of error or an XML string defining the capabilities.'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='emulatorbin' type='const char *' info='optional path to emulator'/> <arg name='arch' type='const char *' info='optional domain architecture'/> <arg name='machine' type='const char *' info='optional machine type'/> <arg name='virttype' type='const char *' info='optional virtualization type'/> <arg name='flags' type='int' info='unused, always pass 0'/> </function> <function name='virNetworkPortSetParameters' file='python'> <info>Change the port tunables</info> <return type='int' info='-1 in case of error, 0 in case of success.'/> <arg name='port' type='virNetworkPortPtr' info='pointer to network port object'/> <arg name='params' type='virTypedParameterPtr' info='pointer to tunable objects'/> <arg name='flags' type='int' info='unused, always pass 0'/> </function> <function name='virNetworkPortGetParameters' file='python'> <info>Get the port parameters</info> <return type='char *' info='None in case of error, returns a dictionary of params'/> <arg name='port' type='virNetworkPortPtr' info='pointer to network port object'/> <arg name='flags' type='int' info='unused, always pass 0'/> </function> <function name='virDomainGetGuestInfo' file='python'> <info>Get aggregated info from guest agent</info> <return type='char *' info='None in case of error, returns a dictionary of params'/> <arg name='dom' type='virDomainPtr' info='pointer to the domain'/> <arg name='types' type='int' info='optional binary-OR of virDomainGuestInfoTypes'/> <arg name='flags' type='int' info='unused, always pass 0'/> </function> <function name='virConnectSetIdentity' file='libvirt-host' module='libvirt-host'> <info>Override the default identity information associated with the connection.</info> <return type='int' info='0 if the identity change was accepted, -1 on error'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='params' type='virTypedParameterPtr' info='parameters containing the identity attributes'/> <arg name='flags' type='unsigned int' info='currently unused, pass 0'/> </function> <function name='virDomainAuthorizedSSHKeysGet' file='python'> <info>Fetch list of public SSH authorized keys for given user in domain.</info> <return type='char *' info='list of authorized keys'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='user' type='const char *' info='user'/> <arg name='flags' type='unsigned int' info='optional fine-tuning flags, currently unused, pass 0.'/> </function> <function name='virDomainAuthorizedSSHKeysSet' file='python'> <info>Manipulate set of public SSH authorized keys for given user in domain.</info> <return type='int' info='0 in case of success, -1 in case of failure.'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='user' type='const char *' info='user'/> <arg name='keys' type='char *' info='optional list of authorized keys to set/append/remove'/> <arg name='flags' type='int' info='optional OR'ed set of virDomainAuthorizedSSHKeysSetFlags'/> </function> <function name='virDomainGetMessages' file='python'> <info>Fetch list of messages reported against domain.</info> <return type='char *' info='list of messages'/> <arg name='domain' type='virDomainPtr' info='a domain object'/> <arg name='flags' type='unsigned int' info='optional fine-tuning flags'/> </function> <function name='virDomainSetLaunchSecurityState' file='python'> <info>Set a launch security secret in the guest's memory.</info> <return type='int' info='0 in case of success, -1 in case of failure.'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='params' type='virTypedParameterPtr' info='pointer to launch security state objects'/> <arg name='flags' type='unsigned int' info='currently used, set to 0.'/> </function> <function name='virDomainSaveParams' file='python'> <info>This method will suspend a domain and save its memory contents to a file on disk.</info> <return type='int' info='0 in case of success and -1 in case of failure'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='params' type='virTypedParameterPtr' info='pointer to save parameter objects'/> <arg name='flags' type='int' info='an OR'ed set of virDomainSaveRestoreFlags'/> </function> <function name='virDomainRestoreParams' file='python'> <info>This method will restore a domain saved to disk.</info> <return type='int' info='0 in case of success and -1 in case of failure'/> <arg name='conn' type='virConnectPtr' info='pointer to the hypervisor connection'/> <arg name='params' type='virTypedParameterPtr' info='pointer to save parameter objects'/> <arg name='flags' type='int' info='an OR'ed set of virDomainSaveRestoreFlags'/> </function> </symbols> </api> ./libvirt-python-9.10.0/libvirt-override-virConnect.py0000644000000000000000000007540014555064067021422 0ustar rootroot def __del__(self) -> None: try: self.domainEventCallbacks.clear() del self.domainEventCallbacks libvirtmod.virConnectDomainEventDeregister(self._o, self) except AttributeError: pass if self._o is not None: libvirtmod.virConnectClose(self._o) self._o = None def __enter__(self) -> 'virConnect': return self def __exit__(self, exc_type_: Optional[Type[BaseException]], exc_value_: Optional[BaseException], traceback_: Optional[TracebackType]) -> None: self.close() def domainEventDeregister(self, cb: _DomainCB) -> None: """Removes a Domain Event Callback. De-registering for a domain callback will disable delivery of this event type """ try: del self.domainEventCallbacks[cb] if len(self.domainEventCallbacks) == 0: del self.domainEventCallbacks ret = libvirtmod.virConnectDomainEventDeregister(self._o, self) if ret == -1: raise libvirtError('virConnectDomainEventDeregister() failed') except AttributeError: pass def domainEventRegister(self, cb: _DomainCB, opaque: _T) -> None: """Adds a Domain Event Callback. Registering for a domain callback will enable delivery of the events """ try: self.domainEventCallbacks[cb] = opaque except AttributeError: self.domainEventCallbacks = {cb: opaque} # type: Dict[_DomainCB, _T] ret = libvirtmod.virConnectDomainEventRegister(self._o, self) if ret == -1: raise libvirtError('virConnectDomainEventRegister() failed') def _dispatchDomainEventCallbacks(self, dom: 'virDomain', event: int, detail: int) -> None: """Dispatches events to python user domain event callbacks """ try: for cb, opaque in self.domainEventCallbacks.items(): cb(self, virDomain(self, _obj=dom), event, detail, opaque) except AttributeError: pass def _dispatchDomainEventLifecycleCallback(self, dom: 'virDomain', event: int, detail: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user domain lifecycle event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), event, detail, opaque) return 0 def _dispatchDomainEventGenericCallback(self, dom: 'virDomain', cbData: Dict[str, Any]) -> int: """Dispatches events to python user domain generic event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), opaque) return 0 def _dispatchDomainEventRTCChangeCallback(self, dom: 'virDomain', offset: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user domain RTC change event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), offset, opaque) return 0 def _dispatchDomainEventWatchdogCallback(self, dom: 'virDomain', action: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user domain watchdog event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), action, opaque) return 0 def _dispatchDomainEventIOErrorCallback(self, dom: 'virDomain', srcPath: str, devAlias: str, action: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user domain IO error event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), srcPath, devAlias, action, opaque) return 0 def _dispatchDomainEventIOErrorReasonCallback(self, dom: 'virDomain', srcPath: str, devAlias: str, action: int, reason: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user domain IO error event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), srcPath, devAlias, action, reason, opaque) return 0 def _dispatchDomainEventGraphicsCallback(self, dom: 'virDomain', phase: int, localAddr: Any, remoteAddr: Any, authScheme: str, subject: Any, cbData: Dict[str, Any]) -> int: """Dispatches events to python user domain graphics event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), phase, localAddr, remoteAddr, authScheme, subject, opaque) return 0 def _dispatchDomainEventBlockJobCallback(self, dom: 'virDomain', disk: str, type: int, status: int, cbData: Dict[str, Any]) -> None: """Dispatches events to python user domain blockJob/blockJob2 event callbacks """ try: cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), disk, type, status, opaque) except AttributeError: pass def _dispatchDomainEventDiskChangeCallback(self, dom: 'virDomain', oldSrcPath: str, newSrcPath: str, devAlias: str, reason: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain diskChange event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), oldSrcPath, newSrcPath, devAlias, reason, opaque) return 0 def _dispatchDomainEventTrayChangeCallback(self, dom: 'virDomain', devAlias: str, reason: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain trayChange event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), devAlias, reason, opaque) return 0 def _dispatchDomainEventPMWakeupCallback(self, dom: 'virDomain', reason: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain pmwakeup event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), reason, opaque) return 0 def _dispatchDomainEventPMSuspendCallback(self, dom: 'virDomain', reason: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain pmsuspend event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), reason, opaque) return 0 def _dispatchDomainEventBalloonChangeCallback(self, dom: 'virDomain', actual: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user domain balloon change event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), actual, opaque) return 0 def _dispatchDomainEventPMSuspendDiskCallback(self, dom: 'virDomain', reason: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain pmsuspend-disk event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), reason, opaque) return 0 def _dispatchDomainEventDeviceRemovedCallback(self, dom: 'virDomain', devAlias: str, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain device removed event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), devAlias, opaque) return 0 def _dispatchDomainEventTunableCallback(self, dom: 'virDomain', params: Any, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain tunable event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), params, opaque) return 0 def _dispatchDomainEventAgentLifecycleCallback(self, dom: 'virDomain', state: int, reason: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain agent lifecycle event callback """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), state, reason, opaque) return 0 def _dispatchDomainEventDeviceAddedCallback(self, dom: 'virDomain', devAlias: str, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain device added event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), devAlias, opaque) return 0 def _dispatchDomainEventMigrationIterationCallback(self, dom: 'virDomain', iteration: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain migration iteration event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), iteration, opaque) return 0 def _dispatchDomainEventJobCompletedCallback(self, dom: 'virDomain', params: Dict[str, Any], cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain job completed callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), params, opaque) return 0 def _dispatchDomainEventDeviceRemovalFailedCallback(self, dom: 'virDomain', devAlias: str, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain device removal failed event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), devAlias, opaque) return 0 def _dispatchDomainEventMetadataChangeCallback(self, dom: 'virDomain', mtype: int, nsuri: str, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain metadata change event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), mtype, nsuri, opaque) return 0 def _dispatchDomainEventBlockThresholdCallback(self, dom: 'virDomain', dev: str, path: str, threshold: int, excess: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain block device threshold event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), dev, path, threshold, excess, opaque) return 0 def _dispatchDomainEventMemoryFailureCallback(self, dom: 'virDomain', recipient: int, action: int, flags: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain memory failure event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), recipient, action, flags, opaque) return 0 def _dispatchDomainEventMemoryDeviceSizeChangeCallback(self, dom: 'virDomain', alias: str, size: int, cbData: Dict[str, Any]) -> int: """Dispatches event to python user domain memory device size change event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virDomain(self, _obj=dom), alias, size, opaque) return 0 def domainEventDeregisterAny(self, callbackID: int) -> None: """Removes a Domain Event Callback. De-registering for a domain callback will disable delivery of this event type """ try: ret = libvirtmod.virConnectDomainEventDeregisterAny(self._o, callbackID) if ret == -1: raise libvirtError('virConnectDomainEventDeregisterAny() failed') del self.domainEventCallbackID[callbackID] except AttributeError: pass def _dispatchNetworkEventLifecycleCallback(self, net: 'virNetwork', event: int, detail: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user network lifecycle event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virNetwork(self, _obj=net), event, detail, opaque) return 0 def _dispatchNetworkEventMetadataChangeCallback(self, dom: 'virNetwork', mtype: int, nsuri: str, cbData: Dict[str, Any]) -> int: """Dispatches event to python user network metadata change event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virNetwork(self, _obj=dom), mtype, nsuri, opaque) return 0 def networkEventDeregisterAny(self, callbackID: int) -> None: """Removes a Network Event Callback. De-registering for a network callback will disable delivery of this event type""" try: ret = libvirtmod.virConnectNetworkEventDeregisterAny(self._o, callbackID) if ret == -1: raise libvirtError('virConnectNetworkEventDeregisterAny() failed') del self.networkEventCallbackID[callbackID] except AttributeError: pass def networkEventRegisterAny(self, net: Optional['virNetwork'], eventID: int, cb: Callable, opaque: _T) -> int: """Adds a Network Event Callback. Registering for a network callback will enable delivery of the events""" if not hasattr(self, 'networkEventCallbackID'): self.networkEventCallbackID = {} # type: Dict[int, _T] cbData = {"cb": cb, "conn": self, "opaque": opaque} if net is None: ret = libvirtmod.virConnectNetworkEventRegisterAny(self._o, None, eventID, cbData) else: ret = libvirtmod.virConnectNetworkEventRegisterAny(self._o, net._o, eventID, cbData) if ret == -1: raise libvirtError('virConnectNetworkEventRegisterAny() failed') self.networkEventCallbackID[ret] = opaque return ret def domainEventRegisterAny(self, dom: Optional['virDomain'], eventID: int, cb: Callable, opaque: _T) -> int: """Adds a Domain Event Callback. Registering for a domain callback will enable delivery of the events """ if not hasattr(self, 'domainEventCallbackID'): self.domainEventCallbackID = {} # type: Dict[int, _T] cbData = {"cb": cb, "conn": self, "opaque": opaque} if dom is None: ret = libvirtmod.virConnectDomainEventRegisterAny(self._o, None, eventID, cbData) else: ret = libvirtmod.virConnectDomainEventRegisterAny(self._o, dom._o, eventID, cbData) if ret == -1: raise libvirtError('virConnectDomainEventRegisterAny() failed') self.domainEventCallbackID[ret] = opaque return ret def _dispatchStoragePoolEventLifecycleCallback(self, pool: 'virStoragePool', event: int, detail: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user storage pool lifecycle event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virStoragePool(self, _obj=pool), event, detail, opaque) return 0 def _dispatchStoragePoolEventGenericCallback(self, pool: 'virStoragePool', cbData: Dict[str, Any]) -> int: """Dispatches events to python user storage pool generic event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virStoragePool(self, _obj=pool), opaque) return 0 def storagePoolEventDeregisterAny(self, callbackID: int) -> None: """Removes a Storage Pool Event Callback. De-registering for a storage pool callback will disable delivery of this event type""" try: ret = libvirtmod.virConnectStoragePoolEventDeregisterAny(self._o, callbackID) if ret == -1: raise libvirtError('virConnectStoragePoolEventDeregisterAny() failed') del self.storagePoolEventCallbackID[callbackID] except AttributeError: pass def storagePoolEventRegisterAny(self, pool: Optional['virStoragePool'], eventID: int, cb: Callable, opaque: _T) -> int: """Adds a Storage Pool Event Callback. Registering for a storage pool callback will enable delivery of the events""" if not hasattr(self, 'storagePoolEventCallbackID'): self.storagePoolEventCallbackID = {} # type: Dict[int, _T] cbData = {"cb": cb, "conn": self, "opaque": opaque} if pool is None: ret = libvirtmod.virConnectStoragePoolEventRegisterAny(self._o, None, eventID, cbData) else: ret = libvirtmod.virConnectStoragePoolEventRegisterAny(self._o, pool._o, eventID, cbData) if ret == -1: raise libvirtError('virConnectStoragePoolEventRegisterAny() failed') self.storagePoolEventCallbackID[ret] = opaque return ret def _dispatchNodeDeviceEventLifecycleCallback(self, dev: 'virNodeDevice', event: int, detail: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user node device lifecycle event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virNodeDevice(self, _obj=dev), event, detail, opaque) return 0 def _dispatchNodeDeviceEventGenericCallback(self, dev: 'virNodeDevice', cbData: Dict[str, Any]) -> int: """Dispatches events to python user node device generic event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virNodeDevice(self, _obj=dev), opaque) return 0 def nodeDeviceEventDeregisterAny(self, callbackID: int) -> None: """Removes a Node Device Event Callback. De-registering for a node device callback will disable delivery of this event type""" try: ret = libvirtmod.virConnectNodeDeviceEventDeregisterAny(self._o, callbackID) if ret == -1: raise libvirtError('virConnectNodeDeviceEventDeregisterAny() failed') del self.nodeDeviceEventCallbackID[callbackID] except AttributeError: pass def nodeDeviceEventRegisterAny(self, dev: Optional['virNodeDevice'], eventID: int, cb: Callable, opaque: _T) -> int: """Adds a Node Device Event Callback. Registering for a node device callback will enable delivery of the events""" if not hasattr(self, 'nodeDeviceEventCallbackID'): self.nodeDeviceEventCallbackID = {} # type: Dict[int, _T] cbData = {"cb": cb, "conn": self, "opaque": opaque} if dev is None: ret = libvirtmod.virConnectNodeDeviceEventRegisterAny(self._o, None, eventID, cbData) else: ret = libvirtmod.virConnectNodeDeviceEventRegisterAny(self._o, dev._o, eventID, cbData) if ret == -1: raise libvirtError('virConnectNodeDeviceEventRegisterAny() failed') self.nodeDeviceEventCallbackID[ret] = opaque return ret def _dispatchSecretEventLifecycleCallback(self, secret: 'virSecret', event: int, detail: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user secret lifecycle event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virSecret(self, _obj=secret), event, detail, opaque) return 0 def _dispatchSecretEventGenericCallback(self, secret: 'virSecret', cbData: Dict[str, Any]) -> int: """Dispatches events to python user secret generic event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, virSecret(self, _obj=secret), opaque) return 0 def secretEventDeregisterAny(self, callbackID: int) -> None: """Removes a Secret Event Callback. De-registering for a secret callback will disable delivery of this event type""" try: ret = libvirtmod.virConnectSecretEventDeregisterAny(self._o, callbackID) if ret == -1: raise libvirtError('virConnectSecretEventDeregisterAny() failed') del self.secretEventCallbackID[callbackID] except AttributeError: pass def secretEventRegisterAny(self, secret: Optional['virSecret'], eventID: int, cb: Callable, opaque: _T) -> int: """Adds a Secret Event Callback. Registering for a secret callback will enable delivery of the events""" if not hasattr(self, 'secretEventCallbackID'): self.secretEventCallbackID = {} # type: Dict[int, _T] cbData = {"cb": cb, "conn": self, "opaque": opaque} if secret is None: ret = libvirtmod.virConnectSecretEventRegisterAny(self._o, None, eventID, cbData) else: ret = libvirtmod.virConnectSecretEventRegisterAny(self._o, secret._o, eventID, cbData) if ret == -1: raise libvirtError('virConnectSecretEventRegisterAny() failed') self.secretEventCallbackID[ret] = opaque return ret def listAllDomains(self, flags: int = 0) -> List['virDomain']: """List all domains and returns a list of domain objects""" ret = libvirtmod.virConnectListAllDomains(self._o, flags) if ret is None: raise libvirtError("virConnectListAllDomains() failed") return [virDomain(self, _obj=domptr) for domptr in ret] def listAllStoragePools(self, flags: int = 0) -> List['virStoragePool']: """Returns a list of storage pool objects""" ret = libvirtmod.virConnectListAllStoragePools(self._o, flags) if ret is None: raise libvirtError("virConnectListAllStoragePools() failed") return [virStoragePool(self, _obj=poolptr) for poolptr in ret] def listAllNetworks(self, flags: int = 0) -> List['virNetwork']: """Returns a list of network objects""" ret = libvirtmod.virConnectListAllNetworks(self._o, flags) if ret is None: raise libvirtError("virConnectListAllNetworks() failed") return [virNetwork(self, _obj=netptr) for netptr in ret] def listAllInterfaces(self, flags: int = 0) -> List['virInterface']: """Returns a list of interface objects""" ret = libvirtmod.virConnectListAllInterfaces(self._o, flags) if ret is None: raise libvirtError("virConnectListAllInterfaces() failed") return [virInterface(self, _obj=ifaceptr) for ifaceptr in ret] def listAllDevices(self, flags: int = 0) -> List['virNodeDevice']: """Returns a list of host node device objects""" ret = libvirtmod.virConnectListAllNodeDevices(self._o, flags) if ret is None: raise libvirtError("virConnectListAllNodeDevices() failed") return [virNodeDevice(self, _obj=devptr) for devptr in ret] def listAllNWFilters(self, flags: int = 0) -> List['virNWFilter']: """Returns a list of network filter objects""" ret = libvirtmod.virConnectListAllNWFilters(self._o, flags) if ret is None: raise libvirtError("virConnectListAllNWFilters() failed") return [virNWFilter(self, _obj=filter_ptr) for filter_ptr in ret] def listAllNWFilterBindings(self, flags: int = 0) -> List['virNWFilterBinding']: """Returns a list of network filter binding objects""" ret = libvirtmod.virConnectListAllNWFilterBindings(self._o, flags) if ret is None: raise libvirtError("virConnectListAllNWFilterBindings() failed") return [virNWFilterBinding(self, _obj=filter_ptr) for filter_ptr in ret] def listAllSecrets(self, flags: int = 0) -> List['virSecret']: """Returns a list of secret objects""" ret = libvirtmod.virConnectListAllSecrets(self._o, flags) if ret is None: raise libvirtError("virConnectListAllSecrets() failed") return [virSecret(self, _obj=secret_ptr) for secret_ptr in ret] def _dispatchCloseCallback(self, reason: int, cbData: Dict[str, Any]) -> int: """Dispatches events to python user close callback""" cb = cbData["cb"] opaque = cbData["opaque"] cb(self, reason, opaque) return 0 def unregisterCloseCallback(self) -> None: """Removes a close event callback""" ret = libvirtmod.virConnectUnregisterCloseCallback(self._o) if ret == -1: raise libvirtError('virConnectUnregisterCloseCallback() failed') def registerCloseCallback(self, cb: Callable, opaque: _T) -> int: """Adds a close event callback, providing a notification when a connection fails / closes""" cbData = {"cb": cb, "conn": self, "opaque": opaque} ret = libvirtmod.virConnectRegisterCloseCallback(self._o, cbData) if ret == -1: raise libvirtError('virConnectRegisterCloseCallback() failed') return ret def createXMLWithFiles(self, xmlDesc: str, files: List[int], flags: int = 0) -> 'virDomain': """Launch a new guest domain, based on an XML description similar to the one returned by virDomainGetXMLDesc() This function may require privileged access to the hypervisor. The domain is not persistent, so its definition will disappear when it is destroyed, or if the host is restarted (see virDomainDefineXML() to define persistent domains). @files provides an array of file descriptors which will be made available to the 'init' process of the guest. The file handles exposed to the guest will be renumbered to start from 3 (ie immediately following stderr). This is only supported for guests which use container based virtualization technology. If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain will be started, but its CPUs will remain paused. The CPUs can later be manually started using virDomainResume. If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest domain will be automatically destroyed when the virConnectPtr object is finally released. This will also happen if the client application crashes / loses its connection to the libvirtd daemon. Any domains marked for auto destroy will block attempts at migration, save-to-file, or snapshots. """ ret = libvirtmod.virDomainCreateXMLWithFiles(self._o, xmlDesc, files, flags) if ret is None: raise libvirtError('virDomainCreateXMLWithFiles() failed') __tmp = virDomain(self, _obj=ret) return __tmp def getAllDomainStats(self, stats: int = 0, flags: int = 0) -> List[Tuple['virDomain', Dict[str, Any]]]: """Query statistics for all domains on a given connection. Report statistics of various parameters for a running VM according to @stats field. The statistics are returned as an array of structures for each queried domain. The structure contains an array of typed parameters containing the individual statistics. The typed parameter name for each statistic field consists of a dot-separated string containing name of the requested group followed by a group specific description of the statistic value. The statistic groups are enabled using the @stats parameter which is a binary-OR of enum virDomainStatsTypes. The following groups are available (although not necessarily implemented for each hypervisor): VIR_DOMAIN_STATS_STATE: Return domain state and reason for entering that state. The typed parameter keys are in this format: "state.state" - state of the VM, returned as int from virDomainState enum "state.reason" - reason for entering given state, returned as int from virDomain*Reason enum corresponding to given state. Using 0 for @stats returns all stats groups supported by the given hypervisor. Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes the function return error in case some of the stat types in @stats were not recognized by the daemon. Similarly to virConnectListAllDomains, @flags can contain various flags to filter the list of domains to provide stats for. VIR_CONNECT_GET_ALL_DOMAINS_STATS_ACTIVE selects online domains while VIR_CONNECT_GET_ALL_DOMAINS_STATS_INACTIVE selects offline ones. VIR_CONNECT_GET_ALL_DOMAINS_STATS_PERSISTENT and VIR_CONNECT_GET_ALL_DOMAINS_STATS_TRANSIENT allow to filter the list according to their persistence. To filter the list of VMs by domain state @flags can contain VIR_CONNECT_GET_ALL_DOMAINS_STATS_RUNNING, VIR_CONNECT_GET_ALL_DOMAINS_STATS_PAUSED, VIR_CONNECT_GET_ALL_DOMAINS_STATS_SHUTOFF and/or VIR_CONNECT_GET_ALL_DOMAINS_STATS_OTHER for all other states. """ ret = libvirtmod.virConnectGetAllDomainStats(self._o, stats, flags) if ret is None: raise libvirtError("virConnectGetAllDomainStats() failed") return [(virDomain(self, _obj=elem[0]), elem[1]) for elem in ret] def domainListGetStats(self, doms: List['virDomain'], stats: int = 0, flags: int = 0) -> List[Tuple['virDomain', Dict[str, Any]]]: """ Query statistics for given domains. Report statistics of various parameters for a running VM according to @stats field. The statistics are returned as an array of structures for each queried domain. The structure contains an array of typed parameters containing the individual statistics. The typed parameter name for each statistic field consists of a dot-separated string containing name of the requested group followed by a group specific description of the statistic value. The statistic groups are enabled using the @stats parameter which is a binary-OR of enum virDomainStatsTypes. The following groups are available (although not necessarily implemented for each hypervisor): VIR_DOMAIN_STATS_STATE: Return domain state and reason for entering that state. The typed parameter keys are in this format: "state.state" - state of the VM, returned as int from virDomainState enum "state.reason" - reason for entering given state, returned as int from virDomain*Reason enum corresponding to given state. Using 0 for @stats returns all stats groups supported by the given hypervisor. Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes the function return error in case some of the stat types in @stats were not recognized by the daemon. Get statistics about domains provided as a list in @doms. @stats is a bit field selecting requested statistics types.""" domlist = list() for dom in doms: if not isinstance(dom, virDomain): raise libvirtError("domain list contains non-domain elements") domlist.append(dom._o) ret = libvirtmod.virDomainListGetStats(self._o, domlist, stats, flags) if ret is None: raise libvirtError("virDomainListGetStats() failed") return [(virDomain(self, _obj=elem[0]), elem[1]) for elem in ret] ./libvirt-python-9.10.0/libvirt-override-virDomain.py0000644000000000000000000001277414555064067021245 0ustar rootroot def listAllSnapshots(self, flags: int = 0) -> List['virDomainSnapshot']: """List all snapshots and returns a list of snapshot objects""" ret = libvirtmod.virDomainListAllSnapshots(self._o, flags) if ret is None: raise libvirtError("virDomainListAllSnapshots() failed") return [virDomainSnapshot(self, _obj=snapptr) for snapptr in ret] def listAllCheckpoints(self, flags: int = 0) -> List['virDomainCheckpoint']: """List all checkpoints and returns a list of checkpoint objects""" ret = libvirtmod.virDomainListAllCheckpoints(self._o, flags) if ret is None: raise libvirtError("virDomainListAllCheckpoints() failed") return [virDomainCheckpoint(self, _obj=chkptr) for chkptr in ret] def createWithFiles(self, files: List[int], flags: int = 0) -> 'virDomain': """Launch a defined domain. If the call succeeds the domain moves from the defined to the running domains pools. @files provides an array of file descriptors which will be made available to the 'init' process of the guest. The file handles exposed to the guest will be renumbered to start from 3 (ie immediately following stderr). This is only supported for guests which use container based virtualization technology. If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain has a managed save image that requested paused state (see virDomainManagedSave()) the guest domain will be started, but its CPUs will remain paused. The CPUs can later be manually started using virDomainResume(). In all other cases, the guest domain will be running. If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest domain will be automatically destroyed when the virConnectPtr object is finally released. This will also happen if the client application crashes / loses its connection to the libvirtd daemon. Any domains marked for auto destroy will block attempts at migration, save-to-file, or snapshots. If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a managed save file for this domain (created by virDomainManagedSave()), then libvirt will attempt to bypass the file system cache while restoring the file, or fail if it cannot do so for the given system; this can allow less pressure on file system cache, but also risks slowing loads from NFS. If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save file for this domain is discarded, and the domain boots from scratch. """ ret = libvirtmod.virDomainCreateWithFiles(self._o, files, flags) if ret == -1: raise libvirtError('virDomainCreateWithFiles() failed') return ret def fsFreeze(self, mountpoints: List[str] = None, flags: int = 0) -> int: """Freeze specified filesystems within the guest """ ret = libvirtmod.virDomainFSFreeze(self._o, mountpoints, flags) if ret == -1: raise libvirtError('virDomainFSFreeze() failed') return ret def fsThaw(self, mountpoints: List[str] = None, flags: int = 0) -> int: """Thaw specified filesystems within the guest """ ret = libvirtmod.virDomainFSThaw(self._o, mountpoints, flags) if ret == -1: raise libvirtError('virDomainFSThaw() failed') return ret def getTime(self, flags: int = 0) -> int: """Extract information about guest time """ ret = libvirtmod.virDomainGetTime(self._o, flags) if ret is None: raise libvirtError('virDomainGetTime() failed') return ret def setTime(self, time: int = None, flags: int = 0) -> int: """Set guest time to the given value. @time is a dict containing 'seconds' field for seconds and 'nseconds' field for nanoseconds """ ret = libvirtmod.virDomainSetTime(self._o, time, flags) if ret == -1: raise libvirtError('virDomainSetTime() failed') return ret def FDAssociate(self, name: str, files: List[int], flags: int = 0) -> int: """Associate the array of FDs passed as @fds with the domain object under @name. The FDs are associated as long as the connection used to associated exists and are disposed of afterwards. FD may still be kept open by the hypervisor for as long as it's needed. Security labelling (e.g. via the selinux) may be applied on the passed FDs when requiredg for usage by the VM. By default libvirt does not restore the seclabels on the FDs afterwards to avoid keeping it open unnecessarily. Restoring of the security label can be requested by passing either VIR_DOMAIN_FD_ASSOCIATE_SECLABEL_RESTORE for a best-effort attempt to restore the security label after use. Requesting the restore of security label will require that the file descriptors are kept open for the whole time they are used by the hypervisor, or other additional overhead. In certain cases usage of the fd group would imply read-only access. Passing VIR_DOMAIN_FD_ASSOCIATE_SECLABEL_WRITABLE in @flags ensures that a writable security label is picked in case when the file represented by the fds may be used in write mode. """ ret = libvirtmod.virDomainFDAssociate(self._o, name, files, flags) if ret == -1: raise libvirtError('virDomainFDAssociate() failed') return ret ./libvirt-python-9.10.0/libvirt-override-virDomainCheckpoint.py0000644000000000000000000000131414555064067023241 0ustar rootroot def getConnect(self) -> 'virConnect': """Get the connection that owns the domain that a checkpoint was created for""" return self.connect() def getDomain(self) -> 'virDomain': """Get the domain that a checkpoint was created for""" return self.domain() def listAllChildren(self, flags: int = 0) -> List['virDomainCheckpoint']: """List all child checkpoints and returns a list of checkpoint objects""" ret = libvirtmod.virDomainCheckpointListAllChildren(self._o, flags) if ret is None: raise libvirtError("virDomainCheckpointListAllChildren() failed") return [virDomainCheckpoint(self.domain(), _obj=chkptr) for chkptr in ret] ./libvirt-python-9.10.0/libvirt-override-virDomainSnapshot.py0000644000000000000000000000127614555064067022760 0ustar rootroot def getConnect(self) -> 'virConnect': """Get the connection that owns the domain that a snapshot was created for""" return self.connect() def getDomain(self) -> 'virDomain': """Get the domain that a snapshot was created for""" return self.domain() def listAllChildren(self, flags: int = 0) -> List['virDomainSnapshot']: """List all child snapshots and returns a list of snapshot objects""" ret = libvirtmod.virDomainSnapshotListAllChildren(self._o, flags) if ret is None: raise libvirtError("virDomainSnapshotListAllChildren() failed") return [virDomainSnapshot(self.domain(), _obj=snapptr) for snapptr in ret] ./libvirt-python-9.10.0/libvirt-override-virNetwork.py0000644000000000000000000000057514555064067021463 0ustar rootroot def listAllPorts(self, flags: int = 0) -> List['virNetworkPort']: """List all ports on the network and returns a list of network port objects""" ret = libvirtmod.virNetworkListAllPorts(self._o, flags) if ret is None: raise libvirtError("virNetworkListAllPorts() failed") return [virNetworkPort(self, _obj=domptr) for domptr in ret] ./libvirt-python-9.10.0/libvirt-override-virStoragePool.py0000644000000000000000000000061414555064067022262 0ustar rootroot def listAllVolumes(self, flags: int = 0) -> List['virStorageVol']: """List all storage volumes and returns a list of storage volume objects""" ret = libvirtmod.virStoragePoolListAllVolumes(self._o, flags) if ret is None: raise libvirtError("virStoragePoolListAllVolumes() failed") return [virStorageVol(self._conn, _obj=volptr) for volptr in ret] ./libvirt-python-9.10.0/libvirt-override-virStream.py0000644000000000000000000002627514555064067021272 0ustar rootroot def __del__(self) -> None: try: if self.cb: libvirtmod.virStreamEventRemoveCallback(self._o) except AttributeError: pass if self._o is not None: libvirtmod.virStreamFree(self._o) self._o = None def _dispatchStreamEventCallback(self, events: int, cbData: Dict[str, Any]) -> int: """ Dispatches events to python user's stream event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(self, events, opaque) return 0 def eventAddCallback(self, events: int, cb: Callable[['virStream', int, _T], None], opaque: _T) -> None: self.cb = cb cbData = {"stream": self, "cb": cb, "opaque": opaque} ret = libvirtmod.virStreamEventAddCallback(self._o, events, cbData) if ret == -1: raise libvirtError('virStreamEventAddCallback() failed') def recvAll(self, handler: Callable[['virStream', bytes, _T], int], opaque: _T) -> None: """Receive the entire data stream, sending the data to the requested data sink. This is simply a convenient alternative to virStreamRecv, for apps that do blocking-I/O. A hypothetical handler function looks like: def handler(stream, # virStream instance buf, # string containing received data opaque): # extra data passed to recvAll as opaque fd = opaque return os.write(fd, buf) """ while True: got = self.recv(virStorageVol.streamBufSize) if got == -2: raise libvirtError("cannot use recvAll with " "nonblocking stream") if len(got) == 0: break try: ret = handler(self, got, opaque) if isinstance(ret, int) and ret < 0: raise RuntimeError("recvAll handler returned %d" % ret) except BaseException: try: self.abort() except Exception: pass raise def sendAll(self, handler: Callable[['virStream', int, _T], bytes], opaque: _T) -> None: """ Send the entire data stream, reading the data from the requested data source. This is simply a convenient alternative to virStreamSend, for apps that do blocking-I/O. A hypothetical handler function looks like: def handler(stream, # virStream instance nbytes, # int amt of data to read opaque): # extra data passed to recvAll as opaque fd = opaque return os.read(fd, nbytes) """ while True: try: got = handler(self, virStorageVol.streamBufSize, opaque) except BaseException: try: self.abort() except Exception: pass raise if not got: break ret = self.send(got) if ret == -2: raise libvirtError("cannot use sendAll with " "nonblocking stream") def recv(self, nbytes: int) -> bytes: """Reads a series of bytes from the stream. This method may block the calling application for an arbitrary amount of time. Errors are not guaranteed to be reported synchronously with the call, but may instead be delayed until a subsequent call. On success, the received data is returned. On failure, an exception is raised. If the stream is a NONBLOCK stream and the request would block, integer -2 is returned. """ ret = libvirtmod.virStreamRecv(self._o, nbytes) if ret is None: raise libvirtError('virStreamRecv() failed') return ret def send(self, data: bytes) -> int: """Write a series of bytes to the stream. This method may block the calling application for an arbitrary amount of time. Once an application has finished sending data it should call virStreamFinish to wait for successful confirmation from the driver, or detect any error This method may not be used if a stream source has been registered Errors are not guaranteed to be reported synchronously with the call, but may instead be delayed until a subsequent call. """ ret = libvirtmod.virStreamSend(self._o, data) if ret == -1: raise libvirtError('virStreamSend() failed') return ret def recvHole(self, flags: int = 0) -> int: """This method is used to determine the length in bytes of the empty space to be created in a stream's target file when uploading or downloading sparsely populated files. This is the counterpart to sendHole. """ ret = libvirtmod.virStreamRecvHole(self._o, flags) if ret is None: raise libvirtError('virStreamRecvHole() failed') return ret def sendHole(self, length: int, flags: int = 0) -> int: """Rather than transmitting empty file space, this method directs the stream target to create length bytes of empty space. This method would be used when uploading or downloading sparsely populated files to avoid the needless copy of empty file space. """ ret = libvirtmod.virStreamSendHole(self._o, length, flags) if ret == -1: raise libvirtError('virStreamSendHole() failed') return ret def recvFlags(self, nbytes: int, flags: int = 0) -> Union[bytes, int]: """Reads a series of bytes from the stream. This method may block the calling application for an arbitrary amount of time. This is just like recv except it has flags argument. Errors are not guaranteed to be reported synchronously with the call, but may instead be delayed until a subsequent call. On success, the received data is returned. On failure, an exception is raised. If the stream is a NONBLOCK stream and the request would block, integer -2 is returned. """ ret = libvirtmod.virStreamRecvFlags(self._o, nbytes, flags) if ret is None: raise libvirtError('virStreamRecvFlags() failed') return ret def sparseRecvAll(self, handler: Callable[['virStream', bytes, _T], Union[bytes, int]], holeHandler: Callable[['virStream', int, _T], Optional[int]], opaque: _T) -> None: """Receive the entire data stream, sending the data to the requested data sink handler and calling the skip holeHandler to generate holes for sparse stream targets. This is simply a convenient alternative to recvFlags, for apps that do blocking-I/O and want to preserve sparseness. Hypothetical callbacks can look like this: def handler(stream, # virStream instance buf, # string containing received data opaque): # extra data passed to sparseRecvAll as opaque fd = opaque return os.write(fd, buf) def holeHandler(stream, # virStream instance length, # number of bytes to skip opaque): # extra data passed to sparseRecvAll as opaque fd = opaque cur = os.lseek(fd, length, os.SEEK_CUR) return os.ftruncate(fd, cur) # take this extra step to # actually allocate the hole """ while True: want = virStorageVol.streamBufSize got = self.recvFlags(want, VIR_STREAM_RECV_STOP_AT_HOLE) if got == -2: raise libvirtError("cannot use sparseRecvAll with " "nonblocking stream") elif got == -3: length = self.recvHole() if length is None: self.abort() raise RuntimeError("recvHole handler failed") ret_hole = holeHandler(self, length, opaque) if isinstance(ret_hole, int) and ret_hole < 0: self.abort() raise RuntimeError("holeHandler handler returned %d" % ret_hole) continue elif isinstance(got, int): raise ValueError(got) elif not isinstance(got, bytes): raise TypeError(type(got)) if len(got) == 0: break ret_data = handler(self, got, opaque) if isinstance(ret_data, int) and ret_data < 0: self.abort() raise RuntimeError("sparseRecvAll handler returned %d" % ret_data) def sparseSendAll(self, handler: Callable[['virStream', int, _T], Union[bytes, int]], holeHandler: Callable[['virStream', _T], Tuple[bool, int]], skipHandler: Callable[['virStream', int, _T], int], opaque: _T) -> None: """Send the entire data stream, reading the data from the requested data source. This is simply a convenient alternative to virStreamSend, for apps that do blocking-I/O and want to preserve sparseness. Hypothetical callbacks can look like this: def handler(stream, # virStream instance nbytes, # int amt of data to read opaque): # extra data passed to sparseSendAll as opaque fd = opaque return os.read(fd, nbytes) def holeHandler(stream, # virStream instance opaque): # extra data passed to sparseSendAll as opaque fd = opaque cur = os.lseek(fd, 0, os.SEEK_CUR) # ... find out current section and its boundaries # and set inData = True/False and sectionLen correspondingly os.lseek(fd, cur, os.SEEK_SET) return [inData, sectionLen] def skipHandler(stream, # virStream instance length, # number of bytes to skip opaque): # extra data passed to sparseSendAll as opaque fd = opaque return os.lseek(fd, length, os.SEEK_CUR) """ while True: [inData, sectionLen] = holeHandler(self, opaque) if not inData and sectionLen > 0: if (self.sendHole(sectionLen) < 0 or skipHandler(self, sectionLen, opaque) < 0): self.abort() continue want = virStorageVol.streamBufSize if (want > sectionLen): want = sectionLen got = handler(self, want, opaque) if isinstance(got, int) and got < 0: self.abort() raise RuntimeError("sparseSendAll handler returned %d" % got) if not got: break assert isinstance(got, bytes) ret = self.send(got) if ret == -2: raise libvirtError("cannot use sparseSendAll with " "nonblocking stream") ./libvirt-python-9.10.0/libvirt-override.py0000644000000000000000000002354514555064067017315 0ustar rootroot from types import TracebackType from typing import Any, Callable, Dict, List, Optional, overload, Tuple, Type, TypeVar, Union _T = TypeVar('_T') _EventCB = Callable[[int, int, int, _T], None] _EventAddHandleFunc = Callable[[int, int, _EventCB, _T], int] _EventUpdateHandleFunc = Callable[[int, int], None] _EventRemoveHandleFunc = Callable[[int], int] _TimerCB = Callable[[int, _T], None] _EventAddTimeoutFunc = Callable[[int, _TimerCB, _T], int] _EventUpdateTimeoutFunc = Callable[[int, int], None] _EventRemoveTimeoutFunc = Callable[[int], int] _DomainCB = Callable[['virConnect', 'virDomain', int, int, _T], Optional[int]] _BlkioParameter = Dict[str, Any] _MemoryParameter = Dict[str, Any] _SchedParameter = Dict[str, Any] _TypedParameter = Dict[str, Any] # The root of all libvirt errors. class libvirtError(Exception): def __init__(self, defmsg: str) -> None: # Never call virConnGetLastError(). # virGetLastError() is now thread local err = libvirtmod.virGetLastError() # type: Optional[Tuple[int, int, str, int, str, Optional[str], Optional[str], int, int]] if err is None: msg = defmsg else: msg = err[2] Exception.__init__(self, msg) self.err = err def get_error_code(self) -> Optional[int]: if self.err is None: return None return self.err[0] def get_error_domain(self) -> Optional[int]: if self.err is None: return None return self.err[1] def get_error_message(self) -> Optional[str]: if self.err is None: return None return self.err[2] def get_error_level(self) -> Optional[int]: if self.err is None: return None return self.err[3] def get_str1(self) -> Optional[str]: if self.err is None: return None return self.err[4] def get_str2(self) -> Optional[str]: if self.err is None: return None return self.err[5] def get_str3(self) -> Optional[str]: if self.err is None: return None return self.err[6] def get_int1(self) -> Optional[int]: if self.err is None: return None return self.err[7] def get_int2(self) -> Optional[int]: if self.err is None: return None return self.err[8] # # register the libvirt global error handler # def registerErrorHandler(f: Callable[[_T, List], None], ctx: _T) -> int: """Register a Python function for error reporting. The function is called back as f(ctx, error), with error being a list of information about the error being raised. Returns 1 in case of success.""" return libvirtmod.virRegisterErrorHandler(f, ctx) def openAuth(uri: str, auth: List, flags: int = 0) -> 'virConnect': # TODO: The C code rquires a List and there is not *Mutable*Tuple for a better description such as # auth: Tuple[List[int], Callable[[List[MutableTuple[int, str, str, str, Any]], _T], int], _T] """ This function should be called first to get a connection to the Hypervisor. If necessary, authentication will be performed fetching credentials via the callback. See :py:func:`open` for notes about environment variables which can have an effect on opening drivers and freeing the connection resources. :param str uri: (Optional) connection URI, see https://libvirt.org/uri.html :param auth: a list that contains 3 items: - a list of supported credential types - a callable that takes 2 arguments (credentials, user-data) and returns 0 on succcess and -1 on errors. The credentials argument is a list of credentials that libvirt (actually the ESX driver) would like to request. An element of this list is itself a list containing 5 items (4 inputs, 1 output): - the credential type, e.g. :py:const:`libvirt.VIR_CRED_AUTHNAME` - a prompt to be displayed to the user - a challenge, the ESX driver sets this to the hostname to allow automatic distinction between requests for ESX and vCenter credentials - a default result for the request - a place to store the actual result for the request - user data that will be passed to the callable as second argument :param int flags: bitwise-OR of virConnectFlags :returns: a :py:class:`virConnect` instance on success. :raises libvirtError: on errors. """ ret = libvirtmod.virConnectOpenAuth(uri, auth, flags) if ret is None: raise libvirtError('virConnectOpenAuth() failed') return virConnect(_obj=ret) # # Return library version. # def getVersion(name: Optional[str] = None) -> int: """If no name parameter is passed (or name is None) then the version of the libvirt library is returned as an integer. If a name is passed and it refers to a driver linked to the libvirt library, then this returns a tuple of (library version, driver version). If the name passed refers to a non-existent driver, then you will get the exception 'no support for hypervisor'. Versions numbers are integers: 1000000*major + 1000*minor + release.""" if name is None: ret = libvirtmod.virGetVersion() else: ret = libvirtmod.virGetVersion(name) if ret is None: raise libvirtError("virGetVersion() failed") return ret # # Invoke an EventHandle callback # @overload def _eventInvokeHandleCallback(watch: int, fd: int, event: int, opaque: Tuple[_EventCB, _T], opaquecompat: None = None) -> None: ... # noqa E704 @overload # noqa F811 def _eventInvokeHandleCallback(watch: int, fd: int, event: int, opaque: _EventCB, opaquecompat: _T = None) -> None: ... # noqa E704 def _eventInvokeHandleCallback(watch: int, fd: int, event: int, opaque: Union[Tuple[_EventCB, _T], _EventCB], opaquecompat: Optional[_T] = None) -> None: # noqa F811 """ Invoke the Event Impl Handle Callback in C """ # libvirt 0.9.2 and earlier required custom event loops to know # that opaque=(cb, original_opaque) and pass the values individually # to this wrapper. This should handle the back compat case, and make # future invocations match the virEventHandleCallback prototype if opaquecompat: callback = opaque opaque_ = opaquecompat else: assert isinstance(opaque, tuple) callback = opaque[0] opaque_ = opaque[1] libvirtmod.virEventInvokeHandleCallback(watch, fd, event, callback, opaque_) # # Invoke an EventTimeout callback # def _eventInvokeTimeoutCallback(timer: int, opaque: Union[Tuple[_TimerCB, _T], _TimerCB], opaquecompat: Optional[_T] = None) -> None: """ Invoke the Event Impl Timeout Callback in C """ # libvirt 0.9.2 and earlier required custom event loops to know # that opaque=(cb, original_opaque) and pass the values individually # to this wrapper. This should handle the back compat case, and make # future invocations match the virEventTimeoutCallback prototype if opaquecompat: callback = opaque opaque_ = opaquecompat else: assert isinstance(opaque, tuple) callback = opaque[0] opaque_ = opaque[1] libvirtmod.virEventInvokeTimeoutCallback(timer, callback, opaque_) def _dispatchEventHandleCallback(watch: int, fd: int, events: int, cbData: Dict[str, Any]) -> int: cb = cbData["cb"] opaque = cbData["opaque"] cb(watch, fd, events, opaque) return 0 def _dispatchEventTimeoutCallback(timer: int, cbData: Dict[str, Any]) -> int: cb = cbData["cb"] opaque = cbData["opaque"] cb(timer, opaque) return 0 def virEventAddHandle(fd: int, events: int, cb: _EventCB, opaque: _T) -> int: """ register a callback for monitoring file handle events @fd: file handle to monitor for events @events: bitset of events to watch from virEventHandleType constants @cb: callback to invoke when an event occurs @opaque: user data to pass to callback Example callback prototype is: def cb(watch, # int id of the handle fd, # int file descriptor the event occurred on events, # int bitmap of events that have occurred opaque): # opaque data passed to eventAddHandle """ cbData = {"cb": cb, "opaque": opaque} ret = libvirtmod.virEventAddHandle(fd, events, cbData) if ret == -1: raise libvirtError('virEventAddHandle() failed') return ret def virEventAddTimeout(timeout: int, cb: _TimerCB, opaque: _T) -> int: """ register a callback for a timer event @timeout: time between events in milliseconds @cb: callback to invoke when an event occurs @opaque: user data to pass to callback Setting timeout to -1 will disable the timer. Setting the timeout to zero will cause it to fire on every event loop iteration. Example callback prototype is: def cb(timer, # int id of the timer opaque): # opaque data passed to eventAddTimeout """ cbData = {"cb": cb, "opaque": opaque} ret = libvirtmod.virEventAddTimeout(timeout, cbData) if ret == -1: raise libvirtError('virEventAddTimeout() failed') return ret # # a caller for the ff callbacks for custom event loop implementations # def virEventInvokeFreeCallback(opaque: Any) -> None: """ Execute callback which frees the opaque buffer @opaque: the opaque object passed to addHandle or addTimeout WARNING: This function should not be called from any call by libvirt's core. It will most probably cause deadlock in C-level libvirt code. Instead it should be scheduled and called from implementation's stack. See https://libvirt.org/html/libvirt-libvirt-event.html#virEventAddHandleFunc for more information. This function is not dependent on any event loop implementation. """ libvirtmod.virEventInvokeFreeCallback(opaque[2], opaque[1]) ./libvirt-python-9.10.0/libvirt-python.spec.in0000644000000000000000000000525414555064067017723 0ustar rootroot# -*- rpm-spec -*- # This spec file assumes you are building on a Fedora or RHEL version # that's still supported by the vendor. It may work on other distros # or versions, but no effort will be made to ensure that going forward %define min_rhel 8 %define min_fedora 33 %if (0%{?fedora} && 0%{?fedora} >= %{min_fedora}) || (0%{?rhel} && 0%{?rhel} >= %{min_rhel}) %define supported_platform 1 %else %define supported_platform 0 %endif Summary: The libvirt virtualization API python3 binding Name: libvirt-python Version: @PY_VERSION@ Release: 1%{?dist} Source0: https://libvirt.org/sources/python/%{name}-%{version}.tar.gz Url: https://libvirt.org License: LGPL-2.1-or-later BuildRequires: libvirt-devel == %{version} BuildRequires: python3-devel BuildRequires: python3-pytest BuildRequires: python3-lxml BuildRequires: python3-setuptools BuildRequires: gcc # Don't want provides for python shared objects %{?filter_provides_in: %filter_provides_in %{python3_sitearch}/.*\.so} %{?filter_setup} %description The libvirt-python package contains a module that permits applications written in the Python programming language to use the interface supplied by the libvirt library to use the virtualization capabilities of recent versions of Linux (and other OSes). %package -n python3-libvirt Summary: The libvirt virtualization API python3 binding Url: http://libvirt.org License: LGPLv2+ %{?python_provide:%python_provide python3-libvirt} Provides: libvirt-python3 = %{version}-%{release} Obsoletes: libvirt-python3 <= 3.6.0-1%{?dist} %description -n python3-libvirt The python3-libvirt package contains a module that permits applications written in the Python 3.x programming language to use the interface supplied by the libvirt library to use the virtualization capabilities of recent versions of Linux (and other OSes). %prep %setup -q # Unset execute bit for example scripts; it can introduce spurious # RPM dependencies, like /usr/bin/python3 # for the -python3 package find examples -type f -exec chmod 0644 \{\} \; %build %if ! %{supported_platform} echo "This RPM requires either Fedora >= %{min_fedora} or RHEL >= %{min_rhel}" exit 1 %endif %py3_build %install %py3_install %check %pytest %files -n python3-libvirt %doc ChangeLog AUTHORS README COPYING examples/ %{python3_sitearch}/libvirt.py* %{python3_sitearch}/libvirtaio.py* %{python3_sitearch}/libvirt_qemu.py* %{python3_sitearch}/libvirt_lxc.py* %{python3_sitearch}/__pycache__/libvirt.cpython-*.py* %{python3_sitearch}/__pycache__/libvirt_qemu.cpython-*.py* %{python3_sitearch}/__pycache__/libvirt_lxc.cpython-*.py* %{python3_sitearch}/__pycache__/libvirtaio.cpython-*.py* %{python3_sitearch}/libvirtmod* %{python3_sitearch}/*egg-info %changelog ./libvirt-python-9.10.0/libvirt-qemu-override-api.xml0000644000000000000000000000215714555064067021175 0ustar rootroot<?xml version="1.0"?> <api name='libvir-qemu-python'> <symbols> <function name='virDomainQemuMonitorCommand' file='python-qemu'> <info>Send an arbitrary monitor command through qemu monitor of domain</info> <return type='char *' info='the command output or None in case of error'/> <arg name='domain' type='virDomainPtr' info='pointer to domain object'/> <arg name='cmd' type='const char *' info='the command which will be passed to QEMU monitor'/> <arg name='flags' type='unsigned int' info='an OR'ed set of virDomainQemuMonitorCommandFlags'/> </function> <function name='virDomainQemuAgentCommand' file='python-qemu'> <info>Send a Guest Agent command to domain</info> <return type='char *' info='the command output'/> <arg name='domain' type='virDomainPtr' info='pointer to the domain'/> <arg name='cmd' type='const char *' info='guest agent command on domain'/> <arg name='timeout' type='int' info='timeout seconds'/> <arg name='flags' type='unsigned int' info='execution flags'/> </function> </symbols> </api> ./libvirt-python-9.10.0/libvirt-qemu-override.c0000644000000000000000000003335014555064067020047 0ustar rootroot/* * libvir.c: this modules implements the main part of the glue of the * libvir library and the Python interpreter. It provides the * entry points where an automatically generated stub is * unpractical * * Copyright (C) 2011-2019 Red Hat, Inc. * * Daniel Veillard <veillard@redhat.com> */ /* Horrible kludge to work around even more horrible name-space pollution via Python.h. That file includes /usr/include/python3.x/pyconfig*.h, which has over 180 autoconf-style HAVE_* definitions. Shame on them. */ #undef HAVE_PTHREAD_H #include <stdio.h> #include <Python.h> #include <libvirt/libvirt-qemu.h> #include <libvirt/virterror.h> #include "typewrappers.h" #include "libvirt-utils.h" #include "build/libvirt-qemu.h" #ifndef __CYGWIN__ # include <fcntl.h> #endif #ifndef __CYGWIN__ extern PyObject *PyInit_libvirtmod_qemu(void); #else extern PyObject *PyInit_cygvirtmod_qemu(void); #endif #if 0 # define DEBUG_ERROR 1 #endif #if DEBUG_ERROR # define DEBUG(fmt, ...) \ printf(fmt, __VA_ARGS__) #else # define DEBUG(fmt, ...) \ while (0) {printf(fmt, __VA_ARGS__);} #endif /******************************************* * Helper functions to avoid importing modules * for every callback *******************************************/ #if LIBVIR_CHECK_VERSION(1, 2, 3) static PyObject *libvirt_qemu_module; static PyObject *libvirt_qemu_dict; static PyObject * getLibvirtQemuModuleObject(void) { if (libvirt_qemu_module) return libvirt_qemu_module; // PyImport_ImportModule returns a new reference /* Bogus (char *) cast for RHEL-5 python API brokenness */ libvirt_qemu_module = PyImport_ImportModule((char *)"libvirt_qemu"); if (!libvirt_qemu_module) { DEBUG("%s Error importing libvirt_qemu module\n", __FUNCTION__); PyErr_Print(); return NULL; } return libvirt_qemu_module; } static PyObject * getLibvirtQemuDictObject(void) { if (libvirt_qemu_dict) return libvirt_qemu_dict; // PyModule_GetDict returns a borrowed reference libvirt_qemu_dict = PyModule_GetDict(getLibvirtQemuModuleObject()); if (!libvirt_qemu_dict) { DEBUG("%s Error importing libvirt_qemu dictionary\n", __FUNCTION__); PyErr_Print(); return NULL; } Py_INCREF(libvirt_qemu_dict); return libvirt_qemu_dict; } static PyObject * libvirt_qemu_lookupPythonFunc(const char *funcname) { PyObject *python_cb; /* Lookup the python callback */ python_cb = PyDict_GetItemString(getLibvirtQemuDictObject(), funcname); if (!python_cb) { DEBUG("%s: Error finding %s\n", __FUNCTION__, funcname); PyErr_Print(); PyErr_Clear(); return NULL; } if (!PyCallable_Check(python_cb)) { DEBUG("%s: %s is not callable\n", __FUNCTION__, funcname); return NULL; } return python_cb; } #endif /* LIBVIR_CHECK_VERSION(1, 2, 3) */ /************************************************************************ * * * Statistics * * * ************************************************************************/ static PyObject * libvirt_qemu_virDomainQemuMonitorCommand(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char *result = NULL; virDomainPtr domain; PyObject *pyobj_domain; unsigned int flags; char *cmd; int c_retval; if (!PyArg_ParseTuple(args, (char *)"OzI:virDomainQemuMonitorCommand", &pyobj_domain, &cmd, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (domain == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainQemuMonitorCommand(domain, cmd, &result, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; py_retval = libvirt_constcharPtrWrap(result); VIR_FREE(result); return py_retval; } #if LIBVIR_CHECK_VERSION(0, 10, 0) static PyObject * libvirt_qemu_virDomainQemuAgentCommand(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char *result = NULL; virDomainPtr domain; PyObject *pyobj_domain; int timeout; unsigned int flags; char *cmd; if (!PyArg_ParseTuple(args, (char *)"OziI:virDomainQemuAgentCommand", &pyobj_domain, &cmd, &timeout, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (domain == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; result = virDomainQemuAgentCommand(domain, cmd, timeout, flags); LIBVIRT_END_ALLOW_THREADS; if (!result) return VIR_PY_NONE; py_retval = libvirt_constcharPtrWrap(result); VIR_FREE(result); return py_retval; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 0) */ #if LIBVIR_CHECK_VERSION(1, 2, 3) static void libvirt_qemu_virConnectDomainQemuMonitorEventFreeFunc(void *opaque) { PyObject *pyobj_conn = (PyObject*)opaque; LIBVIRT_ENSURE_THREAD_STATE; Py_DECREF(pyobj_conn); LIBVIRT_RELEASE_THREAD_STATE; } static void libvirt_qemu_virConnectDomainQemuMonitorEventCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *event, long long seconds, unsigned int micros, const char *details, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; PyObject *pyobj_cb; LIBVIRT_ENSURE_THREAD_STATE; pyobj_cb = libvirt_qemu_lookupPythonFunc("_dispatchQemuMonitorEventCallback"); if (!pyobj_cb) goto cleanup; dictKey = libvirt_constcharPtrWrap("conn"); if (!dictKey) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallFunction(pyobj_cb, (char *)"OOsLIsO", pyobj_conn, pyobj_dom, event, seconds, micros, details, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); } LIBVIRT_RELEASE_THREAD_STATE; } static PyObject * libvirt_qemu_virConnectDomainQemuMonitorEventRegister(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; PyObject *pyobj_conn; PyObject *pyobj_dom; PyObject *pyobj_cbData; const char *event; virConnectPtr conn; int ret = 0; virConnectDomainQemuMonitorEventCallback cb = NULL; virDomainPtr dom; unsigned int flags; if (!PyArg_ParseTuple(args, (char *) "OOzOI:virConnectDomainQemuMonitorEventRegister", &pyobj_conn, &pyobj_dom, &event, &pyobj_cbData, &flags)) return NULL; DEBUG("libvirt_qemu_virConnectDomainQemuMonitorEventRegister(%p %p %s %p %x) called\n", pyobj_conn, pyobj_dom, NULLSTR(event), pyobj_cbData, flags); conn = PyvirConnect_Get(pyobj_conn); if (pyobj_dom == Py_None) dom = NULL; else dom = PyvirDomain_Get(pyobj_dom); cb = libvirt_qemu_virConnectDomainQemuMonitorEventCallback; Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectDomainQemuMonitorEventRegister(conn, dom, event, cb, pyobj_cbData, libvirt_qemu_virConnectDomainQemuMonitorEventFreeFunc, flags); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } py_retval = libvirt_intWrap(ret); return py_retval; } static PyObject * libvirt_qemu_virConnectDomainQemuMonitorEventDeregister(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; PyObject *pyobj_conn; int callbackID; virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "Oi:virConnectDomainQemuMonitorEventDeregister", &pyobj_conn, &callbackID)) return NULL; DEBUG("libvirt_qemu_virConnectDomainQemuMonitorEventDeregister(%p) called\n", pyobj_conn); conn = PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectDomainQemuMonitorEventDeregister(conn, callbackID); LIBVIRT_END_ALLOW_THREADS; py_retval = libvirt_intWrap(ret); return py_retval; } #endif /* LIBVIR_CHECK_VERSION(1, 2, 3) */ #if LIBVIR_CHECK_VERSION(8, 2, 0) static PyObject * libvirt_qemu_virDomainQemuMonitorCommandWithFiles(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_domain; const char *cmd; PyObject *pyobj_files; unsigned int flags; virDomainPtr domain; unsigned int ninfiles; int *infiles = NULL; unsigned int noutfiles = 0; int *outfiles = NULL; char *result = NULL; size_t i; PyObject *py_outfiles = NULL; PyObject *py_retval = NULL; int c_retval; if (!PyArg_ParseTuple(args, (char *) "Os|OI:virDomainQemuMonitorCommandWithFiles", &pyobj_domain, &cmd, &pyobj_files, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); ninfiles = PyList_Size(pyobj_files); if (VIR_ALLOC_N(infiles, ninfiles) < 0) return PyErr_NoMemory(); for (i = 0; i < ninfiles; i++) { PyObject *pyfd; int fd; pyfd = PyList_GetItem(pyobj_files, i); if (libvirt_intUnwrap(pyfd, &fd) < 0) goto cleanup; infiles[i] = fd; } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainQemuMonitorCommandWithFiles(domain, cmd, ninfiles, infiles, &noutfiles, &outfiles, &result, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } if (!(py_outfiles = PyList_New(0)) || !(py_retval = PyTuple_New(2))) { goto error; } for (i = 0; i < noutfiles; i++) { int fd = outfiles[i]; const char *mode = "r+b"; /* Since FD passing works only on UNIX-like systems, we can do this. */ #ifndef __CYGWIN__ int fflags; if ((fflags = fcntl(fd, F_GETFL)) < 0) goto error; switch (fflags & (O_ACCMODE | O_APPEND)) { case O_RDONLY: mode = "rb"; break; case O_WRONLY: mode = "wb"; break; case O_RDWR: mode = "r+b"; break; case O_WRONLY | O_APPEND: mode = "ab"; break; case O_RDWR | O_APPEND: mode = "a+b"; break; } #endif VIR_PY_LIST_APPEND_GOTO(py_outfiles, PyFile_FromFd(fd, NULL, mode, 0, NULL, NULL, NULL, 1), error); } VIR_PY_TUPLE_SET_GOTO(py_retval, 0, libvirt_charPtrWrap(result), error); VIR_PY_TUPLE_SET_GOTO(py_retval, 1, py_outfiles, error); /* stolen by py_retval */ py_outfiles = NULL; cleanup: Py_XDECREF(py_outfiles); VIR_FREE(result); VIR_FREE(outfiles); VIR_FREE(infiles); return py_retval; error: while (noutfiles > 0) { VIR_FORCE_CLOSE(outfiles[--noutfiles]); } Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(8, 2, 0) */ /************************************************************************ * * * The registration stuff * * * ************************************************************************/ static PyMethodDef libvirtQemuMethods[] = { #include "build/libvirt-qemu-export.c" {(char *) "virDomainQemuMonitorCommand", libvirt_qemu_virDomainQemuMonitorCommand, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 0) {(char *) "virDomainQemuAgentCommand", libvirt_qemu_virDomainQemuAgentCommand, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 0) */ #if LIBVIR_CHECK_VERSION(1, 2, 3) {(char *) "virConnectDomainQemuMonitorEventRegister", libvirt_qemu_virConnectDomainQemuMonitorEventRegister, METH_VARARGS, NULL}, {(char *) "virConnectDomainQemuMonitorEventDeregister", libvirt_qemu_virConnectDomainQemuMonitorEventDeregister, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 2, 3) */ #if LIBVIR_CHECK_VERSION(8, 2, 0) {(char *) "virDomainQemuMonitorCommandWithFiles", libvirt_qemu_virDomainQemuMonitorCommandWithFiles, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(8, 2, 0) */ {NULL, NULL, 0, NULL} }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, #ifndef __CYGWIN__ "libvirtmod_qemu", #else "cygvirtmod_qemu", #endif NULL, -1, libvirtQemuMethods, NULL, NULL, NULL, NULL }; PyObject * #ifndef __CYGWIN__ PyInit_libvirtmod_qemu #else PyInit_cygvirtmod_qemu #endif (void) { PyObject *module; if (virInitialize() < 0) return NULL; module = PyModule_Create(&moduledef); return module; } ./libvirt-python-9.10.0/libvirt-qemu-override.py0000644000000000000000000000657414555064067020265 0ustar rootrootfrom typing import Any, Callable, Dict, List, IO def _dispatchQemuMonitorEventCallback(conn: libvirt.virConnect, dom: libvirt.virDomain, event: str, seconds: int, micros: int, details: str, cbData: Dict[str, Any]) -> int: """Dispatches events to python user qemu monitor event callbacks """ cb = cbData["cb"] opaque = cbData["opaque"] cb(conn, libvirt.virDomain(conn, _obj=dom), event, seconds, micros, details, opaque) return 0 def qemuMonitorEventDeregister(conn: libvirt.virConnect, callbackID: int) -> None: """Removes a qemu monitor event callback. De-registering for a callback will disable delivery of this event type""" try: ret = libvirtmod_qemu.virConnectDomainQemuMonitorEventDeregister(conn._o, callbackID) if ret == -1: raise libvirt.libvirtError('virConnectDomainQemuMonitorEventDeregister() failed') del conn.qemuMonitorEventCallbackID[callbackID] # type: ignore except AttributeError: pass def qemuMonitorEventRegister(conn: libvirt.virConnect, dom: libvirt.virDomain, event: str, cb: Callable[[libvirt.virConnect, libvirt.virDomain, str, int, int, str, libvirt._T], None], opaque: libvirt._T, flags: int = 0) -> int: """Adds a qemu monitor event callback. Registering for a monitor callback will enable delivery of the events""" if not hasattr(conn, 'qemuMonitorEventCallbackID'): conn.qemuMonitorEventCallbackID = {} # type: ignore cbData = {"cb": cb, "conn": conn, "opaque": opaque} if dom is None: ret = libvirtmod_qemu.virConnectDomainQemuMonitorEventRegister(conn._o, None, event, cbData, flags) else: ret = libvirtmod_qemu.virConnectDomainQemuMonitorEventRegister(conn._o, dom._o, event, cbData, flags) if ret == -1: raise libvirt.libvirtError('virConnectDomainQemuMonitorEventRegister() failed') conn.qemuMonitorEventCallbackID[ret] = opaque # type: ignore return ret def qemuMonitorCommandWithFiles(domain: libvirt.virDomain, cmd: str, files: List[int] = [], flags: int = 0) -> (str, List[IO]): """This API is QEMU specific, so it will only work with hypervisor connections to the QEMU driver with local connections using the unix socket. Send an arbitrary monitor command @cmd with file descriptors @files to domain through the QEMU monitor and optionally return a list of files in the returned tuple. There are several requirements to safely and successfully use this API: - A @cmd that queries state without making any modifications is safe - A @cmd that alters state that is also tracked by libvirt is unsafe, and may cause libvirtd to crash - A @cmd that alters state not tracked by the current version of libvirt is possible as a means to test new qemu features before they have support in libvirt, but no guarantees are made to safety If VIR_DOMAIN_QEMU_MONITOR_COMMAND_HMP is set, the command is considered to be a human monitor command and libvirt will automatically convert it into QMP if needed. In that case the @result will also be converted back from QMP. Returns a tuple consisting of the string output from @cmd and a list of files respectively.""" ret = libvirtmod_qemu.virDomainQemuMonitorCommandWithFiles(domain._o, cmd, files, flags) if ret is None: raise libvirt.libvirtError('virDomainQemuMonitorCommandWithFiles() failed') return ret ./libvirt-python-9.10.0/libvirt-utils.c0000644000000000000000000003751614555064067016433 0ustar rootroot/* * libvirt-utils.c: misc helper APIs for python binding * * Copyright (C) 2013-2019 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. * */ #include <string.h> #include <Python.h> /* Ugly python defines that, which is also defined in errno.h */ #undef _POSIC_C_SOURCE /* We want to see *_LAST enums. */ #define VIR_ENUM_SENTINELS #include <errno.h> #include <stddef.h> #include <stdlib.h> #include <unistd.h> #include <libvirt/libvirt.h> #include "libvirt-utils.h" #include "typewrappers.h" /** * virAlloc: * @ptrptr: pointer to pointer for address of allocated memory * @size: number of bytes to allocate * * Allocate 'size' bytes of memory. Return the address of the * allocated memory in 'ptrptr'. The newly allocated memory is * filled with zeros. * * Returns -1 on failure to allocate, zero on success */ int virAlloc(void *ptrptr, size_t size) { *(void **)ptrptr = calloc(1, size); if (*(void **)ptrptr == NULL) { return -1; } return 0; } /** * virAllocN: * @ptrptr: pointer to pointer for address of allocated memory * @size: number of bytes to allocate * @count: number of elements to allocate * * Allocate an array of memory 'count' elements long, * each with 'size' bytes. Return the address of the * allocated memory in 'ptrptr'. The newly allocated * memory is filled with zeros. * * Returns -1 on failure to allocate, zero on success */ int virAllocN(void *ptrptr, size_t size, size_t count) { *(void**)ptrptr = calloc(count, size); if (*(void**)ptrptr == NULL) { return -1; } return 0; } /** * virReallocN: * @ptrptr: pointer to pointer for address of allocated memory * @size: number of bytes to allocate * @count: number of elements in array * * Resize the block of memory in 'ptrptr' to be an array of * 'count' elements, each 'size' bytes in length. Update 'ptrptr' * with the address of the newly allocated memory. On failure, * 'ptrptr' is not changed and still points to the original memory * block. Any newly allocated memory in 'ptrptr' is uninitialized. * * Returns -1 on failure to allocate, zero on success */ int virReallocN(void *ptrptr, size_t size, size_t count) { void *tmp; if (xalloc_oversized(count, size)) { errno = ENOMEM; return -1; } tmp = realloc(*(void**)ptrptr, size * count); if (!tmp && ((size * count) != 0)) { return -1; } *(void**)ptrptr = tmp; return 0; } /** * virFree: * @ptrptr: pointer to pointer for address of memory to be freed * * Release the chunk of memory in the pointer pointed to by * the 'ptrptr' variable. After release, 'ptrptr' will be * updated to point to NULL. */ void virFree(void *ptrptr) { int save_errno = errno; free(*(void**)ptrptr); *(void**)ptrptr = NULL; errno = save_errno; } int virFileClose(int *fdptr) { int saved_errno = 0; int rc = 0; saved_errno = errno; if (*fdptr < 0) return 0; rc = close(*fdptr); *fdptr = -1; errno = saved_errno; return rc; } #if ! LIBVIR_CHECK_VERSION(1, 0, 2) /** * virTypedParamsClear: * @params: the array of the typed parameters * @nparams: number of parameters in the @params array * * Frees all memory used by string parameters. The memory occupied by @params * is not free; use virTypedParamsFree if you want it to be freed too. * * Returns nothing. */ void virTypedParamsClear(virTypedParameterPtr params, int nparams) { size_t i; if (!params) return; for (i = 0; i < nparams; i++) { if (params[i].type == VIR_TYPED_PARAM_STRING) VIR_FREE(params[i].value.s); } } /** * virTypedParamsFree: * @params: the array of the typed parameters * @nparams: number of parameters in the @params array * * Frees all memory used by string parameters and the memory occuiped by * @params. * * Returns nothing. */ void virTypedParamsFree(virTypedParameterPtr params, int nparams) { virTypedParamsClear(params, nparams); VIR_FREE(params); } #endif /* ! LIBVIR_CHECK_VERSION(1, 0, 2) */ /* Helper function to convert a virTypedParameter output array into a * Python dictionary for return to the user. Return NULL on failure, * after raising a python exception. */ PyObject * getPyVirTypedParameter(const virTypedParameter *params, int nparams) { PyObject *key, *val, *info; ssize_t i; if ((info = PyDict_New()) == NULL) return NULL; for (i = 0; i < nparams; i++) { switch (params[i].type) { case VIR_TYPED_PARAM_INT: val = libvirt_intWrap(params[i].value.i); break; case VIR_TYPED_PARAM_UINT: val = libvirt_intWrap(params[i].value.ui); break; case VIR_TYPED_PARAM_LLONG: val = libvirt_longlongWrap(params[i].value.l); break; case VIR_TYPED_PARAM_ULLONG: val = libvirt_ulonglongWrap(params[i].value.ul); break; case VIR_TYPED_PARAM_DOUBLE: val = PyFloat_FromDouble(params[i].value.d); break; case VIR_TYPED_PARAM_BOOLEAN: val = PyBool_FromLong(params[i].value.b); break; case VIR_TYPED_PARAM_STRING: val = libvirt_constcharPtrWrap(params[i].value.s); break; default: /* Possible if a newer server has a bug and sent stuff we * don't recognize. */ PyErr_Format(PyExc_LookupError, "Type value \"%d\" not recognized", params[i].type); val = NULL; break; } key = libvirt_constcharPtrWrap(params[i].field); VIR_PY_DICT_SET_GOTO(info, key, val, cleanup); } return info; cleanup: Py_DECREF(info); return NULL; } /* Allocate a new typed parameter array with the same contents and * length as info, and using the array params of length nparams as * hints on what types to use when creating the new array. The caller * must clear the array before freeing it. Return NULL on failure, * after raising a python exception. */ virTypedParameterPtr setPyVirTypedParameter(PyObject *info, const virTypedParameter *params, int nparams) { PyObject *key, *value; Py_ssize_t pos = 0; virTypedParameterPtr temp = NULL, ret = NULL; Py_ssize_t size; ssize_t i; if ((size = PyDict_Size(info)) < 0) return NULL; /* Libvirt APIs use NULL array and 0 size as a special case; * setting should have at least one parameter. */ if (size == 0) { PyErr_Format(PyExc_LookupError, "Dictionary must not be empty"); return NULL; } if (VIR_ALLOC_N(ret, size) < 0) { PyErr_NoMemory(); return NULL; } temp = &ret[0]; while (PyDict_Next(info, &pos, &key, &value)) { char *keystr = NULL; if (libvirt_charPtrUnwrap(key, &keystr) < 0) goto cleanup; for (i = 0; i < nparams; i++) { if (STREQ(params[i].field, keystr)) break; } if (i == nparams) { PyErr_Format(PyExc_LookupError, "Attribute name \"%s\" could not be recognized", keystr); VIR_FREE(keystr); goto cleanup; } strncpy(temp->field, keystr, VIR_TYPED_PARAM_FIELD_LENGTH - 1); temp->type = params[i].type; VIR_FREE(keystr); switch (params[i].type) { case VIR_TYPED_PARAM_INT: if (libvirt_intUnwrap(value, &temp->value.i) < 0) goto cleanup; break; case VIR_TYPED_PARAM_UINT: if (libvirt_uintUnwrap(value, &temp->value.ui) < 0) goto cleanup; break; case VIR_TYPED_PARAM_LLONG: if (libvirt_longlongUnwrap(value, &temp->value.l) < 0) goto cleanup; break; case VIR_TYPED_PARAM_ULLONG: if (libvirt_ulonglongUnwrap(value, &temp->value.ul) < 0) goto cleanup; break; case VIR_TYPED_PARAM_DOUBLE: if (libvirt_doubleUnwrap(value, &temp->value.d) < 0) goto cleanup; break; case VIR_TYPED_PARAM_BOOLEAN: { bool b; if (libvirt_boolUnwrap(value, &b) < 0) goto cleanup; temp->value.b = b; break; } case VIR_TYPED_PARAM_STRING: { char *string_val; if (libvirt_charPtrUnwrap(value, &string_val) < 0) goto cleanup; temp->value.s = string_val; break; } default: /* Possible if a newer server has a bug and sent stuff we * don't recognize. */ PyErr_Format(PyExc_LookupError, "Type value \"%d\" not recognized", params[i].type); goto cleanup; } temp++; } return ret; cleanup: virTypedParamsFree(ret, size); return NULL; } /* While these appeared in libvirt in 1.0.2, we only * need them in the python from 1.1.0 onwards */ #if LIBVIR_CHECK_VERSION(1, 1, 0) int virPyDictToTypedParamOne(virTypedParameterPtr *params, int *n, int *max, virPyTypedParamsHintPtr hints, int nhints, const char *keystr, PyObject *value) { int rv = -1, type = -1; ssize_t i; for (i = 0; i < nhints; i++) { if (STREQ(hints[i].name, keystr)) { type = hints[i].type; break; } } if (type == -1) { if (libvirt_PyString_Check(value)) { type = VIR_TYPED_PARAM_STRING; } else if (PyBool_Check(value)) { type = VIR_TYPED_PARAM_BOOLEAN; } else if (PyLong_Check(value)) { unsigned long long ull = PyLong_AsUnsignedLongLong(value); if (ull == (unsigned long long) -1 && PyErr_Occurred()) { type = VIR_TYPED_PARAM_LLONG; PyErr_Clear(); } else { type = VIR_TYPED_PARAM_ULLONG; } } else if (PyFloat_Check(value)) { type = VIR_TYPED_PARAM_DOUBLE; } } if (type == -1) { PyErr_Format(PyExc_TypeError, "Unknown type of \"%s\" field", keystr); goto cleanup; } switch ((virTypedParameterType) type) { case VIR_TYPED_PARAM_INT: { int val; if (libvirt_intUnwrap(value, &val) < 0 || virTypedParamsAddInt(params, n, max, keystr, val) < 0) goto cleanup; break; } case VIR_TYPED_PARAM_UINT: { unsigned int val; if (libvirt_uintUnwrap(value, &val) < 0 || virTypedParamsAddUInt(params, n, max, keystr, val) < 0) goto cleanup; break; } case VIR_TYPED_PARAM_LLONG: { long long val; if (libvirt_longlongUnwrap(value, &val) < 0 || virTypedParamsAddLLong(params, n, max, keystr, val) < 0) goto cleanup; break; } case VIR_TYPED_PARAM_ULLONG: { unsigned long long val; if (libvirt_ulonglongUnwrap(value, &val) < 0 || virTypedParamsAddULLong(params, n, max, keystr, val) < 0) goto cleanup; break; } case VIR_TYPED_PARAM_DOUBLE: { double val; if (libvirt_doubleUnwrap(value, &val) < 0 || virTypedParamsAddDouble(params, n, max, keystr, val) < 0) goto cleanup; break; } case VIR_TYPED_PARAM_BOOLEAN: { bool val; if (libvirt_boolUnwrap(value, &val) < 0 || virTypedParamsAddBoolean(params, n, max, keystr, val) < 0) goto cleanup; break; } case VIR_TYPED_PARAM_STRING: { char *val;; if (libvirt_charPtrUnwrap(value, &val) < 0 || virTypedParamsAddString(params, n, max, keystr, val) < 0) { VIR_FREE(val); goto cleanup; } VIR_FREE(val); break; } case VIR_TYPED_PARAM_LAST: break; /* unreachable */ } rv = 0; cleanup: return rv; } /* Automatically convert dict into type parameters based on types reported * by python. All integer types are converted into LLONG (in case of a negative * value) or ULLONG (in case of a positive value). If you need different * handling, use @hints to explicitly specify what types should be used for * specific parameters. */ int virPyDictToTypedParams(PyObject *dict, virTypedParameterPtr *ret_params, int *ret_nparams, virPyTypedParamsHintPtr hints, int nhints) { PyObject *key; PyObject *value; Py_ssize_t pos = 0; virTypedParameterPtr params = NULL; int n = 0; int max = 0; int ret = -1; char *keystr = NULL; *ret_params = NULL; *ret_nparams = 0; if (PyDict_Size(dict) < 0) return -1; while (PyDict_Next(dict, &pos, &key, &value)) { if (libvirt_charPtrUnwrap(key, &keystr) < 0) goto cleanup; if (PyList_Check(value) || PyTuple_Check(value)) { Py_ssize_t i, size = PySequence_Size(value); for (i = 0; i < size; i++) { PyObject *v = PySequence_GetItem(value, i); if (virPyDictToTypedParamOne(¶ms, &n, &max, hints, nhints, keystr, v) < 0) goto cleanup; } } else if (virPyDictToTypedParamOne(¶ms, &n, &max, hints, nhints, keystr, value) < 0) goto cleanup; VIR_FREE(keystr); } *ret_params = params; *ret_nparams = n; params = NULL; ret = 0; cleanup: VIR_FREE(keystr); virTypedParamsFree(params, n); return ret; } #endif /* LIBVIR_CHECK_VERSION(1, 1, 0) */ /* virPyCpumapConvert * @cpunum: the number of physical cpus of the host. * @pycpumap: source cpu map, python tuple of bools. * @cpumapptr: destination cpu map. * @cpumaplen: destination cpu map length. * * Helper function to convert a pycpumap to char*. * * Returns 0 on success, -1 on failure with error set. */ int virPyCpumapConvert(int cpunum, PyObject *pycpumap, unsigned char **cpumapptr, int *cpumaplen) { int tuple_size; ssize_t i; *cpumapptr = NULL; if (!PyTuple_Check(pycpumap)) { PyErr_SetString(PyExc_TypeError, "Unexpected type, tuple is required"); return -1; } *cpumaplen = VIR_CPU_MAPLEN(cpunum); if ((tuple_size = PyTuple_Size(pycpumap)) == -1) return -1; if (VIR_ALLOC_N(*cpumapptr, *cpumaplen) < 0) { PyErr_NoMemory(); return -1; } for (i = 0; i < cpunum && i < tuple_size; i++) { PyObject *flag = PyTuple_GetItem(pycpumap, i); bool b; if (!flag || libvirt_boolUnwrap(flag, &b) < 0) { VIR_FREE(*cpumapptr); return -1; } if (b) VIR_USE_CPU(*cpumapptr, i); } return 0; } ./libvirt-python-9.10.0/libvirt-utils.h0000644000000000000000000003173214555064067016432 0ustar rootroot/* * libvirt-utils.h: misc helper APIs for python binding * * Copyright (C) 2013 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see * <http://www.gnu.org/licenses/>. * */ #ifndef __LIBVIRT_UTILS_H__ # define __LIBVIRT_UTILS_H__ # include <Python.h> # include <libvirt/libvirt.h> # define STREQ(a,b) (strcmp(a,b) == 0) # ifndef MIN # define MIN(a,b) (((a) < (b)) ? (a) : (b)) # endif /** * libvirt.h provides this as of version 1.2.0, but we want to be able * to support older versions of libvirt so copy and paste the macro from * libvirt.h */ # ifndef LIBVIR_CHECK_VERSION # define LIBVIR_CHECK_VERSION(major, minor, micro) \ ((major) * 1000000 + (minor) * 1000 + (micro) <= LIBVIR_VERSION_NUMBER) # endif /* Return 1 if an array of N objects, each of size S, cannot exist due to size arithmetic overflow. S must be positive and N must be nonnegative. This is a macro, not a function, so that it works correctly even when SIZE_MAX < N. By gnulib convention, SIZE_MAX represents overflow in size calculations, so the conservative dividend to use here is SIZE_MAX - 1, since SIZE_MAX might represent an overflowed value. However, malloc (SIZE_MAX) fails on all known hosts where sizeof (ptrdiff_t) <= sizeof (size_t), so do not bother to test for exactly-SIZE_MAX allocations on such hosts; this avoids a test and branch when S is known to be 1. */ # define xalloc_oversized(n, s) \ ((size_t) (sizeof (ptrdiff_t) <= sizeof (size_t) ? -1 : -2) / (s) < (n)) /* The __attribute__((__warn_unused_result__)) feature is available in gcc versions 3.4 and newer, while the typeof feature has been available since 2.7 at least. */ # if 3 < __GNUC__ + (4 <= __GNUC_MINOR__) # define ignore_value(x) \ (__extension__ ({ __typeof__ (x) __x = (x); (void) __x; })) # else # define ignore_value(x) ((void) (x)) # endif # ifdef __GNUC__ # ifndef __GNUC_PREREQ # if defined __GNUC__ && defined __GNUC_MINOR__ # define __GNUC_PREREQ(maj, min) \ ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min)) # else # define __GNUC_PREREQ(maj, min) 0 # endif # endif /* __GNUC_PREREQ */ /** * ATTRIBUTE_UNUSED: * * Macro to flag consciously unused parameters to functions */ # ifndef ATTRIBUTE_UNUSED # define ATTRIBUTE_UNUSED __attribute__((__unused__)) # endif /* gcc's handling of attribute nonnull is less than stellar - it does * NOT improve diagnostics, and merely allows gcc to optimize away * null code checks even when the caller manages to pass null in spite * of the attribute, leading to weird crashes. Coverity, on the other * hand, knows how to do better static analysis based on knowing * whether a parameter is nonnull. Make this attribute conditional * based on whether we are compiling for real or for analysis, while * still requiring correct gcc syntax when it is turned off. See also * http://gcc.gnu.org/bugzilla/show_bug.cgi?id=17308 */ # ifndef ATTRIBUTE_NONNULL # if __GNUC_PREREQ (3, 3) # if STATIC_ANALYSIS # define ATTRIBUTE_NONNULL(m) __attribute__((__nonnull__(m))) # else # define ATTRIBUTE_NONNULL(m) __attribute__(()) # endif # else # define ATTRIBUTE_NONNULL(m) # endif # endif # ifndef ATTRIBUTE_RETURN_CHECK # if __GNUC_PREREQ (3, 4) # define ATTRIBUTE_RETURN_CHECK __attribute__((__warn_unused_result__)) # else # define ATTRIBUTE_RETURN_CHECK # endif # endif # else # ifndef ATTRIBUTE_UNUSED # define ATTRIBUTE_UNUSED # endif # ifndef ATTRIBUTE_NONNULL # define ATTRIBUTE_NONNULL(m) # endif # ifndef ATTRIBUTE_RETURN_CHECK # define ATTRIBUTE_RETURN_CHECK # endif # endif /* __GNUC__ */ /* Don't call these directly - use the macros below */ int virAlloc(void *ptrptr, size_t size) ATTRIBUTE_RETURN_CHECK ATTRIBUTE_NONNULL(1); int virAllocN(void *ptrptr, size_t size, size_t count) ATTRIBUTE_RETURN_CHECK ATTRIBUTE_NONNULL(1); int virReallocN(void *ptrptr, size_t size, size_t count) ATTRIBUTE_RETURN_CHECK ATTRIBUTE_NONNULL(1); void virFree(void *ptrptr) ATTRIBUTE_NONNULL(1); # define libvirt_PyString_Check PyUnicode_Check #define VIR_N_ELEMENTS(array) (sizeof(array) / sizeof(*(array))) /* The two-statement sequence "Py_INCREF(Py_None); return Py_None;" is so common that we encapsulate it here. Now, each use is simply return VIR_PY_NONE; */ #define VIR_PY_NONE (Py_INCREF (Py_None), Py_None) #define VIR_PY_INT_FAIL (libvirt_intWrap(-1)) #define VIR_PY_INT_SUCCESS (libvirt_intWrap(0)) /** * VIR_PY_TUPLE_SET_GOTO: * @TUPLE: a pointer to a tuple object * @INDEX: a position in the tuple object * @VALUE: a pointer to a python object to add into the tuple * @GOTO: a label to jump to in case of error * * Add the new value to specific place into the python tuple object. In case of * error it will jump to provided label and DECREF the value to not leak memory. */ #define VIR_PY_TUPLE_SET_GOTO(TUPLE, INDEX, VALUE, GOTO) \ do { \ PyObject *tmpVal = VALUE; \ if (!tmpVal || PyTuple_SetItem(TUPLE, INDEX, tmpVal) < 0) \ goto GOTO; \ } while (0) /** * VIR_PY_LIST_SET_GOTO: * @LIST: a pointer to a list object * @INDEX: a position in the list object * @VALUE: a pointer to a python object to add into the list * @GOTO: a label to jump to in case of error * * Add the new value to specific place into the python list object. In case of * error it will jump to provided label and DECREF the value to not leak memory. */ #define VIR_PY_LIST_SET_GOTO(LIST, INDEX, VALUE, GOTO) \ do { \ PyObject *tmpVal = VALUE; \ if (!tmpVal || PyList_SetItem(LIST, INDEX, tmpVal) < 0) \ goto GOTO; \ } while (0) /** * VIR_PY_LIST_APPEND_GOTO: * @LIST: a pointer to a python list object * @VALUE: a pointer to a python object to add into the list * @GOTO: a label to jump to in case of error * * Append the new value into the end of the python list object. In case of * error it will jump to provided label and DECREF the value to not leak memory. */ #define VIR_PY_LIST_APPEND_GOTO(LIST, VALUE, GOTO) \ do { \ PyObject *tmpVal = VALUE; \ if (!tmpVal || PyList_Append(LIST, tmpVal) < 0) { \ Py_XDECREF(tmpVal); \ goto GOTO; \ } \ Py_DECREF(tmpVal); \ } while (0) /** * VIR_PY_DICT_SET_GOTO: * @DICT: a pointer to a python dict object * @KEY: a pointer to a python string object which will be used as a key * @VALUE: a pointer to a python object to add into the dict under provided key * @GOTO: a label to jump to in case of error * * Add a new pair of key:value into the python dict object. In case of error it * will jump to provided label. It will DECREF both key and value in case of * success or error. */ #define VIR_PY_DICT_SET_GOTO(DICT, KEY, VALUE, GOTO) \ do { \ PyObject *tmpKey = KEY; \ PyObject *tmpVal = VALUE; \ if (!tmpKey || !tmpVal || \ PyDict_SetItem(DICT, tmpKey, tmpVal) < 0) { \ Py_XDECREF(tmpKey); \ Py_XDECREF(tmpVal); \ goto GOTO; \ } \ Py_DECREF(tmpKey); \ Py_DECREF(tmpVal); \ } while (0) /** * VIR_ALLOC: * @ptr: pointer to hold address of allocated memory * * Allocate sizeof(*ptr) bytes of memory and store * the address of allocated memory in 'ptr'. Fill the * newly allocated memory with zeros. * * This macro is safe to use on arguments with side effects. * * Returns -1 on failure (with OOM error reported), 0 on success */ # define VIR_ALLOC(ptr) virAlloc(&(ptr), sizeof(*(ptr))) /** * VIR_ALLOC_N: * @ptr: pointer to hold address of allocated memory * @count: number of elements to allocate * * Allocate an array of 'count' elements, each sizeof(*ptr) * bytes long and store the address of allocated memory in * 'ptr'. Fill the newly allocated memory with zeros. * * This macro is safe to use on arguments with side effects. * * Returns -1 on failure (with OOM error reported), 0 on success */ # define VIR_ALLOC_N(ptr, count) virAllocN(&(ptr), sizeof(*(ptr)), (count)) /** * VIR_REALLOC_N: * @ptr: pointer to hold address of allocated memory * @count: number of elements to allocate * * Re-allocate an array of 'count' elements, each sizeof(*ptr) * bytes long and store the address of allocated memory in * 'ptr'. If 'ptr' grew, the added memory is uninitialized. * * This macro is safe to use on arguments with side effects. * * Returns -1 on failure (with OOM error reported), 0 on success */ # define VIR_REALLOC_N(ptr, count) virReallocN(&(ptr), sizeof(*(ptr)), (count)) /** * VIR_FREE: * @ptr: pointer holding address to be freed * * Free the memory stored in 'ptr' and update to point * to NULL. * * This macro is safe to use on arguments with side effects. */ # if !STATIC_ANALYSIS /* The ternary ensures that ptr is a pointer and not an integer type, * while evaluating ptr only once. This gives us extra compiler * safety when compiling under gcc. For now, we intentionally cast * away const, since a number of callers safely pass const char *. */ # define VIR_FREE(ptr) virFree((void *) (1 ? (const void *) &(ptr) : (ptr))) # else /* The Coverity static analyzer considers the else path of the "?:" and * flags the VIR_FREE() of the address of the address of memory as a * RESOURCE_LEAK resulting in numerous false positives (eg, VIR_FREE(&ptr)) */ # define VIR_FREE(ptr) virFree((void *) &(ptr)) # endif /* Don't call this directly - use the macro below */ int virFileClose(int *fdptr) ATTRIBUTE_RETURN_CHECK; # define VIR_FORCE_CLOSE(FD) \ ignore_value(virFileClose(&(FD))) # if ! LIBVIR_CHECK_VERSION(1, 0, 2) void virTypedParamsClear(virTypedParameterPtr params, int nparams); void virTypedParamsFree(virTypedParameterPtr params, int nparams); # endif /* ! LIBVIR_CHECK_VERSION(1, 0, 2) */ PyObject * getPyVirTypedParameter(const virTypedParameter *params, int nparams); virTypedParameterPtr setPyVirTypedParameter(PyObject *info, const virTypedParameter *params, int nparams) ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2); # if LIBVIR_CHECK_VERSION(1, 1, 0) typedef struct { const char *name; int type; } virPyTypedParamsHint; typedef virPyTypedParamsHint *virPyTypedParamsHintPtr; int virPyDictToTypedPramaOne(virTypedParameterPtr *params, int *n, int *max, virPyTypedParamsHintPtr hints, int nhints, const char *keystr, PyObject *value); int virPyDictToTypedParams(PyObject *dict, virTypedParameterPtr *ret_params, int *ret_nparams, virPyTypedParamsHintPtr hints, int nhints) ATTRIBUTE_NONNULL(1) ATTRIBUTE_NONNULL(2) ATTRIBUTE_NONNULL(3); # endif /* LIBVIR_CHECK_VERSION(1, 1, 0) */ int virPyCpumapConvert(int cpunum, PyObject *pycpumap, unsigned char **cpumapptr, int *cpumaplen); #endif /* __LIBVIRT_UTILS_H__ */ ./libvirt-python-9.10.0/libvirtaio.py0000644000000000000000000004107514555064067016167 0ustar rootroot# # libvirtaio -- asyncio adapter for libvirt # Copyright (C) 2017 Wojtek Porczyk <woju@invisiblethingslab.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, see # <http://www.gnu.org/licenses/>. # '''Libvirt event loop implementation using asyncio Register the implementation of default loop: import asyncio import libvirtaio async def myapp(): libvirtaio.virEventRegisterAsyncIOImpl() conn = libvirt.open("test:///default") For compatibility with Python < 3.7: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(myapp()) asyncio.set_event_loop(None) loop.close() If Python >= 3.7 can be required then asyncio.run(myapp()) .. seealso:: https://libvirt.org/html/libvirt-libvirt-event.html ''' import asyncio import itertools import logging import warnings import libvirt from typing import Any, Callable, Dict, Generator, Optional, TypeVar # noqa F401 _T = TypeVar('_T') __author__ = 'Wojtek Porczyk <woju@invisiblethingslab.com>' __license__ = 'LGPL-2.1+' __all__ = [ 'getCurrentImpl', 'virEventAsyncIOImpl', 'virEventRegisterAsyncIOImpl', ] class Callback(object): '''Base class for holding callback :param virEventAsyncIOImpl impl: the implementation in which we run :param cb: the callback itself :param opaque: the opaque tuple passed by libvirt ''' # pylint: disable=too-few-public-methods _iden_counter = itertools.count() def __init__(self, impl: "virEventAsyncIOImpl", cb: Callable[[int, _T], None], opaque: _T, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) # type: ignore self.iden = next(self._iden_counter) self.impl = impl self.cb = cb self.opaque = opaque def __repr__(self) -> str: return '<{} iden={}>'.format(self.__class__.__name__, self.iden) def close(self) -> None: '''Schedule *ff* callback''' self.impl.log.debug('callback %d close(), scheduling ff', self.iden) self.impl.schedule_ff_callback(self.iden, self.opaque) # # file descriptors # class Descriptor(object): '''Manager of one file descriptor :param virEventAsyncIOImpl impl: the implementation in which we run :param int fd: the file descriptor ''' def __init__(self, impl: "virEventAsyncIOImpl", fd: int) -> None: self.impl = impl self.fd = fd self.callbacks = {} # type: Dict def _handle(self, event: int) -> None: '''Dispatch the event to the descriptors :param int event: The event (from libvirt's constants) being dispatched ''' for callback in list(self.callbacks.values()): if callback.event is not None and callback.event & event: callback.cb(callback.iden, self.fd, event, callback.opaque) def update(self) -> None: '''Register or unregister callbacks at event loop This should be called after change of any ``.event`` in callbacks. ''' # It seems like loop.add_{reader,writer} can be run multiple times # and will still register the callback only once. Likewise, # remove_{reader,writer} may be run even if the reader/writer # is not registered (and will just return False). # For the edge case of empty callbacks, any() returns False. if any(callback.event & ~( libvirt.VIR_EVENT_HANDLE_READABLE | libvirt.VIR_EVENT_HANDLE_WRITABLE) for callback in self.callbacks.values()): warnings.warn( 'The only event supported are VIR_EVENT_HANDLE_READABLE ' 'and VIR_EVENT_HANDLE_WRITABLE', UserWarning) if any(callback.event & libvirt.VIR_EVENT_HANDLE_READABLE for callback in self.callbacks.values()): self.impl.loop.add_reader( self.fd, self._handle, libvirt.VIR_EVENT_HANDLE_READABLE) else: self.impl.loop.remove_reader(self.fd) if any(callback.event & libvirt.VIR_EVENT_HANDLE_WRITABLE for callback in self.callbacks.values()): self.impl.loop.add_writer( self.fd, self._handle, libvirt.VIR_EVENT_HANDLE_WRITABLE) else: self.impl.loop.remove_writer(self.fd) def add_handle(self, callback: "FDCallback") -> None: '''Add a callback to the descriptor :param FDCallback callback: the callback to add :rtype: None After adding the callback, it is immediately watched. ''' self.callbacks[callback.iden] = callback self.update() def remove_handle(self, iden: int) -> None: '''Remove a callback from the descriptor :param int iden: the identifier of the callback :returns: the callback :rtype: FDCallback After removing the callback, the descriptor may be unwatched, if there are no more handles for it. ''' callback = self.callbacks.pop(iden) self.update() return callback class DescriptorDict(dict): '''Descriptors collection This is used internally by virEventAsyncIOImpl to hold descriptors. ''' def __init__(self, impl: "virEventAsyncIOImpl") -> None: super().__init__() self.impl = impl def __missing__(self, fd: int) -> Descriptor: descriptor = Descriptor(self.impl, fd) self[fd] = descriptor return descriptor class FDCallback(Callback): '''Callback for file descriptor (watcher) :param Descriptor descriptor: the descriptor manager :param int event: bitset of events on which to fire the callback ''' # pylint: disable=too-few-public-methods def __init__(self, *args: Any, descriptor: Descriptor, event: int, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.descriptor = descriptor self.event = event def __repr__(self) -> str: return '<{} iden={} fd={} event={}>'.format( self.__class__.__name__, self.iden, self.descriptor.fd, self.event) def update(self, event: int) -> None: '''Update the callback and fix descriptor's watchers''' self.event = event self.descriptor.update() # # timeouts # class TimeoutCallback(Callback): '''Callback for timer''' def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) self.timeout = -1 self._task = None def __repr__(self) -> str: return '<{} iden={} timeout={}>'.format( self.__class__.__name__, self.iden, self.timeout) async def _timer(self) -> Generator[Any, None, None]: '''An actual timer running on the event loop. This is a coroutine. ''' while True: try: if self.timeout > 0: timeout = self.timeout * 1e-3 self.impl.log.debug('sleeping %r', timeout) await asyncio.sleep(timeout) else: # scheduling timeout for next loop iteration await asyncio.sleep(0) except asyncio.CancelledError: self.impl.log.debug('timer %d cancelled', self.iden) break self.cb(self.iden, self.opaque) self.impl.log.debug('timer %r callback ended', self.iden) def update(self, timeout: int) -> None: '''Start or the timer, possibly updating timeout''' self.timeout = timeout if self.timeout >= 0 and self._task is None: self.impl.log.debug('timer %r start', self.iden) self._task = asyncio.ensure_future(self._timer(), loop=self.impl.loop) elif self.timeout < 0 and self._task is not None: self.impl.log.debug('timer %r stop', self.iden) self._task.cancel() # pylint: disable=no-member self._task = None def close(self) -> None: '''Stop the timer and call ff callback''' self.update(timeout=-1) super(TimeoutCallback, self).close() # # main implementation # class virEventAsyncIOImpl(object): '''Libvirt event adapter to asyncio. :param loop: asyncio's event loop If *loop* is not specified, the current (or default) event loop is used. ''' def __init__(self, loop: asyncio.AbstractEventLoop = None) -> None: self.loop = loop or asyncio.get_event_loop() self.callbacks = {} # type: Dict[int, Callback] self.descriptors = DescriptorDict(self) self.log = logging.getLogger(self.__class__.__name__) self._pending = 0 # Transient asyncio.Event instance dynamically created # and destroyed by drain() # NOTE invariant: _finished.is_set() iff _pending == 0 self._finished = None def __repr__(self) -> str: return '<{} callbacks={} descriptors={}>'.format( type(self).__name__, self.callbacks, self.descriptors) def _pending_inc(self) -> None: '''Increase the count of pending affairs. Do not use directly.''' self._pending += 1 if self._finished is not None: self._finished.clear() def _pending_dec(self) -> None: '''Decrease the count of pending affairs. Do not use directly.''' assert self._pending > 0 self._pending -= 1 if self._pending == 0 and self._finished is not None: self._finished.set() def register(self) -> "virEventAsyncIOImpl": '''Register this instance as event loop implementation''' # pylint: disable=bad-whitespace self.log.debug('register()') libvirt.virEventRegisterImpl( self._add_handle, self._update_handle, self._remove_handle, self._add_timeout, self._update_timeout, self._remove_timeout) return self def schedule_ff_callback(self, iden: int, opaque: _T) -> None: '''Schedule a ff callback from one of the handles or timers''' asyncio.ensure_future(self._ff_callback(iden, opaque), loop=self.loop) async def _ff_callback(self, iden: int, opaque: _T) -> None: '''Directly free the opaque object This is a coroutine. ''' self.log.debug('ff_callback(iden=%d, opaque=...)', iden) libvirt.virEventInvokeFreeCallback(opaque) self._pending_dec() async def drain(self) -> None: '''Wait for the implementation to become idle. This is a coroutine. ''' self.log.debug('drain()') if self._pending: assert self._finished is None self._finished = asyncio.Event() await self._finished.wait() self._finished = None assert self._pending == 0 self.log.debug('drain ended') def is_idle(self) -> bool: '''Returns False if there are leftovers from a connection Those may happen if there are sematical problems while closing a connection. For example, not deregistered events before .close(). ''' return not self.callbacks and not self._pending def _add_handle(self, fd: int, event: int, cb: libvirt._EventCB, opaque: _T) -> int: '''Register a callback for monitoring file handle events :param int fd: file descriptor to listen on :param int event: bitset of events on which to fire the callback :param cb: the callback to be called when an event occurrs :param opaque: user data to pass to the callback :rtype: int :returns: handle watch number to be used for updating and unregistering for events .. seealso:: https://libvirt.org/html/libvirt-libvirt-event.html#virEventAddHandleFuncFunc ''' callback = FDCallback(self, cb, opaque, descriptor=self.descriptors[fd], event=event) assert callback.iden not in self.callbacks self.log.debug('add_handle(fd=%d, event=%d, cb=..., opaque=...) = %d', fd, event, callback.iden) self.callbacks[callback.iden] = callback self.descriptors[fd].add_handle(callback) self._pending_inc() return callback.iden def _update_handle(self, watch: int, event: int) -> None: '''Change event set for a monitored file handle :param int watch: file descriptor watch to modify :param int event: new events to listen on .. seealso:: https://libvirt.org/html/libvirt-libvirt-event.html#virEventUpdateHandleFunc ''' self.log.debug('update_handle(watch=%d, event=%d)', watch, event) callback = self.callbacks[watch] assert isinstance(callback, FDCallback) callback.update(event=event) def _remove_handle(self, watch: int) -> int: '''Unregister a callback from a file handle. :param int watch: file descriptor watch to stop listening on :returns: -1 on error, 0 on success .. seealso:: https://libvirt.org/html/libvirt-libvirt-event.html#virEventRemoveHandleFunc ''' self.log.debug('remove_handle(watch=%d)', watch) try: callback = self.callbacks.pop(watch) except KeyError as err: self.log.warning('remove_handle(): no such handle: %r', err.args[0]) return -1 assert isinstance(callback, FDCallback) fd = callback.descriptor.fd assert callback is self.descriptors[fd].remove_handle(watch) if len(self.descriptors[fd].callbacks) == 0: del self.descriptors[fd] callback.close() return 0 def _add_timeout(self, timeout: int, cb: libvirt._TimerCB, opaque: _T) -> int: '''Register a callback for a timer event :param int timeout: the timeout to monitor :param cb: the callback to call when timeout has expired :param opaque: user data to pass to the callback :rtype: int :returns: a timer value .. seealso:: https://libvirt.org/html/libvirt-libvirt-event.html#virEventAddTimeoutFunc ''' callback = TimeoutCallback(self, cb, opaque) assert callback.iden not in self.callbacks self.log.debug('add_timeout(timeout=%d, cb=..., opaque=...) = %d', timeout, callback.iden) self.callbacks[callback.iden] = callback callback.update(timeout=timeout) self._pending_inc() return callback.iden def _update_timeout(self, timer: int, timeout: int) -> None: '''Change frequency for a timer :param int timer: the timer to modify :param int timeout: the new timeout value in ms .. seealso:: https://libvirt.org/html/libvirt-libvirt-event.html#virEventUpdateTimeoutFunc ''' self.log.debug('update_timeout(timer=%d, timeout=%d)', timer, timeout) callback = self.callbacks[timer] assert isinstance(callback, TimeoutCallback) callback.update(timeout=timeout) def _remove_timeout(self, timer: int) -> int: '''Unregister a callback for a timer :param int timer: the timer to remove :returns: -1 on error, 0 on success .. seealso:: https://libvirt.org/html/libvirt-libvirt-event.html#virEventRemoveTimeoutFunc ''' self.log.debug('remove_timeout(timer=%d)', timer) try: callback = self.callbacks.pop(timer) except KeyError as err: self.log.warning('remove_timeout(): no such timeout: %r', err.args[0]) return -1 callback.close() return 0 _current_impl = None # type: Optional[virEventAsyncIOImpl] def getCurrentImpl() -> Optional[virEventAsyncIOImpl]: '''Return the current implementation, or None if not yet registered''' return _current_impl def virEventRegisterAsyncIOImpl(loop: asyncio.AbstractEventLoop = None) -> virEventAsyncIOImpl: '''Arrange for libvirt's callbacks to be dispatched via asyncio event loop The implementation object is returned, but in normal usage it can safely be discarded. ''' global _current_impl _current_impl = virEventAsyncIOImpl(loop=loop).register() return _current_impl ./libvirt-python-9.10.0/pyproject.toml0000644000000000000000000000012114555064067016350 0ustar rootroot[build-system] requires = ["setuptools"] build-backend = "setuptools.build_meta" ./libvirt-python-9.10.0/requirements-test.txt0000644000000000000000000000001214555064067017674 0ustar rootrootnose lxml ./libvirt-python-9.10.0/setup.cfg0000644000000000000000000000115514555064067015265 0ustar rootroot[metadata] name = libvirt-python version = file: VERSION description = The libvirt virtualization API python binding long_description = file: README long_description_content_type = text/x-rst url = http://www.libvirt.org maintainer = Libvirt Maintainers maintainer_email = libvir-list@redhat.com license_files = COPYING classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: GNU Lesser General Public License v2 or later (LGPLv2+) Programming Language :: Python :: 3 :: Only [options] python_requires = >=3.6 package_dir = =build ./libvirt-python-9.10.0/setup.py0000755000000000000000000002132214555064067015157 0ustar rootroot#!/usr/bin/env python3 import sys import re import shutil import subprocess import time from pathlib import Path from setuptools import setup, Extension from setuptools.command.build_ext import build_ext from setuptools.command.build_py import build_py from setuptools.command.sdist import sdist def getVersion(): with open("VERSION") as f: return f.read().strip() def check_pkgcfg(): try: proc = subprocess.run(["pkg-config", "--version"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if proc.returncode != 0: print("pkg-config binary does not appear to be functional") sys.exit(1) except FileNotFoundError: print("pkg-config binary is required to compile libvirt-python") sys.exit(1) def check_minimum_libvirt_version(): subprocess.check_call(["pkg-config", "--print-errors", f"--atleast-version={MIN_LIBVIRT}", "libvirt"]) def have_libvirt_lxc(): proc = subprocess.run(["pkg-config", f"--atleast-version={MIN_LIBVIRT_LXC}", "libvirt"]) if proc.returncode == 0: return True return False def get_pkgconfig_data(args, mod, required=True): """Run pkg-config to and return content associated with it""" cmd = ["pkg-config"] + args + [mod] output = subprocess.check_output(cmd, universal_newlines=True) for line in output.splitlines(): if line == "": if required: args_str = " ".join(args) raise Exception(f"Cannot determine '{args_str}' from " "libvirt pkg-config file") line = "" return line.strip() def get_api_xml_files(): """Check with pkg-config that libvirt is present and extract the API XML file paths we need from it""" libvirt_api = get_pkgconfig_data(["--variable", "libvirt_api"], "libvirt") offset = libvirt_api.index("-api.xml") libvirt_qemu_api = libvirt_api[0:offset] + "-qemu-api.xml" offset = libvirt_api.index("-api.xml") libvirt_lxc_api = libvirt_api[0:offset] + "-lxc-api.xml" return (libvirt_api, libvirt_qemu_api, libvirt_lxc_api) def get_module_lists(): """ Determine which modules we are actually building, and all their required config """ c_modules = [] py_modules = [] ldflags = get_pkgconfig_data(["--libs-only-L"], "libvirt", False).split() cflags = get_pkgconfig_data(["--cflags"], "libvirt", False).split() cflags += ["-Wp,-DPy_LIMITED_API=0x03060000"] module = Extension("libvirtmod", sources=[ "libvirt-override.c", "build/libvirt.c", "typewrappers.c", "libvirt-utils.c" ], libraries=["virt"], include_dirs=["."]) module.extra_compile_args.extend(cflags) module.extra_link_args.extend(ldflags) c_modules.append(module) py_modules.append("libvirt") moduleqemu = Extension("libvirtmod_qemu", sources=[ "libvirt-qemu-override.c", "build/libvirt-qemu.c", "typewrappers.c", "libvirt-utils.c" ], libraries=["virt-qemu", "virt"], include_dirs=["."]) moduleqemu.extra_compile_args.extend(cflags) moduleqemu.extra_link_args.extend(ldflags) c_modules.append(moduleqemu) py_modules.append("libvirt_qemu") if have_libvirt_lxc(): modulelxc = Extension("libvirtmod_lxc", sources=[ "libvirt-lxc-override.c", "build/libvirt-lxc.c", "typewrappers.c", "libvirt-utils.c" ], libraries=["virt-lxc", "virt"], include_dirs=["."]) modulelxc.extra_compile_args.extend(cflags) modulelxc.extra_link_args.extend(ldflags) c_modules.append(modulelxc) py_modules.append("libvirt_lxc") py_modules.append("libvirtaio") return c_modules, py_modules ################### # Custom commands # ################### class my_build_ext(build_ext): def run(self): check_minimum_libvirt_version() apis = get_api_xml_files() subprocess.check_call([sys.executable, "generator.py", "libvirt", apis[0], "c"]) subprocess.check_call([sys.executable, "generator.py", "libvirt-qemu", apis[1], "c"]) if have_libvirt_lxc(): subprocess.check_call([sys.executable, "generator.py", "libvirt-lxc", apis[2], "c"]) build_ext.run(self) class my_build_py(build_py): def run(self): check_minimum_libvirt_version() apis = get_api_xml_files() subprocess.check_call([sys.executable, "generator.py", "libvirt", apis[0], "py"]) subprocess.check_call([sys.executable, "generator.py", "libvirt-qemu", apis[1], "py"]) if have_libvirt_lxc(): subprocess.check_call([sys.executable, "generator.py", "libvirt-lxc", apis[2], "py"]) shutil.copy("libvirtaio.py", "build") build_py.run(self) class my_sdist(sdist): user_options = sdist.user_options description = "Update libvirt-python.spec; build sdist-tarball." def initialize_options(self): self.snapshot = None sdist.initialize_options(self) def finalize_options(self): if self.snapshot is not None: self.snapshot = 1 sdist.finalize_options(self) @staticmethod def _gen_from_in(file_in, file_out, replace_pattern, replace): with open(file_in) as f_in, open(file_out, "w") as f_out: for line in f_in: f_out.write(line.replace(replace_pattern, replace)) def gen_rpm_spec(self): return self._gen_from_in("libvirt-python.spec.in", "libvirt-python.spec", "@PY_VERSION@", getVersion()) def gen_authors(self): cmd = ["git", "log", "--pretty=format:%aN <%aE>"] output = subprocess.check_output(cmd, universal_newlines=True) git_authors = {line.strip() for line in output.splitlines()} authors = sorted(git_authors, key=str.lower) authors = [" " + author for author in authors] self._gen_from_in("AUTHORS.in", "AUTHORS", "@AUTHORS@", "\n".join(authors)) def gen_changelog(self): cmd = ["git", "log", "--pretty=format:%H:%ct %an <%ae>%n%n%s%n%b%n"] with open("ChangeLog", "w") as f_out: output = subprocess.check_output(cmd, universal_newlines=True) for line in output.splitlines(): m = re.match(r"([a-f0-9]+):(\d+)\s(.*)", line) if m: t = time.gmtime(int(m.group(2))) fmt = "{: 04d}-{: 02d}-{: 02d} {}\n" f_out.write(fmt.format(t.tm_year, t.tm_mon, t.tm_mday, m.group(3))) else: if re.match(r"Signed-off-by", line): continue f_out.write(" " + line.strip() + "\n") def run(self): if Path(".git").exists(): try: self.gen_rpm_spec() self.gen_authors() self.gen_changelog() sdist.run(self) finally: files = [ "libvirt-python.spec", "AUTHORS", "ChangeLog" ] for f in files: try: Path(f).unlink() except FileNotFoundError: pass else: sdist.run(self) ################## # Invoke setup() # ################## if sys.version_info < (3, 6): print("libvirt-python requires Python >= 3.6 to build") sys.exit(1) MIN_LIBVIRT = "0.9.11" MIN_LIBVIRT_LXC = "1.0.2" # Hack to stop "pip install" failing with error # about missing "build" dir. Path("build").mkdir(exist_ok=True) check_pkgcfg() _c_modules, _py_modules = get_module_lists() setup( ext_modules=_c_modules, py_modules=_py_modules, package_dir={ '': 'build' }, cmdclass={ "build_ext": my_build_ext, "build_py": my_build_py, "sdist": my_sdist, }, ) ./libvirt-python-9.10.0/tests/0000755000000000000000000000000014555064757014612 5ustar rootroot./libvirt-python-9.10.0/tests/eventmock.py0000644000000000000000000000532614555064067017157 0ustar rootroot import libvirt import libvirtmod _add_handle_impl = None _update_handle_impl = None _remove_handle_impl = None _add_timeout_impl = None _update_timeout_impl = None _remove_timeout_impl = None _registered = False def _add_handle(fd: int, event: int, cb: libvirt._EventCB, opaque: libvirt._T) -> int: global _add_handle_impl assert _add_handle_impl != None return _add_handle_impl(fd, event, cb, opaque) def _update_handle(watch: int, event: int) -> None: global _update_handle_impl assert _update_handle_impl != None _update_handle_impl(watch, event) def _remove_handle(watch: int) -> int: global _remove_handle_impl assert _remove_handle_impl != None return _remove_handle_impl(watch) def _add_timeout(timeout: int, cb: libvirt._TimerCB, opaque: libvirt._T) -> int: global _add_timeout_impl assert _add_timeout_impl != None return _add_timeout_impl(timeout, cb, opaque) def _update_timeout(timer: int, timeout: int) -> None: global _update_timeout_impl assert _update_timeout_impl != None _update_timeout_impl(timer, timeout) def _remove_timeout(timer: int) -> int: global _remove_timeout_impl assert _remove_timeout_impl != None return _remove_timeout_impl(timer) # libvirt.virEventRegisterImpl() is a one time call per process # This method is intended to be used with mock patching, so that # tests can get the appearance of being able to call # virEventRegisterImpl many times. # # Note, this relies on the tests closing all connection objects # and not leaving any handles/timers pending when they stop # running their event loop impl. def virEventRegisterImplMock(add_handle_impl, update_handle_impl, remove_handle_impl, add_timeout_impl, update_timeout_impl, remove_timeout_impl): global _add_handle_impl global _update_handle_impl global _remove_handle_impl global _add_timeout_impl global _update_timeout_impl global _remove_timeout_impl _add_handle_impl = add_handle_impl _update_handle_impl = update_handle_impl _remove_handle_impl = remove_handle_impl _add_timeout_impl = add_timeout_impl _update_timeout_impl = update_timeout_impl _remove_timeout_impl = remove_timeout_impl global _registered if not _registered: libvirtmod.virEventRegisterImpl(_add_handle, _update_handle, _remove_timeout, _add_timeout, _update_timeout, _remove_timeout) _registered = True ./libvirt-python-9.10.0/tests/test_aio.py0000644000000000000000000001360014555064067016765 0ustar rootrootimport asyncio import libvirt import libvirtaio import sys import unittest from unittest import mock import eventmock class TestLibvirtAio(unittest.TestCase): async def _run(self, register): def lifecycleCallback(conn, dom, event, detail, domainChangedEvent): if (event == libvirt.VIR_DOMAIN_EVENT_STOPPED or event == libvirt.VIR_DOMAIN_EVENT_STARTED): domainChangedEvent.set() if register: libvirtEvents = libvirtaio.virEventRegisterAsyncIOImpl() else: libvirtEvents = libvirtaio.getCurrentImpl() conn = libvirt.open("test:///default") dom = conn.lookupByName("test") eventRegistered = False domainStopped = False try: # Ensure the VM is running. self.assertEqual([libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_RUNNING_UNKNOWN], dom.state()) self.assertTrue(libvirtEvents.is_idle()) # Register VM start/stopped event handler. domainChangedEvent = asyncio.Event() conn.domainEventRegisterAny(dom, libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE, lifecycleCallback, domainChangedEvent) eventRegistered = True self.assertFalse(libvirtEvents.is_idle()) # Stop the VM. dom.destroy() domainStopped = True # Ensure domain stopped event is received. await asyncio.wait_for(domainChangedEvent.wait(), 2) self.assertEqual([libvirt.VIR_DOMAIN_SHUTOFF, libvirt.VIR_DOMAIN_SHUTOFF_DESTROYED], dom.state()) # Start the VM. domainChangedEvent.clear() domainStopped = False dom.create() # Ensure domain started event is received. await asyncio.wait_for(domainChangedEvent.wait(), 2) self.assertEqual([libvirt.VIR_DOMAIN_RUNNING, libvirt.VIR_DOMAIN_RUNNING_BOOTED], dom.state()) self.assertFalse(libvirtEvents.is_idle()) # Deregister the VM start/stopped event handler. eventRegistered = False conn.domainEventDeregisterAny(libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE) # Wait for event queue to clear. await libvirtEvents.drain() # Make sure event queue is cleared. self.assertTrue(libvirtEvents.is_idle()) finally: if eventRegistered: conn.domainEventDeregisterAny(libvirt.VIR_DOMAIN_EVENT_ID_LIFECYCLE) if domainStopped: dom.create() @mock.patch('libvirt.virEventRegisterImpl', side_effect=eventmock.virEventRegisterImplMock) def testEventsWithManualLoopSetup(self, mock_event_register): # Register libvirt events after starting the asyncio loop. # # Manually create and set the event loop against this # thread. loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(self._run(register=True)) loop.close() asyncio.set_event_loop(None) mock_event_register.assert_called_once() @mock.patch('libvirt.virEventRegisterImpl', side_effect=eventmock.virEventRegisterImplMock) @unittest.skipIf(sys.version_info < (3,7), "test requires Python 3.7+") def testEventsWithAsyncioRun(self, mock_event_register): # Register libvirt events after starting the asyncio loop. # # Use asyncio helper to create and set the event loop # against this thread. asyncio.run(self._run(register=True)) mock_event_register.assert_called_once() @mock.patch('libvirt.virEventRegisterImpl', side_effect=eventmock.virEventRegisterImplMock) def testEventsPreInitExplicit(self, mock_event_register): # Register libvirt events before starting the asyncio loop. # # Tell virEventRegisterAsyncIOImpl() explicitly what loop # to use before we set a loop for this thread. loop = asyncio.new_event_loop() libvirtaio.virEventRegisterAsyncIOImpl(loop) asyncio.set_event_loop(loop) loop.run_until_complete(self._run(register=False)) loop.close() asyncio.set_event_loop(None) mock_event_register.assert_called_once() @mock.patch('libvirt.virEventRegisterImpl', side_effect=eventmock.virEventRegisterImplMock) @unittest.skipIf(sys.version_info >= (3,10), "test incompatible with 3.10") def testEventsPreInitImplicit(self, mock_event_register): # Register libvirt events before starting the asyncio loop. # # Allow virEventRegisterAsyncIOImpl() to implicitly find the # loop we set for this thread. loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) libvirtaio.virEventRegisterAsyncIOImpl() loop.run_until_complete(self._run(register=False)) loop.close() asyncio.set_event_loop(None) mock_event_register.assert_called_once() @mock.patch('libvirt.virEventRegisterImpl', side_effect=eventmock.virEventRegisterImplMock) @unittest.skipIf(sys.version_info >= (3,10), "test incompatible with 3.10") def testEventsImplicitLoopInit(self, mock_event_register): # Register libvirt events before starting the asyncio loop. # # Let virEventRegisterAsyncIOImpl() auto-create a default # event loop, which we then register against this thread. # # Historically this often worked if called from the main thead, # but since Python 3.10 this triggers a deprecation warning, # which will turn into a RuntimeError in a later release. libvirtaio.virEventRegisterAsyncIOImpl() loop = asyncio.get_event_loop() loop.run_until_complete(self._run(register=False)) loop.close() asyncio.set_event_loop(None) mock_event_register.assert_called_once() ./libvirt-python-9.10.0/tests/test_conn.py0000644000000000000000000000550414555064067017156 0ustar rootrootimport unittest import libvirt import tempfile import contextlib import os class TestLibvirtConn(unittest.TestCase): def setUp(self): self.conn = libvirt.open("test:///default") def tearDown(self): self.conn = None def testConnDomainList(self): doms = self.conn.listAllDomains() self.assertEqual(len(doms), 1) self.assertEqual(type(doms[0]), libvirt.virDomain) self.assertEqual(doms[0].name(), "test") class TestLibvirtConnAuth(unittest.TestCase): connXML = """ <node> <auth> <user password="2147483647">marin</user> <user password="87539319">srinivasa</user> </auth> </node>""" def setUp(self): def noop(msg, opaque): pass libvirt.registerErrorHandler(noop, None) @contextlib.contextmanager def tempxmlfile(content): try: fp = tempfile.NamedTemporaryFile(delete=False, prefix="libvirt-python-test", suffix=".xml") fname = fp.name fp.write(content.encode("utf8")) fp.close() yield fname finally: os.unlink(fname) def authHelper(self, username, password): with TestLibvirtConnAuth.tempxmlfile(self.connXML) as fname: magic = 142857 def authCB(creds, opaque): if opaque != magic: return -1 for cred in creds: if (cred[0] == libvirt.VIR_CRED_AUTHNAME and username is not None): cred[4] = username return 0 elif (cred[0] == libvirt.VIR_CRED_PASSPHRASE and password is not None): cred[4] = password return 0 return -1 return 0 auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_ECHOPROMPT, libvirt.VIR_CRED_REALM, libvirt.VIR_CRED_PASSPHRASE, libvirt.VIR_CRED_NOECHOPROMPT, libvirt.VIR_CRED_EXTERNAL], authCB, magic] return libvirt.openAuth("test://" + fname, auth, 0) def testOpenAuthGood(self): conn = self.authHelper("srinivasa", "87539319") def testOpenAuthBad(self): try: conn = self.authHelper("srinivasa", "2147483647") raise Exception("Unexpected open success") except libvirt.libvirtError as ex: pass def testOpenAuthNone(self): try: conn = self.authHelper(None, None) raise Exception("Unexpected open success") except libvirt.libvirtError as ex: pass ./libvirt-python-9.10.0/tests/test_domain.py0000644000000000000000000000136614555064067017472 0ustar rootrootimport unittest import libvirt class TestLibvirtDomain(unittest.TestCase): def setUp(self): self.conn = libvirt.open("test:///default") self.dom = self.conn.lookupByName("test") def tearDown(self): self.dom = None self.conn = None def testDomainSchedParams(self): params = self.dom.schedulerParameters() self.assertEqual(len(params), 1) self.assertTrue("weight" in params) params["weight"] = 100 self.dom.setSchedulerParameters(params) @unittest.skipIf(libvirt.getVersion() == 4000000, "test driver screenshot broken in 4.0.0") def testScreenshot(self): stream = self.conn.newStream() ss = self.dom.screenshot(stream, 0, 0) ./libvirt-python-9.10.0/tests/test_domain_checkpoint.py0000644000000000000000000000105014555064067021667 0ustar rootrootimport unittest import libvirt class TestLibvirtDomainCheckpoint(unittest.TestCase): def setUp(self): self.conn = libvirt.open("test:///default") self.dom = self.conn.lookupByName("test") def tearDown(self): self.dom = None self.conn = None @unittest.skipUnless(hasattr(libvirt.virDomain, "checkpointCreateXML"), "checkpoints not supported in this libvirt") def testCheckpointCreate(self): cp = self.dom.checkpointCreateXML("<domaincheckpoint/>") cp.delete() ./libvirt-python-9.10.0/tests/test_domain_snapshot.py0000644000000000000000000000061614555064067021406 0ustar rootrootimport unittest import libvirt class TestLibvirtDomainSnapshot(unittest.TestCase): def setUp(self): self.conn = libvirt.open("test:///default") self.dom = self.conn.lookupByName("test") def tearDown(self): self.dom = None self.conn = None def testSnapCreate(self): snap = self.dom.snapshotCreateXML("<domainsnapshot/>") snap.delete() ./libvirt-python-9.10.0/tests/test_interface.py0000644000000000000000000000055714555064067020164 0ustar rootrootimport unittest import libvirt class TestLibvirtInterface(unittest.TestCase): def setUp(self): self.conn = libvirt.open("test:///default") self.iface = self.conn.interfaceLookupByName("eth1") def tearDown(self): self.iface = None self.conn = None def testAttr(self): self.assertEqual(self.iface.name(), "eth1") ./libvirt-python-9.10.0/tests/test_network.py0000644000000000000000000000055314555064067017711 0ustar rootrootimport unittest import libvirt class TestLibvirtNetwork(unittest.TestCase): def setUp(self): self.conn = libvirt.open("test:///default") self.net = self.conn.networkLookupByName("default") def tearDown(self): self.net = None self.conn = None def testAttr(self): self.assertEqual(self.net.name(), "default") ./libvirt-python-9.10.0/tests/test_nodedev.py0000644000000000000000000000057414555064067017647 0ustar rootrootimport unittest import libvirt class TestLibvirtNodeDev(unittest.TestCase): def setUp(self): self.conn = libvirt.open("test:///default") self.nodedev = self.conn.nodeDeviceLookupByName("computer") def tearDown(self): self.nodedev = None self.conn = None def testAttr(self): self.assertEqual(self.nodedev.name(), "computer") ./libvirt-python-9.10.0/tests/test_storage.py0000644000000000000000000000113014555064067017654 0ustar rootrootimport unittest import libvirt class TestLibvirtStorage(unittest.TestCase): def setUp(self): self.conn = libvirt.open("test:///default") self.pool = self.conn.storagePoolLookupByName("default-pool") def tearDown(self): self.pool = None self.conn = None def testAttr(self): self.assertEqual(self.pool.name(), "default-pool") def testVol(self): volxml = '''<volume type="file"> <name>raw.img</name> <allocation unit="M">10</allocation> <capacity unit="M">1000</capacity> </volume>''' vol = self.pool.createXML(volxml) ./libvirt-python-9.10.0/tests/test_api_coverage.py0000644000000000000000000003750614555064757020662 0ustar rootroot#!/usr/bin/env python3 import sys from typing import Dict, List, Set, Tuple # noqa F401 import libvirt import unittest import os def get_libvirt_api_xml_path(): import subprocess args = ["pkg-config", "--variable", "libvirt_api", "libvirt"] proc = subprocess.Popen(args, stdout=subprocess.PIPE) stdout, _ = proc.communicate() if proc.returncode: sys.exit(proc.returncode) return stdout.splitlines()[0] # Identify all functions and enums in public API def identify_functions_enums(tree): enumvals = {} # type: Dict[str, Dict[str, int]] second_pass = [] # type: List[str] wantenums = [] # type: List[str] wantfunctions = [] # type: List[str] wantfunctions = tree.xpath('/api/files/file/exports[@type="function"]/@symbol') for n in tree.xpath('/api/symbols/enum'): typ = n.attrib['type'] name = n.attrib['name'] val = n.attrib['value'] if typ not in enumvals: enumvals[typ] = {} # If the value cannot be converted to int, it is reference to # another enum and needs to be sorted out later on try: val = int(val) except ValueError: second_pass.append(n) continue enumvals[typ][name] = int(val) for n in second_pass: typ = n.attrib['type'] name = n.attrib['name'] val = n.attrib['value'] for v in enumvals.values(): if val in v: val = int(v[val]) break # Version 4.0.0 was broken as missing VIR_TYPED_PARAM enums # constants. This is harmless from POV of validating API # coverage so ignore this error. if (not isinstance(val, int) and not val.startswith("VIR_TYPED_PARAM_")): fail = True print("Cannot get a value of enum %s (originally %s)" % (val, name)) enumvals[typ][name] = val for n in tree.xpath('/api/files/file/exports[@type="enum"]/@symbol'): for enumval in enumvals.values(): if n in enumval: enumv = enumval break # Eliminate sentinels if n.endswith('_LAST') and enumv[n] == max(enumv.values()): continue wantenums.append(n) return wantfunctions, wantenums, enumvals # Identify all classes and methods in the 'libvirt' python module def identify_class_methods(wantenums, enumvals): gotenums = [] # type: List[str] gottypes = [] # type: List[str] gotfunctions = {"libvirt": []} # type: Dict[str, List[str]] for name in dir(libvirt): if name.startswith('_'): continue thing = getattr(libvirt, name) # Special-case libvirtError to deal with python 2.4 difference # in Exception class type reporting. if isinstance(thing, int): gotenums.append(name) elif getattr(thing, "__module__", "") == "typing": continue elif type(thing) == type or name == "libvirtError": gottypes.append(name) gotfunctions[name] = [] elif callable(thing): gotfunctions["libvirt"].append(name) for enum in wantenums: if enum not in gotenums: fail = True for typ, enumval in enumvals.items(): if enum in enumval: raise Exception("Missing exported enum %s of type %s" % (enum, typ)) for klassname in gottypes: klassobj = getattr(libvirt, klassname) for name in dir(klassobj): if name.startswith('_'): continue if name == 'c_pointer': continue thing = getattr(klassobj, name) if callable(thing): gotfunctions[klassname].append(name) return gotfunctions, gottypes # First cut at mapping of C APIs to python classes + methods def basic_class_method_mapping(wantfunctions, gottypes): basicklassmap = {} # type: Dict[str, Tuple[str, str, str]] for cname in wantfunctions: name = cname # Some virConnect APIs have stupid names if name[0:7] == "virNode" and name[0:13] != "virNodeDevice": name = "virConnect" + name[7:] if name[0:7] == "virConn" and name[0:10] != "virConnect": name = "virConnect" + name[7:] # The typed param APIs are only for internal use if name[0:14] == "virTypedParams": continue if name[0:23] == "virNetworkDHCPLeaseFree": continue if name[0:28] == "virDomainStatsRecordListFree": continue if name[0:19] == "virDomainFSInfoFree": continue if name[0:25] == "virDomainIOThreadInfoFree": continue if name[0:22] == "virDomainInterfaceFree": continue if name[0:21] == "virDomainListGetStats": name = "virConnectDomainListGetStats" # These aren't functions, they're callback signatures if name in ["virConnectAuthCallbackPtr", "virConnectCloseFunc", "virStreamSinkFunc", "virStreamSourceFunc", "virStreamEventCallback", "virEventHandleCallback", "virEventTimeoutCallback", "virFreeCallback", "virStreamSinkHoleFunc", "virStreamSourceHoleFunc", "virStreamSourceSkipFunc"]: continue if name[0:21] == "virConnectDomainEvent" and name[-8:] == "Callback": continue if name[0:22] == "virConnectNetworkEvent" and name[-8:] == "Callback": continue if (name.startswith("virConnectStoragePoolEvent") and name.endswith("Callback")): continue if (name.startswith("virConnectNodeDeviceEvent") and name.endswith("Callback")): continue if (name.startswith("virConnectSecretEvent") and name.endswith("Callback")): continue # virEvent APIs go into main 'libvirt' namespace not any class if name[0:8] == "virEvent": if name[-4:] == "Func": continue basicklassmap[name] = ("libvirt", name, cname) else: found = False # To start with map APIs to classes based on the # naming prefix. Mistakes will be fixed in next # loop for klassname in gottypes: klen = len(klassname) if name[0:klen] == klassname: found = True if name not in basicklassmap: basicklassmap[name] = (klassname, name[klen:], cname) elif len(basicklassmap[name]) < klen: basicklassmap[name] = (klassname, name[klen:], cname) # Anything which can't map to a class goes into the # global namespaces if not found: basicklassmap[name] = ("libvirt", name[3:], cname) return basicklassmap # Deal with oh so many special cases in C -> python mapping def fixup_class_method_mapping(basicklassmap): finalklassmap = {} # type: Dict[str, Tuple[str, str, str]] for name, (klass, func, cname) in sorted(basicklassmap.items()): # The object lifecycle APIs are irrelevant since they're # used inside the object constructors/destructors. if func in ["Ref", "Free", "New", "GetConnect", "GetDomain", "GetNetwork"]: if klass == "virStream" and func == "New": klass = "virConnect" func = "NewStream" else: continue # All the error handling methods need special handling if klass == "libvirt": if func in ["CopyLastError", "DefaultErrorFunc", "ErrorFunc", "FreeError", "SaveLastError", "ResetError"]: continue elif func in ["GetLastError", "GetLastErrorMessage", "GetLastErrorCode", "GetLastErrorDomain", "ResetLastError", "Initialize"]: func = "vir" + func elif func == "SetErrorFunc": func = "RegisterErrorHandler" elif klass == "virConnect": if func in ["CopyLastError", "SetErrorFunc"]: continue elif func in ["GetLastError", "ResetLastError"]: func = "virConn" + func # Remove 'Get' prefix from most APIs, except those in virConnect # and virDomainSnapshot namespaces which stupidly used a different # convention which we now can't fix without breaking API if func[0:3] == "Get" and klass not in ["virConnect", "virDomainCheckpoint", "virDomainSnapshot", "libvirt"]: if func not in ["GetCPUStats", "GetTime"]: func = func[3:] # The object creation and lookup APIs all have to get re-mapped # into the parent class if func in ["CreateXML", "CreateLinux", "CreateXMLWithFiles", "DefineXML", "CreateXMLFrom", "LookupByUUID", "LookupByUUIDString", "LookupByVolume" "LookupByName", "LookupByID", "LookupByName", "LookupByKey", "LookupByPath", "LookupByMACString", "LookupByUsage", "LookupByVolume", "LookupByTargetPath", "LookupSCSIHostByWWN", "LookupByPortDev", "Restore", "RestoreFlags", "SaveImageDefineXML", "SaveImageGetXMLDesc", "DefineXMLFlags", "CreateXMLFlags"]: if klass != "virDomain": func = klass[3:] + func if klass in ["virDomainCheckpoint", "virDomainSnapshot"]: klass = "virDomain" func = func[6:] elif klass == "virStorageVol" and func in ["StorageVolCreateXMLFrom", "StorageVolCreateXML"]: klass = "virStoragePool" func = func[10:] elif klass == "virNetworkPort": klass = "virNetwork" func = func[7:] elif func == "StoragePoolLookupByVolume": klass = "virStorageVol" elif func == "StorageVolLookupByName": klass = "virStoragePool" else: klass = "virConnect" # The open methods get remapped to primary namespace if klass == "virConnect" and func in ["Open", "OpenAuth", "OpenReadOnly"]: klass = "libvirt" # These are inexplicably renamed in the python API if func == "ListDomains": func = "ListDomainsID" elif func == "ListAllNodeDevices": func = "ListAllDevices" elif func == "ListNodeDevices": func = "ListDevices" # The virInterfaceChangeXXXX APIs go into virConnect. Stupidly # they have lost their 'interface' prefix in names, but we can't # fix this name if func[0:6] == "Change": klass = "virConnect" # Need to special case the checkpoint and snapshot APIs if klass == "virDomainSnapshot" and func in ["Current", "ListNames", "Num"]: klass = "virDomain" func = "snapshot" + func # Names should start with lowercase letter... func = func[0:1].lower() + func[1:] if func[0:8] == "nWFilter": func = "nwfilter" + func[8:] if func[0:8] == "fSFreeze" or func[0:6] == "fSThaw" or func[0:6] == "fSInfo": func = "fs" + func[2:] if func[0:12] == "iOThreadInfo": func = "ioThreadInfo" if klass == "virNetwork": func = func.replace("dHCP", "DHCP") # ...except when they don't. More stupid naming # decisions we can't fix if func == "iD": func = "ID" if func == "uUID": func = "UUID" if func == "uUIDString": func = "UUIDString" if func == "oSType": func = "OSType" if func == "xMLDesc": func = "XMLDesc" if func == "mACString": func = "MACString" finalklassmap[name] = (klass, func, cname) return finalklassmap # Validate that every C API is mapped to a python API def validate_c_to_python_api_mappings(finalklassmap, gotfunctions): usedfunctions = set() # type: Set[str] for name, (klass, func, cname) in sorted(finalklassmap.items()): if func in gotfunctions[klass]: usedfunctions.add("%s.%s" % (klass, func)) else: raise Exception("%s -> %s.%s (C API not mapped to python)" % (name, klass, func)) return usedfunctions # Validate that every python API has a corresponding C API def validate_python_to_c_api_mappings(gotfunctions, usedfunctions): for klass in gotfunctions: if klass == "libvirtError": continue for func in sorted(gotfunctions[klass]): # These are pure python methods with no C APi if func in ["connect", "getConnect", "domain", "getDomain", "virEventInvokeFreeCallback", "network", "sparseRecvAll", "sparseSendAll"]: continue key = "%s.%s" % (klass, func) if key not in usedfunctions: raise Exception("%s.%s (Python API not mapped to C)" % (klass, func)) # Validate that all the low level C APIs have binding def validate_c_api_bindings_present(finalklassmap): for name, (klass, func, cname) in sorted(finalklassmap.items()): pyname = cname if pyname == "virSetErrorFunc": pyname = "virRegisterErrorHandler" elif pyname == "virConnectListDomains": pyname = "virConnectListDomainsID" # These exist in C and exist in python, but we've got # a pure-python impl so don't check them if name in ["virStreamRecvAll", "virStreamSendAll", "virStreamSparseRecvAll", "virStreamSparseSendAll"]: continue try: thing = getattr(libvirt.libvirtmod, pyname) except AttributeError: raise Exception("libvirt.libvirtmod.%s (C binding does not exist)" % pyname) # Historically python lxml is incompatible with any other # use of libxml2 in the same process. Merely importing # 'lxml.etree' will result in libvirt's use of libxml2 # triggering a SEGV: # # https://bugs.launchpad.net/lxml/+bug/1748019 # # per the last comment though, it was somewhat improved by # # https://github.com/lxml/lxml/commit/fa1d856cad369d0ac64323ddec14b02281491706 # # so if we have version >= 4.5.2, we are safe to import # lxml.etree for the purposes of unit tests at least def broken_lxml(): import lxml if not hasattr(lxml, "__version__"): return True digits = [int(d) for d in lxml.__version__.split(".")] # We have 3 digits in versions today, but be paranoid # for possible future changes. if len(digits) != 3: return False version = (digits[0] * 1000 * 1000) + (digits[1] * 1000) + digits[2] if version < 4005002: return True return False api_test_flag = unittest.skipUnless( os.environ.get('LIBVIRT_API_COVERAGE', False), "API coverage test is only for upstream maintainers", ) lxml_broken_flag = unittest.skipIf( broken_lxml(), "lxml version clashes with libxml usage from libvirt" ) @api_test_flag @lxml_broken_flag class LibvirtAPICoverage(unittest.TestCase): def test_libvirt_api(self): xml = get_libvirt_api_xml_path() import lxml.etree with open(xml, "r") as fp: tree = lxml.etree.parse(fp) wantfunctions, wantenums, enumvals = identify_functions_enums(tree) gotfunctions, gottypes = identify_class_methods(wantenums, enumvals) basicklassmap = basic_class_method_mapping(wantfunctions, gottypes) finalklassmap = fixup_class_method_mapping(basicklassmap) usedfunctions = validate_c_to_python_api_mappings(finalklassmap, gotfunctions) validate_python_to_c_api_mappings(gotfunctions, usedfunctions) validate_c_api_bindings_present(finalklassmap) ./libvirt-python-9.10.0/tox.ini0000644000000000000000000000013114555064067014750 0ustar rootroot[tox] envlist = py36,py37,py38 [testenv] deps= lxml pytest commands= pytest ./libvirt-python-9.10.0/typewrappers.c0000644000000000000000000002501014555064067016351 0ustar rootroot/* * types.c: converter functions between the internal representation * and the Python objects * * Copyright (C) 2005-2019 Red Hat, Inc. * * Daniel Veillard <veillard@redhat.com> */ /* Horrible kludge to work around even more horrible name-space pollution * via Python.h. That file includes /usr/include/python3.x/pyconfig*.h, * which has over 180 autoconf-style HAVE_* definitions. Shame on them. */ #undef HAVE_PTHREAD_H #include <stdio.h> #include <string.h> #include "typewrappers.h" #include "libvirt-utils.h" static PyObject * libvirt_buildPyObject(void *cobj, const char *name, PyCapsule_Destructor destr) { return PyCapsule_New(cobj, name, destr); } PyObject * libvirt_intWrap(int val) { return PyLong_FromLong(val); } PyObject * libvirt_uintWrap(unsigned int val) { return PyLong_FromUnsignedLong(val); } PyObject * libvirt_longWrap(long val) { return PyLong_FromLong(val); } PyObject * libvirt_ulongWrap(unsigned long val) { return PyLong_FromLong(val); } PyObject * libvirt_longlongWrap(long long val) { return PyLong_FromLongLong(val); } PyObject * libvirt_ulonglongWrap(unsigned long long val) { return PyLong_FromUnsignedLongLong(val); } PyObject * libvirt_charPtrSizeWrap(char *str, Py_ssize_t size) { if (str == NULL) { return VIR_PY_NONE; } return PyBytes_FromStringAndSize(str, size); } PyObject * libvirt_charPtrWrap(char *str) { if (str == NULL) { return VIR_PY_NONE; } return PyUnicode_FromString(str); } PyObject * libvirt_constcharPtrWrap(const char *str) { if (str == NULL) { return VIR_PY_NONE; } return PyUnicode_FromString(str); } PyObject * libvirt_boolWrap(int val) { if (val) Py_RETURN_TRUE; else Py_RETURN_FALSE; } int libvirt_intUnwrap(PyObject *obj, int *val) { long long_val; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } /* If obj is type of PyInt_Type, PyInt_AsLong converts it * to C long type directly. If it is of PyLong_Type, PyInt_AsLong * will call PyLong_AsLong() to deal with it automatically. */ long_val = PyLong_AsLong(obj); if ((long_val == -1) && PyErr_Occurred()) return -1; #if LONG_MAX != INT_MAX if (long_val >= INT_MIN && long_val <= INT_MAX) { *val = long_val; } else { PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C int"); return -1; } #else *val = long_val; #endif return 0; } int libvirt_uintUnwrap(PyObject *obj, unsigned int *val) { unsigned long long_val; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } long_val = PyLong_AsUnsignedLong(obj); if ((long_val == (unsigned long)-1) && PyErr_Occurred()) return -1; if (long_val <= UINT_MAX) { *val = long_val; } else { PyErr_SetString(PyExc_OverflowError, "Python int too large to convert to C unsigned int"); return -1; } return 0; } int libvirt_longUnwrap(PyObject *obj, long *val) { long long_val; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } long_val = PyLong_AsLong(obj); if ((long_val == -1) && PyErr_Occurred()) return -1; *val = long_val; return 0; } int libvirt_ulongUnwrap(PyObject *obj, unsigned long *val) { long long_val; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } long_val = PyLong_AsLong(obj); if ((long_val == -1) && PyErr_Occurred()) return -1; if (long_val >= 0) { *val = long_val; } else { PyErr_SetString(PyExc_OverflowError, "negative Python int cannot be converted to C unsigned long"); return -1; } return 0; } int libvirt_longlongUnwrap(PyObject *obj, long long *val) { long long llong_val = -1; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } if (PyLong_Check(obj)) llong_val = PyLong_AsLongLong(obj); else PyErr_SetString(PyExc_TypeError, "an integer is required"); if ((llong_val == -1) && PyErr_Occurred()) return -1; *val = llong_val; return 0; } int libvirt_ulonglongUnwrap(PyObject *obj, unsigned long long *val) { unsigned long long ullong_val = -1; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } if (PyLong_Check(obj)) { ullong_val = PyLong_AsUnsignedLongLong(obj); } else { PyErr_SetString(PyExc_TypeError, "an integer is required"); } if ((ullong_val == (unsigned long long)-1) && PyErr_Occurred()) return -1; *val = ullong_val; return 0; } int libvirt_doubleUnwrap(PyObject *obj, double *val) { double double_val; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } double_val = PyFloat_AsDouble(obj); if ((double_val == -1) && PyErr_Occurred()) return -1; *val = double_val; return 0; } int libvirt_boolUnwrap(PyObject *obj, bool *val) { int ret; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } if ((ret = PyObject_IsTrue(obj)) < 0) return ret; *val = ret > 0; return 0; } int libvirt_charPtrUnwrap(PyObject *obj, char **str) { PyObject *bytes; const char *ret; *str = NULL; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } if (!(bytes = PyUnicode_AsUTF8String(obj))) return -1; ret = PyBytes_AsString(bytes); if (ret) { *str = strdup(ret); if (!*str) PyErr_NoMemory(); } Py_DECREF(bytes); return ret && *str ? 0 : -1; } int libvirt_charPtrSizeUnwrap(PyObject *obj, char **str, Py_ssize_t *size) { *str = NULL; *size = 0; if (!obj) { PyErr_SetString(PyExc_TypeError, "unexpected type"); return -1; } return PyBytes_AsStringAndSize(obj, str, size); } PyObject * libvirt_virDomainPtrWrap(virDomainPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virDomainPtr", NULL); return ret; } PyObject * libvirt_virNetworkPtrWrap(virNetworkPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virNetworkPtr", NULL); return ret; } PyObject * libvirt_virNetworkPortPtrWrap(virNetworkPortPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virNetworkPortPtr", NULL); return ret; } PyObject * libvirt_virInterfacePtrWrap(virInterfacePtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virInterfacePtr", NULL); return ret; } PyObject * libvirt_virStoragePoolPtrWrap(virStoragePoolPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virStoragePoolPtr", NULL); return ret; } PyObject * libvirt_virStorageVolPtrWrap(virStorageVolPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virStorageVolPtr", NULL); return ret; } PyObject * libvirt_virConnectPtrWrap(virConnectPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virConnectPtr", NULL); return ret; } PyObject * libvirt_virNodeDevicePtrWrap(virNodeDevicePtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virNodeDevicePtr", NULL); return ret; } PyObject * libvirt_virSecretPtrWrap(virSecretPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virSecretPtr", NULL); return ret; } PyObject * libvirt_virNWFilterPtrWrap(virNWFilterPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virNWFilterPtr", NULL); return ret; } PyObject * libvirt_virNWFilterBindingPtrWrap(virNWFilterBindingPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virNWFilterBindingPtr", NULL); return ret; } PyObject * libvirt_virStreamPtrWrap(virStreamPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virStreamPtr", NULL); return ret; } PyObject * libvirt_virDomainCheckpointPtrWrap(virDomainCheckpointPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virDomainCheckpointPtr", NULL); return ret; } PyObject * libvirt_virDomainSnapshotPtrWrap(virDomainSnapshotPtr node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virDomainSnapshotPtr", NULL); return ret; } PyObject * libvirt_virEventHandleCallbackWrap(virEventHandleCallback node) { PyObject *ret; if (node == NULL) { printf("%s: WARNING - Wrapping None\n", __func__); return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virEventHandleCallback", NULL); return ret; } PyObject * libvirt_virEventTimeoutCallbackWrap(virEventTimeoutCallback node) { PyObject *ret; if (node == NULL) { printf("%s: WARNING - Wrapping None\n", __func__); return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virEventTimeoutCallback", NULL); return ret; } PyObject * libvirt_virFreeCallbackWrap(virFreeCallback node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "virFreeCallback", NULL); return ret; } PyObject * libvirt_virVoidPtrWrap(void* node) { PyObject *ret; if (node == NULL) { return VIR_PY_NONE; } ret = libvirt_buildPyObject(node, "void*", NULL); return ret; } ./libvirt-python-9.10.0/typewrappers.h0000644000000000000000000002202214555064067016356 0ustar rootroot/* * libvirt_wrap.h: type wrappers for libvir python bindings * * Copyright (C) 2005, 2011-2012 Red Hat, Inc. * * Daniel Veillard <veillard@redhat.com> */ #include <Python.h> #include <stdbool.h> #include <libvirt/libvirt.h> #include <libvirt/virterror.h> #ifdef __GNUC__ # ifdef ATTRIBUTE_UNUSED # undef ATTRIBUTE_UNUSED # endif # ifndef ATTRIBUTE_UNUSED # define ATTRIBUTE_UNUSED __attribute__ ((__unused__)) # endif /* ATTRIBUTE_UNUSED */ #else # define ATTRIBUTE_UNUSED #endif #if !LIBVIR_CHECK_VERSION(4, 5, 0) typedef struct _virNWFilterBinding *virNWFilterBindingPtr; #endif #if !LIBVIR_CHECK_VERSION(5, 5, 0) typedef struct _virNetworkPort *virNetworkPortPtr; #endif #if !LIBVIR_CHECK_VERSION(5, 6, 0) typedef struct _virDomainCheckpoint *virDomainCheckpointPtr; #endif #define PyvirConnect_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirConnect_Object *)(v))->obj)) typedef struct { PyObject_HEAD virConnectPtr obj; } PyvirConnect_Object; #define PyvirDomain_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirDomain_Object *)(v))->obj)) typedef struct { PyObject_HEAD virDomainPtr obj; } PyvirDomain_Object; #define PyvirNetwork_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirNetwork_Object *)(v))->obj)) typedef struct { PyObject_HEAD virNetworkPtr obj; } PyvirNetwork_Object; #define PyvirNetworkPort_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirNetworkPort_Object *)(v))->obj)) typedef struct { PyObject_HEAD virNetworkPortPtr obj; } PyvirNetworkPort_Object; #define PyvirInterface_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirInterface_Object *)(v))->obj)) typedef struct { PyObject_HEAD virInterfacePtr obj; } PyvirInterface_Object; #define PyvirStoragePool_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirStoragePool_Object *)(v))->obj)) typedef struct { PyObject_HEAD virStoragePoolPtr obj; } PyvirStoragePool_Object; #define PyvirStorageVol_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirStorageVol_Object *)(v))->obj)) typedef struct { PyObject_HEAD virStorageVolPtr obj; } PyvirStorageVol_Object; #define PyvirNodeDevice_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirNodeDevice_Object *)(v))->obj)) typedef struct { PyObject_HEAD virNodeDevicePtr obj; } PyvirNodeDevice_Object; #define PyvirSecret_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirSecret_Object *)(v))->obj)) typedef struct { PyObject_HEAD virSecretPtr obj; } PyvirSecret_Object; #define PyvirNWFilter_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirNWFilter_Object *)(v))->obj)) typedef struct { PyObject_HEAD virNWFilterPtr obj; } PyvirNWFilter_Object; #define PyvirNWFilterBinding_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirNWFilterBinding_Object *)(v))->obj)) typedef struct { PyObject_HEAD virNWFilterBindingPtr obj; } PyvirNWFilterBinding_Object; #define PyvirStream_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirStream_Object *)(v))->obj)) typedef struct { PyObject_HEAD virStreamPtr obj; } PyvirStream_Object; #define PyvirDomainCheckpoint_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirDomainCheckpoint_Object *)(v))->obj)) typedef struct { PyObject_HEAD virDomainCheckpointPtr obj; } PyvirDomainCheckpoint_Object; #define PyvirDomainSnapshot_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirDomainSnapshot_Object *)(v))->obj)) typedef struct { PyObject_HEAD virDomainSnapshotPtr obj; } PyvirDomainSnapshot_Object; #define PyvirEventHandleCallback_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirEventHandleCallback_Object *)(v))->obj)) typedef struct { PyObject_HEAD virEventHandleCallback obj; } PyvirEventHandleCallback_Object; #define PyvirEventTimeoutCallback_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirEventTimeoutCallback_Object *)(v))->obj)) typedef struct { PyObject_HEAD virEventTimeoutCallback obj; } PyvirEventTimeoutCallback_Object; #define PyvirFreeCallback_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirFreeCallback_Object *)(v))->obj)) typedef struct { PyObject_HEAD virFreeCallback obj; } PyvirFreeCallback_Object; #define PyvirVoidPtr_Get(v) (((v) == Py_None) ? NULL : \ (((PyvirVoidPtr_Object *)(v))->obj)) typedef struct { PyObject_HEAD void* obj; } PyvirVoidPtr_Object; PyObject * libvirt_intWrap(int val); PyObject * libvirt_uintWrap(unsigned int val); PyObject * libvirt_longWrap(long val); PyObject * libvirt_ulongWrap(unsigned long val); PyObject * libvirt_longlongWrap(long long val); PyObject * libvirt_ulonglongWrap(unsigned long long val); PyObject * libvirt_charPtrWrap(char *str); PyObject * libvirt_charPtrSizeWrap(char *str, Py_ssize_t size); PyObject * libvirt_constcharPtrWrap(const char *str); PyObject * libvirt_boolWrap(int val); int libvirt_intUnwrap(PyObject *obj, int *val); int libvirt_uintUnwrap(PyObject *obj, unsigned int *val); int libvirt_longUnwrap(PyObject *obj, long *val); int libvirt_ulongUnwrap(PyObject *obj, unsigned long *val); int libvirt_longlongUnwrap(PyObject *obj, long long *val); int libvirt_ulonglongUnwrap(PyObject *obj, unsigned long long *val); int libvirt_doubleUnwrap(PyObject *obj, double *val); int libvirt_boolUnwrap(PyObject *obj, bool *val); int libvirt_charPtrUnwrap(PyObject *obj, char **str); int libvirt_charPtrSizeUnwrap(PyObject *obj, char **str, Py_ssize_t *size); PyObject * libvirt_virConnectPtrWrap(virConnectPtr node); PyObject * libvirt_virDomainPtrWrap(virDomainPtr node); PyObject * libvirt_virNetworkPtrWrap(virNetworkPtr node); PyObject * libvirt_virNetworkPortPtrWrap(virNetworkPortPtr node); PyObject * libvirt_virInterfacePtrWrap(virInterfacePtr node); PyObject * libvirt_virStoragePoolPtrWrap(virStoragePoolPtr node); PyObject * libvirt_virStorageVolPtrWrap(virStorageVolPtr node); PyObject * libvirt_virEventHandleCallbackWrap(virEventHandleCallback node); PyObject * libvirt_virEventTimeoutCallbackWrap(virEventTimeoutCallback node); PyObject * libvirt_virFreeCallbackWrap(virFreeCallback node); PyObject * libvirt_virVoidPtrWrap(void* node); PyObject * libvirt_virNodeDevicePtrWrap(virNodeDevicePtr node); PyObject * libvirt_virSecretPtrWrap(virSecretPtr node); PyObject * libvirt_virNWFilterPtrWrap(virNWFilterPtr node); PyObject * libvirt_virNWFilterBindingPtrWrap(virNWFilterBindingPtr node); PyObject * libvirt_virStreamPtrWrap(virStreamPtr node); PyObject * libvirt_virDomainCheckpointPtrWrap(virDomainCheckpointPtr node); PyObject * libvirt_virDomainSnapshotPtrWrap(virDomainSnapshotPtr node); /* Provide simple macro statement wrappers (adapted from GLib, in turn from Perl): * LIBVIRT_STMT_START { statements; } LIBVIRT_STMT_END; * can be used as a single statement, as in * if (x) LIBVIRT_STMT_START { ... } LIBVIRT_STMT_END; else ... * * When GCC is compiling C code in non-ANSI mode, it will use the * compiler __extension__ to wrap the statements within `({' and '})' braces. * When compiling on platforms where configure has defined * HAVE_DOWHILE_MACROS, statements will be wrapped with `do' and `while (0)'. * For any other platforms (SunOS4 is known to have this issue), wrap the * statements with `if (1)' and `else (void) 0'. */ #if !(defined (LIBVIRT_STMT_START) && defined (LIBVIRT_STMT_END)) # if defined (__GNUC__) && !defined (__STRICT_ANSI__) && !defined (__cplusplus) # define LIBVIRT_STMT_START (void) __extension__ ( # define LIBVIRT_STMT_END ) # else /* !(__GNUC__ && !__STRICT_ANSI__ && !__cplusplus) */ # if defined (HAVE_DOWHILE_MACROS) # define LIBVIRT_STMT_START do # define LIBVIRT_STMT_END while (0) # else /* !HAVE_DOWHILE_MACROS */ # define LIBVIRT_STMT_START if (1) # define LIBVIRT_STMT_END else (void) 0 # endif /* !HAVE_DOWHILE_MACROS */ # endif /* !(__GNUC__ && !__STRICT_ANSI__ && !__cplusplus) */ #endif #if PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 7 # define LIBVIRT_BEGIN_ALLOW_THREADS \ LIBVIRT_STMT_START { \ PyThreadState *_save = NULL; \ if (PyEval_ThreadsInitialized()) \ _save = PyEval_SaveThread(); # define LIBVIRT_END_ALLOW_THREADS \ if (PyEval_ThreadsInitialized()) \ PyEval_RestoreThread(_save); \ } LIBVIRT_STMT_END # define LIBVIRT_ENSURE_THREAD_STATE \ LIBVIRT_STMT_START { \ PyGILState_STATE _save = PyGILState_UNLOCKED; \ if (PyEval_ThreadsInitialized()) \ _save = PyGILState_Ensure(); # define LIBVIRT_RELEASE_THREAD_STATE \ if (PyEval_ThreadsInitialized()) \ PyGILState_Release(_save); \ } LIBVIRT_STMT_END #else # define LIBVIRT_BEGIN_ALLOW_THREADS \ LIBVIRT_STMT_START { \ PyThreadState *_save = PyEval_SaveThread(); # define LIBVIRT_END_ALLOW_THREADS \ PyEval_RestoreThread(_save); \ } LIBVIRT_STMT_END # define LIBVIRT_ENSURE_THREAD_STATE \ LIBVIRT_STMT_START { \ PyGILState_STATE _save = PyGILState_Ensure(); # define LIBVIRT_RELEASE_THREAD_STATE \ PyGILState_Release(_save); \ } LIBVIRT_STMT_END #endif #ifndef NULLSTR #define NULLSTR(s) ((s) ? (s) : "<null>") #endif ./libvirt-python-9.10.0/VERSION0000644000000000000000000000000714555064757014515 0ustar rootroot9.10.0 ./libvirt-python-9.10.0/libvirt-override.c0000644000000000000000000121023414555064757017107 0ustar rootroot/* * libvir.c: this modules implements the main part of the glue of the * libvir library and the Python interpreter. It provides the * entry points where an automatically generated stub is * unpractical * * Copyright (C) 2005-2019 Red Hat, Inc. * * Daniel Veillard <veillard@redhat.com> */ /* Horrible kludge to work around even more horrible name-space pollution via Python.h. That file includes /usr/include/python3.x/pyconfig*.h, which has over 180 autoconf-style HAVE_* definitions. Shame on them. */ #undef HAVE_PTHREAD_H /* We want to see *_LAST enums. */ #define VIR_ENUM_SENTINELS #define PY_SSIZE_T_CLEAN #include <stdio.h> #include <string.h> #include <Python.h> #include <libvirt/libvirt.h> #include <libvirt/virterror.h> #include <stddef.h> #include "typewrappers.h" #include "build/libvirt.h" #include "libvirt-utils.h" #ifndef __CYGWIN__ extern PyObject *PyInit_libvirtmod(void); #else extern PyObject *PyInit_cygvirtmod(void); #endif #if 0 # define DEBUG_ERROR 1 #endif #if DEBUG_ERROR # define DEBUG(fmt, ...) \ printf(fmt, __VA_ARGS__) #else # define DEBUG(fmt, ...) \ while (0) {printf(fmt, __VA_ARGS__);} #endif /* * Utility function to retrieve the number of node CPUs present. * It first tries virNodeGetCPUMap, which will return the * number reliably, if available. * As a fallback and for compatibility with backlevel libvirt * versions virNodeGetInfo will be called to calculate the * CPU number, which has the potential to return a too small * number if some host CPUs are offline. */ static int getPyNodeCPUCount(virConnectPtr conn) { int i_retval; #if LIBVIR_CHECK_VERSION(1, 0, 0) LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNodeGetCPUMap(conn, NULL, NULL, 0); LIBVIRT_END_ALLOW_THREADS; #else /* fallback: use nodeinfo */ virNodeInfo nodeinfo; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNodeGetInfo(conn, &nodeinfo); LIBVIRT_END_ALLOW_THREADS; if (i_retval >= 0) i_retval = VIR_NODEINFO_MAXCPUS(nodeinfo); #endif /* LIBVIR_CHECK_VERSION(1, 0, 0) */ return i_retval; } /************************************************************************ * * * Statistics * * * ************************************************************************/ static PyObject * libvirt_virDomainBlockStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; char * path; int c_retval; virDomainBlockStatsStruct stats; PyObject *info; if (!PyArg_ParseTuple(args, (char *)"Oz:virDomainBlockStats", &pyobj_domain, &path)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainBlockStats(domain, path, &stats, sizeof(stats)); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; /* convert to a Python tuple of long objects */ if ((info = PyTuple_New(5)) == NULL) return NULL; VIR_PY_TUPLE_SET_GOTO(info, 0, libvirt_longlongWrap(stats.rd_req), error); VIR_PY_TUPLE_SET_GOTO(info, 1, libvirt_longlongWrap(stats.rd_bytes), error); VIR_PY_TUPLE_SET_GOTO(info, 2, libvirt_longlongWrap(stats.wr_req), error); VIR_PY_TUPLE_SET_GOTO(info, 3, libvirt_longlongWrap(stats.wr_bytes), error); VIR_PY_TUPLE_SET_GOTO(info, 4, libvirt_longlongWrap(stats.errs), error); return info; error: Py_DECREF(info); return NULL; } static PyObject * libvirt_virDomainBlockStatsFlags(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *ret = NULL; int i_retval; int nparams = 0; unsigned int flags; virTypedParameterPtr params; const char *path; if (!PyArg_ParseTuple(args, (char *)"OzI:virDomainBlockStatsFlags", &pyobj_domain, &path, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainBlockStatsFlags(domain, path, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; if (!nparams) return PyDict_New(); if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainBlockStatsFlags(domain, path, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } static PyObject * libvirt_virDomainGetCPUStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *totalbool; PyObject *ret = NULL; PyObject *error = NULL; int ncpus = -1, start_cpu = 0; int sumparams = 0, nparams = -1; ssize_t i; int i_retval; unsigned int flags; bool totalflag; virTypedParameterPtr params = NULL, cpuparams; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainGetCPUStats", &pyobj_domain, &totalbool, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (libvirt_boolUnwrap(totalbool, &totalflag) < 0) return NULL; if ((ret = PyList_New(0)) == NULL) return NULL; if (!totalflag) { LIBVIRT_BEGIN_ALLOW_THREADS; ncpus = virDomainGetCPUStats(domain, NULL, 0, 0, 0, flags); LIBVIRT_END_ALLOW_THREADS; if (ncpus < 0) { error = VIR_PY_NONE; goto error; } LIBVIRT_BEGIN_ALLOW_THREADS; nparams = virDomainGetCPUStats(domain, NULL, 0, 0, 1, flags); LIBVIRT_END_ALLOW_THREADS; if (nparams < 0) { error = VIR_PY_NONE; goto error; } sumparams = nparams * MIN(ncpus, 128); if (VIR_ALLOC_N(params, sumparams) < 0) { error = PyErr_NoMemory(); goto error; } while (ncpus) { int queried_ncpus = MIN(ncpus, 128); if (nparams) { LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetCPUStats(domain, params, nparams, start_cpu, queried_ncpus, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { error = VIR_PY_NONE; goto error; } } else { i_retval = 0; } for (i = 0; i < queried_ncpus; i++) { cpuparams = ¶ms[i * nparams]; VIR_PY_LIST_APPEND_GOTO(ret, getPyVirTypedParameter(cpuparams, i_retval), error); } start_cpu += queried_ncpus; ncpus -= queried_ncpus; virTypedParamsClear(params, sumparams); } } else { LIBVIRT_BEGIN_ALLOW_THREADS; nparams = virDomainGetCPUStats(domain, NULL, 0, -1, 1, flags); LIBVIRT_END_ALLOW_THREADS; if (nparams < 0) { error = VIR_PY_NONE; goto error; } if (nparams) { sumparams = nparams; if (VIR_ALLOC_N(params, nparams) < 0) { error = PyErr_NoMemory(); goto error; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetCPUStats(domain, params, nparams, -1, 1, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { error = VIR_PY_NONE; goto error; } } else { i_retval = 0; } VIR_PY_LIST_APPEND_GOTO(ret, getPyVirTypedParameter(params, i_retval), error); } virTypedParamsFree(params, sumparams); return ret; error: virTypedParamsFree(params, sumparams); Py_DECREF(ret); return error; } static PyObject * libvirt_virDomainInterfaceStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; char * path; int c_retval; virDomainInterfaceStatsStruct stats; PyObject *info; if (!PyArg_ParseTuple(args, (char *)"Oz:virDomainInterfaceStats", &pyobj_domain, &path)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainInterfaceStats(domain, path, &stats, sizeof(stats)); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; /* convert to a Python tuple of long objects */ if ((info = PyTuple_New(8)) == NULL) return NULL; VIR_PY_TUPLE_SET_GOTO(info, 0, libvirt_longlongWrap(stats.rx_bytes), error); VIR_PY_TUPLE_SET_GOTO(info, 1, libvirt_longlongWrap(stats.rx_packets), error); VIR_PY_TUPLE_SET_GOTO(info, 2, libvirt_longlongWrap(stats.rx_errs), error); VIR_PY_TUPLE_SET_GOTO(info, 3, libvirt_longlongWrap(stats.rx_drop), error); VIR_PY_TUPLE_SET_GOTO(info, 4, libvirt_longlongWrap(stats.tx_bytes), error); VIR_PY_TUPLE_SET_GOTO(info, 5, libvirt_longlongWrap(stats.tx_packets), error); VIR_PY_TUPLE_SET_GOTO(info, 6, libvirt_longlongWrap(stats.tx_errs), error); VIR_PY_TUPLE_SET_GOTO(info, 7, libvirt_longlongWrap(stats.tx_drop), error); return info; error: Py_DECREF(info); return NULL; } static PyObject * libvirt_virDomainMemoryStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; unsigned int nr_stats; size_t i; virDomainMemoryStatStruct stats[VIR_DOMAIN_MEMORY_STAT_NR]; PyObject *info; PyObject *key = NULL, *val = NULL; if (!PyArg_ParseTuple(args, (char *)"O:virDomainMemoryStats", &pyobj_domain)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; nr_stats = virDomainMemoryStats(domain, stats, VIR_DOMAIN_MEMORY_STAT_NR, 0); LIBVIRT_END_ALLOW_THREADS; if (nr_stats == (unsigned int)-1) return VIR_PY_NONE; /* convert to a Python dictionary */ if ((info = PyDict_New()) == NULL) return NULL; for (i = 0; i < nr_stats; i++) { switch (stats[i].tag) { case VIR_DOMAIN_MEMORY_STAT_SWAP_IN: key = libvirt_constcharPtrWrap("swap_in"); break; case VIR_DOMAIN_MEMORY_STAT_SWAP_OUT: key = libvirt_constcharPtrWrap("swap_out"); break; case VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT: key = libvirt_constcharPtrWrap("major_fault"); break; case VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT: key = libvirt_constcharPtrWrap("minor_fault"); break; case VIR_DOMAIN_MEMORY_STAT_UNUSED: key = libvirt_constcharPtrWrap("unused"); break; case VIR_DOMAIN_MEMORY_STAT_AVAILABLE: key = libvirt_constcharPtrWrap("available"); break; case VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON: key = libvirt_constcharPtrWrap("actual"); break; case VIR_DOMAIN_MEMORY_STAT_RSS: key = libvirt_constcharPtrWrap("rss"); break; #if LIBVIR_CHECK_VERSION(2, 1, 0) case VIR_DOMAIN_MEMORY_STAT_USABLE: key = libvirt_constcharPtrWrap("usable"); break; case VIR_DOMAIN_MEMORY_STAT_LAST_UPDATE: key = libvirt_constcharPtrWrap("last_update"); break; #endif /* LIBVIR_CHECK_VERSION(2, 1, 0) */ #if LIBVIR_CHECK_VERSION(4, 6, 0) case VIR_DOMAIN_MEMORY_STAT_DISK_CACHES: key = libvirt_constcharPtrWrap("disk_caches"); break; #endif /* LIBVIR_CHECK_VERSION(4, 6, 0) */ #if LIBVIR_CHECK_VERSION(5, 4, 0) case VIR_DOMAIN_MEMORY_STAT_HUGETLB_PGALLOC: key = libvirt_constcharPtrWrap("hugetlb_pgalloc"); break; case VIR_DOMAIN_MEMORY_STAT_HUGETLB_PGFAIL: key = libvirt_constcharPtrWrap("hugetlb_pgfail"); break; #endif /* LIBVIR_CHECK_VERSION(5, 4, 0) */ default: continue; } val = libvirt_ulonglongWrap(stats[i].val); VIR_PY_DICT_SET_GOTO(info, key, val, error); } return info; error: Py_DECREF(info); return NULL; } static PyObject * libvirt_virDomainGetSchedulerType(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *info; char *c_retval; int nparams; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetScedulerType", &pyobj_domain)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetSchedulerType(domain, &nparams); LIBVIRT_END_ALLOW_THREADS; if (c_retval == NULL) return VIR_PY_NONE; /* convert to a Python tuple of long objects */ if ((info = PyTuple_New(2)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(info, 0, libvirt_constcharPtrWrap(c_retval), error); VIR_PY_TUPLE_SET_GOTO(info, 1, libvirt_intWrap(nparams), error); cleanup: VIR_FREE(c_retval); return info; error: Py_CLEAR(info); goto cleanup; } static PyObject * libvirt_virDomainGetSchedulerParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *ret = NULL; char *c_retval; int i_retval; int nparams = 0; virTypedParameterPtr params; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetScedulerParameters", &pyobj_domain)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetSchedulerType(domain, &nparams); LIBVIRT_END_ALLOW_THREADS; if (c_retval == NULL) return VIR_PY_NONE; VIR_FREE(c_retval); if (!nparams) return PyDict_New(); if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetSchedulerParameters(domain, params, &nparams); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } static PyObject * libvirt_virDomainGetSchedulerParametersFlags(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *ret = NULL; char *c_retval; int i_retval; int nparams = 0; unsigned int flags; virTypedParameterPtr params; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetScedulerParametersFlags", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetSchedulerType(domain, &nparams); LIBVIRT_END_ALLOW_THREADS; if (c_retval == NULL) return VIR_PY_NONE; VIR_FREE(c_retval); if (!nparams) return PyDict_New(); if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetSchedulerParametersFlags(domain, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } static PyObject * libvirt_virDomainSetSchedulerParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *info; PyObject *ret = NULL; char *c_retval; int i_retval; int nparams = 0; Py_ssize_t size = 0; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OO:virDomainSetSchedulerParameters", &pyobj_domain, &info)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetSchedulerType(domain, &nparams); LIBVIRT_END_ALLOW_THREADS; if (c_retval == NULL) return VIR_PY_INT_FAIL; VIR_FREE(c_retval); if (nparams == 0) { PyErr_Format(PyExc_LookupError, "Domain has no settable attributes"); return NULL; } if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetSchedulerParameters(domain, params, &nparams); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainSetSchedulerParameters(domain, new_params, size); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } static PyObject * libvirt_virDomainSetSchedulerParametersFlags(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *info; PyObject *ret = NULL; char *c_retval; int i_retval; int nparams = 0; Py_ssize_t size = 0; unsigned int flags; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainSetSchedulerParametersFlags", &pyobj_domain, &info, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetSchedulerType(domain, &nparams); LIBVIRT_END_ALLOW_THREADS; if (c_retval == NULL) return VIR_PY_INT_FAIL; VIR_FREE(c_retval); if (nparams == 0) { PyErr_Format(PyExc_LookupError, "Domain has no settable attributes"); return NULL; } if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetSchedulerParametersFlags(domain, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainSetSchedulerParametersFlags(domain, new_params, size, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } static PyObject * libvirt_virDomainSetBlkioParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *info; PyObject *ret = NULL; int i_retval; int nparams = 0; Py_ssize_t size = 0; unsigned int flags; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainSetBlkioParameters", &pyobj_domain, &info, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetBlkioParameters(domain, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_INT_FAIL; if (nparams == 0) { PyErr_Format(PyExc_LookupError, "Domain has no settable attributes"); return NULL; } if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetBlkioParameters(domain, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainSetBlkioParameters(domain, new_params, size, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } static PyObject * libvirt_virDomainGetBlkioParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *ret = NULL; int i_retval; int nparams = 0; unsigned int flags; virTypedParameterPtr params; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetBlkioParameters", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetBlkioParameters(domain, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; if (!nparams) return PyDict_New(); if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetBlkioParameters(domain, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } static PyObject * libvirt_virDomainSetMemoryParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *info; PyObject *ret = NULL; int i_retval; int nparams = 0; Py_ssize_t size = 0; unsigned int flags; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainSetMemoryParameters", &pyobj_domain, &info, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetMemoryParameters(domain, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_INT_FAIL; if (nparams == 0) { PyErr_Format(PyExc_LookupError, "Domain has no settable attributes"); return NULL; } if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetMemoryParameters(domain, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainSetMemoryParameters(domain, new_params, size, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } static PyObject * libvirt_virDomainGetMemoryParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *ret = NULL; int i_retval; int nparams = 0; unsigned int flags; virTypedParameterPtr params; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetMemoryParameters", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetMemoryParameters(domain, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; if (!nparams) return PyDict_New(); if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetMemoryParameters(domain, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } static PyObject * libvirt_virDomainSetNumaParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *info; PyObject *ret = NULL; int i_retval; int nparams = 0; Py_ssize_t size = 0; unsigned int flags; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainSetNumaParameters", &pyobj_domain, &info, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetNumaParameters(domain, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_INT_FAIL; if (nparams == 0) { PyErr_Format(PyExc_LookupError, "Domain has no settable attributes"); return NULL; } if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetNumaParameters(domain, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainSetNumaParameters(domain, new_params, size, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } static PyObject * libvirt_virDomainGetNumaParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *ret = NULL; int i_retval; int nparams = 0; unsigned int flags; virTypedParameterPtr params; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetNumaParameters", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetNumaParameters(domain, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; if (!nparams) return PyDict_New(); if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetNumaParameters(domain, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } static PyObject * libvirt_virDomainSetInterfaceParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *info; PyObject *ret = NULL; int i_retval; int nparams = 0; Py_ssize_t size = 0; unsigned int flags; const char *device = NULL; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OzOI:virDomainSetInterfaceParameters", &pyobj_domain, &device, &info, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetInterfaceParameters(domain, device, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_INT_FAIL; if (nparams == 0) { PyErr_Format(PyExc_LookupError, "Domain has no settable attributes"); return NULL; } if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetInterfaceParameters(domain, device, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainSetInterfaceParameters(domain, device, new_params, size, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } static PyObject * libvirt_virDomainGetInterfaceParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *ret = NULL; int i_retval; int nparams = 0; unsigned int flags; const char *device = NULL; virTypedParameterPtr params; if (!PyArg_ParseTuple(args, (char *)"OzI:virDomainGetInterfaceParameters", &pyobj_domain, &device, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetInterfaceParameters(domain, device, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; if (!nparams) return PyDict_New(); if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetInterfaceParameters(domain, device, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } static PyObject * libvirt_virDomainGetVcpus(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *pyretval = NULL; PyObject *pycpuinfo = NULL, *pycpumap = NULL; PyObject *error = NULL; virDomainInfo dominfo; virVcpuInfoPtr cpuinfo = NULL; unsigned char *cpumap = NULL; ssize_t cpumaplen, i; int i_retval, cpunum; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetVcpus", &pyobj_domain)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((cpunum = getPyNodeCPUCount(virDomainGetConnect(domain))) < 0) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetInfo(domain, &dominfo); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; if (VIR_ALLOC_N(cpuinfo, dominfo.nrVirtCpu) < 0) return PyErr_NoMemory(); cpumaplen = VIR_CPU_MAPLEN(cpunum); if (xalloc_oversized(dominfo.nrVirtCpu, cpumaplen) || VIR_ALLOC_N(cpumap, dominfo.nrVirtCpu * cpumaplen) < 0) { error = PyErr_NoMemory(); goto cleanup; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetVcpus(domain, cpuinfo, dominfo.nrVirtCpu, cpumap, cpumaplen); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { error = VIR_PY_NONE; goto cleanup; } /* convert to a Python tuple of long objects */ if ((pyretval = PyTuple_New(2)) == NULL) goto cleanup; if ((pycpuinfo = PyList_New(dominfo.nrVirtCpu)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyretval, 0, pycpuinfo, cleanup); if ((pycpumap = PyList_New(dominfo.nrVirtCpu)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyretval, 1, pycpumap, cleanup); for (i = 0; i < dominfo.nrVirtCpu; i++) { PyObject *info = PyTuple_New(4); if (info == NULL) goto cleanup; VIR_PY_LIST_SET_GOTO(pycpuinfo, i, info, cleanup); VIR_PY_TUPLE_SET_GOTO(info, 0, libvirt_intWrap(cpuinfo[i].number), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 1, libvirt_intWrap(cpuinfo[i].state), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 2, libvirt_ulonglongWrap(cpuinfo[i].cpuTime), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 3, libvirt_intWrap(cpuinfo[i].cpu), cleanup); } for (i = 0; i < dominfo.nrVirtCpu; i++) { PyObject *info = PyTuple_New(cpunum); ssize_t j; if (info == NULL) goto cleanup; VIR_PY_LIST_SET_GOTO(pycpumap, i, info, cleanup); for (j = 0; j < cpunum; j++) { VIR_PY_TUPLE_SET_GOTO(info, j, PyBool_FromLong(VIR_CPU_USABLE(cpumap, cpumaplen, i, j)), cleanup); } } VIR_FREE(cpuinfo); VIR_FREE(cpumap); return pyretval; cleanup: VIR_FREE(cpuinfo); VIR_FREE(cpumap); Py_XDECREF(pyretval); return error; } static PyObject * libvirt_virDomainPinVcpu(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *pycpumap; PyObject *ret = NULL; unsigned char *cpumap; int cpumaplen, vcpu, cpunum; int i_retval; if (!PyArg_ParseTuple(args, (char *)"OiO:virDomainPinVcpu", &pyobj_domain, &vcpu, &pycpumap)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((cpunum = getPyNodeCPUCount(virDomainGetConnect(domain))) < 0) return VIR_PY_INT_FAIL; if (virPyCpumapConvert(cpunum, pycpumap, &cpumap, &cpumaplen) < 0) return NULL; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainPinVcpu(domain, vcpu, cpumap, cpumaplen); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: VIR_FREE(cpumap); return ret; } static PyObject * libvirt_virDomainPinVcpuFlags(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *pycpumap; PyObject *ret = NULL; unsigned char *cpumap; int cpumaplen, vcpu, cpunum; unsigned int flags; int i_retval; if (!PyArg_ParseTuple(args, (char *)"OiOI:virDomainPinVcpuFlags", &pyobj_domain, &vcpu, &pycpumap, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((cpunum = getPyNodeCPUCount(virDomainGetConnect(domain))) < 0) return VIR_PY_INT_FAIL; if (virPyCpumapConvert(cpunum, pycpumap, &cpumap, &cpumaplen) < 0) return NULL; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainPinVcpuFlags(domain, vcpu, cpumap, cpumaplen, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: VIR_FREE(cpumap); return ret; } static PyObject * libvirt_virDomainGetVcpuPinInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *pycpumaps = NULL, *error = NULL; virDomainInfo dominfo; unsigned char *cpumaps = NULL; ssize_t cpumaplen, vcpu, pcpu; unsigned int flags; int i_retval, cpunum; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetVcpuPinInfo", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((cpunum = getPyNodeCPUCount(virDomainGetConnect(domain))) < 0) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetInfo(domain, &dominfo); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; cpumaplen = VIR_CPU_MAPLEN(cpunum); if (xalloc_oversized(dominfo.nrVirtCpu, cpumaplen) || VIR_ALLOC_N(cpumaps, dominfo.nrVirtCpu * cpumaplen) < 0) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetVcpuPinInfo(domain, dominfo.nrVirtCpu, cpumaps, cpumaplen, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { error = VIR_PY_NONE; goto cleanup; } if ((pycpumaps = PyList_New(dominfo.nrVirtCpu)) == NULL) goto cleanup; for (vcpu = 0; vcpu < dominfo.nrVirtCpu; vcpu++) { PyObject *mapinfo = PyTuple_New(cpunum); if (mapinfo == NULL) goto cleanup; VIR_PY_LIST_SET_GOTO(pycpumaps, vcpu, mapinfo, cleanup); for (pcpu = 0; pcpu < cpunum; pcpu++) { VIR_PY_TUPLE_SET_GOTO(mapinfo, pcpu, PyBool_FromLong(VIR_CPU_USABLE(cpumaps, cpumaplen, vcpu, pcpu)), cleanup); } } VIR_FREE(cpumaps); return pycpumaps; cleanup: VIR_FREE(cpumaps); Py_XDECREF(pycpumaps); return error; } #if LIBVIR_CHECK_VERSION(0, 10, 0) static PyObject * libvirt_virDomainPinEmulator(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *pycpumap; unsigned char *cpumap = NULL; int cpumaplen, cpunum; int i_retval; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainPinEmulator", &pyobj_domain, &pycpumap, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((cpunum = getPyNodeCPUCount(virDomainGetConnect(domain))) < 0) return VIR_PY_INT_FAIL; if (virPyCpumapConvert(cpunum, pycpumap, &cpumap, &cpumaplen) < 0) return NULL; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainPinEmulator(domain, cpumap, cpumaplen, flags); LIBVIRT_END_ALLOW_THREADS; VIR_FREE(cpumap); if (i_retval < 0) return VIR_PY_INT_FAIL; return VIR_PY_INT_SUCCESS; } static PyObject * libvirt_virDomainGetEmulatorPinInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *pycpumap; unsigned char *cpumap; ssize_t cpumaplen; ssize_t pcpu; unsigned int flags; int ret; int cpunum; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetEmulatorPinInfo", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((cpunum = getPyNodeCPUCount(virDomainGetConnect(domain))) < 0) return VIR_PY_NONE; cpumaplen = VIR_CPU_MAPLEN(cpunum); if (VIR_ALLOC_N(cpumap, cpumaplen) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virDomainGetEmulatorPinInfo(domain, cpumap, cpumaplen, flags); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { VIR_FREE(cpumap); return VIR_PY_NONE; } if (!(pycpumap = PyTuple_New(cpunum))) { VIR_FREE(cpumap); return NULL; } for (pcpu = 0; pcpu < cpunum; pcpu++) { VIR_PY_TUPLE_SET_GOTO(pycpumap, pcpu, PyBool_FromLong(VIR_CPU_USABLE(cpumap, cpumaplen, 0, pcpu)), error); } cleanup: VIR_FREE(cpumap); return pycpumap; error: Py_CLEAR(pycpumap); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 0) */ #if LIBVIR_CHECK_VERSION(1, 2, 14) static PyObject * libvirt_virDomainGetIOThreadInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *py_retval = NULL; PyObject *py_iothrinfo = NULL; virDomainIOThreadInfoPtr *iothrinfo = NULL; unsigned int flags; ssize_t pcpu, i; int niothreads, cpunum; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetIOThreadInfo", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((cpunum = getPyNodeCPUCount(virDomainGetConnect(domain))) < 0) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; niothreads = virDomainGetIOThreadInfo(domain, &iothrinfo, flags); LIBVIRT_END_ALLOW_THREADS; if (niothreads < 0) { py_retval = VIR_PY_NONE; goto cleanup; } /* convert to a Python list */ if ((py_iothrinfo = PyList_New(niothreads)) == NULL) goto cleanup; /* NOTE: If there are zero IOThreads we will return an empty list */ for (i = 0; i < niothreads; i++) { PyObject *iothrtpl = NULL; PyObject *iothrmap = NULL; virDomainIOThreadInfoPtr iothr = iothrinfo[i]; if (iothr == NULL) { py_retval = VIR_PY_NONE; goto cleanup; } if ((iothrtpl = PyTuple_New(2)) == NULL) goto cleanup; VIR_PY_LIST_SET_GOTO(py_iothrinfo, i, iothrtpl, cleanup); /* 0: IOThread ID */ VIR_PY_TUPLE_SET_GOTO(iothrtpl, 0, libvirt_uintWrap(iothr->iothread_id), cleanup); /* 1: CPU map */ if ((iothrmap = PyList_New(cpunum)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(iothrtpl, 1, iothrmap, cleanup); for (pcpu = 0; pcpu < cpunum; pcpu++) if (VIR_CPU_MAPLEN(pcpu + 1) > iothr->cpumaplen) { VIR_PY_LIST_SET_GOTO(iothrmap, pcpu, PyBool_FromLong(0), cleanup); } else { VIR_PY_LIST_SET_GOTO(iothrmap, pcpu, PyBool_FromLong(VIR_CPU_USED(iothr->cpumap, pcpu)), cleanup); } } py_retval = py_iothrinfo; py_iothrinfo = NULL; cleanup: if (niothreads > 0) { for (i = 0; i < niothreads; i++) virDomainIOThreadInfoFree(iothrinfo[i]); } VIR_FREE(iothrinfo); Py_XDECREF(py_iothrinfo); return py_retval; } static PyObject * libvirt_virDomainPinIOThread(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *pycpumap; PyObject *ret = NULL; unsigned char *cpumap; int cpumaplen, iothread_val, cpunum; unsigned int flags; int i_retval; if (!PyArg_ParseTuple(args, (char *)"OiOI:virDomainPinIOThread", &pyobj_domain, &iothread_val, &pycpumap, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((cpunum = getPyNodeCPUCount(virDomainGetConnect(domain))) < 0) return VIR_PY_INT_FAIL; if (virPyCpumapConvert(cpunum, pycpumap, &cpumap, &cpumaplen) < 0) return NULL; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainPinIOThread(domain, iothread_val, cpumap, cpumaplen, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: VIR_FREE(cpumap); return ret; } #endif /* LIBVIR_CHECK_VERSION(1, 2, 14) */ #if LIBVIR_CHECK_VERSION(4, 10, 0) static virPyTypedParamsHint virPyDomainSetIOThreadParams[] = { { VIR_DOMAIN_IOTHREAD_POLL_MAX_NS, VIR_TYPED_PARAM_ULLONG }, { VIR_DOMAIN_IOTHREAD_POLL_GROW, VIR_TYPED_PARAM_UINT }, { VIR_DOMAIN_IOTHREAD_POLL_SHRINK, VIR_TYPED_PARAM_UINT }, # if LIBVIR_CHECK_VERSION(8, 5, 0) { VIR_DOMAIN_IOTHREAD_THREAD_POOL_MIN, VIR_TYPED_PARAM_INT }, { VIR_DOMAIN_IOTHREAD_THREAD_POOL_MAX, VIR_TYPED_PARAM_INT }, # endif /* LIBVIR_CHECK_VERSION(8, 5, 0) */ }; static PyObject * libvirt_virDomainSetIOThreadParams(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_dom = NULL; PyObject *pyobj_dict = NULL; virDomainPtr dom; int iothread_val; virTypedParameterPtr params = NULL; int nparams = 0; unsigned int flags; int c_retval; if (!PyArg_ParseTuple(args, (char *)"OiOI:virDomainSetIOThreadParams", &pyobj_dom, &iothread_val, &pyobj_dict, &flags)) return NULL; if (PyDict_Check(pyobj_dict)) { if (virPyDictToTypedParams(pyobj_dict, ¶ms, &nparams, virPyDomainSetIOThreadParams, VIR_N_ELEMENTS(virPyDomainSetIOThreadParams)) < 0) { return NULL; } } else { PyErr_Format(PyExc_TypeError, "IOThread polling params must be " "a dictionary"); return NULL; } dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainSetIOThreadParams(dom, iothread_val, params, nparams, flags); LIBVIRT_END_ALLOW_THREADS; virTypedParamsFree(params, nparams); return libvirt_intWrap(c_retval); } #endif /* LIBVIR_CHECK_VERSION(4, 10, 0) */ /************************************************************************ * * * Global error handler at the Python level * * * ************************************************************************/ static PyObject *libvirt_virPythonErrorFuncHandler = NULL; static PyObject *libvirt_virPythonErrorFuncCtxt = NULL; static PyObject * libvirt_virGetLastError(PyObject *self ATTRIBUTE_UNUSED, PyObject *args ATTRIBUTE_UNUSED) { virError *err; PyObject *info; if ((err = virGetLastError()) == NULL) return VIR_PY_NONE; if ((info = PyTuple_New(9)) == NULL) return NULL; VIR_PY_TUPLE_SET_GOTO(info, 0, libvirt_intWrap(err->code), error); VIR_PY_TUPLE_SET_GOTO(info, 1, libvirt_intWrap(err->domain), error); VIR_PY_TUPLE_SET_GOTO(info, 2, libvirt_constcharPtrWrap(err->message), error); VIR_PY_TUPLE_SET_GOTO(info, 3, libvirt_intWrap(err->level), error); VIR_PY_TUPLE_SET_GOTO(info, 4, libvirt_constcharPtrWrap(err->str1), error); VIR_PY_TUPLE_SET_GOTO(info, 5, libvirt_constcharPtrWrap(err->str2), error); VIR_PY_TUPLE_SET_GOTO(info, 6, libvirt_constcharPtrWrap(err->str3), error); VIR_PY_TUPLE_SET_GOTO(info, 7, libvirt_intWrap(err->int1), error); VIR_PY_TUPLE_SET_GOTO(info, 8, libvirt_intWrap(err->int2), error); return info; error: Py_XDECREF(info); return NULL; } static PyObject * libvirt_virConnGetLastError(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virError *err; PyObject *info; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConGetLastError", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; err = virConnGetLastError(conn); LIBVIRT_END_ALLOW_THREADS; if (err == NULL) return VIR_PY_NONE; if ((info = PyTuple_New(9)) == NULL) return NULL; VIR_PY_TUPLE_SET_GOTO(info, 0, libvirt_intWrap(err->code), error); VIR_PY_TUPLE_SET_GOTO(info, 1, libvirt_intWrap(err->domain), error); VIR_PY_TUPLE_SET_GOTO(info, 2, libvirt_constcharPtrWrap(err->message), error); VIR_PY_TUPLE_SET_GOTO(info, 3, libvirt_intWrap(err->level), error); VIR_PY_TUPLE_SET_GOTO(info, 4, libvirt_constcharPtrWrap(err->str1), error); VIR_PY_TUPLE_SET_GOTO(info, 5, libvirt_constcharPtrWrap(err->str2), error); VIR_PY_TUPLE_SET_GOTO(info, 6, libvirt_constcharPtrWrap(err->str3), error); VIR_PY_TUPLE_SET_GOTO(info, 7, libvirt_intWrap(err->int1), error); VIR_PY_TUPLE_SET_GOTO(info, 8, libvirt_intWrap(err->int2), error); return info; error: Py_XDECREF(info); return NULL; } static void libvirt_virErrorFuncHandler(ATTRIBUTE_UNUSED void *ctx, virErrorPtr err) { PyObject *list = NULL, *info = NULL; PyObject *result; DEBUG("libvirt_virErrorFuncHandler(%p, %s, ...) called\n", ctx, err->message); if ((err == NULL) || (err->code == VIR_ERR_OK)) return; LIBVIRT_ENSURE_THREAD_STATE; if ((libvirt_virPythonErrorFuncHandler == NULL) || (libvirt_virPythonErrorFuncHandler == Py_None)) { virDefaultErrorFunc(err); } else { if ((list = PyTuple_New(2)) == NULL) goto cleanup; Py_XINCREF(libvirt_virPythonErrorFuncCtxt); VIR_PY_TUPLE_SET_GOTO(list, 0, libvirt_virPythonErrorFuncCtxt, cleanup); if ((info = PyTuple_New(9)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(list, 1, info, cleanup); VIR_PY_TUPLE_SET_GOTO(info, 0, libvirt_intWrap(err->code), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 1, libvirt_intWrap(err->domain), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 2, libvirt_constcharPtrWrap(err->message), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 3, libvirt_intWrap(err->level), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 4, libvirt_constcharPtrWrap(err->str1), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 5, libvirt_constcharPtrWrap(err->str2), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 6, libvirt_constcharPtrWrap(err->str3), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 7, libvirt_intWrap(err->int1), cleanup); VIR_PY_TUPLE_SET_GOTO(info, 8, libvirt_intWrap(err->int2), cleanup); /* TODO pass conn and dom if available */ result = PyObject_Call(libvirt_virPythonErrorFuncHandler, list, NULL); Py_XDECREF(result); } cleanup: Py_XDECREF(list); LIBVIRT_RELEASE_THREAD_STATE; } static PyObject * libvirt_virRegisterErrorHandler(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) { PyObject *py_retval; PyObject *pyobj_f; PyObject *pyobj_ctx; if (!PyArg_ParseTuple(args, (char *) "OO:virRegisterErrorHandler", &pyobj_f, &pyobj_ctx)) return NULL; DEBUG("libvirt_virRegisterErrorHandler(%p, %p) called\n", pyobj_ctx, pyobj_f); virSetErrorFunc(NULL, libvirt_virErrorFuncHandler); Py_XDECREF(libvirt_virPythonErrorFuncHandler); Py_XDECREF(libvirt_virPythonErrorFuncCtxt); if ((pyobj_f == Py_None) && (pyobj_ctx == Py_None)) { libvirt_virPythonErrorFuncHandler = NULL; libvirt_virPythonErrorFuncCtxt = NULL; } else { Py_XINCREF(pyobj_ctx); Py_XINCREF(pyobj_f); /* TODO: check f is a function ! */ libvirt_virPythonErrorFuncHandler = pyobj_f; libvirt_virPythonErrorFuncCtxt = pyobj_ctx; } py_retval = libvirt_intWrap(1); return py_retval; } static int virConnectCredCallbackWrapper(virConnectCredentialPtr cred, unsigned int ncred, void *cbdata) { PyObject *list = NULL; PyObject *pycred; PyObject *pyauth = (PyObject *)cbdata; PyObject *pycbdata; PyObject *pycb; PyObject *pyret = NULL; int ret = -1; size_t i; LIBVIRT_ENSURE_THREAD_STATE; pycb = PyList_GetItem(pyauth, 1); pycbdata = PyList_GetItem(pyauth, 2); if ((list = PyTuple_New(2)) == NULL) goto cleanup; if ((pycred = PyTuple_New(ncred)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(list, 0, pycred, cleanup); for (i = 0; i < ncred; i++) { PyObject *pycreditem; if ((pycreditem = PyList_New(5)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pycred, i, pycreditem, cleanup); VIR_PY_LIST_SET_GOTO(pycreditem, 0, libvirt_intWrap(cred[i].type), cleanup); VIR_PY_LIST_SET_GOTO(pycreditem, 1, libvirt_constcharPtrWrap(cred[i].prompt), cleanup); if (cred[i].challenge) { VIR_PY_LIST_SET_GOTO(pycreditem, 2, libvirt_constcharPtrWrap(cred[i].challenge), cleanup); } else { VIR_PY_LIST_SET_GOTO(pycreditem, 2, VIR_PY_NONE, cleanup); } if (cred[i].defresult) { VIR_PY_LIST_SET_GOTO(pycreditem, 3, libvirt_constcharPtrWrap(cred[i].defresult), cleanup); } else { VIR_PY_LIST_SET_GOTO(pycreditem, 3, VIR_PY_NONE, cleanup); } VIR_PY_LIST_SET_GOTO(pycreditem, 4, VIR_PY_NONE, cleanup); } Py_XINCREF(pycbdata); VIR_PY_TUPLE_SET_GOTO(list, 1, pycbdata, cleanup); PyErr_Clear(); pyret = PyObject_Call(pycb, list, NULL); if (PyErr_Occurred()) { PyErr_Print(); goto cleanup; } ret = PyLong_AsLong(pyret); if (ret == 0) { for (i = 0; i < ncred; i++) { PyObject *pycreditem; PyObject *pyresult; char *result = NULL; pycreditem = PyTuple_GetItem(pycred, i); pyresult = PyList_GetItem(pycreditem, 4); if (pyresult != Py_None) { libvirt_charPtrUnwrap(pyresult, &result); PyErr_Clear(); } if (result != NULL) { cred[i].result = result; cred[i].resultlen = strlen(result); } else { cred[i].result = NULL; cred[i].resultlen = 0; } } } cleanup: Py_XDECREF(list); Py_XDECREF(pyret); LIBVIRT_RELEASE_THREAD_STATE; return ret; } static PyObject * libvirt_virConnectOpenAuth(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; virConnectPtr c_retval = NULL; char * name; unsigned int flags; PyObject *pyauth; PyObject *pycredcb; PyObject *pycredtype; virConnectAuth auth; memset(&auth, 0, sizeof(auth)); if (!PyArg_ParseTuple(args, (char *)"zOI:virConnectOpenAuth", &name, &pyauth, &flags)) return NULL; pycredtype = PyList_GetItem(pyauth, 0); pycredcb = PyList_GetItem(pyauth, 1); auth.ncredtype = PyList_Size(pycredtype); if (auth.ncredtype) { size_t i; if (VIR_ALLOC_N(auth.credtype, auth.ncredtype) < 0) return PyErr_NoMemory(); for (i = 0; i < auth.ncredtype; i++) { PyObject *val; val = PyList_GetItem(pycredtype, i); if (libvirt_intUnwrap(val, &auth.credtype[i]) < 0) goto cleanup; } } if (pycredcb && pycredcb != Py_None) auth.cb = virConnectCredCallbackWrapper; auth.cbdata = pyauth; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectOpenAuth(name, &auth, flags); LIBVIRT_END_ALLOW_THREADS; cleanup: VIR_FREE(auth.credtype); py_retval = libvirt_virConnectPtrWrap((virConnectPtr) c_retval); return py_retval; } /************************************************************************ * * * Wrappers for functions where generator fails * * * ************************************************************************/ static PyObject * libvirt_virGetVersion(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { char *type = NULL; unsigned long libVer, typeVer = 0; int c_retval; if (!PyArg_ParseTuple(args, (char *) "|s:virGetVersion", &type)) return NULL; LIBVIRT_BEGIN_ALLOW_THREADS; if (type == NULL) c_retval = virGetVersion(&libVer, NULL, NULL); else c_retval = virGetVersion(&libVer, type, &typeVer); LIBVIRT_END_ALLOW_THREADS; if (c_retval == -1) return VIR_PY_NONE; if (type == NULL) return libvirt_intWrap(libVer); else return Py_BuildValue((char *) "kk", libVer, typeVer); } static PyObject * libvirt_virConnectGetVersion(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { unsigned long hvVersion; int c_retval; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectGetVersion", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectGetVersion(conn, &hvVersion); LIBVIRT_END_ALLOW_THREADS; if (c_retval == -1) return VIR_PY_INT_FAIL; return libvirt_intWrap(hvVersion); } #if LIBVIR_CHECK_VERSION(1, 1, 3) static PyObject * libvirt_virConnectGetCPUModelNames(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int c_retval; virConnectPtr conn; PyObject *rv = NULL, *pyobj_conn; char **models = NULL; ssize_t i; unsigned int flags = 0; const char *arch = NULL; if (!PyArg_ParseTuple(args, (char *)"OsI:virConnectGetCPUModelNames", &pyobj_conn, &arch, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectGetCPUModelNames(conn, arch, &models, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval == -1) return VIR_PY_NONE; if ((rv = PyList_New(c_retval)) == NULL) goto error; for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(rv, i, libvirt_constcharPtrWrap(models[i]), error); done: if (models) { for (i = 0; i < c_retval; i++) VIR_FREE(models[i]); VIR_FREE(models); } return rv; error: Py_CLEAR(rv); goto done; } #endif /* LIBVIR_CHECK_VERSION(1, 1, 3) */ static PyObject * libvirt_virConnectGetLibVersion(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { unsigned long libVer; int c_retval; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectGetLibVersion", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectGetLibVersion(conn, &libVer); LIBVIRT_END_ALLOW_THREADS; if (c_retval == -1) return VIR_PY_INT_FAIL; return libvirt_intWrap(libVer); } static PyObject * libvirt_virConnectListDomainsID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int *ids = NULL, c_retval; ssize_t i; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListDomains", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfDomains(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(ids, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListDomains(conn, ids, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (ids) for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_intWrap(ids[i]), error); cleanup: VIR_FREE(ids); return py_retval; error: VIR_FREE(ids); Py_XDECREF(py_retval); return NULL; } #if LIBVIR_CHECK_VERSION(0, 9, 13) static PyObject * libvirt_virConnectListAllDomains(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval = NULL; virConnectPtr conn; virDomainPtr *doms = NULL; int c_retval = 0; ssize_t i; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virConnectListAllDomains", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListAllDomains(conn, &doms, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virDomainPtrWrap(doms[i]), error); /* python steals the pointer */ doms[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (doms[i]) virDomainFree(doms[i]); VIR_FREE(doms); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 9, 13) */ static PyObject * libvirt_virConnectListDefinedDomains(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListDefinedDomains", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfDefinedDomains(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListDefinedDomains(conn, names, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (names) { for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); } cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(5, 6, 0) static PyObject * libvirt_virDomainListAllCheckpoints(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; virDomainCheckpointPtr *chks = NULL; int c_retval; ssize_t i; virDomainPtr dom; PyObject *pyobj_dom; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainListAllCheckpoints", &pyobj_dom, &flags)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainListAllCheckpoints(dom, &chks, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virDomainCheckpointPtrWrap(chks[i]), error); chks[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (chks[i]) virDomainCheckpointFree(chks[i]); VIR_FREE(chks); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } static PyObject * libvirt_virDomainCheckpointListAllChildren(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; virDomainCheckpointPtr *chks = NULL; int c_retval; ssize_t i; virDomainCheckpointPtr parent; PyObject *pyobj_parent; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainCheckpointListAllChildren", &pyobj_parent, &flags)) return NULL; parent = (virDomainCheckpointPtr) PyvirDomainCheckpoint_Get(pyobj_parent); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainCheckpointListAllChildren(parent, &chks, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virDomainCheckpointPtrWrap(chks[i]), error); chks[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (chks[i]) virDomainCheckpointFree(chks[i]); VIR_FREE(chks); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(5, 6, 0) */ static PyObject * libvirt_virDomainSnapshotListNames(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virDomainPtr dom; PyObject *pyobj_dom; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainSnapshotListNames", &pyobj_dom, &flags)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainSnapshotNum(dom, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainSnapshotListNames(dom, names, c_retval, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } py_retval = PyList_New(c_retval); if (!py_retval) goto cleanup; for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(0, 9, 13) static PyObject * libvirt_virDomainListAllSnapshots(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; virDomainSnapshotPtr *snaps = NULL; int c_retval; ssize_t i; virDomainPtr dom; PyObject *pyobj_dom; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainListAllSnapshots", &pyobj_dom, &flags)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainListAllSnapshots(dom, &snaps, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virDomainSnapshotPtrWrap(snaps[i]), error); snaps[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (snaps[i]) virDomainSnapshotFree(snaps[i]); VIR_FREE(snaps); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 9, 13) */ static PyObject * libvirt_virDomainSnapshotListChildrenNames(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virDomainSnapshotPtr snap; PyObject *pyobj_snap; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainSnapshotListChildrenNames", &pyobj_snap, &flags)) return NULL; snap = (virDomainSnapshotPtr) PyvirDomainSnapshot_Get(pyobj_snap); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainSnapshotNumChildren(snap, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainSnapshotListChildrenNames(snap, names, c_retval, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(0, 9, 13) static PyObject * libvirt_virDomainSnapshotListAllChildren(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; virDomainSnapshotPtr *snaps = NULL; int c_retval; ssize_t i; virDomainSnapshotPtr parent; PyObject *pyobj_parent; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainSnapshotListAllChildren", &pyobj_parent, &flags)) return NULL; parent = (virDomainSnapshotPtr) PyvirDomainSnapshot_Get(pyobj_parent); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainSnapshotListAllChildren(parent, &snaps, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virDomainSnapshotPtrWrap(snaps[i]), error); snaps[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (snaps[i]) virDomainSnapshotFree(snaps[i]); VIR_FREE(snaps); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 9, 13) */ static PyObject * libvirt_virDomainRevertToSnapshot(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int c_retval; virDomainSnapshotPtr snap; PyObject *pyobj_snap; PyObject *pyobj_dom; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainRevertToSnapshot", &pyobj_dom, &pyobj_snap, &flags)) return NULL; snap = (virDomainSnapshotPtr) PyvirDomainSnapshot_Get(pyobj_snap); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainRevertToSnapshot(snap, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_INT_FAIL; return libvirt_intWrap(c_retval); } static PyObject * libvirt_virDomainGetInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; virDomainInfo info; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetInfo", &pyobj_domain)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetInfo(domain, &info); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(5)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_intWrap(info.state), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_ulongWrap(info.maxMem), error); VIR_PY_LIST_SET_GOTO(py_retval, 2, libvirt_ulongWrap(info.memory), error); VIR_PY_LIST_SET_GOTO(py_retval, 3, libvirt_intWrap(info.nrVirtCpu), error); VIR_PY_LIST_SET_GOTO(py_retval, 4, libvirt_ulonglongWrap(info.cpuTime), error); return py_retval; error: Py_XDECREF(py_retval); return NULL; } static PyObject * libvirt_virDomainGetState(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; int state; int reason; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetState", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetState(domain, &state, &reason, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(2)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_intWrap(state), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_intWrap(reason), error); return py_retval; error: Py_XDECREF(py_retval); return NULL; } static PyObject * libvirt_virDomainGetControlInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; virDomainControlInfo info; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetControlInfo", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetControlInfo(domain, &info, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(3)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_intWrap(info.state), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_intWrap(info.details), error); VIR_PY_LIST_SET_GOTO(py_retval, 2, libvirt_ulonglongWrap(info.stateTime), error); return py_retval; error: Py_XDECREF(py_retval); return NULL; } static PyObject * libvirt_virDomainGetBlockInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; virDomainBlockInfo info; const char *path; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OzI:virDomainGetBlockInfo", &pyobj_domain, &path, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetBlockInfo(domain, path, &info, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(3)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_ulonglongWrap(info.capacity), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_ulonglongWrap(info.allocation), error); VIR_PY_LIST_SET_GOTO(py_retval, 2, libvirt_ulonglongWrap(info.physical), error); return py_retval; error: Py_XDECREF(py_retval); return NULL; } static PyObject * libvirt_virNodeGetInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virConnectPtr conn; PyObject *pyobj_conn; virNodeInfo info; if (!PyArg_ParseTuple(args, (char *)"O:virNodeGetInfo", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeGetInfo(conn, &info); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(8)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_constcharPtrWrap(&info.model[0]), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_ulongWrap(info.memory >> 10), error); VIR_PY_LIST_SET_GOTO(py_retval, 2, libvirt_intWrap(info.cpus), error); VIR_PY_LIST_SET_GOTO(py_retval, 3, libvirt_intWrap(info.mhz), error); VIR_PY_LIST_SET_GOTO(py_retval, 4, libvirt_intWrap(info.nodes), error); VIR_PY_LIST_SET_GOTO(py_retval, 5, libvirt_intWrap(info.sockets), error); VIR_PY_LIST_SET_GOTO(py_retval, 6, libvirt_intWrap(info.cores), error); VIR_PY_LIST_SET_GOTO(py_retval, 7, libvirt_intWrap(info.threads), error); return py_retval; error: Py_XDECREF(py_retval); return NULL; } static PyObject * libvirt_virNodeGetSecurityModel(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virConnectPtr conn; PyObject *pyobj_conn; virSecurityModel model; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetSecurityModel", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeGetSecurityModel(conn, &model); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(2)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_constcharPtrWrap(&model.model[0]), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_constcharPtrWrap(&model.doi[0]), error); return py_retval; error: Py_XDECREF(py_retval); return NULL; } static PyObject * libvirt_virDomainGetSecurityLabel(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virDomainPtr dom; PyObject *pyobj_dom; virSecurityLabel label; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetSecurityLabel", &pyobj_dom)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetSecurityLabel(dom, &label); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(2)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_constcharPtrWrap(&label.label[0]), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_boolWrap(label.enforcing), error); return py_retval; error: Py_XDECREF(py_retval); return NULL; } #if LIBVIR_CHECK_VERSION(0, 10, 0) static PyObject * libvirt_virDomainGetSecurityLabelList(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virDomainPtr dom; PyObject *pyobj_dom; virSecurityLabel *labels = NULL; ssize_t i; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetSecurityLabelList", &pyobj_dom)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetSecurityLabelList(dom, &labels); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(0))) goto error; for (i = 0 ; i < c_retval ; i++) { PyObject *entry; if (!(entry = PyList_New(2))) goto error; VIR_PY_LIST_APPEND_GOTO(py_retval, entry, error); VIR_PY_LIST_SET_GOTO(entry, 0, libvirt_constcharPtrWrap(&labels[i].label[0]), error); VIR_PY_LIST_SET_GOTO(entry, 1, libvirt_boolWrap(labels[i].enforcing), error); } cleanup: VIR_FREE(labels); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 0) */ static PyObject * libvirt_virDomainGetUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { unsigned char uuid[VIR_UUID_BUFLEN]; virDomainPtr domain; PyObject *pyobj_domain; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetUUID", &pyobj_domain)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (domain == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetUUID(domain, &uuid[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_charPtrSizeWrap((char *) &uuid[0], VIR_UUID_BUFLEN); } static PyObject * libvirt_virDomainGetUUIDString(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { char uuidstr[VIR_UUID_STRING_BUFLEN]; virDomainPtr dom; PyObject *pyobj_dom; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetUUIDString", &pyobj_dom)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); if (dom == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetUUIDString(dom, &uuidstr[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_constcharPtrWrap((char *) &uuidstr[0]); } static PyObject * libvirt_virDomainLookupByUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr c_retval; virConnectPtr conn; PyObject *pyobj_conn; unsigned char * uuid; Py_ssize_t len; if (!PyArg_ParseTuple(args, (char *)"Oz#:virDomainLookupByUUID", &pyobj_conn, &uuid, &len)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if ((uuid == NULL) || (len != VIR_UUID_BUFLEN)) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainLookupByUUID(conn, uuid); LIBVIRT_END_ALLOW_THREADS; return libvirt_virDomainPtrWrap((virDomainPtr) c_retval); } static PyObject * libvirt_virConnectListNetworks(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListNetworks", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfNetworks(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListNetworks(conn, names, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (names) for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } static PyObject * libvirt_virConnectListDefinedNetworks(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListDefinedNetworks", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfDefinedNetworks(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListDefinedNetworks(conn, names, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(0, 10, 2) static PyObject * libvirt_virConnectListAllNetworks(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval = NULL; virConnectPtr conn; virNetworkPtr *nets = NULL; int c_retval = 0; ssize_t i; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virConnectListAllNetworks", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListAllNetworks(conn, &nets, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virNetworkPtrWrap(nets[i]), error); nets[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (nets[i]) virNetworkFree(nets[i]); VIR_FREE(nets); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ static PyObject * libvirt_virNetworkGetUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { unsigned char uuid[VIR_UUID_BUFLEN]; virNetworkPtr domain; PyObject *pyobj_domain; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virNetworkGetUUID", &pyobj_domain)) return NULL; domain = (virNetworkPtr) PyvirNetwork_Get(pyobj_domain); if (domain == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNetworkGetUUID(domain, &uuid[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_charPtrSizeWrap((char *) &uuid[0], VIR_UUID_BUFLEN); } static PyObject * libvirt_virNetworkGetUUIDString(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { char uuidstr[VIR_UUID_STRING_BUFLEN]; virNetworkPtr net; PyObject *pyobj_net; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virNetworkGetUUIDString", &pyobj_net)) return NULL; net = (virNetworkPtr) PyvirNetwork_Get(pyobj_net); if (net == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNetworkGetUUIDString(net, &uuidstr[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_constcharPtrWrap((char *) &uuidstr[0]); } static PyObject * libvirt_virNetworkLookupByUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virNetworkPtr c_retval; virConnectPtr conn; PyObject *pyobj_conn; unsigned char * uuid; Py_ssize_t len; if (!PyArg_ParseTuple(args, (char *)"Oz#:virNetworkLookupByUUID", &pyobj_conn, &uuid, &len)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if ((uuid == NULL) || (len != VIR_UUID_BUFLEN)) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNetworkLookupByUUID(conn, uuid); LIBVIRT_END_ALLOW_THREADS; return libvirt_virNetworkPtrWrap((virNetworkPtr) c_retval); } static PyObject * libvirt_virDomainGetAutostart(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int c_retval, autostart; virDomainPtr domain; PyObject *pyobj_domain; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetAutostart", &pyobj_domain)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetAutostart(domain, &autostart); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_INT_FAIL; return libvirt_intWrap(autostart); } static PyObject * libvirt_virNetworkGetAutostart(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int c_retval, autostart; virNetworkPtr network; PyObject *pyobj_network; if (!PyArg_ParseTuple(args, (char *)"O:virNetworkGetAutostart", &pyobj_network)) return NULL; network = (virNetworkPtr) PyvirNetwork_Get(pyobj_network); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNetworkGetAutostart(network, &autostart); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_INT_FAIL; return libvirt_intWrap(autostart); } #if LIBVIR_CHECK_VERSION(7, 8, 0) static PyObject * libvirt_virNodeDeviceGetAutostart(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int c_retval, autostart; virNodeDevicePtr dev; PyObject *pyobj_dev; if (!PyArg_ParseTuple(args, (char *)"O:virNodeDeviceGetAutostart", &pyobj_dev)) return NULL; dev = (virNodeDevicePtr) PyvirNodeDevice_Get(pyobj_dev); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeDeviceGetAutostart(dev, &autostart); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_INT_FAIL; return libvirt_intWrap(autostart); } #endif /* LIBVIR_CHECK_VERSION(7, 8, 0) */ static PyObject * libvirt_virNodeGetCellsFreeMemory(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; PyObject *pyobj_conn; int startCell, maxCells, c_retval; ssize_t i; virConnectPtr conn; unsigned long long *freeMems; if (!PyArg_ParseTuple(args, (char *)"Oii:virNodeGetCellsFreeMemory", &pyobj_conn, &startCell, &maxCells)) return NULL; if ((startCell < 0) || (maxCells <= 0) || (startCell + maxCells > 10000)) return VIR_PY_NONE; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if (VIR_ALLOC_N(freeMems, maxCells) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeGetCellsFreeMemory(conn, freeMems, startCell, maxCells); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_ulonglongWrap(freeMems[i]), error); cleanup: VIR_FREE(freeMems); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } static PyObject * libvirt_virNodeGetCPUStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *ret = NULL; PyObject *key = NULL; PyObject *val = NULL; PyObject *pyobj_conn; virConnectPtr conn; unsigned int flags; int cpuNum, c_retval; ssize_t i; int nparams = 0; virNodeCPUStatsPtr stats = NULL; if (!PyArg_ParseTuple(args, (char *)"OiI:virNodeGetCPUStats", &pyobj_conn, &cpuNum, &flags)) return ret; conn = (virConnectPtr)(PyvirConnect_Get(pyobj_conn)); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeGetCPUStats(conn, cpuNum, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (nparams) { if (VIR_ALLOC_N(stats, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeGetCPUStats(conn, cpuNum, stats, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { VIR_FREE(stats); return VIR_PY_NONE; } } if (!(ret = PyDict_New())) goto error; for (i = 0; i < nparams; i++) { key = libvirt_constcharPtrWrap(stats[i].field); val = libvirt_ulonglongWrap(stats[i].value); VIR_PY_DICT_SET_GOTO(ret, key, val, error); } cleanup: VIR_FREE(stats); return ret; error: Py_CLEAR(ret); goto cleanup; } static PyObject * libvirt_virNodeGetMemoryStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *ret = NULL; PyObject *key = NULL; PyObject *val = NULL; PyObject *pyobj_conn; virConnectPtr conn; unsigned int flags; int cellNum, c_retval; ssize_t i; int nparams = 0; virNodeMemoryStatsPtr stats = NULL; if (!PyArg_ParseTuple(args, (char *)"OiI:virNodeGetMemoryStats", &pyobj_conn, &cellNum, &flags)) return NULL; conn = (virConnectPtr)(PyvirConnect_Get(pyobj_conn)); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeGetMemoryStats(conn, cellNum, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (nparams) { if (VIR_ALLOC_N(stats, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeGetMemoryStats(conn, cellNum, stats, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { VIR_FREE(stats); return VIR_PY_NONE; } } if (!(ret = PyDict_New())) goto error; for (i = 0; i < nparams; i++) { key = libvirt_constcharPtrWrap(stats[i].field); val = libvirt_ulonglongWrap(stats[i].value); VIR_PY_DICT_SET_GOTO(ret, key, val, error); } cleanup: VIR_FREE(stats); return ret; error: Py_CLEAR(ret); goto cleanup; } static PyObject * libvirt_virConnectListStoragePools(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListStoragePools", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfStoragePools(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListStoragePools(conn, names, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } static PyObject * libvirt_virConnectListDefinedStoragePools(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListDefinedStoragePools", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfDefinedStoragePools(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListDefinedStoragePools(conn, names, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (names) { for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); } cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(0, 10, 2) static PyObject * libvirt_virConnectListAllStoragePools(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval = NULL; virConnectPtr conn; virStoragePoolPtr *pools = NULL; int c_retval = 0; ssize_t i; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virConnectListAllStoragePools", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListAllStoragePools(conn, &pools, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virStoragePoolPtrWrap(pools[i]), error); /* python steals the pointer */ pools[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (pools[i]) virStoragePoolFree(pools[i]); VIR_FREE(pools); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ static PyObject * libvirt_virStoragePoolListVolumes(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virStoragePoolPtr pool; PyObject *pyobj_pool; if (!PyArg_ParseTuple(args, (char *)"O:virStoragePoolListVolumes", &pyobj_pool)) return NULL; pool = (virStoragePoolPtr) PyvirStoragePool_Get(pyobj_pool); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStoragePoolNumOfVolumes(pool); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStoragePoolListVolumes(pool, names, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (names) for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(0, 10, 2) static PyObject * libvirt_virStoragePoolListAllVolumes(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; virStoragePoolPtr pool; virStorageVolPtr *vols = NULL; int c_retval = 0; ssize_t i; unsigned int flags; PyObject *pyobj_pool; if (!PyArg_ParseTuple(args, (char *)"OI:virStoragePoolListAllVolumes", &pyobj_pool, &flags)) return NULL; pool = (virStoragePoolPtr) PyvirStoragePool_Get(pyobj_pool); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStoragePoolListAllVolumes(pool, &vols, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virStorageVolPtrWrap(vols[i]), error); /* python steals the pointer */ vols[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (vols[i]) virStorageVolFree(vols[i]); VIR_FREE(vols); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ static PyObject * libvirt_virStoragePoolGetAutostart(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int c_retval, autostart; virStoragePoolPtr pool; PyObject *pyobj_pool; if (!PyArg_ParseTuple(args, (char *)"O:virStoragePoolGetAutostart", &pyobj_pool)) return NULL; pool = (virStoragePoolPtr) PyvirStoragePool_Get(pyobj_pool); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStoragePoolGetAutostart(pool, &autostart); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_INT_FAIL; return libvirt_intWrap(autostart); } static PyObject * libvirt_virStoragePoolGetInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virStoragePoolPtr pool; PyObject *pyobj_pool; virStoragePoolInfo info; if (!PyArg_ParseTuple(args, (char *)"O:virStoragePoolGetInfo", &pyobj_pool)) return NULL; pool = (virStoragePoolPtr) PyvirStoragePool_Get(pyobj_pool); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStoragePoolGetInfo(pool, &info); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(4)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_intWrap(info.state), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_ulonglongWrap(info.capacity), error); VIR_PY_LIST_SET_GOTO(py_retval, 2, libvirt_ulonglongWrap(info.allocation), error); VIR_PY_LIST_SET_GOTO(py_retval, 3, libvirt_ulonglongWrap(info.available), error); return py_retval; error: Py_XDECREF(py_retval); return NULL; } static PyObject * libvirt_virStorageVolGetInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virStorageVolPtr pool; PyObject *pyobj_pool; virStorageVolInfo info; if (!PyArg_ParseTuple(args, (char *)"O:virStorageVolGetInfo", &pyobj_pool)) return NULL; pool = (virStorageVolPtr) PyvirStorageVol_Get(pyobj_pool); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStorageVolGetInfo(pool, &info); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(3)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_intWrap(info.type), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_ulonglongWrap(info.capacity), error); VIR_PY_LIST_SET_GOTO(py_retval, 2, libvirt_ulonglongWrap(info.allocation), error); return py_retval; error: Py_DECREF(py_retval); return NULL; } #if LIBVIR_CHECK_VERSION(3, 0, 0) static PyObject * libvirt_virStorageVolGetInfoFlags(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virStorageVolPtr pool; PyObject *pyobj_pool; virStorageVolInfo info; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virStorageVolGetInfoFlags", &pyobj_pool, &flags)) return NULL; pool = (virStorageVolPtr) PyvirStorageVol_Get(pyobj_pool); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStorageVolGetInfoFlags(pool, &info, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(3)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_intWrap(info.type), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_ulonglongWrap(info.capacity), error); VIR_PY_LIST_SET_GOTO(py_retval, 2, libvirt_ulonglongWrap(info.allocation), error); return py_retval; error: Py_DECREF(py_retval); return NULL; } #endif static PyObject * libvirt_virStoragePoolGetUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { unsigned char uuid[VIR_UUID_BUFLEN]; virStoragePoolPtr pool; PyObject *pyobj_pool; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virStoragePoolGetUUID", &pyobj_pool)) return NULL; pool = (virStoragePoolPtr) PyvirStoragePool_Get(pyobj_pool); if (pool == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStoragePoolGetUUID(pool, &uuid[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_charPtrSizeWrap((char *) &uuid[0], VIR_UUID_BUFLEN); } static PyObject * libvirt_virStoragePoolGetUUIDString(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { char uuidstr[VIR_UUID_STRING_BUFLEN]; virStoragePoolPtr pool; PyObject *pyobj_pool; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virStoragePoolGetUUIDString", &pyobj_pool)) return NULL; pool = (virStoragePoolPtr) PyvirStoragePool_Get(pyobj_pool); if (pool == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStoragePoolGetUUIDString(pool, &uuidstr[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_constcharPtrWrap((char *) &uuidstr[0]); } static PyObject * libvirt_virStoragePoolLookupByUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virStoragePoolPtr c_retval; virConnectPtr conn; PyObject *pyobj_conn; unsigned char * uuid; Py_ssize_t len; if (!PyArg_ParseTuple(args, (char *)"Oz#:virStoragePoolLookupByUUID", &pyobj_conn, &uuid, &len)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if ((uuid == NULL) || (len != VIR_UUID_BUFLEN)) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virStoragePoolLookupByUUID(conn, uuid); LIBVIRT_END_ALLOW_THREADS; return libvirt_virStoragePoolPtrWrap((virStoragePoolPtr) c_retval); } static PyObject * libvirt_virNodeListDevices(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virConnectPtr conn; PyObject *pyobj_conn; char *cap; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OzI:virNodeListDevices", &pyobj_conn, &cap, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeNumOfDevices(conn, cap, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeListDevices(conn, cap, names, c_retval, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (names) for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(0, 10, 2) static PyObject * libvirt_virConnectListAllNodeDevices(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval = NULL; virConnectPtr conn; virNodeDevicePtr *devices = NULL; int c_retval = 0; ssize_t i; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virConnectListAllNodeDevices", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListAllNodeDevices(conn, &devices, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virNodeDevicePtrWrap(devices[i]), error); /* python steals the pointer */ devices[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (devices[i]) virNodeDeviceFree(devices[i]); VIR_FREE(devices); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ static PyObject * libvirt_virNodeDeviceListCaps(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virNodeDevicePtr dev; PyObject *pyobj_dev; if (!PyArg_ParseTuple(args, (char *)"O:virNodeDeviceListCaps", &pyobj_dev)) return NULL; dev = (virNodeDevicePtr) PyvirNodeDevice_Get(pyobj_dev); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeDeviceNumOfCaps(dev); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeDeviceListCaps(dev, names, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (names) for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } static PyObject * libvirt_virSecretGetUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { unsigned char uuid[VIR_UUID_BUFLEN]; virSecretPtr secret; PyObject *pyobj_secret; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virSecretGetUUID", &pyobj_secret)) return NULL; secret = (virSecretPtr) PyvirSecret_Get(pyobj_secret); if (secret == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virSecretGetUUID(secret, &uuid[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_charPtrSizeWrap((char *) &uuid[0], VIR_UUID_BUFLEN); } static PyObject * libvirt_virSecretGetUUIDString(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { char uuidstr[VIR_UUID_STRING_BUFLEN]; virSecretPtr dom; PyObject *pyobj_dom; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virSecretGetUUIDString", &pyobj_dom)) return NULL; dom = (virSecretPtr) PyvirSecret_Get(pyobj_dom); if (dom == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virSecretGetUUIDString(dom, &uuidstr[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_constcharPtrWrap((char *) &uuidstr[0]); } static PyObject * libvirt_virSecretLookupByUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virSecretPtr c_retval; virConnectPtr conn; PyObject *pyobj_conn; unsigned char * uuid; Py_ssize_t len; if (!PyArg_ParseTuple(args, (char *)"Oz#:virSecretLookupByUUID", &pyobj_conn, &uuid, &len)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if ((uuid == NULL) || (len != VIR_UUID_BUFLEN)) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virSecretLookupByUUID(conn, uuid); LIBVIRT_END_ALLOW_THREADS; return libvirt_virSecretPtrWrap((virSecretPtr) c_retval); } static PyObject * libvirt_virConnectListSecrets(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **uuids = NULL; virConnectPtr conn; int c_retval; ssize_t i; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListSecrets", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfSecrets(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(uuids, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListSecrets(conn, uuids, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (uuids) { for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(uuids[i]), error); } cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(uuids[i]); VIR_FREE(uuids); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(0, 10, 2) static PyObject * libvirt_virConnectListAllSecrets(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval = NULL; virConnectPtr conn; virSecretPtr *secrets = NULL; int c_retval = 0; ssize_t i; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virConnectListAllSecrets", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListAllSecrets(conn, &secrets, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virSecretPtrWrap(secrets[i]), error); /* python steals the pointer */ secrets[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (secrets[i]) virSecretFree(secrets[i]); VIR_FREE(secrets); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ static PyObject * libvirt_virSecretGetValue(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; unsigned char *c_retval; size_t size; virSecretPtr secret; PyObject *pyobj_secret; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virSecretGetValue", &pyobj_secret, &flags)) return NULL; secret = (virSecretPtr) PyvirSecret_Get(pyobj_secret); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virSecretGetValue(secret, &size, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval == NULL) return VIR_PY_NONE; py_retval = libvirt_charPtrSizeWrap((char*)c_retval, size); VIR_FREE(c_retval); return py_retval; } static PyObject * libvirt_virSecretSetValue(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int c_retval; virSecretPtr secret; PyObject *pyobj_secret; const char *value; Py_ssize_t size; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"Oz#I:virSecretSetValue", &pyobj_secret, &value, &size, &flags)) return NULL; secret = (virSecretPtr) PyvirSecret_Get(pyobj_secret); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virSecretSetValue(secret, (const unsigned char *)value, (size_t) size, flags); LIBVIRT_END_ALLOW_THREADS; return libvirt_intWrap(c_retval); } static PyObject * libvirt_virNWFilterGetUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { unsigned char uuid[VIR_UUID_BUFLEN]; virNWFilterPtr nwfilter; PyObject *pyobj_nwfilter; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virNWFilterGetUUID", &pyobj_nwfilter)) return NULL; nwfilter = (virNWFilterPtr) PyvirNWFilter_Get(pyobj_nwfilter); if (nwfilter == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNWFilterGetUUID(nwfilter, &uuid[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_charPtrSizeWrap((char *) &uuid[0], VIR_UUID_BUFLEN); } static PyObject * libvirt_virNWFilterGetUUIDString(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { char uuidstr[VIR_UUID_STRING_BUFLEN]; virNWFilterPtr nwfilter; PyObject *pyobj_nwfilter; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virNWFilterGetUUIDString", &pyobj_nwfilter)) return NULL; nwfilter = (virNWFilterPtr) PyvirNWFilter_Get(pyobj_nwfilter); if (nwfilter == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNWFilterGetUUIDString(nwfilter, &uuidstr[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_constcharPtrWrap((char *) &uuidstr[0]); } static PyObject * libvirt_virNWFilterLookupByUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virNWFilterPtr c_retval; virConnectPtr conn; PyObject *pyobj_conn; unsigned char * uuid; Py_ssize_t len; if (!PyArg_ParseTuple(args, (char *)"Oz#:virNWFilterLookupByUUID", &pyobj_conn, &uuid, &len)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if ((uuid == NULL) || (len != VIR_UUID_BUFLEN)) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNWFilterLookupByUUID(conn, uuid); LIBVIRT_END_ALLOW_THREADS; return libvirt_virNWFilterPtrWrap((virNWFilterPtr) c_retval); } static PyObject * libvirt_virConnectListNWFilters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **uuids = NULL; virConnectPtr conn; int c_retval; ssize_t i; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListNWFilters", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfNWFilters(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(uuids, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListNWFilters(conn, uuids, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (uuids) for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(uuids[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(uuids[i]); VIR_FREE(uuids); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(0, 10, 2) static PyObject * libvirt_virConnectListAllNWFilters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval = NULL; virConnectPtr conn; virNWFilterPtr *filters = NULL; int c_retval = 0; ssize_t i; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virConnectListAllNWFilters", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListAllNWFilters(conn, &filters, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virNWFilterPtrWrap(filters[i]), error); /* python steals the pointer */ filters[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (filters[i]) virNWFilterFree(filters[i]); VIR_FREE(filters); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ #if LIBVIR_CHECK_VERSION(4, 5, 0) static PyObject * libvirt_virConnectListAllNWFilterBindings(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval = NULL; virConnectPtr conn; virNWFilterBindingPtr *bindings = NULL; int c_retval = 0; ssize_t i; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virConnectListAllNWFilterBindings", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListAllNWFilterBindings(conn, &bindings, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virNWFilterBindingPtrWrap(bindings[i]), error); /* python steals the pointer */ bindings[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (bindings[i]) virNWFilterBindingFree(bindings[i]); VIR_FREE(bindings); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(4, 5, 0) */ static PyObject * libvirt_virConnectListInterfaces(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListInterfaces", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfInterfaces(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListInterfaces(conn, names, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (names) for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } static PyObject * libvirt_virConnectListDefinedInterfaces(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; char **names = NULL; int c_retval; ssize_t i; virConnectPtr conn; PyObject *pyobj_conn; if (!PyArg_ParseTuple(args, (char *)"O:virConnectListDefinedInterfaces", &pyobj_conn)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectNumOfDefinedInterfaces(conn); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (c_retval) { if (VIR_ALLOC_N(names, c_retval) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListDefinedInterfaces(conn, names, c_retval); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if ((py_retval = PyList_New(c_retval)) == NULL) goto cleanup; if (names) { for (i = 0; i < c_retval; i++) VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_constcharPtrWrap(names[i]), error); } cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) VIR_FREE(names[i]); VIR_FREE(names); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(0, 10, 2) static PyObject * libvirt_virConnectListAllInterfaces(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval = NULL; virConnectPtr conn; virInterfacePtr *ifaces = NULL; int c_retval = 0; ssize_t i; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virConnectListAllInterfaces", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virConnectListAllInterfaces(conn, &ifaces, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virInterfacePtrWrap(ifaces[i]), error); /* python steals the pointer */ ifaces[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (ifaces[i]) virInterfaceFree(ifaces[i]); VIR_FREE(ifaces); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ static PyObject * libvirt_virConnectBaselineCPU(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *list; virConnectPtr conn; unsigned int flags; char **xmlcpus = NULL; int ncpus = 0; char *base_cpu; PyObject *pybase_cpu; ssize_t i, j; if (!PyArg_ParseTuple(args, (char *)"OOI:virConnectBaselineCPU", &pyobj_conn, &list, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if (PyList_Check(list)) { ncpus = PyList_Size(list); if (VIR_ALLOC_N(xmlcpus, ncpus) < 0) return PyErr_NoMemory(); for (i = 0; i < ncpus; i++) { if (libvirt_charPtrUnwrap(PyList_GetItem(list, i), &(xmlcpus[i])) < 0) { for (j = 0 ; j < i ; j++) VIR_FREE(xmlcpus[j]); VIR_FREE(xmlcpus); return NULL; } } } LIBVIRT_BEGIN_ALLOW_THREADS; base_cpu = virConnectBaselineCPU(conn, (const char **)xmlcpus, ncpus, flags); LIBVIRT_END_ALLOW_THREADS; for (i = 0 ; i < ncpus ; i++) VIR_FREE(xmlcpus[i]); VIR_FREE(xmlcpus); if (base_cpu == NULL) return VIR_PY_NONE; pybase_cpu = libvirt_constcharPtrWrap(base_cpu); VIR_FREE(base_cpu); return pybase_cpu; } static PyObject * libvirt_virDomainGetJobInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; virDomainJobInfo info; if (!PyArg_ParseTuple(args, (char *)"O:virDomainGetJobInfo", &pyobj_domain)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetJobInfo(domain, &info); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if ((py_retval = PyList_New(12)) == NULL) return NULL; VIR_PY_LIST_SET_GOTO(py_retval, 0, libvirt_intWrap(info.type), error); VIR_PY_LIST_SET_GOTO(py_retval, 1, libvirt_ulonglongWrap(info.timeElapsed), error); VIR_PY_LIST_SET_GOTO(py_retval, 2, libvirt_ulonglongWrap(info.timeRemaining), error); VIR_PY_LIST_SET_GOTO(py_retval, 3, libvirt_ulonglongWrap(info.dataTotal), error); VIR_PY_LIST_SET_GOTO(py_retval, 4, libvirt_ulonglongWrap(info.dataProcessed), error); VIR_PY_LIST_SET_GOTO(py_retval, 5, libvirt_ulonglongWrap(info.dataRemaining), error); VIR_PY_LIST_SET_GOTO(py_retval, 6, libvirt_ulonglongWrap(info.memTotal), error); VIR_PY_LIST_SET_GOTO(py_retval, 7, libvirt_ulonglongWrap(info.memProcessed), error); VIR_PY_LIST_SET_GOTO(py_retval, 8, libvirt_ulonglongWrap(info.memRemaining), error); VIR_PY_LIST_SET_GOTO(py_retval, 9, libvirt_ulonglongWrap(info.fileTotal), error); VIR_PY_LIST_SET_GOTO(py_retval, 10, libvirt_ulonglongWrap(info.fileProcessed), error); VIR_PY_LIST_SET_GOTO(py_retval, 11, libvirt_ulonglongWrap(info.fileRemaining), error); return py_retval; error: Py_DECREF(py_retval); return NULL; } #if LIBVIR_CHECK_VERSION(1, 0, 3) static PyObject * libvirt_virDomainGetJobStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_domain; virDomainPtr domain; unsigned int flags; virTypedParameterPtr params = NULL; int nparams = 0; int type; PyObject *dict = NULL; int rc; if (!PyArg_ParseTuple(args, (char *) "OI:virDomainGetJobStats", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; rc = virDomainGetJobStats(domain, &type, ¶ms, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (rc < 0) return VIR_PY_NONE; if (!(dict = getPyVirTypedParameter(params, nparams))) goto cleanup; VIR_PY_DICT_SET_GOTO(dict, libvirt_constcharPtrWrap("type"), libvirt_intWrap(type), error); cleanup: virTypedParamsFree(params, nparams); return dict; error: Py_CLEAR(dict); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(1, 0, 3) */ static PyObject * libvirt_virDomainGetBlockJobInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; const char *path; unsigned int flags; virDomainBlockJobInfo info; int c_ret; PyObject *dict; if (!PyArg_ParseTuple(args, (char *)"OzI:virDomainGetBlockJobInfo", &pyobj_domain, &path, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_ret = virDomainGetBlockJobInfo(domain, path, &info, flags); LIBVIRT_END_ALLOW_THREADS; if (c_ret < 0) return VIR_PY_NONE; if ((dict = PyDict_New()) == NULL) return NULL; if (c_ret == 0) return dict; VIR_PY_DICT_SET_GOTO(dict, libvirt_constcharPtrWrap("type"), libvirt_intWrap(info.type), error); VIR_PY_DICT_SET_GOTO(dict, libvirt_constcharPtrWrap("bandwidth"), libvirt_ulongWrap(info.bandwidth), error); VIR_PY_DICT_SET_GOTO(dict, libvirt_constcharPtrWrap("cur"), libvirt_ulonglongWrap(info.cur), error); VIR_PY_DICT_SET_GOTO(dict, libvirt_constcharPtrWrap("end"), libvirt_ulonglongWrap(info.end), error); return dict; error: Py_DECREF(dict); return NULL; } static PyObject * libvirt_virDomainSetBlockIoTune(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *info; PyObject *ret = NULL; int i_retval; int nparams = 0; Py_ssize_t size = 0; const char *disk; unsigned int flags; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OzOI:virDomainSetBlockIoTune", &pyobj_domain, &disk, &info, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetBlockIoTune(domain, disk, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_INT_FAIL; if (nparams == 0) { PyErr_Format(PyExc_LookupError, "Domain has no settable attributes"); return NULL; } if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetBlockIoTune(domain, disk, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainSetBlockIoTune(domain, disk, new_params, size, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } static PyObject * libvirt_virDomainGetBlockIoTune(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *ret = NULL; int i_retval; int nparams = 0; const char *disk; unsigned int flags; virTypedParameterPtr params; if (!PyArg_ParseTuple(args, (char *)"OzI:virDomainGetBlockIoTune", &pyobj_domain, &disk, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetBlockIoTune(domain, disk, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; if (!nparams) return PyDict_New(); if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetBlockIoTune(domain, disk, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } static PyObject * libvirt_virDomainGetDiskErrors(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = VIR_PY_NONE; virDomainPtr domain; PyObject *pyobj_domain; unsigned int flags; virDomainDiskErrorPtr disks = NULL; unsigned int ndisks; int count; ssize_t i; if (!PyArg_ParseTuple(args, (char *) "OI:virDomainGetDiskErrors", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; count = virDomainGetDiskErrors(domain, NULL, 0, 0); LIBVIRT_END_ALLOW_THREADS; if (count < 0) return VIR_PY_NONE; ndisks = count; if (ndisks) { if (VIR_ALLOC_N(disks, ndisks) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; count = virDomainGetDiskErrors(domain, disks, ndisks, 0); LIBVIRT_END_ALLOW_THREADS; if (count < 0) { py_retval = VIR_PY_NONE; goto cleanup; } } if (!(py_retval = PyDict_New())) goto cleanup; for (i = 0; i < count; i++) { VIR_PY_DICT_SET_GOTO(py_retval, libvirt_constcharPtrWrap(disks[i].disk), libvirt_intWrap(disks[i].error), error); } cleanup: if (count > 0) for (i = 0; i < count; i++) VIR_FREE(disks[i].disk); VIR_FREE(disks); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #if LIBVIR_CHECK_VERSION(1, 2, 14) static PyObject * libvirt_virDomainInterfaceAddresses(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = VIR_PY_NONE; PyObject *pyobj_domain; virDomainPtr domain; virDomainInterfacePtr *ifaces = NULL; unsigned int source; unsigned int flags; int ifaces_count = 0; ssize_t i; if (!PyArg_ParseTuple(args, (char *) "OII:virDomainInterfaceAddresses", &pyobj_domain, &source, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; ifaces_count = virDomainInterfaceAddresses(domain, &ifaces, source, flags); LIBVIRT_END_ALLOW_THREADS; if (ifaces_count < 0) goto cleanup; if (!(py_retval = PyDict_New())) goto error; for (i = 0; i < ifaces_count; i++) { virDomainInterfacePtr iface = ifaces[i]; PyObject *py_addrs = NULL; PyObject *py_iface = NULL; size_t j; if (!(py_iface = PyDict_New())) goto error; VIR_PY_DICT_SET_GOTO(py_retval, libvirt_charPtrWrap(iface->name), py_iface, error); if (iface->naddrs) { if (!(py_addrs = PyList_New(iface->naddrs))) { goto error; } } else { py_addrs = VIR_PY_NONE; } VIR_PY_DICT_SET_GOTO(py_iface, libvirt_constcharPtrWrap("addrs"), py_addrs, error); VIR_PY_DICT_SET_GOTO(py_iface, libvirt_constcharPtrWrap("hwaddr"), libvirt_constcharPtrWrap(iface->hwaddr), error); for (j = 0; j < iface->naddrs; j++) { virDomainIPAddressPtr addr = &(iface->addrs[j]); PyObject *py_addr = PyDict_New(); if (!py_addr) goto error; VIR_PY_LIST_SET_GOTO(py_addrs, j, py_addr, error); VIR_PY_DICT_SET_GOTO(py_addr, libvirt_constcharPtrWrap("addr"), libvirt_constcharPtrWrap(addr->addr), error); VIR_PY_DICT_SET_GOTO(py_addr, libvirt_constcharPtrWrap("prefix"), libvirt_uintWrap(addr->prefix), error); VIR_PY_DICT_SET_GOTO(py_addr, libvirt_constcharPtrWrap("type"), libvirt_intWrap(addr->type), error); } } cleanup: if (ifaces && ifaces_count > 0) { for (i = 0; i < ifaces_count; i++) { virDomainInterfaceFree(ifaces[i]); } } VIR_FREE(ifaces); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(1, 2, 14) */ /******************************************* * Helper functions to avoid importing modules * for every callback *******************************************/ static PyObject *libvirt_module = NULL; static PyObject *libvirt_dict = NULL; static PyObject * getLibvirtModuleObject(void) { if (libvirt_module) return libvirt_module; // PyImport_ImportModule returns a new reference /* Bogus (char *) cast for RHEL-5 python API brokenness */ libvirt_module = PyImport_ImportModule((char *)"libvirt"); if (!libvirt_module) { DEBUG("%s Error importing libvirt module\n", __FUNCTION__); PyErr_Print(); return NULL; } return libvirt_module; } static PyObject * getLibvirtDictObject(void) { if (libvirt_dict) return libvirt_dict; // PyModule_GetDict returns a borrowed reference libvirt_dict = PyModule_GetDict(getLibvirtModuleObject()); if (!libvirt_dict) { DEBUG("%s Error importing libvirt dictionary\n", __FUNCTION__); PyErr_Print(); return NULL; } Py_INCREF(libvirt_dict); return libvirt_dict; } static PyObject * libvirt_lookupPythonFunc(const char *funcname) { PyObject *python_cb; /* Lookup the python callback */ python_cb = PyDict_GetItemString(getLibvirtDictObject(), funcname); if (!python_cb) { DEBUG("%s: Error finding %s\n", __FUNCTION__, funcname); PyErr_Print(); PyErr_Clear(); return NULL; } if (!PyCallable_Check(python_cb)) { DEBUG("%s: %s is not callable\n", __FUNCTION__, funcname); return NULL; } return python_cb; } /******************************************* * Domain Events *******************************************/ static int libvirt_virConnectDomainEventCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int event, int detail, void *opaque) { PyObject *pyobj_ret = NULL; PyObject *pyobj_conn = (PyObject*)opaque; PyObject *pyobj_dom; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventCallbacks", (char*)"Oii", pyobj_dom, event, detail); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static PyObject * libvirt_virConnectDomainEventRegister(ATTRIBUTE_UNUSED PyObject *self, PyObject *args) { PyObject *pyobj_conn; /* virConnectPtr */ PyObject *pyobj_conn_inst; /* virConnect Python object */ virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "OO:virConnectDomainEventRegister", &pyobj_conn, &pyobj_conn_inst)) return NULL; DEBUG("libvirt_virConnectDomainEventRegister(%p %p) called\n", pyobj_conn, pyobj_conn_inst); conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); Py_INCREF(pyobj_conn_inst); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectDomainEventRegister(conn, libvirt_virConnectDomainEventCallback, pyobj_conn_inst, NULL); LIBVIRT_END_ALLOW_THREADS; return libvirt_intWrap(ret); } static PyObject * libvirt_virConnectDomainEventDeregister(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *pyobj_conn_inst; virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "OO:virConnectDomainEventDeregister", &pyobj_conn, &pyobj_conn_inst)) return NULL; DEBUG("libvirt_virConnectDomainEventDeregister(%p) called\n", pyobj_conn); conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectDomainEventDeregister(conn, libvirt_virConnectDomainEventCallback); LIBVIRT_END_ALLOW_THREADS; Py_DECREF(pyobj_conn_inst); return libvirt_intWrap(ret); } /******************************************* * Event Impl *******************************************/ static PyObject *addHandleObj; static PyObject *updateHandleObj; static PyObject *removeHandleObj; static PyObject *addTimeoutObj; static PyObject *updateTimeoutObj; static PyObject *removeTimeoutObj; static int libvirt_virEventAddHandleFunc(int fd, int event, virEventHandleCallback cb, void *opaque, virFreeCallback ff) { PyObject *result; PyObject *python_cb = NULL; PyObject *cb_args = NULL; PyObject *pyobj_args = NULL; int retval = -1; LIBVIRT_ENSURE_THREAD_STATE; if ((pyobj_args = PyTuple_New(4)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyobj_args, 0, libvirt_intWrap(fd), cleanup); VIR_PY_TUPLE_SET_GOTO(pyobj_args, 1, libvirt_intWrap(event), cleanup); /* Lookup the python callback */ python_cb = libvirt_lookupPythonFunc("_eventInvokeHandleCallback"); if (!python_cb) { goto cleanup; } Py_INCREF(python_cb); VIR_PY_TUPLE_SET_GOTO(pyobj_args, 2, python_cb, cleanup); if ((cb_args = PyTuple_New(3)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyobj_args, 3, cb_args, cleanup); /* If changing contents of the opaque object, please also change * virEventInvokeFreeCallback() in libvirt-override.py */ VIR_PY_TUPLE_SET_GOTO(cb_args, 0, libvirt_virEventHandleCallbackWrap(cb), cleanup); VIR_PY_TUPLE_SET_GOTO(cb_args, 1, libvirt_virVoidPtrWrap(opaque), cleanup); VIR_PY_TUPLE_SET_GOTO(cb_args, 2, libvirt_virFreeCallbackWrap(ff), cleanup); result = PyObject_Call(addHandleObj, pyobj_args, NULL); if (!result) { PyErr_Print(); PyErr_Clear(); } else { libvirt_intUnwrap(result, &retval); } Py_XDECREF(result); cleanup: Py_XDECREF(pyobj_args); LIBVIRT_RELEASE_THREAD_STATE; return retval; } static void libvirt_virEventUpdateHandleFunc(int watch, int event) { PyObject *result = NULL; PyObject *pyobj_args; LIBVIRT_ENSURE_THREAD_STATE; if ((pyobj_args = PyTuple_New(2)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyobj_args, 0, libvirt_intWrap(watch), cleanup); VIR_PY_TUPLE_SET_GOTO(pyobj_args, 1, libvirt_intWrap(event), cleanup); result = PyObject_Call(updateHandleObj, pyobj_args, NULL); if (!result) { PyErr_Print(); PyErr_Clear(); } cleanup: Py_XDECREF(result); Py_XDECREF(pyobj_args); LIBVIRT_RELEASE_THREAD_STATE; } static int libvirt_virEventRemoveHandleFunc(int watch) { PyObject *result = NULL; PyObject *pyobj_args; int retval = -1; LIBVIRT_ENSURE_THREAD_STATE; if ((pyobj_args = PyTuple_New(1)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyobj_args, 0, libvirt_intWrap(watch), cleanup); result = PyObject_Call(removeHandleObj, pyobj_args, NULL); if (result) { retval = 0; } else { PyErr_Print(); PyErr_Clear(); } cleanup: Py_XDECREF(result); Py_XDECREF(pyobj_args); LIBVIRT_RELEASE_THREAD_STATE; return retval; } static int libvirt_virEventAddTimeoutFunc(int timeout, virEventTimeoutCallback cb, void *opaque, virFreeCallback ff) { PyObject *result = NULL; PyObject *python_cb = NULL; PyObject *cb_args = NULL; PyObject *pyobj_args = NULL; int retval = -1; LIBVIRT_ENSURE_THREAD_STATE; if ((pyobj_args = PyTuple_New(3)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyobj_args, 0, libvirt_intWrap(timeout), cleanup); /* Lookup the python callback */ python_cb = libvirt_lookupPythonFunc("_eventInvokeTimeoutCallback"); if (!python_cb) { goto cleanup; } Py_INCREF(python_cb); VIR_PY_TUPLE_SET_GOTO(pyobj_args, 1, python_cb, cleanup); if ((cb_args = PyTuple_New(3)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyobj_args, 2, cb_args, cleanup); /* If changing contents of the opaque object, please also change * virEventInvokeFreeCallback() in libvirt-override.py */ VIR_PY_TUPLE_SET_GOTO(cb_args, 0, libvirt_virEventTimeoutCallbackWrap(cb), cleanup); VIR_PY_TUPLE_SET_GOTO(cb_args, 1, libvirt_virVoidPtrWrap(opaque), cleanup); VIR_PY_TUPLE_SET_GOTO(cb_args, 2, libvirt_virFreeCallbackWrap(ff), cleanup); result = PyObject_Call(addTimeoutObj, pyobj_args, NULL); if (!result) { PyErr_Print(); PyErr_Clear(); } else { libvirt_intUnwrap(result, &retval); } cleanup: Py_XDECREF(result); Py_XDECREF(pyobj_args); LIBVIRT_RELEASE_THREAD_STATE; return retval; } static void libvirt_virEventUpdateTimeoutFunc(int timer, int timeout) { PyObject *result = NULL; PyObject *pyobj_args; LIBVIRT_ENSURE_THREAD_STATE; if ((pyobj_args = PyTuple_New(2)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyobj_args, 0, libvirt_intWrap(timer), cleanup); VIR_PY_TUPLE_SET_GOTO(pyobj_args, 1, libvirt_intWrap(timeout), cleanup); result = PyObject_Call(updateTimeoutObj, pyobj_args, NULL); if (!result) { PyErr_Print(); PyErr_Clear(); } cleanup: Py_XDECREF(result); Py_XDECREF(pyobj_args); LIBVIRT_RELEASE_THREAD_STATE; } static int libvirt_virEventRemoveTimeoutFunc(int timer) { PyObject *result = NULL; PyObject *pyobj_args; int retval = -1; LIBVIRT_ENSURE_THREAD_STATE; if ((pyobj_args = PyTuple_New(1)) == NULL) goto cleanup; VIR_PY_TUPLE_SET_GOTO(pyobj_args, 0, libvirt_intWrap(timer), cleanup); result = PyObject_Call(removeTimeoutObj, pyobj_args, NULL); if (result) { retval = 0; } else { PyErr_Print(); PyErr_Clear(); } cleanup: Py_XDECREF(result); Py_XDECREF(pyobj_args); LIBVIRT_RELEASE_THREAD_STATE; return retval; } static PyObject * libvirt_virEventRegisterImpl(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { if (addHandleObj || updateHandleObj || removeHandleObj || addTimeoutObj || updateTimeoutObj || removeTimeoutObj) { PyErr_SetString(PyExc_RuntimeError, "Event loop is already registered"); return NULL; } /* Parse and check arguments */ if (!PyArg_ParseTuple(args, (char *) "OOOOOO:virEventRegisterImpl", &addHandleObj, &updateHandleObj, &removeHandleObj, &addTimeoutObj, &updateTimeoutObj, &removeTimeoutObj) || !PyCallable_Check(addHandleObj) || !PyCallable_Check(updateHandleObj) || !PyCallable_Check(removeHandleObj) || !PyCallable_Check(addTimeoutObj) || !PyCallable_Check(updateTimeoutObj) || !PyCallable_Check(removeTimeoutObj)) return NULL; /* Inc refs since we're holding on to these objects until * the next call (if any) to this function. */ Py_INCREF(addHandleObj); Py_INCREF(updateHandleObj); Py_INCREF(removeHandleObj); Py_INCREF(addTimeoutObj); Py_INCREF(updateTimeoutObj); Py_INCREF(removeTimeoutObj); /* Now register our C EventImpl, which will dispatch * to the Python callbacks passed in as args. */ LIBVIRT_BEGIN_ALLOW_THREADS; virEventRegisterImpl(libvirt_virEventAddHandleFunc, libvirt_virEventUpdateHandleFunc, libvirt_virEventRemoveHandleFunc, libvirt_virEventAddTimeoutFunc, libvirt_virEventUpdateTimeoutFunc, libvirt_virEventRemoveTimeoutFunc); LIBVIRT_END_ALLOW_THREADS; return VIR_PY_INT_SUCCESS; } static PyObject * libvirt_virEventInvokeHandleCallback(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int watch, fd, event; PyObject *py_f; PyObject *py_opaque; virEventHandleCallback cb; void *opaque; if (!PyArg_ParseTuple(args, (char *) "iiiOO:virEventInvokeHandleCallback", &watch, &fd, &event, &py_f, &py_opaque)) return NULL; cb = (virEventHandleCallback) PyvirEventHandleCallback_Get(py_f); opaque = (void *) PyvirVoidPtr_Get(py_opaque); if (cb) { LIBVIRT_BEGIN_ALLOW_THREADS; cb(watch, fd, event, opaque); LIBVIRT_END_ALLOW_THREADS; } return VIR_PY_INT_SUCCESS; } static PyObject * libvirt_virEventInvokeTimeoutCallback(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int timer; PyObject *py_f; PyObject *py_opaque; virEventTimeoutCallback cb; void *opaque; if (!PyArg_ParseTuple(args, (char *) "iOO:virEventInvokeTimeoutCallback", &timer, &py_f, &py_opaque)) return NULL; cb = (virEventTimeoutCallback) PyvirEventTimeoutCallback_Get(py_f); opaque = (void *) PyvirVoidPtr_Get(py_opaque); if (cb) { LIBVIRT_BEGIN_ALLOW_THREADS; cb(timer, opaque); LIBVIRT_END_ALLOW_THREADS; } return VIR_PY_INT_SUCCESS; } static PyObject * libvirt_virEventInvokeFreeCallback(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_f; PyObject *py_opaque; virFreeCallback cb; void *opaque; if (!PyArg_ParseTuple(args, (char *) "OO:virEventInvokeFreeCallback", &py_f, &py_opaque)) return NULL; cb = (virFreeCallback) PyvirEventHandleCallback_Get(py_f); opaque = (void *) PyvirVoidPtr_Get(py_opaque); if (cb) { LIBVIRT_BEGIN_ALLOW_THREADS; cb(opaque); LIBVIRT_END_ALLOW_THREADS; } return VIR_PY_INT_SUCCESS; } static void libvirt_virEventHandleCallback(int watch, int fd, int events, void *opaque) { PyObject *pyobj_cbData = (PyObject *)opaque; PyObject *pyobj_ret; PyObject *python_cb; LIBVIRT_ENSURE_THREAD_STATE; /* Lookup the python callback */ python_cb = libvirt_lookupPythonFunc("_dispatchEventHandleCallback"); if (!python_cb) { goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the pure python dispatcher */ pyobj_ret = PyObject_CallFunction(python_cb, (char *)"iiiO", watch, fd, events, pyobj_cbData); Py_DECREF(pyobj_cbData); if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); } cleanup: LIBVIRT_RELEASE_THREAD_STATE; } static PyObject * libvirt_virEventAddHandle(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_cbData; virEventHandleCallback cb = libvirt_virEventHandleCallback; int events; int fd; int ret; if (!PyArg_ParseTuple(args, (char *) "iiO:virEventAddHandle", &fd, &events, &pyobj_cbData)) return NULL; Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virEventAddHandle(fd, events, cb, pyobj_cbData, NULL); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } return libvirt_intWrap(ret); } static void libvirt_virEventTimeoutCallback(int timer, void *opaque) { PyObject *pyobj_cbData = (PyObject *)opaque; PyObject *pyobj_ret; PyObject *python_cb; LIBVIRT_ENSURE_THREAD_STATE; /* Lookup the python callback */ python_cb = libvirt_lookupPythonFunc("_dispatchEventTimeoutCallback"); if (!python_cb) { goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the pure python dispatcher */ pyobj_ret = PyObject_CallFunction(python_cb, (char *)"iO", timer, pyobj_cbData); Py_DECREF(pyobj_cbData); if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); } cleanup: LIBVIRT_RELEASE_THREAD_STATE; } static PyObject * libvirt_virEventAddTimeout(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_cbData; virEventTimeoutCallback cb = libvirt_virEventTimeoutCallback; int timeout; int ret; if (!PyArg_ParseTuple(args, (char *) "iO:virEventAddTimeout", &timeout, &pyobj_cbData)) return NULL; Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virEventAddTimeout(timeout, cb, pyobj_cbData, NULL); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } return libvirt_intWrap(ret); } static void libvirt_virConnectDomainEventFreeFunc(void *opaque) { PyObject *pyobj_conn = (PyObject*)opaque; LIBVIRT_ENSURE_THREAD_STATE; Py_DECREF(pyobj_conn); LIBVIRT_RELEASE_THREAD_STATE; } static int libvirt_virConnectDomainEventLifecycleCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int event, int detail, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventLifecycleCallback", (char*)"OiiO", pyobj_dom, event, detail, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventGenericCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventGenericCallback", (char*)"OO", pyobj_dom, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventRTCChangeCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, long long utcoffset, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventRTCChangeCallback", (char*)"OLO", pyobj_dom, (PY_LONG_LONG)utcoffset, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventWatchdogCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int action, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventWatchdogCallback", (char*)"OiO", pyobj_dom, action, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventIOErrorCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *srcPath, const char *devAlias, int action, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventIOErrorCallback", (char*)"OssiO", pyobj_dom, srcPath, devAlias, action, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventIOErrorReasonCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *srcPath, const char *devAlias, int action, const char *reason, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventIOErrorReasonCallback", (char*)"OssisO", pyobj_dom, srcPath, devAlias, action, reason, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventGraphicsCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int phase, virDomainEventGraphicsAddressPtr local, virDomainEventGraphicsAddressPtr remote, const char *authScheme, virDomainEventGraphicsSubjectPtr subject, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom = NULL; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; PyObject *pyobj_local = NULL; PyObject *pyobj_remote = NULL; PyObject *pyobj_subject = NULL; int ret = -1; ssize_t i; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); if ((pyobj_local = PyDict_New()) == NULL) goto cleanup; VIR_PY_DICT_SET_GOTO(pyobj_local, libvirt_constcharPtrWrap("family"), libvirt_intWrap(local->family), cleanup); VIR_PY_DICT_SET_GOTO(pyobj_local, libvirt_constcharPtrWrap("node"), libvirt_constcharPtrWrap(local->node), cleanup); VIR_PY_DICT_SET_GOTO(pyobj_local, libvirt_constcharPtrWrap("service"), libvirt_constcharPtrWrap(local->service), cleanup); if ((pyobj_remote = PyDict_New()) == NULL) goto cleanup; VIR_PY_DICT_SET_GOTO(pyobj_remote, libvirt_constcharPtrWrap("family"), libvirt_intWrap(remote->family), cleanup); VIR_PY_DICT_SET_GOTO(pyobj_remote, libvirt_constcharPtrWrap("node"), libvirt_constcharPtrWrap(remote->node), cleanup); VIR_PY_DICT_SET_GOTO(pyobj_remote, libvirt_constcharPtrWrap("service"), libvirt_constcharPtrWrap(remote->service), cleanup); if ((pyobj_subject = PyList_New(subject->nidentity)) == NULL) goto cleanup; for (i = 0; i < subject->nidentity; i++) { PyObject *pair = PyTuple_New(2); if (pair == NULL) goto cleanup; VIR_PY_LIST_SET_GOTO(pyobj_subject, i, pair, cleanup); VIR_PY_TUPLE_SET_GOTO(pair, 0, libvirt_constcharPtrWrap(subject->identities[i].type), cleanup); VIR_PY_TUPLE_SET_GOTO(pair, 1, libvirt_constcharPtrWrap(subject->identities[i].name), cleanup); } /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventGraphicsCallback", (char*)"OiOOsOO", pyobj_dom, phase, pyobj_local, pyobj_remote, authScheme, pyobj_subject, pyobj_cbData); cleanup: Py_DECREF(pyobj_cbData); Py_XDECREF(pyobj_dom); if (!pyobj_ret) { Py_XDECREF(pyobj_local); Py_XDECREF(pyobj_remote); Py_XDECREF(pyobj_subject); DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventBlockJobCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *disk, int type, int status, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventBlockJobCallback", (char*)"OsiiO", pyobj_dom, disk, type, status, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventDiskChangeCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *oldSrcPath, const char *newSrcPath, const char *devAlias, int reason, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventDiskChangeCallback", (char*)"OsssiO", pyobj_dom, oldSrcPath, newSrcPath, devAlias, reason, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventTrayChangeCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *devAlias, int reason, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventTrayChangeCallback", (char*)"OsiO", pyobj_dom, devAlias, reason, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventPMWakeupCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int reason, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventPMWakeupCallback", (char*)"OiO", pyobj_dom, reason, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectDomainEventPMSuspendCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int reason, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventPMSuspendCallback", (char*)"OiO", pyobj_dom, reason, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #ifdef VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE static int libvirt_virConnectDomainEventBalloonChangeCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, unsigned long long actual, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventBalloonChangeCallback", (char*)"OLO", pyobj_dom, (PY_LONG_LONG)actual, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE */ #ifdef VIR_DOMAIN_EVENT_ID_PMSUSPEND_DISK static int libvirt_virConnectDomainEventPMSuspendDiskCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int reason, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventPMSuspendDiskCallback", (char*)"OiO", pyobj_dom, reason, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_PMSUSPEND_DISK */ #ifdef VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED static int libvirt_virConnectDomainEventDeviceRemovedCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *devAlias, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventDeviceRemovedCallback", (char*)"OsO", pyobj_dom, devAlias, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED */ #ifdef VIR_DOMAIN_EVENT_ID_TUNABLE static int libvirt_virConnectDomainEventTunableCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, virTypedParameterPtr params, int nparams, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; PyObject *pyobj_dict = NULL; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; pyobj_dict = getPyVirTypedParameter(params, nparams); if (!pyobj_dict) goto cleanup; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventTunableCallback", (char*)"OOO", pyobj_dom, pyobj_dict, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } Py_XDECREF(pyobj_dict); LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_TUNABLE */ #ifdef VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE static int libvirt_virConnectDomainEventAgentLifecycleCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int state, int reason, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventAgentLifecycleCallback", (char*)"OiiO", pyobj_dom, state, reason, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE */ #ifdef VIR_DOMAIN_EVENT_ID_DEVICE_ADDED static int libvirt_virConnectDomainEventDeviceAddedCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *devAlias, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventDeviceAddedCallback", (char*)"OsO", pyobj_dom, devAlias, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_DEVICE_ADDED */ #ifdef VIR_DOMAIN_EVENT_ID_MIGRATION_ITERATION static int libvirt_virConnectDomainEventMigrationIterationCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int iteration, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventMigrationIterationCallback", (char*)"OiO", pyobj_dom, iteration, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_MIGRATION_ITERATION */ #ifdef VIR_DOMAIN_EVENT_ID_JOB_COMPLETED static int libvirt_virConnectDomainEventJobCompletedCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, virTypedParameterPtr params, int nparams, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; PyObject *pyobj_dict = NULL; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; pyobj_dict = getPyVirTypedParameter(params, nparams); if (!pyobj_dict) goto cleanup; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventJobCompletedCallback", (char*)"OOO", pyobj_dom, pyobj_dict, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); Py_XDECREF(pyobj_dict); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_JOB_COMPLETED */ #ifdef VIR_DOMAIN_EVENT_ID_DEVICE_REMOVAL_FAILED static int libvirt_virConnectDomainEventDeviceRemovalFailedCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *devAlias, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventDeviceRemovalFailedCallback", (char*)"OsO", pyobj_dom, devAlias, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_DEVICE_REMOVAL_FAILED */ #ifdef VIR_DOMAIN_EVENT_ID_METADATA_CHANGE static int libvirt_virConnectDomainEventMetadataChangeCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int type, const char *nsuri, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventMetadataChangeCallback", (char*)"OisO", pyobj_dom, type, nsuri, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_METADATA_CHANGE */ #ifdef VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD static int libvirt_virConnectDomainEventBlockThresholdCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *dev, const char *path, unsigned long long threshold, unsigned long long excess, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventBlockThresholdCallback", (char*)"OssKKO", pyobj_dom, dev, path, threshold, excess, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD */ #ifdef VIR_DOMAIN_EVENT_ID_MEMORY_FAILURE static int libvirt_virConnectDomainEventMemoryFailureCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, int recipient, int action, unsigned int flags, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventMemoryFailureCallback", (char*)"OiiiO", pyobj_dom, recipient, action, flags, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_MEMORY_FAILURE */ #ifdef VIR_DOMAIN_EVENT_ID_MEMORY_DEVICE_SIZE_CHANGE static int libvirt_virConnectDomainEventMemoryDeviceSizeChangeCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virDomainPtr dom, const char *alias, unsigned long long size, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virDomainPtr */ virDomainRef(dom); if (!(pyobj_dom = libvirt_virDomainPtrWrap(dom))) { virDomainFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchDomainEventMemoryDeviceSizeChangeCallback", (char*)"OsKO", pyobj_dom, alias, size, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_DOMAIN_EVENT_ID_MEMORY_DEVICE_SIZE_CHANGE */ static PyObject * libvirt_virConnectDomainEventRegisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval; /* return value */ PyObject *pyobj_conn; /* virConnectPtr */ PyObject *pyobj_dom; PyObject *pyobj_cbData; /* hash of callback data */ int eventID; virConnectPtr conn; int ret = 0; virConnectDomainEventGenericCallback cb = NULL; virDomainPtr dom; if (!PyArg_ParseTuple(args, (char *) "OOiO:virConnectDomainEventRegisterAny", &pyobj_conn, &pyobj_dom, &eventID, &pyobj_cbData)) return NULL; DEBUG("libvirt_virConnectDomainEventRegister(%p %p %d %p) called\n", pyobj_conn, pyobj_dom, eventID, pyobj_cbData); conn = PyvirConnect_Get(pyobj_conn); if (pyobj_dom == Py_None) dom = NULL; else dom = PyvirDomain_Get(pyobj_dom); switch ((virDomainEventID) eventID) { case VIR_DOMAIN_EVENT_ID_LIFECYCLE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventLifecycleCallback); break; case VIR_DOMAIN_EVENT_ID_REBOOT: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventGenericCallback); break; case VIR_DOMAIN_EVENT_ID_RTC_CHANGE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventRTCChangeCallback); break; case VIR_DOMAIN_EVENT_ID_WATCHDOG: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventWatchdogCallback); break; case VIR_DOMAIN_EVENT_ID_IO_ERROR: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventIOErrorCallback); break; case VIR_DOMAIN_EVENT_ID_IO_ERROR_REASON: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventIOErrorReasonCallback); break; case VIR_DOMAIN_EVENT_ID_GRAPHICS: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventGraphicsCallback); break; case VIR_DOMAIN_EVENT_ID_CONTROL_ERROR: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventGenericCallback); break; case VIR_DOMAIN_EVENT_ID_BLOCK_JOB: #ifdef VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2 case VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2: #endif /* VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2 */ cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventBlockJobCallback); break; case VIR_DOMAIN_EVENT_ID_DISK_CHANGE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventDiskChangeCallback); break; case VIR_DOMAIN_EVENT_ID_TRAY_CHANGE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventTrayChangeCallback); break; case VIR_DOMAIN_EVENT_ID_PMWAKEUP: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventPMWakeupCallback); break; case VIR_DOMAIN_EVENT_ID_PMSUSPEND: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventPMSuspendCallback); break; #ifdef VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE case VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventBalloonChangeCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_BALLOON_CHANGE */ #ifdef VIR_DOMAIN_EVENT_ID_PMSUSPEND_DISK case VIR_DOMAIN_EVENT_ID_PMSUSPEND_DISK: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventPMSuspendDiskCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_PMSUSPEND_DISK */ #ifdef VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED case VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventDeviceRemovedCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED */ #ifdef VIR_DOMAIN_EVENT_ID_TUNABLE case VIR_DOMAIN_EVENT_ID_TUNABLE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventTunableCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_TUNABLE */ #ifdef VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE case VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventAgentLifecycleCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_AGENT_LIFECYCLE */ #ifdef VIR_DOMAIN_EVENT_ID_DEVICE_ADDED case VIR_DOMAIN_EVENT_ID_DEVICE_ADDED: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventDeviceAddedCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_DEVICE_ADDED */ #ifdef VIR_DOMAIN_EVENT_ID_MIGRATION_ITERATION case VIR_DOMAIN_EVENT_ID_MIGRATION_ITERATION: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventMigrationIterationCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_MIGRATION_ITERATION */ #ifdef VIR_DOMAIN_EVENT_ID_JOB_COMPLETED case VIR_DOMAIN_EVENT_ID_JOB_COMPLETED: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventJobCompletedCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_JOB_COMPLETED */ #ifdef VIR_DOMAIN_EVENT_ID_DEVICE_REMOVAL_FAILED case VIR_DOMAIN_EVENT_ID_DEVICE_REMOVAL_FAILED: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventDeviceRemovalFailedCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_DEVICE_REMOVAL_FAILED */ #ifdef VIR_DOMAIN_EVENT_ID_METADATA_CHANGE case VIR_DOMAIN_EVENT_ID_METADATA_CHANGE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventMetadataChangeCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_METADATA_CHANGE */ #ifdef VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD case VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventBlockThresholdCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD */ #ifdef VIR_DOMAIN_EVENT_ID_MEMORY_FAILURE case VIR_DOMAIN_EVENT_ID_MEMORY_FAILURE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventMemoryFailureCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_MEMORY_FAILURE */ #ifdef VIR_DOMAIN_EVENT_ID_MEMORY_DEVICE_SIZE_CHANGE case VIR_DOMAIN_EVENT_ID_MEMORY_DEVICE_SIZE_CHANGE: cb = VIR_DOMAIN_EVENT_CALLBACK(libvirt_virConnectDomainEventMemoryDeviceSizeChangeCallback); break; #endif /* VIR_DOMAIN_EVENT_ID_MEMORY_DEVICE_SIZE_CHANGE */ case VIR_DOMAIN_EVENT_ID_LAST: break; } if (!cb) { return VIR_PY_INT_FAIL; } Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectDomainEventRegisterAny(conn, dom, eventID, cb, pyobj_cbData, libvirt_virConnectDomainEventFreeFunc); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } py_retval = libvirt_intWrap(ret); return py_retval; } static PyObject * libvirt_virConnectDomainEventDeregisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; int callbackID; virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "Oi:virConnectDomainEventDeregister", &pyobj_conn, &callbackID)) return NULL; DEBUG("libvirt_virConnectDomainEventDeregister(%p) called\n", pyobj_conn); conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectDomainEventDeregisterAny(conn, callbackID); LIBVIRT_END_ALLOW_THREADS; return libvirt_intWrap(ret); } #if LIBVIR_CHECK_VERSION(1, 2, 1) static void libvirt_virConnectNetworkEventFreeFunc(void *opaque) { PyObject *pyobj_conn = (PyObject*)opaque; LIBVIRT_ENSURE_THREAD_STATE; Py_DECREF(pyobj_conn); LIBVIRT_RELEASE_THREAD_STATE; } static int libvirt_virConnectNetworkEventLifecycleCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virNetworkPtr net, int event, int detail, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_net; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virNetworkPtr */ virNetworkRef(net); if (!(pyobj_net = libvirt_virNetworkPtrWrap(net))) { virNetworkFree(net); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchNetworkEventLifecycleCallback", (char*)"OiiO", pyobj_net, event, detail, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_net); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #ifdef VIR_NETWORK_EVENT_ID_METADATA_CHANGE static int libvirt_virConnectNetworkEventMetadataChangeCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virNetworkPtr dom, int type, const char *nsuri, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dom; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virNetworkPtr */ virNetworkRef(dom); if (!(pyobj_dom = libvirt_virNetworkPtrWrap(dom))) { virNetworkFree(dom); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchNetworkEventMetadataChangeCallback", (char*)"OisO", pyobj_dom, type, nsuri, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dom); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } #endif /* VIR_NETWORK_EVENT_ID_METADATA_CHANGE */ static PyObject * libvirt_virConnectNetworkEventRegisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; /* virConnectPtr */ PyObject *pyobj_net; PyObject *pyobj_cbData; /* hash of callback data */ int eventID; virConnectPtr conn; int ret = 0; virConnectNetworkEventGenericCallback cb = NULL; virNetworkPtr net; if (!PyArg_ParseTuple(args, (char *) "OOiO:virConnectNetworkEventRegisterAny", &pyobj_conn, &pyobj_net, &eventID, &pyobj_cbData)) return NULL; DEBUG("libvirt_virConnectNetworkEventRegister(%p %p %d %p) called\n", pyobj_conn, pyobj_net, eventID, pyobj_cbData); conn = PyvirConnect_Get(pyobj_conn); if (pyobj_net == Py_None) net = NULL; else net = PyvirNetwork_Get(pyobj_net); switch ((virNetworkEventID) eventID) { case VIR_NETWORK_EVENT_ID_LIFECYCLE: cb = VIR_NETWORK_EVENT_CALLBACK(libvirt_virConnectNetworkEventLifecycleCallback); break; #ifdef VIR_NETWORK_EVENT_ID_METADATA_CHANGE case VIR_NETWORK_EVENT_ID_METADATA_CHANGE: cb = VIR_NETWORK_EVENT_CALLBACK(libvirt_virConnectNetworkEventMetadataChangeCallback); break; #endif /* VIR_NETWORK_EVENT_ID_METADATA_CHANGE */ case VIR_NETWORK_EVENT_ID_LAST: break; } if (!cb) { return VIR_PY_INT_FAIL; } Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectNetworkEventRegisterAny(conn, net, eventID, cb, pyobj_cbData, libvirt_virConnectNetworkEventFreeFunc); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } return libvirt_intWrap(ret); } static PyObject * libvirt_virConnectNetworkEventDeregisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; int callbackID; virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "Oi:virConnectNetworkEventDeregister", &pyobj_conn, &callbackID)) return NULL; DEBUG("libvirt_virConnectNetworkEventDeregister(%p) called\n", pyobj_conn); conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectNetworkEventDeregisterAny(conn, callbackID); LIBVIRT_END_ALLOW_THREADS; return libvirt_intWrap(ret); } #endif /* LIBVIR_CHECK_VERSION(1, 2, 1)*/ #if LIBVIR_CHECK_VERSION(0, 10, 0) static void libvirt_virConnectCloseCallbackDispatch(virConnectPtr conn ATTRIBUTE_UNUSED, int reason, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_ret; PyObject *pyobj_conn; PyObject *dictKey; LIBVIRT_ENSURE_THREAD_STATE; Py_INCREF(pyobj_cbData); dictKey = libvirt_constcharPtrWrap("conn"); pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchCloseCallback", (char*)"iO", reason, pyobj_cbData); Py_DECREF(pyobj_cbData); if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); } LIBVIRT_RELEASE_THREAD_STATE; } static PyObject * libvirt_virConnectRegisterCloseCallback(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; /* virConnectPtr */ PyObject *pyobj_cbData; /* hash of callback data */ virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "OO:virConnectRegisterCloseCallback", &pyobj_conn, &pyobj_cbData)) return NULL; DEBUG("libvirt_virConnectRegisterCloseCallback(%p %p) called\n", pyobj_conn, pyobj_cbData); conn = PyvirConnect_Get(pyobj_conn); Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectRegisterCloseCallback(conn, libvirt_virConnectCloseCallbackDispatch, pyobj_cbData, libvirt_virConnectDomainEventFreeFunc); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } return libvirt_intWrap(ret); } static PyObject * libvirt_virConnectUnregisterCloseCallback(PyObject * self ATTRIBUTE_UNUSED, PyObject * args) { PyObject *pyobj_conn; virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "O:virConnectUnregisterCloseCallback", &pyobj_conn)) return NULL; DEBUG("libvirt_virConnectDomainEventUnregister(%p) called\n", pyobj_conn); conn = PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectUnregisterCloseCallback(conn, libvirt_virConnectCloseCallbackDispatch); LIBVIRT_END_ALLOW_THREADS; return libvirt_intWrap(ret); } #endif /* LIBVIR_CHECK_VERSION(0, 10, 0) */ static void libvirt_virStreamEventFreeFunc(void *opaque) { PyObject *pyobj_stream = (PyObject*)opaque; LIBVIRT_ENSURE_THREAD_STATE; Py_DECREF(pyobj_stream); LIBVIRT_RELEASE_THREAD_STATE; } static void libvirt_virStreamEventCallback(virStreamPtr st ATTRIBUTE_UNUSED, int events, void *opaque) { PyObject *pyobj_cbData = (PyObject *)opaque; PyObject *pyobj_stream; PyObject *pyobj_ret; PyObject *dictKey; LIBVIRT_ENSURE_THREAD_STATE; Py_INCREF(pyobj_cbData); dictKey = libvirt_constcharPtrWrap("stream"); pyobj_stream = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Call the pure python dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_stream, (char *)"_dispatchStreamEventCallback", (char *)"iO", events, pyobj_cbData); Py_DECREF(pyobj_cbData); if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); } LIBVIRT_RELEASE_THREAD_STATE; } static PyObject * libvirt_virStreamEventAddCallback(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_stream; PyObject *pyobj_cbData; virStreamPtr stream; virStreamEventCallback cb = libvirt_virStreamEventCallback; int ret; int events; if (!PyArg_ParseTuple(args, (char *) "OiO:virStreamEventAddCallback", &pyobj_stream, &events, &pyobj_cbData)) return NULL; DEBUG("libvirt_virStreamEventAddCallback(%p, %d, %p) called\n", pyobj_stream, events, pyobj_cbData); stream = PyvirStream_Get(pyobj_stream); Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virStreamEventAddCallback(stream, events, cb, pyobj_cbData, libvirt_virStreamEventFreeFunc); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } return libvirt_intWrap(ret); } static PyObject * libvirt_virStreamRecv(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_stream; PyObject *rv; virStreamPtr stream; char *buf = NULL; int ret; int nbytes; if (!PyArg_ParseTuple(args, (char *) "Oi:virStreamRecv", &pyobj_stream, &nbytes)) { return NULL; } stream = PyvirStream_Get(pyobj_stream); if (VIR_ALLOC_N(buf, nbytes+1 > 0 ? nbytes+1 : 1) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virStreamRecv(stream, buf, nbytes); LIBVIRT_END_ALLOW_THREADS; buf[ret > -1 ? ret : 0] = '\0'; DEBUG("StreamRecv ret=%d strlen=%zu\n", ret, strlen(buf)); if (ret == -2) { VIR_FREE(buf); return libvirt_intWrap(ret); } if (ret < 0) { VIR_FREE(buf); return VIR_PY_NONE; } rv = libvirt_charPtrSizeWrap((char *) buf, (Py_ssize_t) ret); VIR_FREE(buf); return rv; } static PyObject * libvirt_virStreamSend(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_stream; PyObject *pyobj_data; virStreamPtr stream; char *data; Py_ssize_t datalen; int ret; if (!PyArg_ParseTuple(args, (char *) "OO:virStreamSend", &pyobj_stream, &pyobj_data)) return NULL; stream = PyvirStream_Get(pyobj_stream); libvirt_charPtrSizeUnwrap(pyobj_data, &data, &datalen); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virStreamSend(stream, data, datalen); LIBVIRT_END_ALLOW_THREADS; DEBUG("StreamSend ret=%d\n", ret); return libvirt_intWrap(ret); } static PyObject * libvirt_virDomainSendKey(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; PyObject *pyobj_list; int codeset; int holdtime; unsigned int flags; int ret; ssize_t i; unsigned int keycodes[VIR_DOMAIN_SEND_KEY_MAX_KEYS]; int nkeycodes; if (!PyArg_ParseTuple(args, (char *)"OiiOII:virDomainSendKey", &pyobj_domain, &codeset, &holdtime, &pyobj_list, &nkeycodes, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (!PyList_Check(pyobj_list)) { return VIR_PY_INT_FAIL; } if (nkeycodes != PyList_Size(pyobj_list) || nkeycodes > VIR_DOMAIN_SEND_KEY_MAX_KEYS) { return VIR_PY_INT_FAIL; } for (i = 0; i < nkeycodes; i++) { if (libvirt_uintUnwrap(PyList_GetItem(pyobj_list, i), &keycodes[i]) < 0) return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; ret = virDomainSendKey(domain, codeset, holdtime, keycodes, nkeycodes, flags); LIBVIRT_END_ALLOW_THREADS; DEBUG("virDomainSendKey ret=%d\n", ret); return libvirt_intWrap(ret); } #if LIBVIR_CHECK_VERSION(1, 0, 3) static PyObject * libvirt_virDomainMigrateGetCompressionCache(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_domain; virDomainPtr domain; unsigned int flags; unsigned long long cacheSize; int rc; if (!PyArg_ParseTuple(args, (char *) "OI:virDomainMigrateGetCompressionCache", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; rc = virDomainMigrateGetCompressionCache(domain, &cacheSize, flags); LIBVIRT_END_ALLOW_THREADS; if (rc < 0) return VIR_PY_NONE; return libvirt_ulonglongWrap(cacheSize); } #endif /* LIBVIR_CHECK_VERSION(1, 0, 3) */ static PyObject * libvirt_virDomainMigrateGetMaxSpeed(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { int c_retval; unsigned long bandwidth; virDomainPtr domain; PyObject *pyobj_domain; unsigned int flags = 0; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainMigrateGetMaxSpeed", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainMigrateGetMaxSpeed(domain, &bandwidth, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_INT_FAIL; return libvirt_ulongWrap(bandwidth); } #if LIBVIR_CHECK_VERSION(3, 7, 0) static PyObject * libvirt_virDomainMigrateGetMaxDowntime(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_domain; virDomainPtr domain; unsigned int flags; unsigned long long downtime; int rc; if (!PyArg_ParseTuple(args, (char *) "OI:virDomainMigrateGetMaxDowntime", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; rc = virDomainMigrateGetMaxDowntime(domain, &downtime, flags); LIBVIRT_END_ALLOW_THREADS; if (rc < 0) return VIR_PY_NONE; return libvirt_ulonglongWrap(downtime); } #endif /* LIBVIR_CHECK_VERSION(3, 7, 0) */ #if LIBVIR_CHECK_VERSION(1, 1, 0) static virPyTypedParamsHint virPyDomainMigrate3Params[] = { # ifdef VIR_MIGRATE_PARAM_URI { VIR_MIGRATE_PARAM_URI, VIR_TYPED_PARAM_STRING }, # endif # ifdef VIR_MIGRATE_PARAM_DEST_NAME { VIR_MIGRATE_PARAM_DEST_NAME, VIR_TYPED_PARAM_STRING }, # endif # ifdef VIR_MIGRATE_PARAM_DEST_XML { VIR_MIGRATE_PARAM_DEST_XML, VIR_TYPED_PARAM_STRING }, # endif # ifdef VIR_MIGRATE_PARAM_PERSIST_XML { VIR_MIGRATE_PARAM_PERSIST_XML, VIR_TYPED_PARAM_STRING }, # endif # ifdef VIR_MIGRATE_PARAM_BANDWIDTH { VIR_MIGRATE_PARAM_BANDWIDTH, VIR_TYPED_PARAM_ULLONG }, # endif # ifdef VIR_MIGRATE_PARAM_GRAPHICS_URI { VIR_MIGRATE_PARAM_GRAPHICS_URI, VIR_TYPED_PARAM_STRING }, # endif # ifdef VIR_MIGRATE_PARAM_LISTEN_ADDRESS { VIR_MIGRATE_PARAM_LISTEN_ADDRESS, VIR_TYPED_PARAM_STRING }, # endif # ifdef VIR_MIGRATE_PARAM_MIGRATE_DISKS { VIR_MIGRATE_PARAM_MIGRATE_DISKS, VIR_TYPED_PARAM_STRING }, # endif # ifdef VIR_MIGRATE_PARAM_DISKS_PORT { VIR_MIGRATE_PARAM_DISKS_PORT, VIR_TYPED_PARAM_INT }, # endif # ifdef VIR_MIGRATE_PARAM_COMPRESSION { VIR_MIGRATE_PARAM_COMPRESSION, VIR_TYPED_PARAM_STRING }, # endif # ifdef VIR_MIGRATE_PARAM_COMPRESSION_MT_LEVEL { VIR_MIGRATE_PARAM_COMPRESSION_MT_LEVEL, VIR_TYPED_PARAM_INT }, # endif # ifdef VIR_MIGRATE_PARAM_COMPRESSION_MT_THREADS { VIR_MIGRATE_PARAM_COMPRESSION_MT_THREADS, VIR_TYPED_PARAM_INT }, # endif # ifdef VIR_MIGRATE_PARAM_COMPRESSION_MT_DTHREADS { VIR_MIGRATE_PARAM_COMPRESSION_MT_DTHREADS, VIR_TYPED_PARAM_INT }, # endif # ifdef VIR_MIGRATE_PARAM_COMPRESSION_XBZRLE_CACHE { VIR_MIGRATE_PARAM_COMPRESSION_XBZRLE_CACHE, VIR_TYPED_PARAM_ULLONG }, # endif # ifdef VIR_MIGRATE_PARAM_AUTO_CONVERGE_INITIAL { VIR_MIGRATE_PARAM_AUTO_CONVERGE_INITIAL, VIR_TYPED_PARAM_INT }, # endif # ifdef VIR_MIGRATE_PARAM_AUTO_CONVERGE_INCREMENT { VIR_MIGRATE_PARAM_AUTO_CONVERGE_INCREMENT, VIR_TYPED_PARAM_INT }, # endif # ifdef VIR_MIGRATE_PARAM_BANDWIDTH_POSTCOPY { VIR_MIGRATE_PARAM_BANDWIDTH_POSTCOPY, VIR_TYPED_PARAM_ULLONG }, # endif # ifdef VIR_MIGRATE_PARAM_PARALLEL_CONNECTIONS { VIR_MIGRATE_PARAM_PARALLEL_CONNECTIONS, VIR_TYPED_PARAM_INT }, # endif # ifdef VIR_MIGRATE_PARAM_DISKS_URI { VIR_MIGRATE_PARAM_DISKS_URI, VIR_TYPED_PARAM_STRING }, #endif #ifdef VIR_MIGRATE_PARAM_TLS_DESTINATION { VIR_MIGRATE_PARAM_TLS_DESTINATION, VIR_TYPED_PARAM_STRING }, #endif #ifdef VIR_MIGRATE_PARAM_COMPRESSION_ZLIB_LEVEL { VIR_MIGRATE_PARAM_COMPRESSION_ZLIB_LEVEL, VIR_TYPED_PARAM_INT }, #endif #ifdef VIR_MIGRATE_PARAM_COMPRESSION_ZSTD_LEVEL { VIR_MIGRATE_PARAM_COMPRESSION_ZSTD_LEVEL, VIR_TYPED_PARAM_INT }, #endif }; static PyObject * libvirt_virDomainMigrate3(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_domain; virDomainPtr domain; PyObject *pyobj_dconn; virConnectPtr dconn; PyObject *dict; unsigned int flags; virTypedParameterPtr params; int nparams = 0; virDomainPtr ddom = NULL; if (!PyArg_ParseTuple(args, (char *) "OOOI:virDomainMigrate3", &pyobj_domain, &pyobj_dconn, &dict, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); dconn = (virConnectPtr) PyvirConnect_Get(pyobj_dconn); if (!PyDict_Check(dict)) { PyErr_Format(PyExc_TypeError, "migration params must be a dictionary"); return NULL; } if (virPyDictToTypedParams(dict, ¶ms, &nparams, virPyDomainMigrate3Params, VIR_N_ELEMENTS(virPyDomainMigrate3Params)) < 0) { return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; ddom = virDomainMigrate3(domain, dconn, params, nparams, flags); LIBVIRT_END_ALLOW_THREADS; virTypedParamsFree(params, nparams); return libvirt_virDomainPtrWrap(ddom); } static PyObject * libvirt_virDomainMigrateToURI3(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_domain; virDomainPtr domain; char *dconnuri; PyObject *dict; unsigned int flags; virTypedParameterPtr params; int nparams; int ret = -1; if (!PyArg_ParseTuple(args, (char *) "OzOI:virDomainMigrate3", &pyobj_domain, &dconnuri, &dict, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (!PyDict_Check(dict)) { PyErr_Format(PyExc_TypeError, "migration params must be a dictionary"); return NULL; } if (virPyDictToTypedParams(dict, ¶ms, &nparams, virPyDomainMigrate3Params, VIR_N_ELEMENTS(virPyDomainMigrate3Params)) < 0) { return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; ret = virDomainMigrateToURI3(domain, dconnuri, params, nparams, flags); LIBVIRT_END_ALLOW_THREADS; virTypedParamsFree(params, nparams); return libvirt_intWrap(ret); } #endif /* LIBVIR_CHECK_VERSION(1, 1, 0) */ static PyObject * libvirt_virDomainBlockPeek(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; const char *disk; unsigned long long offset; size_t size; char *buf; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OzKkI:virDomainBlockPeek", &pyobj_domain, &disk, &offset, &size, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (VIR_ALLOC_N(buf, size) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainBlockPeek(domain, disk, offset, size, buf, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } py_retval = libvirt_charPtrSizeWrap(buf, size); cleanup: VIR_FREE(buf); return py_retval; } static PyObject * libvirt_virDomainMemoryPeek(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; unsigned long long start; size_t size; char *buf; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OKkI:virDomainMemoryPeek", &pyobj_domain, &start, &size, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (VIR_ALLOC_N(buf, size) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainMemoryPeek(domain, start, size, buf, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } py_retval = libvirt_charPtrSizeWrap(buf, size); cleanup: VIR_FREE(buf); return py_retval; } #if LIBVIR_CHECK_VERSION(0, 10, 2) static PyObject * libvirt_virNodeSetMemoryParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virConnectPtr conn; PyObject *pyobj_conn, *info; PyObject *ret = NULL; int i_retval; int nparams = 0; Py_ssize_t size = 0; unsigned int flags; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OOI:virNodeSetMemoryParameters", &pyobj_conn, &info, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNodeGetMemoryParameters(conn, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_INT_FAIL; if (nparams == 0) { PyErr_Format(PyExc_LookupError, "no settable attributes"); return NULL; } if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNodeGetMemoryParameters(conn, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNodeSetMemoryParameters(conn, new_params, size, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } static PyObject * libvirt_virNodeGetMemoryParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virConnectPtr conn; PyObject *pyobj_conn; PyObject *ret = NULL; int i_retval; int nparams = 0; unsigned int flags; virTypedParameterPtr params; if (!PyArg_ParseTuple(args, (char *)"OI:virNodeGetMemoryParameters", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNodeGetMemoryParameters(conn, NULL, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; if (!nparams) return PyDict_New(); if (VIR_ALLOC_N(params, nparams) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNodeGetMemoryParameters(conn, params, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ #if LIBVIR_CHECK_VERSION(1, 0, 0) static PyObject * libvirt_virNodeGetCPUMap(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virConnectPtr conn; PyObject *pyobj_conn; PyObject *ret = NULL; PyObject *pycpumap = NULL; int i_retval; unsigned char *cpumap = NULL; unsigned int online = 0; unsigned int flags; ssize_t i; if (!PyArg_ParseTuple(args, (char *)"OI:virNodeGetCPUMap", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNodeGetCPUMap(conn, &cpumap, &online, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_NONE; if ((ret = PyTuple_New(3)) == NULL) goto error; /* 0: number of CPUs */ VIR_PY_TUPLE_SET_GOTO(ret, 0, libvirt_intWrap(i_retval), error); /* 1: CPU map */ if ((pycpumap = PyList_New(i_retval)) == NULL) goto error; VIR_PY_TUPLE_SET_GOTO(ret, 1, pycpumap, error); for (i = 0; i < i_retval; i++) VIR_PY_LIST_SET_GOTO(pycpumap, i, PyBool_FromLong(VIR_CPU_USED(cpumap, i)), error); /* 2: number of online CPUs */ VIR_PY_TUPLE_SET_GOTO(ret, 2, libvirt_uintWrap(online), error); cleanup: VIR_FREE(cpumap); return ret; error: Py_CLEAR(ret); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(1, 0, 0) */ #if LIBVIR_CHECK_VERSION(1, 1, 1) static PyObject * libvirt_virDomainCreateWithFiles(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; PyObject *pyobj_files; unsigned int flags; unsigned int nfiles; int *files = NULL; size_t i; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainCreateWithFiles", &pyobj_domain, &pyobj_files, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); nfiles = PyList_Size(pyobj_files); if (VIR_ALLOC_N(files, nfiles) < 0) return PyErr_NoMemory(); for (i = 0; i < nfiles; i++) { PyObject *pyfd; int fd; pyfd = PyList_GetItem(pyobj_files, i); if (libvirt_intUnwrap(pyfd, &fd) < 0) goto cleanup; files[i] = fd; } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainCreateWithFiles(domain, nfiles, files, flags); LIBVIRT_END_ALLOW_THREADS; py_retval = libvirt_intWrap(c_retval); cleanup: VIR_FREE(files); return py_retval; } static PyObject * libvirt_virDomainCreateXMLWithFiles(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; virDomainPtr c_retval; virConnectPtr conn; PyObject *pyobj_conn; char * xmlDesc; PyObject *pyobj_files; unsigned int flags; unsigned int nfiles; int *files = NULL; size_t i; if (!PyArg_ParseTuple(args, (char *)"OzOI:virDomainCreateXMLWithFiles", &pyobj_conn, &xmlDesc, &pyobj_files, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); nfiles = PyList_Size(pyobj_files); if (VIR_ALLOC_N(files, nfiles) < 0) return PyErr_NoMemory(); for (i = 0; i < nfiles; i++) { PyObject *pyfd; int fd; pyfd = PyList_GetItem(pyobj_files, i); if (libvirt_intUnwrap(pyfd, &fd) < 0) goto cleanup; files[i] = fd; } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainCreateXMLWithFiles(conn, xmlDesc, nfiles, files, flags); LIBVIRT_END_ALLOW_THREADS; py_retval = libvirt_virDomainPtrWrap((virDomainPtr) c_retval); cleanup: VIR_FREE(files); return py_retval; } #endif /* LIBVIR_CHECK_VERSION(1, 1, 1) */ #if LIBVIR_CHECK_VERSION(1, 2, 5) static PyObject * libvirt_virDomainFSFreeze(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; PyObject *pyobj_list; unsigned int flags; unsigned int nmountpoints = 0; char **mountpoints = NULL; size_t i = 0; size_t j = 0; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainFSFreeze", &pyobj_domain, &pyobj_list, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (PyList_Check(pyobj_list)) { nmountpoints = PyList_Size(pyobj_list); if (VIR_ALLOC_N(mountpoints, nmountpoints) < 0) return PyErr_NoMemory(); for (i = 0; i < nmountpoints; i++) { if (libvirt_charPtrUnwrap(PyList_GetItem(pyobj_list, i), mountpoints+i) < 0) goto cleanup; } } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainFSFreeze(domain, (const char **) mountpoints, nmountpoints, flags); LIBVIRT_END_ALLOW_THREADS; py_retval = libvirt_intWrap(c_retval); cleanup: for (j = 0 ; j < i ; j++) VIR_FREE(mountpoints[j]); VIR_FREE(mountpoints); return py_retval; } static PyObject * libvirt_virDomainFSThaw(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; PyObject *pyobj_list; unsigned int flags; unsigned int nmountpoints = 0; char **mountpoints = NULL; size_t i = 0; size_t j = 0; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainFSThaw", &pyobj_domain, &pyobj_list, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (PyList_Check(pyobj_list)) { nmountpoints = PyList_Size(pyobj_list); if (VIR_ALLOC_N(mountpoints, nmountpoints) < 0) return PyErr_NoMemory(); for (i = 0; i < nmountpoints; i++) { if (libvirt_charPtrUnwrap(PyList_GetItem(pyobj_list, i), mountpoints+i) < 0) goto cleanup; } } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainFSThaw(domain, (const char **) mountpoints, nmountpoints, flags); LIBVIRT_END_ALLOW_THREADS; py_retval = libvirt_intWrap(c_retval); cleanup: for (j = 0 ; j < i ; j++) VIR_FREE(mountpoints[j]); VIR_FREE(mountpoints); return py_retval; } static PyObject * libvirt_virDomainGetTime(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; PyObject *dict = NULL; PyObject *pyobj_domain; virDomainPtr domain; long long seconds; unsigned int nseconds; unsigned int flags; int c_retval; if (!PyArg_ParseTuple(args, (char*)"OI:virDomainGetTime", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (!(dict = PyDict_New())) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetTime(domain, &seconds, &nseconds, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } VIR_PY_DICT_SET_GOTO(dict, libvirt_constcharPtrWrap("seconds"), libvirt_longlongWrap(seconds), cleanup); VIR_PY_DICT_SET_GOTO(dict, libvirt_constcharPtrWrap("nseconds"), libvirt_longlongWrap(nseconds), cleanup); py_retval = dict; dict = NULL; cleanup: Py_XDECREF(dict); return py_retval; } static PyObject * libvirt_virDomainSetTime(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_domain; PyObject *pyobj_seconds; PyObject *pyobj_nseconds; PyObject *py_dict; virDomainPtr domain; long long seconds = 0; unsigned int nseconds = 0; unsigned int flags; ssize_t py_dict_size = 0; int c_retval; if (!PyArg_ParseTuple(args, (char*)"OOI:virDomainSetTime", &pyobj_domain, &py_dict, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if (PyDict_Check(py_dict)) { py_dict_size = PyDict_Size(py_dict); if ((pyobj_seconds = PyDict_GetItemString(py_dict, "seconds"))) { if (libvirt_longlongUnwrap(pyobj_seconds, &seconds) < 0) return NULL; } else { PyErr_Format(PyExc_LookupError, "Dictionary must contains 'seconds'"); return NULL; } if ((pyobj_nseconds = PyDict_GetItemString(py_dict, "nseconds"))) { if (libvirt_uintUnwrap(pyobj_nseconds, &nseconds) < 0) return NULL; } else if (py_dict_size > 1) { PyErr_Format(PyExc_LookupError, "Dictionary contains unknown key"); return NULL; } } else if (py_dict != Py_None || !flags) { PyErr_Format(PyExc_TypeError, "time must be a dictionary " "or None with flags set"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainSetTime(domain, seconds, nseconds, flags); LIBVIRT_END_ALLOW_THREADS; return libvirt_intWrap(c_retval); } #endif /* LIBVIR_CHECK_VERSION(1, 2, 5) */ #if LIBVIR_CHECK_VERSION(1, 2, 6) static PyObject * libvirt_virNodeGetFreePages(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; PyObject *pyobj_conn; PyObject *pyobj_pagesize; PyObject *pyobj_counts = NULL; virConnectPtr conn; unsigned int *pages = NULL; int startCell; unsigned int cellCount; unsigned int flags; unsigned long long *counts = NULL; int c_retval; ssize_t pyobj_pagesize_size, i, j; if (!PyArg_ParseTuple(args, (char *)"OOiII:virNodeGetFreePages", &pyobj_conn, &pyobj_pagesize, &startCell, &cellCount, &flags)) return NULL; if (!PyList_Check(pyobj_pagesize)) { PyErr_Format(PyExc_TypeError, "pagesize must be list"); return NULL; } if (cellCount == 0) { PyErr_Format(PyExc_LookupError, "cellCount must not be zero"); return NULL; } conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); pyobj_pagesize_size = PyList_Size(pyobj_pagesize); if (VIR_ALLOC_N(pages, pyobj_pagesize_size) < 0 || VIR_ALLOC_N(counts, pyobj_pagesize_size * cellCount) < 0) { PyErr_NoMemory(); goto cleanup; } if (!(pyobj_counts = PyDict_New())) goto cleanup; for (i = 0; i < pyobj_pagesize_size; i++) { PyObject *tmp = PyList_GetItem(pyobj_pagesize, i); if (libvirt_uintUnwrap(tmp, &pages[i]) < 0) goto cleanup; } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeGetFreePages(conn, pyobj_pagesize_size, pages, startCell, cellCount, counts, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } for (i = 0; i < c_retval;) { PyObject *per_node = NULL; if (!(per_node = PyDict_New())) goto cleanup; VIR_PY_DICT_SET_GOTO(pyobj_counts, libvirt_intWrap(startCell + i/pyobj_pagesize_size), per_node, cleanup); for (j = 0; j < pyobj_pagesize_size; j ++) VIR_PY_DICT_SET_GOTO(per_node, libvirt_intWrap(pages[j]), libvirt_intWrap(counts[i + j]), cleanup); i += pyobj_pagesize_size; } py_retval = pyobj_counts; pyobj_counts = NULL; cleanup: Py_XDECREF(pyobj_counts); VIR_FREE(pages); VIR_FREE(counts); return py_retval; } static PyObject * libvirt_virNetworkGetDHCPLeases(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; PyObject *py_lease = NULL; virNetworkPtr network; PyObject *pyobj_network; unsigned int flags; virNetworkDHCPLeasePtr *leases = NULL; int leases_count; char *mac = NULL; ssize_t i; if (!PyArg_ParseTuple(args, (char *) "OzI:virNetworkGetDHCPLeases", &pyobj_network, &mac, &flags)) return NULL; network = (virNetworkPtr) PyvirNetwork_Get(pyobj_network); LIBVIRT_BEGIN_ALLOW_THREADS; leases_count = virNetworkGetDHCPLeases(network, mac, &leases, flags); LIBVIRT_END_ALLOW_THREADS; if (leases_count < 0) { py_retval = VIR_PY_NONE; goto cleanup; } if (!(py_retval = PyList_New(leases_count))) goto error; for (i = 0; i < leases_count; i++) { virNetworkDHCPLeasePtr lease = leases[i]; if ((py_lease = PyDict_New()) == NULL) goto error; VIR_PY_LIST_SET_GOTO(py_retval, i, py_lease, error); VIR_PY_DICT_SET_GOTO(py_lease, libvirt_constcharPtrWrap("iface"), libvirt_charPtrWrap(lease->iface), error); VIR_PY_DICT_SET_GOTO(py_lease, libvirt_constcharPtrWrap("expirytime"), libvirt_longlongWrap(lease->expirytime), error); VIR_PY_DICT_SET_GOTO(py_lease, libvirt_constcharPtrWrap("type"), libvirt_intWrap(lease->type), error); VIR_PY_DICT_SET_GOTO(py_lease, libvirt_constcharPtrWrap("mac"), libvirt_charPtrWrap(lease->mac), error); VIR_PY_DICT_SET_GOTO(py_lease, libvirt_constcharPtrWrap("ipaddr"), libvirt_charPtrWrap(lease->ipaddr), error); VIR_PY_DICT_SET_GOTO(py_lease, libvirt_constcharPtrWrap("prefix"), libvirt_uintWrap(lease->prefix), error); VIR_PY_DICT_SET_GOTO(py_lease, libvirt_constcharPtrWrap("hostname"), libvirt_charPtrWrap(lease->hostname), error); VIR_PY_DICT_SET_GOTO(py_lease, libvirt_constcharPtrWrap("clientid"), libvirt_charPtrWrap(lease->clientid), error); VIR_PY_DICT_SET_GOTO(py_lease, libvirt_constcharPtrWrap("iaid"), libvirt_charPtrWrap(lease->iaid), error); } cleanup: if (leases_count > 0) for (i = 0; i < leases_count; i++) virNetworkDHCPLeaseFree(leases[i]); VIR_FREE(leases); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(1, 2, 6) */ #if LIBVIR_CHECK_VERSION(1, 2, 8) static PyObject * convertDomainStatsRecord(virDomainStatsRecordPtr *records, int nrecords) { PyObject *py_retval; PyObject *py_record; PyObject *py_record_stats = NULL; virDomainPtr dom = NULL; ssize_t i; if (!(py_retval = PyList_New(nrecords))) return NULL; for (i = 0; i < nrecords; i++) { if (!(py_record = PyTuple_New(2))) goto error; VIR_PY_LIST_SET_GOTO(py_retval, i, py_record, error); dom = records[i]->dom; virDomainRef(dom); VIR_PY_TUPLE_SET_GOTO(py_record, 0, libvirt_virDomainPtrWrap(dom), error); dom = NULL; if (!(py_record_stats = getPyVirTypedParameter(records[i]->params, records[i]->nparams))) goto error; VIR_PY_TUPLE_SET_GOTO(py_record, 1, py_record_stats, error); } return py_retval; error: if (dom) virDomainFree(dom); Py_XDECREF(py_retval); return NULL; } static PyObject * libvirt_virConnectGetAllDomainStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval; virConnectPtr conn; virDomainStatsRecordPtr *records; int nrecords; unsigned int flags; unsigned int stats; if (!PyArg_ParseTuple(args, (char *)"OII:virConnectGetAllDomainStats", &pyobj_conn, &stats, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; nrecords = virConnectGetAllDomainStats(conn, stats, &records, flags); LIBVIRT_END_ALLOW_THREADS; if (nrecords < 0) return VIR_PY_NONE; py_retval = convertDomainStatsRecord(records, nrecords); virDomainStatsRecordListFree(records); return py_retval; } static PyObject * libvirt_virDomainListGetStats(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval; PyObject *py_domlist; virDomainStatsRecordPtr *records = NULL; virDomainPtr *doms = NULL; int nrecords; int ndoms; ssize_t i; unsigned int flags; unsigned int stats; if (!PyArg_ParseTuple(args, (char *)"OOII:virDomainListGetStats", &pyobj_conn, &py_domlist, &stats, &flags)) return NULL; if (PyList_Check(py_domlist)) { ndoms = PyList_Size(py_domlist); if (VIR_ALLOC_N(doms, ndoms + 1) < 0) return PyErr_NoMemory(); for (i = 0; i < ndoms; i++) doms[i] = PyvirDomain_Get(PyList_GetItem(py_domlist, i)); } LIBVIRT_BEGIN_ALLOW_THREADS; nrecords = virDomainListGetStats(doms, stats, &records, flags); LIBVIRT_END_ALLOW_THREADS; if (nrecords < 0) { py_retval = VIR_PY_NONE; goto cleanup; } py_retval = convertDomainStatsRecord(records, nrecords); cleanup: virDomainStatsRecordListFree(records); VIR_FREE(doms); return py_retval; } static virPyTypedParamsHint virPyDomainBlockCopyParams[] = { { VIR_DOMAIN_BLOCK_COPY_BANDWIDTH, VIR_TYPED_PARAM_ULLONG }, { VIR_DOMAIN_BLOCK_COPY_GRANULARITY, VIR_TYPED_PARAM_UINT }, { VIR_DOMAIN_BLOCK_COPY_BUF_SIZE, VIR_TYPED_PARAM_ULLONG }, }; static PyObject * libvirt_virDomainBlockCopy(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_dom = NULL; PyObject *pyobj_dict = NULL; virDomainPtr dom; char *disk = NULL; char *destxml = NULL; virTypedParameterPtr params = NULL; int nparams = 0; unsigned int flags = 0; int c_retval; if (!PyArg_ParseTuple(args, (char *) "Ozz|OI:virDomainBlockCopy", &pyobj_dom, &disk, &destxml, &pyobj_dict, &flags)) return NULL; if (PyDict_Check(pyobj_dict)) { if (virPyDictToTypedParams(pyobj_dict, ¶ms, &nparams, virPyDomainBlockCopyParams, VIR_N_ELEMENTS(virPyDomainBlockCopyParams)) < 0) { return NULL; } } else if (pyobj_dict != Py_None) { PyErr_Format(PyExc_TypeError, "block params must be a dictionary"); return NULL; } dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainBlockCopy(dom, disk, destxml, params, nparams, flags); LIBVIRT_END_ALLOW_THREADS; virTypedParamsFree(params, nparams); return libvirt_intWrap(c_retval); } #endif /* LIBVIR_CHECK_VERSION(1, 2, 8) */ #if LIBVIR_CHECK_VERSION(1, 2, 9) static PyObject * libvirt_virNodeAllocPages(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *pyobj_pages; Py_ssize_t size = 0; Py_ssize_t pos = 0; PyObject *key, *value; virConnectPtr conn; unsigned int npages = 0; unsigned int *pageSizes = NULL; unsigned long long *pageCounts = NULL; int startCell = -1; unsigned int cellCount = 1; unsigned int flags = VIR_NODE_ALLOC_PAGES_ADD; int c_retval; if (!PyArg_ParseTuple(args, (char *)"OOiII:virNodeAllocPages", &pyobj_conn, &pyobj_pages, &startCell, &cellCount, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if ((size = PyDict_Size(pyobj_pages)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to pages attribute"); return NULL; } if (VIR_ALLOC_N(pageSizes, size) < 0 || VIR_ALLOC_N(pageCounts, size) < 0) { PyErr_NoMemory(); goto error; } while (PyDict_Next(pyobj_pages, &pos, &key, &value)) { if (libvirt_uintUnwrap(key, &pageSizes[npages]) < 0 || libvirt_ulonglongUnwrap(value, &pageCounts[npages]) < 0) goto error; npages++; } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNodeAllocPages(conn, npages, pageSizes, pageCounts, startCell, cellCount, flags); LIBVIRT_END_ALLOW_THREADS; VIR_FREE(pageSizes); VIR_FREE(pageCounts); return libvirt_intWrap(c_retval); error: VIR_FREE(pageSizes); VIR_FREE(pageCounts); return NULL; } #endif /* LIBVIR_CHECK_VERSION(1, 2, 8) */ #if LIBVIR_CHECK_VERSION(1, 2, 11) static PyObject * libvirt_virDomainGetFSInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain; unsigned int flags; virDomainFSInfoPtr *fsinfo = NULL; int c_retval, i; size_t j; PyObject *py_retval = NULL; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetFSInfo", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainGetFSInfo(domain, &fsinfo, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) { py_retval = VIR_PY_NONE; goto cleanup; } /* convert to a Python list */ if ((py_retval = PyList_New(c_retval)) == NULL) goto error; for (i = 0; i < c_retval; i++) { virDomainFSInfoPtr fs = fsinfo[i]; PyObject *info, *alias; if (fs == NULL) goto error; info = PyTuple_New(4); if (info == NULL) goto error; VIR_PY_LIST_SET_GOTO(py_retval, i, info, error); VIR_PY_TUPLE_SET_GOTO(info, 0, libvirt_constcharPtrWrap(fs->mountpoint), error); VIR_PY_TUPLE_SET_GOTO(info, 1, libvirt_constcharPtrWrap(fs->name), error); VIR_PY_TUPLE_SET_GOTO(info, 2, libvirt_constcharPtrWrap(fs->fstype), error); alias = PyList_New(0); if (alias == NULL) goto error; VIR_PY_TUPLE_SET_GOTO(info, 3, alias, error); for (j = 0; j < fs->ndevAlias; j++) VIR_PY_LIST_APPEND_GOTO(alias, libvirt_constcharPtrWrap(fs->devAlias[j]), error); } cleanup: if (c_retval > 0) for (i = 0; i < c_retval; i++) virDomainFSInfoFree(fsinfo[i]); VIR_FREE(fsinfo); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } #endif /* LIBVIR_CHECK_VERSION(1, 2, 11) */ #if LIBVIR_CHECK_VERSION(1, 3, 3) static PyObject * libvirt_virDomainGetPerfEvents(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_domain; virDomainPtr domain; virTypedParameterPtr params = NULL; int nparams = 0; PyObject *dict = NULL; unsigned int flags; int rc; if (!PyArg_ParseTuple(args, (char *) "OI:virDomainGetPerfEvents", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; rc = virDomainGetPerfEvents(domain, ¶ms, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (rc < 0) return VIR_PY_NONE; if (!(dict = getPyVirTypedParameter(params, nparams))) goto cleanup; cleanup: virTypedParamsFree(params, nparams); return dict; } static PyObject * libvirt_virDomainSetPerfEvents(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virDomainPtr domain; PyObject *pyobj_domain, *info; PyObject *ret = NULL; int i_retval; int nparams = 0; Py_ssize_t size = 0; unsigned int flags; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainSetPerfEvents", &pyobj_domain, &info, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetPerfEvents(domain, ¶ms, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_INT_FAIL; if (nparams == 0) { PyErr_Format(PyExc_LookupError, "Domain has no settable attributes"); return NULL; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainSetPerfEvents(domain, new_params, size, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } #endif /* LIBVIR_CHECK_VERSION(1, 3, 3) */ #if LIBVIR_CHECK_VERSION(2, 0, 0) static void libvirt_virConnectStoragePoolEventFreeFunc(void *opaque) { PyObject *pyobj_conn = (PyObject*)opaque; LIBVIRT_ENSURE_THREAD_STATE; Py_DECREF(pyobj_conn); LIBVIRT_RELEASE_THREAD_STATE; } static int libvirt_virConnectStoragePoolEventLifecycleCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virStoragePoolPtr pool, int event, int detail, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_pool; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virStoragePoolPtr */ virStoragePoolRef(pool); if (!(pyobj_pool = libvirt_virStoragePoolPtrWrap(pool))) { virStoragePoolFree(pool); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchStoragePoolEventLifecycleCallback", (char*)"OiiO", pyobj_pool, event, detail, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_pool); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectStoragePoolEventGenericCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virStoragePoolPtr pool, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_pool; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virStoragePoolPtr */ virStoragePoolRef(pool); if (!(pyobj_pool = libvirt_virStoragePoolPtrWrap(pool))) { virStoragePoolFree(pool); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchStoragePoolEventGenericCallback", (char*)"OO", pyobj_pool, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_pool); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static PyObject * libvirt_virConnectStoragePoolEventRegisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; /* virConnectPtr */ PyObject *pyobj_pool; PyObject *pyobj_cbData; /* hash of callback data */ int eventID; virConnectPtr conn; int ret = 0; virConnectStoragePoolEventGenericCallback cb = NULL; virStoragePoolPtr pool; if (!PyArg_ParseTuple(args, (char *) "OOiO:virConnectStoragePoolEventRegisterAny", &pyobj_conn, &pyobj_pool, &eventID, &pyobj_cbData)) return NULL; DEBUG("libvirt_virConnectStoragePoolEventRegister(%p %p %d %p) called\n", pyobj_conn, pyobj_pool, eventID, pyobj_cbData); conn = PyvirConnect_Get(pyobj_conn); if (pyobj_pool == Py_None) pool = NULL; else pool = PyvirStoragePool_Get(pyobj_pool); switch ((virStoragePoolEventID) eventID) { case VIR_STORAGE_POOL_EVENT_ID_LIFECYCLE: cb = VIR_STORAGE_POOL_EVENT_CALLBACK(libvirt_virConnectStoragePoolEventLifecycleCallback); break; case VIR_STORAGE_POOL_EVENT_ID_REFRESH: cb = VIR_STORAGE_POOL_EVENT_CALLBACK(libvirt_virConnectStoragePoolEventGenericCallback); break; case VIR_STORAGE_POOL_EVENT_ID_LAST: break; } if (!cb) { return VIR_PY_INT_FAIL; } Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectStoragePoolEventRegisterAny(conn, pool, eventID, cb, pyobj_cbData, libvirt_virConnectStoragePoolEventFreeFunc); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } return libvirt_intWrap(ret); } static PyObject * libvirt_virConnectStoragePoolEventDeregisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; int callbackID; virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "Oi:virConnectStoragePoolEventDeregisterAny", &pyobj_conn, &callbackID)) return NULL; DEBUG("libvirt_virConnectStoragePoolEventDeregister(%p) called\n", pyobj_conn); conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectStoragePoolEventDeregisterAny(conn, callbackID); LIBVIRT_END_ALLOW_THREADS; return libvirt_intWrap(ret); } static PyObject * libvirt_virDomainGetGuestVcpus(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_domain; virDomainPtr domain; virTypedParameterPtr params = NULL; unsigned int nparams = 0; unsigned int flags; int i_retval; PyObject *ret = NULL; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetGuestVcpus", &pyobj_domain, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetGuestVcpus(domain, ¶ms, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } #endif /* LIBVIR_CHECK_VERSION(2, 0, 0)*/ #if LIBVIR_CHECK_VERSION(2, 2, 0) static void libvirt_virConnectNodeDeviceEventFreeFunc(void *opaque) { PyObject *pyobj_conn = (PyObject*)opaque; LIBVIRT_ENSURE_THREAD_STATE; Py_DECREF(pyobj_conn); LIBVIRT_RELEASE_THREAD_STATE; } static int libvirt_virConnectNodeDeviceEventLifecycleCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virNodeDevicePtr dev, int event, int detail, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dev; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virNodeDevicePtr */ virNodeDeviceRef(dev); if (!(pyobj_dev = libvirt_virNodeDevicePtrWrap(dev))) { virNodeDeviceFree(dev); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchNodeDeviceEventLifecycleCallback", (char*)"OiiO", pyobj_dev, event, detail, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dev); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectNodeDeviceEventGenericCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virNodeDevicePtr dev, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_dev; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virNodeDevicePtr */ virNodeDeviceRef(dev); if (!(pyobj_dev = libvirt_virNodeDevicePtrWrap(dev))) { virNodeDeviceFree(dev); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchNodeDeviceEventGenericCallback", (char*)"OO", pyobj_dev, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_dev); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static PyObject * libvirt_virConnectNodeDeviceEventRegisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; /* virConnectPtr */ PyObject *pyobj_dev; PyObject *pyobj_cbData; /* hash of callback data */ int eventID; virConnectPtr conn; int ret = 0; virConnectNodeDeviceEventGenericCallback cb = NULL; virNodeDevicePtr dev; if (!PyArg_ParseTuple(args, (char *) "OOiO:virConnectNodeDeviceEventRegisterAny", &pyobj_conn, &pyobj_dev, &eventID, &pyobj_cbData)) return NULL; DEBUG("libvirt_virConnectNodeDeviceEventRegister(%p %p %d %p) called\n", pyobj_conn, pyobj_dev, eventID, pyobj_cbData); conn = PyvirConnect_Get(pyobj_conn); if (pyobj_dev == Py_None) dev = NULL; else dev = PyvirNodeDevice_Get(pyobj_dev); switch ((virNodeDeviceEventID) eventID) { case VIR_NODE_DEVICE_EVENT_ID_LIFECYCLE: cb = VIR_NODE_DEVICE_EVENT_CALLBACK(libvirt_virConnectNodeDeviceEventLifecycleCallback); break; case VIR_NODE_DEVICE_EVENT_ID_UPDATE: cb = VIR_NODE_DEVICE_EVENT_CALLBACK(libvirt_virConnectNodeDeviceEventGenericCallback); break; case VIR_NODE_DEVICE_EVENT_ID_LAST: break; } if (!cb) { return VIR_PY_INT_FAIL; } Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectNodeDeviceEventRegisterAny(conn, dev, eventID, cb, pyobj_cbData, libvirt_virConnectNodeDeviceEventFreeFunc); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } return libvirt_intWrap(ret); } static PyObject * libvirt_virConnectNodeDeviceEventDeregisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; int callbackID; virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "Oi:virConnectNodeDeviceEventDeregister", &pyobj_conn, &callbackID)) return NULL; DEBUG("libvirt_virConnectNodeDeviceEventDeregister(%p) called\n", pyobj_conn); conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectNodeDeviceEventDeregisterAny(conn, callbackID); LIBVIRT_END_ALLOW_THREADS; return libvirt_intWrap(ret); } #endif /* LIBVIR_CHECK_VERSION(2, 2, 0)*/ #if LIBVIR_CHECK_VERSION(3, 0, 0) static void libvirt_virConnectSecretEventFreeFunc(void *opaque) { PyObject *pyobj_conn = (PyObject*)opaque; LIBVIRT_ENSURE_THREAD_STATE; Py_DECREF(pyobj_conn); LIBVIRT_RELEASE_THREAD_STATE; } static int libvirt_virConnectSecretEventLifecycleCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virSecretPtr secret, int event, int detail, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_secret; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virSecretPtr */ virSecretRef(secret); if (!(pyobj_secret = libvirt_virSecretPtrWrap(secret))) { virSecretFree(secret); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchSecretEventLifecycleCallback", (char*)"OiiO", pyobj_secret, event, detail, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_secret); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static int libvirt_virConnectSecretEventGenericCallback(virConnectPtr conn ATTRIBUTE_UNUSED, virSecretPtr secret, void *opaque) { PyObject *pyobj_cbData = (PyObject*)opaque; PyObject *pyobj_secret; PyObject *pyobj_ret = NULL; PyObject *pyobj_conn; PyObject *dictKey; int ret = -1; LIBVIRT_ENSURE_THREAD_STATE; if (!(dictKey = libvirt_constcharPtrWrap("conn"))) goto cleanup; pyobj_conn = PyDict_GetItem(pyobj_cbData, dictKey); Py_DECREF(dictKey); /* Create a python instance of this virSecretPtr */ virSecretRef(secret); if (!(pyobj_secret = libvirt_virSecretPtrWrap(secret))) { virSecretFree(secret); goto cleanup; } Py_INCREF(pyobj_cbData); /* Call the Callback Dispatcher */ pyobj_ret = PyObject_CallMethod(pyobj_conn, (char*)"_dispatchSecretEventGenericCallback", (char*)"OO", pyobj_secret, pyobj_cbData); Py_DECREF(pyobj_cbData); Py_DECREF(pyobj_secret); cleanup: if (!pyobj_ret) { DEBUG("%s - ret:%p\n", __FUNCTION__, pyobj_ret); PyErr_Print(); } else { Py_DECREF(pyobj_ret); ret = 0; } LIBVIRT_RELEASE_THREAD_STATE; return ret; } static PyObject * libvirt_virConnectSecretEventRegisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; /* virConnectPtr */ PyObject *pyobj_secret; PyObject *pyobj_cbData; /* hash of callback data */ int eventID; virConnectPtr conn; int ret = 0; virConnectSecretEventGenericCallback cb = NULL; virSecretPtr secret; if (!PyArg_ParseTuple(args, (char *) "OOiO:virConnectSecretEventRegisterAny", &pyobj_conn, &pyobj_secret, &eventID, &pyobj_cbData)) return NULL; DEBUG("libvirt_virConnectSecretEventRegister(%p %p %d %p) called\n", pyobj_conn, pyobj_secret, eventID, pyobj_cbData); conn = PyvirConnect_Get(pyobj_conn); if (pyobj_secret == Py_None) secret = NULL; else secret = PyvirSecret_Get(pyobj_secret); switch ((virSecretEventID) eventID) { case VIR_SECRET_EVENT_ID_LIFECYCLE: cb = VIR_SECRET_EVENT_CALLBACK(libvirt_virConnectSecretEventLifecycleCallback); break; case VIR_SECRET_EVENT_ID_VALUE_CHANGED: cb = VIR_SECRET_EVENT_CALLBACK(libvirt_virConnectSecretEventGenericCallback); break; case VIR_SECRET_EVENT_ID_LAST: break; } if (!cb) { return VIR_PY_INT_FAIL; } Py_INCREF(pyobj_cbData); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectSecretEventRegisterAny(conn, secret, eventID, cb, pyobj_cbData, libvirt_virConnectSecretEventFreeFunc); LIBVIRT_END_ALLOW_THREADS; if (ret < 0) { Py_DECREF(pyobj_cbData); } return libvirt_intWrap(ret); } static PyObject * libvirt_virConnectSecretEventDeregisterAny(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; int callbackID; virConnectPtr conn; int ret = 0; if (!PyArg_ParseTuple(args, (char *) "Oi:virConnectSecretEventDeregister", &pyobj_conn, &callbackID)) return NULL; DEBUG("libvirt_virConnectSecretEventDeregister(%p) called\n", pyobj_conn); conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virConnectSecretEventDeregisterAny(conn, callbackID); LIBVIRT_END_ALLOW_THREADS; return libvirt_intWrap(ret); } #endif /* LIBVIR_CHECK_VERSION(3, 0, 0)*/ #if LIBVIR_CHECK_VERSION(3, 4, 0) static PyObject * libvirt_virStreamRecvHole(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_stream; virStreamPtr stream; long long length = -1; unsigned int flags; int ret; if (!PyArg_ParseTuple(args, (char *) "OI:virStreamRecvHole", &pyobj_stream, &flags)) return NULL; stream = PyvirStream_Get(pyobj_stream); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virStreamRecvHole(stream, &length, flags); LIBVIRT_END_ALLOW_THREADS; DEBUG("StreamRecvHole ret=%d length=%lld\n", ret, length); if (ret < 0) return VIR_PY_NONE; return libvirt_longlongWrap(length); } static PyObject * libvirt_virStreamSendHole(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_stream; virStreamPtr stream; long long length; unsigned int flags; int ret; if (!PyArg_ParseTuple(args, (char *) "OLI:virStreamSendHole", &pyobj_stream, &length, &flags)) return NULL; stream = PyvirStream_Get(pyobj_stream); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virStreamSendHole(stream, length, flags); LIBVIRT_END_ALLOW_THREADS; DEBUG("StreamSendHole ret=%d\n", ret); return libvirt_intWrap(ret); } static PyObject * libvirt_virStreamRecvFlags(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_stream; PyObject *rv; virStreamPtr stream; char *buf = NULL; size_t nbytes; unsigned int flags; int ret; if (!PyArg_ParseTuple(args, (char *) "OkI:virStreamRecvFlags", &pyobj_stream, &nbytes, &flags)) return NULL; stream = PyvirStream_Get(pyobj_stream); if (VIR_ALLOC_N(buf, nbytes + 1) < 0) return PyErr_NoMemory(); LIBVIRT_BEGIN_ALLOW_THREADS; ret = virStreamRecvFlags(stream, buf, nbytes, flags); LIBVIRT_END_ALLOW_THREADS; buf[ret > -1 ? ret : 0] = '\0'; DEBUG("StreamRecvFlags ret=%d strlen=%zu\n", ret, strlen(buf)); if (ret == -2 || ret == -3) return libvirt_intWrap(ret); if (ret < 0) return VIR_PY_NONE; rv = libvirt_charPtrSizeWrap((char *) buf, (Py_ssize_t) ret); VIR_FREE(buf); return rv; } #endif /* LIBVIR_CHECK_VERSION(3, 4, 0) */ #if LIBVIR_CHECK_VERSION(4, 4, 0) static PyObject * libvirt_virConnectBaselineHypervisorCPU(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virConnectPtr conn; PyObject *pyobj_conn; char *emulator; char *arch; char *machine; char *virttype; PyObject *list; unsigned int flags; char **xmlCPUs = NULL; int ncpus = 0; ssize_t i; char *cpu; PyObject *ret = NULL; if (!PyArg_ParseTuple(args, (char *)"OzzzzOI:virConnectBaselineHypervisorCPU", &pyobj_conn, &emulator, &arch, &machine, &virttype, &list, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if (PyList_Check(list)) { ncpus = PyList_Size(list); if (VIR_ALLOC_N(xmlCPUs, ncpus) < 0) return PyErr_NoMemory(); for (i = 0; i < ncpus; i++) { if (libvirt_charPtrUnwrap(PyList_GetItem(list, i), &(xmlCPUs[i])) < 0) goto cleanup; } } LIBVIRT_BEGIN_ALLOW_THREADS; cpu = virConnectBaselineHypervisorCPU(conn, emulator, arch, machine, virttype, (const char **)xmlCPUs, ncpus, flags); LIBVIRT_END_ALLOW_THREADS; ret = libvirt_constcharPtrWrap(cpu); cleanup: for (i = 0; i < ncpus; i++) VIR_FREE(xmlCPUs[i]); VIR_FREE(xmlCPUs); VIR_FREE(cpu); return ret; } #endif /* LIBVIR_CHECK_VERSION(4, 4, 0) */ #if LIBVIR_CHECK_VERSION(4, 5, 0) static PyObject * libvirt_virDomainGetLaunchSecurityInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_dom = NULL; PyObject *ret = NULL; virDomainPtr dom = NULL; virTypedParameterPtr params = NULL; int nparams = 0; unsigned int flags = 0; int i_retval; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetLaunchSecurityInfo", &pyobj_dom, &flags)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virDomainGetLaunchSecurityInfo(dom, ¶ms, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } static PyObject * libvirt_virNodeGetSEVInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn = NULL; PyObject *ret = NULL; virConnectPtr conn = NULL; virTypedParameterPtr params = NULL; int nparams = 0; unsigned int flags = 0; int i_retval; if (!PyArg_ParseTuple(args, (char *)"OI:virNodeGetSEVInfo", &pyobj_conn, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNodeGetSEVInfo(conn, ¶ms, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_NONE; goto cleanup; } ret = getPyVirTypedParameter(params, nparams); cleanup: virTypedParamsFree(params, nparams); return ret; } #endif /* LIBVIR_CHECK_VERSION(4, 5, 0) */ #if LIBVIR_CHECK_VERSION(5, 5, 0) static PyObject * libvirt_virNetworkListAllPorts(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn; PyObject *py_retval = NULL; virNetworkPtr conn; virNetworkPortPtr *doms = NULL; int c_retval = 0; ssize_t i; unsigned int flags; if (!PyArg_ParseTuple(args, (char *)"OI:virNetworkListAllPorts", &pyobj_conn, &flags)) return NULL; conn = (virNetworkPtr) PyvirNetwork_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNetworkListAllPorts(conn, &doms, flags); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; if (!(py_retval = PyList_New(c_retval))) goto cleanup; for (i = 0; i < c_retval; i++) { VIR_PY_LIST_SET_GOTO(py_retval, i, libvirt_virNetworkPortPtrWrap(doms[i]), error); /* python steals the pointer */ doms[i] = NULL; } cleanup: for (i = 0; i < c_retval; i++) if (doms[i]) virNetworkPortFree(doms[i]); VIR_FREE(doms); return py_retval; error: Py_CLEAR(py_retval); goto cleanup; } static PyObject * libvirt_virNetworkPortSetParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virNetworkPortPtr port; PyObject *pyobj_port, *info; PyObject *ret = NULL; int i_retval; int nparams = 0; Py_ssize_t size = 0; unsigned int flags; virTypedParameterPtr params = NULL, new_params = NULL; if (!PyArg_ParseTuple(args, (char *)"OOI:virNetworkPortSetParameters", &pyobj_port, &info, &flags)) return NULL; port = (virNetworkPortPtr) PyvirNetworkPort_Get(pyobj_port); if ((size = PyDict_Size(info)) < 0) return NULL; if (size == 0) { PyErr_Format(PyExc_LookupError, "Need non-empty dictionary to set attributes"); return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNetworkPortGetParameters(port, ¶ms, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) return VIR_PY_INT_FAIL; if (nparams == 0) { PyErr_Format(PyExc_LookupError, "Port has no settable attributes"); return NULL; } new_params = setPyVirTypedParameter(info, params, nparams); if (!new_params) goto cleanup; LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virNetworkPortSetParameters(port, new_params, size, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); virTypedParamsFree(new_params, size); return ret; } static PyObject * libvirt_virNetworkPortGetParameters(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_port; virNetworkPortPtr port; virTypedParameterPtr params = NULL; int nparams = 0; PyObject *dict = NULL; unsigned int flags; int rc; if (!PyArg_ParseTuple(args, (char *) "OI:virNetworkPortGetParameters", &pyobj_port, &flags)) return NULL; port = (virNetworkPortPtr) PyvirNetworkPort_Get(pyobj_port); LIBVIRT_BEGIN_ALLOW_THREADS; rc = virNetworkPortGetParameters(port, ¶ms, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (rc < 0) return VIR_PY_NONE; dict = getPyVirTypedParameter(params, nparams); virTypedParamsFree(params, nparams); return dict; } static PyObject * libvirt_virNetworkPortGetUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { unsigned char uuid[VIR_UUID_BUFLEN]; virNetworkPortPtr port; PyObject *pyobj_port; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virNetworkPortGetUUID", &pyobj_port)) return NULL; port = (virNetworkPortPtr) PyvirNetworkPort_Get(pyobj_port); if (port == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNetworkPortGetUUID(port, &uuid[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_charPtrSizeWrap((char *) &uuid[0], VIR_UUID_BUFLEN); } static PyObject * libvirt_virNetworkPortGetUUIDString(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { char uuidstr[VIR_UUID_STRING_BUFLEN]; virNetworkPortPtr port; PyObject *pyobj_port; int c_retval; if (!PyArg_ParseTuple(args, (char *)"O:virNetworkPortGetUUIDString", &pyobj_port)) return NULL; port = (virNetworkPortPtr) PyvirNetworkPort_Get(pyobj_port); if (port == NULL) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNetworkPortGetUUIDString(port, &uuidstr[0]); LIBVIRT_END_ALLOW_THREADS; if (c_retval < 0) return VIR_PY_NONE; return libvirt_constcharPtrWrap((char *) &uuidstr[0]); } static PyObject * libvirt_virNetworkPortLookupByUUID(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virNetworkPortPtr c_retval; virNetworkPtr net; PyObject *pyobj_net; unsigned char *uuid; Py_ssize_t len; if (!PyArg_ParseTuple(args, (char *)"Oz#:virNetworkPortLookupByUUID", &pyobj_net, &uuid, &len)) return NULL; net = (virNetworkPtr) PyvirNetwork_Get(pyobj_net); if ((uuid == NULL) || (len != VIR_UUID_BUFLEN)) return VIR_PY_NONE; LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virNetworkPortLookupByUUID(net, uuid); LIBVIRT_END_ALLOW_THREADS; return libvirt_virNetworkPortPtrWrap((virNetworkPortPtr) c_retval); } #endif /* LIBVIR_CHECK_VERSION(5, 5, 0) */ #if LIBVIR_CHECK_VERSION(5, 7, 0) static PyObject * libvirt_virDomainGetGuestInfo(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_dom = NULL; PyObject *dict = NULL; virDomainPtr dom = NULL; virTypedParameterPtr params = NULL; int nparams = 0; unsigned int types; unsigned int flags; int rc; if (!PyArg_ParseTuple(args, (char *) "OII:virDomainGetGuestInfo", &pyobj_dom, &types, &flags)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; rc = virDomainGetGuestInfo(dom, types, ¶ms, &nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (rc < 0) return VIR_PY_NONE; dict = getPyVirTypedParameter(params, nparams); virTypedParamsFree(params, nparams); return dict; } #endif /* LIBVIR_CHECK_VERSION(5, 7, 0) */ #if LIBVIR_CHECK_VERSION(5, 8, 0) static virPyTypedParamsHint virPyConnectSetIdentityParams[] = { { VIR_CONNECT_IDENTITY_USER_NAME, VIR_TYPED_PARAM_STRING }, { VIR_CONNECT_IDENTITY_UNIX_USER_ID, VIR_TYPED_PARAM_ULLONG }, { VIR_CONNECT_IDENTITY_GROUP_NAME, VIR_TYPED_PARAM_STRING }, { VIR_CONNECT_IDENTITY_UNIX_GROUP_ID, VIR_TYPED_PARAM_ULLONG }, { VIR_CONNECT_IDENTITY_PROCESS_ID, VIR_TYPED_PARAM_LLONG }, { VIR_CONNECT_IDENTITY_PROCESS_TIME, VIR_TYPED_PARAM_ULLONG }, { VIR_CONNECT_IDENTITY_SASL_USER_NAME, VIR_TYPED_PARAM_STRING }, { VIR_CONNECT_IDENTITY_X509_DISTINGUISHED_NAME, VIR_TYPED_PARAM_STRING }, { VIR_CONNECT_IDENTITY_SELINUX_CONTEXT, VIR_TYPED_PARAM_STRING }, }; static PyObject * libvirt_virConnectSetIdentity(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { virConnectPtr conn; PyObject *pyobj_conn, *dict; PyObject *ret = NULL; int i_retval; int nparams = 0; unsigned int flags; virTypedParameterPtr params = NULL; if (!PyArg_ParseTuple(args, (char *)"OOI:virConnectSetIdentity", &pyobj_conn, &dict, &flags)) return NULL; conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); if (!PyDict_Check(dict)) { PyErr_Format(PyExc_TypeError, "migration params must be a dictionary"); return NULL; } if (virPyDictToTypedParams(dict, ¶ms, &nparams, virPyConnectSetIdentityParams, VIR_N_ELEMENTS(virPyConnectSetIdentityParams)) < 0) { return NULL; } LIBVIRT_BEGIN_ALLOW_THREADS; i_retval = virConnectSetIdentity(conn, params, nparams, flags); LIBVIRT_END_ALLOW_THREADS; if (i_retval < 0) { ret = VIR_PY_INT_FAIL; goto cleanup; } ret = VIR_PY_INT_SUCCESS; cleanup: virTypedParamsFree(params, nparams); return ret; } #endif /* LIBVIR_CHECK_VERSION(5, 8, 0) */ #if LIBVIR_CHECK_VERSION(6, 10, 0) static PyObject * libvirt_virDomainAuthorizedSSHKeysGet(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_dom = NULL; virDomainPtr dom = NULL; const char *user = NULL; char **keys = NULL; int nkeys; int i; unsigned int flags; PyObject *ret = NULL; if (!PyArg_ParseTuple(args, (char *)"OsI:virDomainAuthorizedSSHKeysGet", &pyobj_dom, &user, &flags)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; nkeys = virDomainAuthorizedSSHKeysGet(dom, user, &keys, flags); LIBVIRT_END_ALLOW_THREADS; if (nkeys < 0) return VIR_PY_NONE; if ((ret = PyList_New(nkeys)) == NULL) goto error; for (i = 0; i < nkeys; i++) VIR_PY_LIST_SET_GOTO(ret, i, libvirt_constcharPtrWrap(keys[i]), error); done: for (i = 0; i < nkeys; i++) VIR_FREE(keys[i]); VIR_FREE(keys); return ret; error: Py_CLEAR(ret); goto done; } static PyObject * libvirt_virDomainAuthorizedSSHKeysSet(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_dom = NULL; virDomainPtr dom = NULL; const char *user = NULL; PyObject *pyobj_keys = NULL; char **keys = NULL; int nkeys = 0; int i; unsigned int flags; int c_retval; PyObject *py_retval = NULL; if (!PyArg_ParseTuple(args, (char *)"OsOI:virDomainAuthorizedSSHKeysSet", &pyobj_dom, &user, &pyobj_keys, &flags)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); if (PyList_Check(pyobj_keys)) { nkeys = PyList_Size(pyobj_keys); if (VIR_ALLOC_N(keys, nkeys) < 0) return PyErr_NoMemory(); for (i = 0; i < nkeys; i++) { if (libvirt_charPtrUnwrap(PyList_GetItem(pyobj_keys, i), &(keys[i])) < 0) goto cleanup; } } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainAuthorizedSSHKeysSet(dom, user, (const char **)keys, nkeys, flags); LIBVIRT_END_ALLOW_THREADS; py_retval = libvirt_intWrap(c_retval); cleanup: for (i = 0 ; i < nkeys ; i++) VIR_FREE(keys[i]); VIR_FREE(keys); return py_retval; } #endif /* LIBVIR_CHECK_VERSION(6, 10, 0) */ #if LIBVIR_CHECK_VERSION(7, 1, 0) static PyObject * libvirt_virDomainGetMessages(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_dom = NULL; virDomainPtr dom = NULL; char **msgs = NULL; int nmsgs; int i; unsigned int flags; PyObject *ret = NULL; if (!PyArg_ParseTuple(args, (char *)"OI:virDomainGetMessages", &pyobj_dom, &flags)) return NULL; dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; nmsgs = virDomainGetMessages(dom, &msgs, flags); LIBVIRT_END_ALLOW_THREADS; if (nmsgs < 0) return VIR_PY_NONE; if ((ret = PyList_New(nmsgs)) == NULL) goto error; for (i = 0; i < nmsgs; i++) VIR_PY_LIST_SET_GOTO(ret, i, libvirt_constcharPtrWrap(msgs[i]), error); done: for (i = 0; i < nmsgs; i++) VIR_FREE(msgs[i]); VIR_FREE(msgs); return ret; error: Py_CLEAR(ret); goto done; } #endif /* LIBVIR_CHECK_VERSION(7, 1, 0) */ #if LIBVIR_CHECK_VERSION(8, 0, 0) static virPyTypedParamsHint virPyDomainSetLaunchSecurityStateParams[] = { { VIR_DOMAIN_LAUNCH_SECURITY_SEV_SECRET, VIR_TYPED_PARAM_STRING }, { VIR_DOMAIN_LAUNCH_SECURITY_SEV_SECRET_HEADER, VIR_TYPED_PARAM_STRING }, { VIR_DOMAIN_LAUNCH_SECURITY_SEV_SECRET_SET_ADDRESS, VIR_TYPED_PARAM_ULLONG }, }; static PyObject * libvirt_virDomainSetLaunchSecurityState(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_dom = NULL; PyObject *pyobj_dict = NULL; virDomainPtr dom; virTypedParameterPtr params = NULL; int nparams = 0; unsigned int flags; int c_retval; if (!PyArg_ParseTuple(args, (char *)"OOI:virDomainSetLaunchSecurityState", &pyobj_dom, &pyobj_dict, &flags)) return NULL; if (PyDict_Check(pyobj_dict)) { if (virPyDictToTypedParams(pyobj_dict, ¶ms, &nparams, virPyDomainSetLaunchSecurityStateParams, VIR_N_ELEMENTS(virPyDomainSetLaunchSecurityStateParams)) < 0) { return NULL; } } else { PyErr_Format(PyExc_TypeError, "Launch security state params must be " "a dictionary"); return NULL; } dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainSetLaunchSecurityState(dom, params, nparams, flags); LIBVIRT_END_ALLOW_THREADS; virTypedParamsFree(params, nparams); return libvirt_intWrap(c_retval); } #endif /* LIBVIR_CHECK_VERSION(8, 0, 0) */ #if LIBVIR_CHECK_VERSION(8, 4, 0) static virPyTypedParamsHint virPyDomainSaveParams[] = { { VIR_DOMAIN_SAVE_PARAM_FILE, VIR_TYPED_PARAM_STRING }, { VIR_DOMAIN_SAVE_PARAM_DXML, VIR_TYPED_PARAM_STRING }, }; static PyObject * libvirt_virDomainSaveParams(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_dom = NULL; PyObject *pyobj_dict = NULL; virDomainPtr dom; virTypedParameterPtr params = NULL; int nparams = 0; unsigned int flags = 0; int c_retval; if (!PyArg_ParseTuple(args, (char *)"OO|I:virDomainSaveParams", &pyobj_dom, &pyobj_dict, &flags)) return NULL; if (PyDict_Check(pyobj_dict)) { if (virPyDictToTypedParams(pyobj_dict, ¶ms, &nparams, virPyDomainSaveParams, VIR_N_ELEMENTS(virPyDomainSaveParams)) < 0) { return NULL; } } else { PyErr_Format(PyExc_TypeError, "Save params must be a dictionary"); return NULL; } dom = (virDomainPtr) PyvirDomain_Get(pyobj_dom); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainSaveParams(dom, params, nparams, flags); LIBVIRT_END_ALLOW_THREADS; virTypedParamsFree(params, nparams); return libvirt_intWrap(c_retval); } static PyObject * libvirt_virDomainRestoreParams(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *pyobj_conn = NULL; PyObject *pyobj_dict = NULL; virConnectPtr conn; virTypedParameterPtr params = NULL; int nparams = 0; unsigned int flags = 0; int c_retval; if (!PyArg_ParseTuple(args, (char *)"OO|I:virDomainRestoreParams", &pyobj_conn, &pyobj_dict, &flags)) return NULL; if (PyDict_Check(pyobj_dict)) { if (virPyDictToTypedParams(pyobj_dict, ¶ms, &nparams, virPyDomainSaveParams, VIR_N_ELEMENTS(virPyDomainSaveParams)) < 0) { return NULL; } } else { PyErr_Format(PyExc_TypeError, "Restore params must be a dictionary"); return NULL; } conn = (virConnectPtr) PyvirConnect_Get(pyobj_conn); LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainRestoreParams(conn, params, nparams, flags); LIBVIRT_END_ALLOW_THREADS; virTypedParamsFree(params, nparams); return libvirt_intWrap(c_retval); } #endif /* LIBVIR_CHECK_VERSION(8, 4, 0) */ #if LIBVIR_CHECK_VERSION(9, 0, 0) static PyObject * libvirt_virDomainFDAssociate(PyObject *self ATTRIBUTE_UNUSED, PyObject *args) { PyObject *py_retval = NULL; int c_retval; virDomainPtr domain; PyObject *pyobj_domain; PyObject *pyobj_files; const char *name = NULL; unsigned int flags; unsigned int nfiles; int *files = NULL; size_t i; if (!PyArg_ParseTuple(args, (char *)"OsOI:virDomainFDAssociate", &pyobj_domain, &name, &pyobj_files, &flags)) return NULL; domain = (virDomainPtr) PyvirDomain_Get(pyobj_domain); nfiles = PyList_Size(pyobj_files); if (VIR_ALLOC_N(files, nfiles) < 0) return PyErr_NoMemory(); for (i = 0; i < nfiles; i++) { PyObject *pyfd; int fd; pyfd = PyList_GetItem(pyobj_files, i); if (libvirt_intUnwrap(pyfd, &fd) < 0) goto cleanup; files[i] = fd; } LIBVIRT_BEGIN_ALLOW_THREADS; c_retval = virDomainFDAssociate(domain, name, nfiles, files, flags); LIBVIRT_END_ALLOW_THREADS; py_retval = libvirt_intWrap(c_retval); cleanup: VIR_FREE(files); return py_retval; } #endif /* LIBVIR_CHECK_VERSION(9, 0, 0) */ /************************************************************************ * * * The registration stuff * * * ************************************************************************/ static PyMethodDef libvirtMethods[] = { #include "build/libvirt-export.c" {(char *) "virGetVersion", libvirt_virGetVersion, METH_VARARGS, NULL}, {(char *) "virConnectGetVersion", libvirt_virConnectGetVersion, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(1, 1, 3) {(char *) "virConnectGetCPUModelNames", libvirt_virConnectGetCPUModelNames, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 1, 3) */ {(char *) "virConnectGetLibVersion", libvirt_virConnectGetLibVersion, METH_VARARGS, NULL}, {(char *) "virConnectOpenAuth", libvirt_virConnectOpenAuth, METH_VARARGS, NULL}, {(char *) "virConnectListDomainsID", libvirt_virConnectListDomainsID, METH_VARARGS, NULL}, {(char *) "virConnectListDefinedDomains", libvirt_virConnectListDefinedDomains, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 9, 13) {(char *) "virConnectListAllDomains", libvirt_virConnectListAllDomains, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 9, 13) */ {(char *) "virConnectDomainEventRegister", libvirt_virConnectDomainEventRegister, METH_VARARGS, NULL}, {(char *) "virConnectDomainEventDeregister", libvirt_virConnectDomainEventDeregister, METH_VARARGS, NULL}, {(char *) "virConnectDomainEventRegisterAny", libvirt_virConnectDomainEventRegisterAny, METH_VARARGS, NULL}, {(char *) "virConnectDomainEventDeregisterAny", libvirt_virConnectDomainEventDeregisterAny, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(1, 2, 1) {(char *) "virConnectNetworkEventRegisterAny", libvirt_virConnectNetworkEventRegisterAny, METH_VARARGS, NULL}, {(char *) "virConnectNetworkEventDeregisterAny", libvirt_virConnectNetworkEventDeregisterAny, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 2, 1) */ #if LIBVIR_CHECK_VERSION(0, 10, 0) {(char *) "virConnectRegisterCloseCallback", libvirt_virConnectRegisterCloseCallback, METH_VARARGS, NULL}, {(char *) "virConnectUnregisterCloseCallback", libvirt_virConnectUnregisterCloseCallback, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 0) */ {(char *) "virStreamEventAddCallback", libvirt_virStreamEventAddCallback, METH_VARARGS, NULL}, {(char *) "virStreamRecv", libvirt_virStreamRecv, METH_VARARGS, NULL}, {(char *) "virStreamSend", libvirt_virStreamSend, METH_VARARGS, NULL}, {(char *) "virDomainGetInfo", libvirt_virDomainGetInfo, METH_VARARGS, NULL}, {(char *) "virDomainGetState", libvirt_virDomainGetState, METH_VARARGS, NULL}, {(char *) "virDomainGetControlInfo", libvirt_virDomainGetControlInfo, METH_VARARGS, NULL}, {(char *) "virDomainGetBlockInfo", libvirt_virDomainGetBlockInfo, METH_VARARGS, NULL}, {(char *) "virNodeGetInfo", libvirt_virNodeGetInfo, METH_VARARGS, NULL}, {(char *) "virNodeGetSecurityModel", libvirt_virNodeGetSecurityModel, METH_VARARGS, NULL}, {(char *) "virDomainGetSecurityLabel", libvirt_virDomainGetSecurityLabel, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 0) {(char *) "virDomainGetSecurityLabelList", libvirt_virDomainGetSecurityLabelList, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 0) */ {(char *) "virNodeGetCPUStats", libvirt_virNodeGetCPUStats, METH_VARARGS, NULL}, {(char *) "virNodeGetMemoryStats", libvirt_virNodeGetMemoryStats, METH_VARARGS, NULL}, {(char *) "virDomainGetUUID", libvirt_virDomainGetUUID, METH_VARARGS, NULL}, {(char *) "virDomainGetUUIDString", libvirt_virDomainGetUUIDString, METH_VARARGS, NULL}, {(char *) "virDomainLookupByUUID", libvirt_virDomainLookupByUUID, METH_VARARGS, NULL}, {(char *) "virRegisterErrorHandler", libvirt_virRegisterErrorHandler, METH_VARARGS, NULL}, {(char *) "virGetLastError", libvirt_virGetLastError, METH_VARARGS, NULL}, {(char *) "virConnGetLastError", libvirt_virConnGetLastError, METH_VARARGS, NULL}, {(char *) "virConnectListNetworks", libvirt_virConnectListNetworks, METH_VARARGS, NULL}, {(char *) "virConnectListDefinedNetworks", libvirt_virConnectListDefinedNetworks, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 2) {(char *) "virConnectListAllNetworks", libvirt_virConnectListAllNetworks, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ {(char *) "virNetworkGetUUID", libvirt_virNetworkGetUUID, METH_VARARGS, NULL}, {(char *) "virNetworkGetUUIDString", libvirt_virNetworkGetUUIDString, METH_VARARGS, NULL}, {(char *) "virNetworkLookupByUUID", libvirt_virNetworkLookupByUUID, METH_VARARGS, NULL}, {(char *) "virDomainGetAutostart", libvirt_virDomainGetAutostart, METH_VARARGS, NULL}, {(char *) "virNetworkGetAutostart", libvirt_virNetworkGetAutostart, METH_VARARGS, NULL}, {(char *) "virDomainBlockStats", libvirt_virDomainBlockStats, METH_VARARGS, NULL}, {(char *) "virDomainBlockStatsFlags", libvirt_virDomainBlockStatsFlags, METH_VARARGS, NULL}, {(char *) "virDomainGetCPUStats", libvirt_virDomainGetCPUStats, METH_VARARGS, NULL}, {(char *) "virDomainInterfaceStats", libvirt_virDomainInterfaceStats, METH_VARARGS, NULL}, {(char *) "virDomainMemoryStats", libvirt_virDomainMemoryStats, METH_VARARGS, NULL}, {(char *) "virNodeGetCellsFreeMemory", libvirt_virNodeGetCellsFreeMemory, METH_VARARGS, NULL}, {(char *) "virDomainGetSchedulerType", libvirt_virDomainGetSchedulerType, METH_VARARGS, NULL}, {(char *) "virDomainGetSchedulerParameters", libvirt_virDomainGetSchedulerParameters, METH_VARARGS, NULL}, {(char *) "virDomainGetSchedulerParametersFlags", libvirt_virDomainGetSchedulerParametersFlags, METH_VARARGS, NULL}, {(char *) "virDomainSetSchedulerParameters", libvirt_virDomainSetSchedulerParameters, METH_VARARGS, NULL}, {(char *) "virDomainSetSchedulerParametersFlags", libvirt_virDomainSetSchedulerParametersFlags, METH_VARARGS, NULL}, {(char *) "virDomainSetBlkioParameters", libvirt_virDomainSetBlkioParameters, METH_VARARGS, NULL}, {(char *) "virDomainGetBlkioParameters", libvirt_virDomainGetBlkioParameters, METH_VARARGS, NULL}, {(char *) "virDomainSetMemoryParameters", libvirt_virDomainSetMemoryParameters, METH_VARARGS, NULL}, {(char *) "virDomainGetMemoryParameters", libvirt_virDomainGetMemoryParameters, METH_VARARGS, NULL}, {(char *) "virDomainSetNumaParameters", libvirt_virDomainSetNumaParameters, METH_VARARGS, NULL}, {(char *) "virDomainGetNumaParameters", libvirt_virDomainGetNumaParameters, METH_VARARGS, NULL}, {(char *) "virDomainSetInterfaceParameters", libvirt_virDomainSetInterfaceParameters, METH_VARARGS, NULL}, {(char *) "virDomainGetInterfaceParameters", libvirt_virDomainGetInterfaceParameters, METH_VARARGS, NULL}, {(char *) "virDomainGetVcpus", libvirt_virDomainGetVcpus, METH_VARARGS, NULL}, {(char *) "virDomainPinVcpu", libvirt_virDomainPinVcpu, METH_VARARGS, NULL}, {(char *) "virDomainPinVcpuFlags", libvirt_virDomainPinVcpuFlags, METH_VARARGS, NULL}, {(char *) "virDomainGetVcpuPinInfo", libvirt_virDomainGetVcpuPinInfo, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 0) {(char *) "virDomainGetEmulatorPinInfo", libvirt_virDomainGetEmulatorPinInfo, METH_VARARGS, NULL}, {(char *) "virDomainPinEmulator", libvirt_virDomainPinEmulator, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 0) */ #if LIBVIR_CHECK_VERSION(1, 2, 14) {(char *) "virDomainGetIOThreadInfo", libvirt_virDomainGetIOThreadInfo, METH_VARARGS, NULL}, {(char *) "virDomainPinIOThread", libvirt_virDomainPinIOThread, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 2, 14) */ #if LIBVIR_CHECK_VERSION(4, 10, 0) {(char *) "virDomainSetIOThreadParams", libvirt_virDomainSetIOThreadParams, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(4, 10, 0) */ {(char *) "virConnectListStoragePools", libvirt_virConnectListStoragePools, METH_VARARGS, NULL}, {(char *) "virConnectListDefinedStoragePools", libvirt_virConnectListDefinedStoragePools, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 2) {(char *) "virConnectListAllStoragePools", libvirt_virConnectListAllStoragePools, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ {(char *) "virStoragePoolGetAutostart", libvirt_virStoragePoolGetAutostart, METH_VARARGS, NULL}, {(char *) "virStoragePoolListVolumes", libvirt_virStoragePoolListVolumes, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 2) {(char *) "virStoragePoolListAllVolumes", libvirt_virStoragePoolListAllVolumes, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ {(char *) "virStoragePoolGetInfo", libvirt_virStoragePoolGetInfo, METH_VARARGS, NULL}, {(char *) "virStorageVolGetInfo", libvirt_virStorageVolGetInfo, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(3, 0, 0) {(char *) "virStorageVolGetInfoFlags", libvirt_virStorageVolGetInfoFlags, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(3, 0, 0) */ {(char *) "virStoragePoolGetUUID", libvirt_virStoragePoolGetUUID, METH_VARARGS, NULL}, {(char *) "virStoragePoolGetUUIDString", libvirt_virStoragePoolGetUUIDString, METH_VARARGS, NULL}, {(char *) "virStoragePoolLookupByUUID", libvirt_virStoragePoolLookupByUUID, METH_VARARGS, NULL}, {(char *) "virEventRegisterImpl", libvirt_virEventRegisterImpl, METH_VARARGS, NULL}, {(char *) "virEventAddHandle", libvirt_virEventAddHandle, METH_VARARGS, NULL}, {(char *) "virEventAddTimeout", libvirt_virEventAddTimeout, METH_VARARGS, NULL}, {(char *) "virEventInvokeHandleCallback", libvirt_virEventInvokeHandleCallback, METH_VARARGS, NULL}, {(char *) "virEventInvokeTimeoutCallback", libvirt_virEventInvokeTimeoutCallback, METH_VARARGS, NULL}, {(char *) "virEventInvokeFreeCallback", libvirt_virEventInvokeFreeCallback, METH_VARARGS, NULL}, {(char *) "virNodeListDevices", libvirt_virNodeListDevices, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 2) {(char *) "virConnectListAllNodeDevices", libvirt_virConnectListAllNodeDevices, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ {(char *) "virNodeDeviceListCaps", libvirt_virNodeDeviceListCaps, METH_VARARGS, NULL}, {(char *) "virSecretGetUUID", libvirt_virSecretGetUUID, METH_VARARGS, NULL}, {(char *) "virSecretGetUUIDString", libvirt_virSecretGetUUIDString, METH_VARARGS, NULL}, {(char *) "virSecretLookupByUUID", libvirt_virSecretLookupByUUID, METH_VARARGS, NULL}, {(char *) "virConnectListSecrets", libvirt_virConnectListSecrets, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 2) {(char *) "virConnectListAllSecrets", libvirt_virConnectListAllSecrets, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ {(char *) "virSecretGetValue", libvirt_virSecretGetValue, METH_VARARGS, NULL}, {(char *) "virSecretSetValue", libvirt_virSecretSetValue, METH_VARARGS, NULL}, {(char *) "virNWFilterGetUUID", libvirt_virNWFilterGetUUID, METH_VARARGS, NULL}, {(char *) "virNWFilterGetUUIDString", libvirt_virNWFilterGetUUIDString, METH_VARARGS, NULL}, {(char *) "virNWFilterLookupByUUID", libvirt_virNWFilterLookupByUUID, METH_VARARGS, NULL}, {(char *) "virConnectListNWFilters", libvirt_virConnectListNWFilters, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 2) {(char *) "virConnectListAllNWFilters", libvirt_virConnectListAllNWFilters, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ #if LIBVIR_CHECK_VERSION(4, 5, 0) {(char *) "virConnectListAllNWFilterBindings", libvirt_virConnectListAllNWFilterBindings, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(4, 5, 0) */ {(char *) "virConnectListInterfaces", libvirt_virConnectListInterfaces, METH_VARARGS, NULL}, {(char *) "virConnectListDefinedInterfaces", libvirt_virConnectListDefinedInterfaces, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 2) {(char *) "virConnectListAllInterfaces", libvirt_virConnectListAllInterfaces, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ {(char *) "virConnectBaselineCPU", libvirt_virConnectBaselineCPU, METH_VARARGS, NULL}, {(char *) "virDomainGetJobInfo", libvirt_virDomainGetJobInfo, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(1, 0, 3) {(char *) "virDomainGetJobStats", libvirt_virDomainGetJobStats, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 0, 3) */ #if LIBVIR_CHECK_VERSION(5, 6, 0) {(char *) "virDomainListAllCheckpoints", libvirt_virDomainListAllCheckpoints, METH_VARARGS, NULL}, {(char *) "virDomainCheckpointListAllChildren", libvirt_virDomainCheckpointListAllChildren, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(5, 6, 0) */ {(char *) "virDomainSnapshotListNames", libvirt_virDomainSnapshotListNames, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 9, 13) {(char *) "virDomainListAllSnapshots", libvirt_virDomainListAllSnapshots, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 9, 13) */ {(char *) "virDomainSnapshotListChildrenNames", libvirt_virDomainSnapshotListChildrenNames, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 9, 13) {(char *) "virDomainSnapshotListAllChildren", libvirt_virDomainSnapshotListAllChildren, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 9, 13) */ {(char *) "virDomainRevertToSnapshot", libvirt_virDomainRevertToSnapshot, METH_VARARGS, NULL}, {(char *) "virDomainGetBlockJobInfo", libvirt_virDomainGetBlockJobInfo, METH_VARARGS, NULL}, {(char *) "virDomainSetBlockIoTune", libvirt_virDomainSetBlockIoTune, METH_VARARGS, NULL}, {(char *) "virDomainGetBlockIoTune", libvirt_virDomainGetBlockIoTune, METH_VARARGS, NULL}, {(char *) "virDomainSendKey", libvirt_virDomainSendKey, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(1, 0, 3) {(char *) "virDomainMigrateGetCompressionCache", libvirt_virDomainMigrateGetCompressionCache, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 0, 3) */ {(char *) "virDomainMigrateGetMaxSpeed", libvirt_virDomainMigrateGetMaxSpeed, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(3, 7, 0) {(char *) "virDomainMigrateGetMaxDowntime", libvirt_virDomainMigrateGetMaxDowntime, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(3, 7, 0) */ {(char *) "virDomainMigrateGetMaxSpeed", libvirt_virDomainMigrateGetMaxSpeed, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(1, 1, 0) {(char *) "virDomainMigrate3", libvirt_virDomainMigrate3, METH_VARARGS, NULL}, {(char *) "virDomainMigrateToURI3", libvirt_virDomainMigrateToURI3, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 1, 0) */ {(char *) "virDomainBlockPeek", libvirt_virDomainBlockPeek, METH_VARARGS, NULL}, {(char *) "virDomainMemoryPeek", libvirt_virDomainMemoryPeek, METH_VARARGS, NULL}, {(char *) "virDomainGetDiskErrors", libvirt_virDomainGetDiskErrors, METH_VARARGS, NULL}, #if LIBVIR_CHECK_VERSION(0, 10, 2) {(char *) "virNodeGetMemoryParameters", libvirt_virNodeGetMemoryParameters, METH_VARARGS, NULL}, {(char *) "virNodeSetMemoryParameters", libvirt_virNodeSetMemoryParameters, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(0, 10, 2) */ #if LIBVIR_CHECK_VERSION(1, 0, 0) {(char *) "virNodeGetCPUMap", libvirt_virNodeGetCPUMap, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 0, 0) */ #if LIBVIR_CHECK_VERSION(1, 1, 1) {(char *) "virDomainCreateXMLWithFiles", libvirt_virDomainCreateXMLWithFiles, METH_VARARGS, NULL}, {(char *) "virDomainCreateWithFiles", libvirt_virDomainCreateWithFiles, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 1, 1) */ #if LIBVIR_CHECK_VERSION(1, 2, 5) {(char *) "virDomainFSFreeze", libvirt_virDomainFSFreeze, METH_VARARGS, NULL}, {(char *) "virDomainFSThaw", libvirt_virDomainFSThaw, METH_VARARGS, NULL}, {(char *) "virDomainGetTime", libvirt_virDomainGetTime, METH_VARARGS, NULL}, {(char *) "virDomainSetTime", libvirt_virDomainSetTime, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 2, 5) */ #if LIBVIR_CHECK_VERSION(1, 2, 6) {(char *) "virNodeGetFreePages", libvirt_virNodeGetFreePages, METH_VARARGS, NULL}, {(char *) "virNetworkGetDHCPLeases", libvirt_virNetworkGetDHCPLeases, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 2, 6) */ #if LIBVIR_CHECK_VERSION(1, 2, 8) {(char *) "virConnectGetAllDomainStats", libvirt_virConnectGetAllDomainStats, METH_VARARGS, NULL}, {(char *) "virDomainListGetStats", libvirt_virDomainListGetStats, METH_VARARGS, NULL}, {(char *) "virDomainBlockCopy", libvirt_virDomainBlockCopy, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 2, 8) */ #if LIBVIR_CHECK_VERSION(1, 2, 9) {(char *) "virNodeAllocPages", libvirt_virNodeAllocPages, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 2, 9) */ #if LIBVIR_CHECK_VERSION(1, 2, 11) {(char *) "virDomainGetFSInfo", libvirt_virDomainGetFSInfo, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 2, 11) */ #if LIBVIR_CHECK_VERSION(1, 2, 14) {(char *) "virDomainInterfaceAddresses", libvirt_virDomainInterfaceAddresses, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 2, 14) */ #if LIBVIR_CHECK_VERSION(1, 3, 3) {(char *) "virDomainGetPerfEvents", libvirt_virDomainGetPerfEvents, METH_VARARGS, NULL}, {(char *) "virDomainSetPerfEvents", libvirt_virDomainSetPerfEvents, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(1, 3, 3) */ #if LIBVIR_CHECK_VERSION(2, 0, 0) {(char *) "virConnectStoragePoolEventRegisterAny", libvirt_virConnectStoragePoolEventRegisterAny, METH_VARARGS, NULL}, {(char *) "virConnectStoragePoolEventDeregisterAny", libvirt_virConnectStoragePoolEventDeregisterAny, METH_VARARGS, NULL}, {(char *) "virDomainGetGuestVcpus", libvirt_virDomainGetGuestVcpus, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(2, 0, 0) */ #if LIBVIR_CHECK_VERSION(2, 2, 0) {(char *) "virConnectNodeDeviceEventRegisterAny", libvirt_virConnectNodeDeviceEventRegisterAny, METH_VARARGS, NULL}, {(char *) "virConnectNodeDeviceEventDeregisterAny", libvirt_virConnectNodeDeviceEventDeregisterAny, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(2, 2, 0) */ #if LIBVIR_CHECK_VERSION(3, 0, 0) {(char *) "virConnectSecretEventRegisterAny", libvirt_virConnectSecretEventRegisterAny, METH_VARARGS, NULL}, {(char *) "virConnectSecretEventDeregisterAny", libvirt_virConnectSecretEventDeregisterAny, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(3, 0, 0) */ #if LIBVIR_CHECK_VERSION(3, 4, 0) {(char *) "virStreamRecvHole", libvirt_virStreamRecvHole, METH_VARARGS, NULL}, {(char *) "virStreamSendHole", libvirt_virStreamSendHole, METH_VARARGS, NULL}, {(char *) "virStreamRecvFlags", libvirt_virStreamRecvFlags, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(3, 4, 0) */ #if LIBVIR_CHECK_VERSION(4, 4, 0) {(char *) "virConnectBaselineHypervisorCPU", libvirt_virConnectBaselineHypervisorCPU, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(4, 4, 0) */ #if LIBVIR_CHECK_VERSION(4, 5, 0) {(char *) "virDomainGetLaunchSecurityInfo", libvirt_virDomainGetLaunchSecurityInfo, METH_VARARGS, NULL}, {(char *) "virNodeGetSEVInfo", libvirt_virNodeGetSEVInfo, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(4, 5, 0) */ #if LIBVIR_CHECK_VERSION(5, 5, 0) {(char *) "virNetworkListAllPorts", libvirt_virNetworkListAllPorts, METH_VARARGS, NULL}, {(char *) "virNetworkPortSetParameters", libvirt_virNetworkPortSetParameters, METH_VARARGS, NULL}, {(char *) "virNetworkPortGetParameters", libvirt_virNetworkPortGetParameters, METH_VARARGS, NULL}, {(char *) "virNetworkPortGetUUID", libvirt_virNetworkPortGetUUID, METH_VARARGS, NULL}, {(char *) "virNetworkPortGetUUIDString", libvirt_virNetworkPortGetUUIDString, METH_VARARGS, NULL}, {(char *) "virNetworkPortLookupByUUID", libvirt_virNetworkPortLookupByUUID, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(5, 5, 0) */ #if LIBVIR_CHECK_VERSION(5, 7, 0) {(char *) "virDomainGetGuestInfo", libvirt_virDomainGetGuestInfo, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(5, 7, 0) */ #if LIBVIR_CHECK_VERSION(5, 8, 0) {(char *) "virConnectSetIdentity", libvirt_virConnectSetIdentity, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(5, 8, 0) */ #if LIBVIR_CHECK_VERSION(6, 10, 0) {(char *) "virDomainAuthorizedSSHKeysGet", libvirt_virDomainAuthorizedSSHKeysGet, METH_VARARGS, NULL}, {(char *) "virDomainAuthorizedSSHKeysSet", libvirt_virDomainAuthorizedSSHKeysSet, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(6, 10, 0) */ #if LIBVIR_CHECK_VERSION(7, 1, 0) {(char *) "virDomainGetMessages", libvirt_virDomainGetMessages, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(7, 1, 0) */ #if LIBVIR_CHECK_VERSION(7, 8, 0) {(char *) "virNodeDeviceGetAutostart", libvirt_virNodeDeviceGetAutostart, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(7, 8, 0) */ #if LIBVIR_CHECK_VERSION(8, 0, 0) {(char *) "virDomainSetLaunchSecurityState", libvirt_virDomainSetLaunchSecurityState, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(8, 0, 0) */ #if LIBVIR_CHECK_VERSION(8, 4, 0) {(char *) "virDomainSaveParams", libvirt_virDomainSaveParams, METH_VARARGS, NULL}, {(char *) "virDomainRestoreParams", libvirt_virDomainRestoreParams, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(8, 4, 0) */ #if LIBVIR_CHECK_VERSION(9, 0, 0) {(char *) "virDomainFDAssociate", libvirt_virDomainFDAssociate, METH_VARARGS, NULL}, #endif /* LIBVIR_CHECK_VERSION(9, 0, 0) */ {NULL, NULL, 0, NULL} }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, #ifndef __CYGWIN__ "libvirtmod", #else "cygvirtmod", #endif NULL, -1, libvirtMethods, NULL, NULL, NULL, NULL }; PyObject * #ifndef __CYGWIN__ PyInit_libvirtmod #else PyInit_cygvirtmod #endif (void) { PyObject *module; if (virInitialize() < 0) return NULL; module = PyModule_Create(&moduledef); return module; } 07070100000001000081A40000000000000000000000016641687F00000952000000000000000000000000000000000000003600000000libvirt-python-1715562623.8e7da98/libvirt-python.spec# -*- rpm-spec -*- Summary: The libvirt virtualization API python3 binding Name: libvirt-python Version: 9.10.0 Release: 2 Source0: http://libvirt.org/sources/python/%{name}-%{version}.tar.gz Url: http://libvirt.org License: LGPLv2+ BuildRequires: libvirt-devel BuildRequires: python3-devel BuildRequires: python3-pytest BuildRequires: python3-lxml BuildRequires: gcc # Don't want provides for python shared objects %{?filter_provides_in: %filter_provides_in %{python3_sitearch}/.*\.so} %{?filter_setup} %description The libvirt-python package contains a module that permits applications written in the Python programming language to use the interface supplied by the libvirt library to use the virtualization capabilities of recent versions of Linux (and other OSes). %package -n python3-libvirt Summary: The libvirt virtualization API python3 binding Url: http://libvirt.org License: LGPLv2+ %{?python_provide:%python_provide python3-libvirt} Provides: libvirt-python3 = %{version}-%{release} Obsoletes: libvirt-python3 <= 3.6.0-1%{?dist} %description -n python3-libvirt The python3-libvirt package contains a module that permits applications written in the Python 3.x programming language to use the interface supplied by the libvirt library to use the virtualization capabilities of recent versions of Linux (and other OSes). %prep %autosetup -p1 # Unset execute bit for example scripts; it can introduce spurious # RPM dependencies, like /usr/bin/python3 # for the -python3 package find examples -type f -exec chmod 0644 \{\} \; %build %py3_build %install %py3_install %check %{__python3} setup.py test %files -n python3-libvirt %defattr(-,root,root) %doc README COPYING examples/ %{python3_sitearch}/libvirt.py* %{python3_sitearch}/libvirtaio.py* %{python3_sitearch}/libvirt_qemu.py* %{python3_sitearch}/libvirt_lxc.py* %{python3_sitearch}/__pycache__/libvirt.cpython-*.py* %{python3_sitearch}/__pycache__/libvirt_qemu.cpython-*.py* %{python3_sitearch}/__pycache__/libvirt_lxc.cpython-*.py* %{python3_sitearch}/__pycache__/libvirtaio.cpython-*.py* %{python3_sitearch}/libvirtmod* %{python3_sitearch}/*egg-info %changelog * Thu Mar 28 2024 mayunlong <mayunlong6@huawei.com> - 9.10.0-2 - Delete BuildRequires python3-libvirt to fix build failure. * Thu Feb 29 2024 mayunlong <mayunlong6@huawei.com> - 9.10.0-1 - Update to 9.10.0 release, Initial package for openEuler. 07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!1726 blocks
Locations
Projects
Search
Status Monitor
Help
Open Build Service
OBS Manuals
API Documentation
OBS Portal
Reporting a Bug
Contact
Mailing List
Forums
Chat (IRC)
Twitter
Open Build Service (OBS)
is an
openSUSE project
.
浙ICP备2022010568号-2