提交 a7a1244a 编写于 作者: D Daniel P. Berrange

Remove python binding

The python binding now lives in

  http://libvirt.org/git/?p=libvirt-python.git

that repo also provides an RPM which is upgrade compatible
with the old libvirt-python sub-RPM.
Signed-off-by: NDaniel P. Berrange <berrange@redhat.com>
上级 604f79b3
......@@ -91,17 +91,7 @@
/mkinstalldirs
/po/*
/proxy/
/python/generated.stamp
/python/generator.py.stamp
/python/libvirt-export.c
/python/libvirt-lxc-export.c
/python/libvirt-lxc.[ch]
/python/libvirt-qemu-export.c
/python/libvirt-qemu.[ch]
/python/libvirt.[ch]
/python/libvirt.py
/python/libvirt_lxc.py
/python/libvirt_qemu.py
/python/
/run
/sc_*
/src/.*.stamp
......
......@@ -20,8 +20,8 @@ LCOV = lcov
GENHTML = genhtml
SUBDIRS = . gnulib/lib include src daemon tools docs gnulib/tests \
python tests po examples/domain-events/events-c examples/hellolibvirt \
examples/dominfo examples/domsuspend examples/python examples/apparmor \
tests po examples/domain-events/events-c examples/hellolibvirt \
examples/dominfo examples/domsuspend examples/apparmor \
examples/xml/nwfilter examples/openauth examples/systemtap
ACLOCAL_AMFLAGS = -I m4
......@@ -40,7 +40,6 @@ EXTRA_DIST = \
Makefile.nonreentrant \
autogen.sh \
cfg.mk \
examples/domain-events/events-python \
run.in \
AUTHORS.in \
$(XML_EXAMPLES)
......@@ -74,8 +73,6 @@ check-local: all tests
tests:
@(cd docs/examples ; $(MAKE) MAKEFLAGS+=--silent tests)
@(if [ "$(pythondir)" != "" ] ; then cd python ; \
$(MAKE) MAKEFLAGS+=--silent tests ; fi)
cov: clean-cov
mkdir $(top_builddir)/coverage
......
......@@ -86,8 +86,7 @@ if test -x /usr/bin/i686-w64-mingw32-gcc ; then
--prefix="$AUTOBUILD_INSTALL_ROOT/i686-w64-mingw32/sys-root/mingw" \
--enable-expensive-tests \
--enable-werror \
--without-libvirtd \
--without-python
--without-libvirtd
make
make install
......@@ -107,8 +106,7 @@ if test -x /usr/bin/x86_64-w64-mingw32-gcc ; then
--prefix="$AUTOBUILD_INSTALL_ROOT/x86_64-w64-mingw32/sys-root/mingw" \
--enable-expensive-tests \
--enable-werror \
--without-libvirtd \
--without-python
--without-libvirtd
make
make install
......
......@@ -958,14 +958,11 @@ exclude_file_name_regexp--sc_prohibit_VIR_ERR_NO_MEMORY = \
exclude_file_name_regexp--sc_prohibit_access_xok = ^src/util/virutil\.c$$
exclude_file_name_regexp--sc_prohibit_always_true_header_tests = \
^python/(libvirt-(lxc-|qemu-)?override|typewrappers)\.c$$
exclude_file_name_regexp--sc_prohibit_asprintf = \
^(bootstrap.conf$$|src/util/virstring\.[ch]$$|examples/domain-events/events-c/event-test\.c$$|tests/vircgroupmock\.c$$)
exclude_file_name_regexp--sc_prohibit_strdup = \
^(docs/|examples/|python/|src/util/virstring\.c|tests/virnetserverclientmock.c$$)
^(docs/|examples/|src/util/virstring\.c|tests/virnetserverclientmock.c$$)
exclude_file_name_regexp--sc_prohibit_close = \
(\.p[yl]$$|^docs/|^(src/util/virfile\.c|src/libvirt\.c|tests/vir(cgroup|pci)mock\.c)$$)
......@@ -1033,7 +1030,7 @@ exclude_file_name_regexp--sc_prohibit_include_public_headers_quote = \
^src/internal\.h$$
exclude_file_name_regexp--sc_prohibit_include_public_headers_brackets = \
^(python/|tools/|examples/|include/libvirt/(virterror|libvirt-(qemu|lxc))\.h$$)
^(tools/|examples/|include/libvirt/(virterror|libvirt-(qemu|lxc))\.h$$)
exclude_file_name_regexp--sc_prohibit_int_ijk = \
^(src/remote_protocol-structs|src/remote/remote_protocol.x|cfg.mk|include/)$
......
......@@ -2012,84 +2012,8 @@ fi
AM_CONDITIONAL([WITH_HYPERV], [test "$with_hyperv" = "yes"])
dnl
dnl check for python
dnl
AC_ARG_WITH([python],
[AS_HELP_STRING([--with-python],
[Build python bindings @<:@default=yes@:>@])],
[],[with_python=yes])
if test "$enable_shared:$with_python" = no:yes; then
AC_MSG_WARN([Disabling shared libraries is incompatible with building Python extensions.])
AC_MSG_WARN([Ignoring --with-python.])
with_python=no
fi
PYTHON_VERSION=
PYTHON_INCLUDES=
if test "$with_python" != "no" ; then
if test -x "$with_python/bin/python"
then
AC_MSG_NOTICE(Found python in $with_python/bin/python)
PYTHON="$with_python/bin/python"
with_python=yes
else
if test -x "$with_python"
then
AC_MSG_NOTICE(Found python in $with_python)
PYTHON="$with_python"
with_python=yes
else
if test -x "$PYTHON"
then
AC_MSG_NOTICE(Found python in environment PYTHON=$PYTHON)
with_python=yes
fi
fi
fi
if test "$with_python" = "yes" ; then
AM_PATH_PYTHON(,, [:])
if test "$PYTHON" != : ; then
PYTHON_CONFIG="$PYTHON-config"
if test -x "$PYTHON_CONFIG"
then
PYTHON_INCLUDES=`$PYTHON_CONFIG --includes`
else
if test -r $PYTHON_EXEC_PREFIX/include/python$PYTHON_VERSION/Python.h
then
PYTHON_INCLUDES=-I$PYTHON_EXEC_PREFIX/include/python$PYTHON_VERSION
else
if test -r $prefix/include/python$PYTHON_VERSION/Python.h
then
PYTHON_INCLUDES=-I$prefix/include/python$PYTHON_VERSION
else
if test -r /usr/include/python$PYTHON_VERSION/Python.h
then
PYTHON_INCLUDES=-I/usr/include/python$PYTHON_VERSION
else
AC_MSG_ERROR([You must install python-devel to build Python bindings])
fi
fi
fi
fi
else
AC_MSG_ERROR([You must install python to build Python bindings])
fi
else
AC_MSG_NOTICE([Could not find python in $with_python, disabling bindings])
with_python=no
fi
fi
AM_CONDITIONAL([WITH_PYTHON], [test "$with_python" = "yes"])
AC_SUBST([PYTHON_VERSION])
AC_SUBST([PYTHON_INCLUDES])
dnl Allow perl overrides
dnl Allow perl/python overrides
AC_PATH_PROG([PYTHON], [python])
AC_PATH_PROG([PERL], [perl])
AC_ARG_ENABLE([with-test-suite],
......@@ -2227,7 +2151,6 @@ dnl Copied from libxml2 configure.in, but I removed mingw changes
dnl for now since I'm not supporting mingw at present. - RWMJ
CYGWIN_EXTRA_LDFLAGS=
CYGWIN_EXTRA_LIBADD=
CYGWIN_EXTRA_PYTHON_LIBADD=
MINGW_EXTRA_LDFLAGS=
WIN32_EXTRA_CFLAGS=
dnl libvirt.syms is generated in builddir, but libvirt_qemu.syms is in git;
......@@ -2241,10 +2164,6 @@ case "$host" in
CYGWIN_EXTRA_LDFLAGS="-no-undefined"
CYGWIN_EXTRA_LIBADD="${INTLLIBS}"
MSCOM_LIBS="-lole32 -loleaut32"
if test "x$PYTHON_VERSION" != "x"; then
CYGWIN_EXTRA_PYTHON_LIBADD="-L/usr/lib/python${PYTHON_VERSION}/config -lpython${PYTHON_VERSION}"
fi
;;
*-*-mingw*)
MINGW_EXTRA_LDFLAGS="-no-undefined"
......@@ -2279,7 +2198,6 @@ case "$host" in
esac
AC_SUBST([CYGWIN_EXTRA_LDFLAGS])
AC_SUBST([CYGWIN_EXTRA_LIBADD])
AC_SUBST([CYGWIN_EXTRA_PYTHON_LIBADD])
AC_SUBST([MINGW_EXTRA_LDFLAGS])
AC_SUBST([WIN32_EXTRA_CFLAGS])
AC_SUBST([LIBVIRT_SYMBOL_FILE])
......@@ -2613,7 +2531,6 @@ AC_CONFIG_FILES([\
libvirt.pc libvirt.spec mingw-libvirt.spec \
po/Makefile.in \
include/libvirt/Makefile include/libvirt/libvirt.h \
python/Makefile \
daemon/Makefile \
tools/Makefile \
tests/Makefile \
......@@ -2622,7 +2539,6 @@ AC_CONFIG_FILES([\
examples/domsuspend/Makefile \
examples/dominfo/Makefile \
examples/openauth/Makefile \
examples/python/Makefile \
examples/hellolibvirt/Makefile \
examples/systemtap/Makefile \
examples/xml/nwfilter/Makefile])
......@@ -2778,7 +2694,6 @@ AC_MSG_NOTICE([])
AC_MSG_NOTICE([ Debug: $enable_debug])
AC_MSG_NOTICE([ Use -Werror: $set_werror])
AC_MSG_NOTICE([ Warning Flags: $WARN_CFLAGS])
AC_MSG_NOTICE([ Python: $with_python])
AC_MSG_NOTICE([ DTrace: $with_dtrace])
AC_MSG_NOTICE([ numad: $with_numad])
AC_MSG_NOTICE([ XML Catalog: $XML_CATALOG_FILE])
......
## Copyright (C) 2005-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/>.
EXTRA_DIST= \
README \
consolecallback.py \
topology.py \
dominfo.py domrestore.py domsave.py domstart.py esxlist.py
Some 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
The XML files in this directory are examples of the XML format that libvirt
expects, and will have to be adapted for your setup. They are only needed
for domstart.py
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.
#!/usr/bin/env python
# consolecallback - provide a persistent console that survives guest reboots
import sys, os, logging, libvirt, tty, termios, atexit
def reset_term():
termios.tcsetattr(0, termios.TCSADRAIN, attrs)
def error_handler(unused, error):
# 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, uuid):
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
self.run_console = True
logging.info("%s initial state %d, reason %d",
self.uuid, self.state[0], self.state[1])
def check_console(console):
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, fd, events, console):
readbuf = os.read(fd, 1024)
if readbuf.startswith(""):
console.run_console = False
return
if console.stream:
console.stream.send(readbuf)
def stream_callback(stream, events, console):
try:
received_data = console.stream.recv(1024)
except:
return
os.write(0, received_data)
def lifecycle_callback (connection, domain, event, detail, console):
console.state = console.domain.state(0)
logging.info("%s transitioned to state %d, reason %d",
console.uuid, console.state[0], console.state[1])
# main
if len(sys.argv) != 3:
print "Usage:", sys.argv[0], "URI UUID"
print "for example:", sys.argv[0], "'qemu:///system' '32ad945f-7e78-c33a-e96d-39f25e025d81'"
sys.exit(1)
uri = sys.argv[1]
uuid = sys.argv[2]
print "Escape character is ^]"
logging.basicConfig(filename='msg.log', level=logging.DEBUG)
logging.info("URI: %s", uri)
logging.info("UUID: %s", uuid)
libvirt.virEventRegisterDefaultImpl()
libvirt.registerErrorHandler(error_handler, None)
atexit.register(reset_term)
attrs = termios.tcgetattr(0)
tty.setraw(0)
console = Console(uri, uuid)
console.stdin_watch = libvirt.virEventAddHandle(0, libvirt.VIR_EVENT_HANDLE_READABLE, stdin_callback, console)
while check_console(console):
libvirt.virEventRunDefaultImpl()
#!/usr/bin/env python
# dominfo - print some information about a domain
import libvirt
import sys
import os
import libxml2
import pdb
def usage():
print 'Usage: %s DOMAIN' % sys.argv[0]
print ' Print information about the domain DOMAIN'
def print_section(title):
print "\n%s" % title
print "=" * 60
def print_entry(key, value):
print "%-10s %-10s" % (key, value)
def print_xml(key, ctx, path):
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
if len(sys.argv) != 2:
usage()
sys.exit(2)
name = sys.argv[1]
# Connect to libvirt
conn = libvirt.openReadOnly(None)
if conn is None:
print 'Failed to open connection to the hypervisor'
sys.exit(1)
try:
dom = conn.lookupByName(name)
# Annoyiingly, libvirt prints its own error message here
except libvirt.libvirtError:
print "Domain %s is not running" % name
sys.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)
#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")
#!/usr/bin/env python
# domstart - make sure a given domU is running, if not start it
import libvirt
import sys
import os
import libxml2
import pdb
def usage():
print 'Usage: %s DIR' % sys.argv[0]
print ' Restore all the domains contained in DIR'
print ' It is assumed that all files in DIR are'
print ' images of domU\'s previously created with save'
if len(sys.argv) != 2:
usage()
sys.exit(2)
dir = sys.argv[1]
imgs = os.listdir(dir)
conn = libvirt.open(None)
if conn is None:
print 'Failed to open connection to the hypervisor'
sys.exit(1)
for img in imgs:
file = os.path.join(dir, img)
print "Restoring %s ... " % img,
sys.stdout.flush()
ret = conn.restore(file)
if ret == 0:
print "done"
else:
print "error %d" % ret
#!/usr/bin/env python
# domstart - make sure a given domU is running, if not start it
import libvirt
import sys
import os
import libxml2
import pdb
def usage():
print 'Usage: %s DIR' % sys.argv[0]
print ' Save all currently running domU\'s into DIR'
print ' DIR must exist and be writable by this process'
if len(sys.argv) != 2:
usage()
sys.exit(2)
dir = sys.argv[1]
conn = libvirt.open(None)
if conn is None:
print 'Failed to open connection to the hypervisor'
sys.exit(1)
doms = conn.listDomainsID()
for id in doms:
if id == 0:
continue
dom = conn.lookupByID(id)
print "Saving %s[%d] ... " % (dom.name(), id),
sys.stdout.flush()
path = os.path.join(dir, dom.name())
ret = dom.save(path)
if ret == 0:
print "done"
else:
print "error %d" % ret
#pdb.set_trace()
#!/usr/bin/env python
# domstart - make sure a given domU is running, if not start it
import libvirt
import sys
import os
import libxml2
import pdb
# 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):
fp = open(fname, "r")
xmldesc = fp.read()
fp.close()
doc = libxml2.parseDoc(xmldesc)
name = doc.xpathNewContext().xpathEval("/domain/name")[0].content
return (name, xmldesc)
def usage():
print 'Usage: %s domain.xml' % sys.argv[0]
print ' Check that the domain described by DOMAIN.XML is running'
print ' If the domain is not running, create it'
print ' DOMAIN.XML must be a XML description of the domain'
print ' in libvirt\'s XML format'
if len(sys.argv) != 2:
usage()
sys.exit(2)
(name, xmldesc) = read_domain(sys.argv[1])
conn = libvirt.open(None)
if conn is None:
print 'Failed to open connection to the hypervisor'
sys.exit(1)
try:
dom = conn.lookupByName(name)
except libvirt.libvirtError:
print "Starting domain %s ... " % name,
sys.stdout.flush()
dom = conn.createLinux(xmldesc, 0)
if dom is None:
print "failed"
sys.exit(1)
else:
print "done"
#!/usr/bin/env python
# esxlist - list active domains of an ESX host and print some info.
# also demonstrates how to use the libvirt.openAuth() method
import libvirt
import sys
import os
import libxml2
import getpass
def usage():
print "Usage: %s HOSTNAME" % sys.argv[0]
print " List active domains of HOSTNAME and print some info"
# 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, user_data):
for credential in credentials:
if credential[0] == libvirt.VIR_CRED_AUTHNAME:
# prompt the user to input a authname. display the provided message
credential[4] = raw_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):
print "\n%s" % title
print "=" * 60
def print_entry(key, value):
print "%-10s %-10s" % (key, value)
def print_xml(key, ctx, path):
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
if len(sys.argv) != 2:
usage()
sys.exit(2)
hostname = sys.argv[1]
# Connect to libvirt
uri = "esx://%s/?no_verify=1" % 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]
conn = libvirt.openAuth(uri, auth, 0)
if conn is None:
print "Failed to open connection to %s" % hostname
sys.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")
#!/usr/bin/env python
# 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
import sys
from xml.dom import minidom
try:
conn = libvirt.openReadOnly(None)
except libvirt.libvirtError:
print 'Failed to connect to the hypervisor'
sys.exit(1)
try:
capsXML = conn.getCapabilities()
except libvirt.libvirtError:
print 'Failed to request capabilities'
sys.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
......@@ -126,7 +126,6 @@
%define with_libssh2 0%{!?_without_libssh2:0}
# Non-server/HV driver defaults which are always enabled
%define with_python 0%{!?_without_python:1}
%define with_sasl 0%{!?_without_sasl:1}
......@@ -425,7 +424,7 @@ BuildRequires: gettext-devel
BuildRequires: libtool
BuildRequires: /usr/bin/pod2man
%endif
BuildRequires: python-devel
BuildRequires: python
%if %{with_systemd}
BuildRequires: systemd-units
%endif
......@@ -1145,19 +1144,6 @@ Includes the Sanlock lock manager plugin for the QEMU
driver
%endif
%if %{with_python}
%package python
Summary: Python bindings for the libvirt library
Group: Development/Libraries
Requires: %{name}-client = %{version}-%{release}
%description python
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).
%endif
%prep
%setup -q
......@@ -1222,10 +1208,6 @@ of recent versions of Linux (and other OSes).
%define _without_polkit --without-polkit
%endif
%if ! %{with_python}
%define _without_python --without-python
%endif
%if ! %{with_libvirtd}
%define _without_libvirtd --without-libvirtd
%endif
......@@ -1378,7 +1360,6 @@ of recent versions of Linux (and other OSes).
%{?_without_sasl} \
%{?_without_avahi} \
%{?_without_polkit} \
%{?_without_python} \
%{?_without_libvirtd} \
%{?_without_uml} \
%{?_without_phyp} \
......@@ -1432,14 +1413,12 @@ rm -fr %{buildroot}
# on RHEL 5, thus we need to expand it here.
make install DESTDIR=%{?buildroot} SYSTEMD_UNIT_DIR=%{_unitdir}
for i in domain-events/events-c dominfo domsuspend hellolibvirt openauth python xml/nwfilter systemtap
for i in domain-events/events-c dominfo domsuspend hellolibvirt openauth xml/nwfilter systemtap
do
(cd examples/$i ; make clean ; rm -rf .deps .libs Makefile Makefile.in)
done
rm -f $RPM_BUILD_ROOT%{_libdir}/*.la
rm -f $RPM_BUILD_ROOT%{_libdir}/*.a
rm -f $RPM_BUILD_ROOT%{_libdir}/python*/site-packages/*.la
rm -f $RPM_BUILD_ROOT%{_libdir}/python*/site-packages/*.a
rm -f $RPM_BUILD_ROOT%{_libdir}/libvirt/lock-driver/*.la
rm -f $RPM_BUILD_ROOT%{_libdir}/libvirt/lock-driver/*.a
%if %{with_driver_modules}
......@@ -2105,18 +2084,6 @@ exit 0
%doc examples/xml
%doc examples/systemtap
%if %{with_python}
%files python
%defattr(-, root, root)
%{_libdir}/python*/site-packages/libvirt.py*
%{_libdir}/python*/site-packages/libvirt_qemu.py*
%{_libdir}/python*/site-packages/libvirt_lxc.py*
%{_libdir}/python*/site-packages/libvirtmod*
%doc examples/python
%doc examples/domain-events/events-python
%endif
%changelog
* Mon Nov 4 2013 Daniel Veillard <veillard@redhat.com> - 1.1.4-1
- Add support for AArch64 architecture
......
......@@ -217,14 +217,6 @@ AC_DEFUN([LIBVIRT_COMPILE_WARNINGS],[
#endif
])
dnl Needed to keep compile quiet on python 2.4
save_WARN_CFLAGS=$WARN_CFLAGS
WARN_CFLAGS=
gl_WARN_ADD([-Wno-redundant-decls])
WARN_PYTHON_CFLAGS=$WARN_CFLAGS
AC_SUBST(WARN_PYTHON_CFLAGS)
WARN_CFLAGS=$save_WARN_CFLAGS
if test "$gl_cv_warn_c__Wlogical_op" = yes &&
test "$lv_cv_gcc_wlogical_op_broken" = yes; then
AC_DEFINE_UNQUOTED([BROKEN_GCC_WLOGICALOP], 1,
......
......@@ -146,7 +146,6 @@ autoreconf -if
--without-sasl \
--without-avahi \
--without-polkit \
--without-python \
--without-libvirtd \
--without-uml \
%{?_without_phyp} \
......
# Makefile for libvirt python library
## Copyright (C) 2005-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/>.
INCLUDES = \
$(PYTHON_INCLUDES) \
-I$(top_builddir)/gnulib/lib \
-I$(top_srcdir)/gnulib/lib \
-I$(top_srcdir) \
-I$(top_builddir)/src \
-I$(top_srcdir)/src \
-I$(top_srcdir)/src/util \
-I$(top_builddir)/include \
-I$(top_srcdir)/include \
$(GETTEXT_CPPFLAGS)
AM_CFLAGS = $(WARN_CFLAGS)
AM_LDFLAGS = \
$(RELRO_LDFLAGS) \
$(NO_INDIRECT_LDFLAGS) \
$(NULL)
CLASSES_EXTRA = \
libvirt-override-virConnect.py \
libvirt-override-virDomain.py \
libvirt-override-virDomainSnapshot.py \
libvirt-override-virStoragePool.py \
libvirt-override-virStream.py
EXTRA_DIST = \
generator.py \
typewrappers.c \
typewrappers.h \
libvirt-override.c \
libvirt-override.py \
libvirt-override-api.xml \
libvirt-lxc-override.c \
libvirt-lxc-override-api.xml \
libvirt-qemu-override.c \
libvirt-qemu-override-api.xml \
sanitytest.py \
$(CLASSES_EXTRA) \
$(DOCS)
if WITH_PYTHON
mylibs = \
$(top_builddir)/src/libvirt.la \
$(top_builddir)/gnulib/lib/libgnu.la
myqemulibs = \
$(top_builddir)/src/libvirt-qemu.la \
$(top_builddir)/gnulib/lib/libgnu.la
mylxclibs = \
$(top_builddir)/src/libvirt-lxc.la \
$(top_builddir)/gnulib/lib/libgnu.la
all-local: libvirt.py libvirt_qemu.py libvirt_lxc.py
pyexec_LTLIBRARIES = libvirtmod.la libvirtmod_qemu.la libvirtmod_lxc.la
libvirtmod_la_SOURCES = libvirt-override.c typewrappers.c
nodist_libvirtmod_la_SOURCES = libvirt.c libvirt.h
# Python <= 2.4 header files contain a redundant decl, hence we
# need extra flags here
libvirtmod_la_CFLAGS = $(WARN_CFLAGS) $(WARN_PYTHON_CFLAGS)
libvirtmod_la_LDFLAGS = -module -avoid-version -shared \
-L$(top_builddir)/src/.libs \
$(AM_LDFLAGS) \
$(CYGWIN_EXTRA_LDFLAGS)
libvirtmod_la_LIBADD = $(mylibs) \
$(CYGWIN_EXTRA_LIBADD) $(CYGWIN_EXTRA_PYTHON_LIBADD)
libvirtmod_qemu_la_SOURCES = libvirt-qemu-override.c typewrappers.c
nodist_libvirtmod_qemu_la_SOURCES = libvirt-qemu.c libvirt-qemu.h
# Python <= 2.4 header files contain a redundant decl, hence we
# need extra flags here
libvirtmod_qemu_la_CFLAGS = $(WARN_PYTHON_CFLAGS)
libvirtmod_qemu_la_LDFLAGS = -module -avoid-version -shared \
-L$(top_builddir)/src/.libs \
$(AM_LDFLAGS) \
$(CYGWIN_EXTRA_LDFLAGS)
libvirtmod_qemu_la_LIBADD = $(myqemulibs) \
$(CYGWIN_EXTRA_LIBADD) $(CYGWIN_EXTRA_PYTHON_LIBADD)
libvirtmod_lxc_la_SOURCES = libvirt-lxc-override.c typewrappers.c
nodist_libvirtmod_lxc_la_SOURCES = libvirt-lxc.c libvirt-lxc.h
# Python <= 2.4 header files contain a redundant decl, hence we
# need extra flags here
libvirtmod_lxc_la_CFLAGS = $(WARN_PYTHON_CFLAGS)
libvirtmod_lxc_la_LDFLAGS = -module -avoid-version -shared \
-L$(top_builddir)/src/.libs \
$(AM_LDFLAGS) \
$(CYGWIN_EXTRA_LDFLAGS)
libvirtmod_lxc_la_LIBADD = $(mylxclibs) \
$(CYGWIN_EXTRA_LIBADD) $(CYGWIN_EXTRA_PYTHON_LIBADD)
GENERATE = generator.py
API_DESC = $(top_srcdir)/docs/libvirt-api.xml \
$(srcdir)/libvirt-override-api.xml
GENERATED= libvirt-export.c \
libvirt.c \
libvirt.h \
libvirt.py
QEMU_API_DESC = $(top_srcdir)/docs/libvirt-qemu-api.xml \
$(srcdir)/libvirt-qemu-override-api.xml
QEMU_GENERATED= libvirt-qemu-export.c \
libvirt-qemu.c \
libvirt-qemu.h \
libvirt_qemu.py
LXC_API_DESC = $(top_srcdir)/docs/libvirt-lxc-api.xml \
$(srcdir)/libvirt-lxc-override-api.xml
LXC_GENERATED= libvirt-lxc-export.c \
libvirt-lxc.c \
libvirt-lxc.h \
libvirt_lxc.py
$(GENERATE).stamp: $(srcdir)/$(GENERATE) \
$(API_DESC) \
$(QEMU_API_DESC) \
$(LXC_API_DESC) \
$(CLASSES_EXTRA)
$(AM_V_GEN)$(PYTHON) $(srcdir)/$(GENERATE) $(PYTHON) && \
touch $@
$(GENERATED) $(QEMU_GENERATED) $(LXC_GENERATED): $(GENERATE).stamp
$(libvirtmod_la_OBJECTS): $(GENERATED)
$(libvirtmod_qemu_la_OBJECTS): $(QEMU_GENERATED)
$(libvirtmod_lxc_la_OBJECTS): $(LXC_GENERATED)
check-local:
$(AM_V_GEN)../run $(PYTHON) $(srcdir)/sanitytest.py
install-data-local:
$(mkinstalldirs) $(DESTDIR)$(pyexecdir)
$(INSTALL) -m 0644 libvirt.py $(DESTDIR)$(pyexecdir)
$(INSTALL) -m 0644 libvirt_lxc.py $(DESTDIR)$(pyexecdir)
$(INSTALL) -m 0644 libvirt_qemu.py $(DESTDIR)$(pyexecdir)
uninstall-local:
rm -f $(DESTDIR)$(pyexecdir)/libvirt.py
rm -f $(DESTDIR)$(pyexecdir)/libvirt_lxc.py
rm -f $(DESTDIR)$(pyexecdir)/libvirt_qemu.py
CLEANFILES= $(GENERATED) $(QEMU_GENERATED) $(LXC_GENERATED) $(GENERATE).stamp \
*.pyc
else ! WITH_PYTHON
all:
endif ! WITH_PYTHON
dummy:
tests test: all dummy
-@(cd tests && $(MAKE) MAKEFLAGS+=--silent tests)
libvirt Python Bindings README
==============================
Most of the libvirt python binding code is automatically generated
using the script generator.py, and the API description from
docs/libvirt-api.xml
Manually written files:
- libvirt-override.c: methods where the C binding needs to be hand crafted
- libvirt-override.py: global methods where the C and python bindings have different args
- libvirt-override-api.xml: methods where the auto-extracted API docs are not
suitable for python auto-generator. Overriding this if the method is going
into libvirt-override.c, but we still want auto-generated libvirt-override.py
- libvirt-override-virConnect.py: virConnect class methods
- typewrappers.h,.c: Python object wrappers for each libvirt C object
Auto-generated files:
- libvirt.py: The main python binding. Comprises auto-generated code, along
with contents from libvirt-override.py and libvirt-override-virConnect.py
- libvirt.c, libvirt.h: The C glue layer for the python binding. Comprises
auto-generated code, along with libvirt-override.c
- libvirt-export.c: List of auto-generated C methods, included into
the libvirt-override.c method table
此差异已折叠。
<?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>
/*
* 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-2013 Red Hat, Inc.
*
* Daniel Veillard <veillard@redhat.com>
*/
#include <config.h>
/* Horrible kludge to work around even more horrible name-space pollution
via Python.h. That file includes /usr/include/python2.5/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-lxc.h"
#include "viralloc.h"
#include "virfile.h"
#ifndef __CYGWIN__
extern void initlibvirtmod_lxc(void);
#else
extern void initcygvirtmod_lxc(void);
#endif
#if 0
# define DEBUG_ERROR 1
#endif
#if DEBUG_ERROR
# define DEBUG(fmt, ...) \
printf(fmt, __VA_ARGS__)
#else
# define DEBUG(fmt, ...) \
do {} while (0)
#endif
/* 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))
/************************************************************************
* *
* 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;
size_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;
py_retval = PyList_New(0);
for (i = 0; i < c_retval; i++) {
PyObject *item = NULL;
if ((item = PyInt_FromLong(fdlist[i])) == NULL)
goto error;
if (PyList_Append(py_retval, item) < 0) {
Py_DECREF(item);
goto error;
}
}
VIR_FREE(fdlist);
return py_retval;
error:
for (i = 0; i < c_retval; i++) {
VIR_FORCE_CLOSE(fdlist[i]);
}
VIR_FREE(fdlist);
return VIR_PY_NONE;
}
/************************************************************************
* *
* The registration stuff *
* *
************************************************************************/
static PyMethodDef libvirtLxcMethods[] = {
#include "libvirt-lxc-export.c"
{(char *) "virDomainLxcOpenNamespace", libvirt_lxc_virDomainLxcOpenNamespace, METH_VARARGS, NULL},
{NULL, NULL, 0, NULL}
};
void
#ifndef __CYGWIN__
initlibvirtmod_lxc
#else
initcygvirtmod_lxc
#endif
(void)
{
static int initialized = 0;
if (initialized != 0)
return;
if (virInitialize() < 0)
return;
/* initialize the python extension module */
Py_InitModule((char *)
#ifndef __CYGWIN__
"libvirtmod_lxc"
#else
"cygvirtmod_lxc"
#endif
, libvirtLxcMethods);
initialized = 1;
}
此差异已折叠。
def __del__(self):
try:
for cb,opaque in self.domainEventCallbacks.items():
del self.domainEventCallbacks[cb]
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 domainEventDeregister(self, cb):
"""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', conn=self)
except AttributeError:
pass
def domainEventRegister(self, cb, opaque):
"""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}
ret = libvirtmod.virConnectDomainEventRegister(self._o, self)
if ret == -1: raise libvirtError ('virConnectDomainEventRegister() failed', conn=self)
def _dispatchDomainEventCallbacks(self, dom, event, detail):
"""Dispatches events to python user domain event callbacks
"""
try:
for cb,opaque in self.domainEventCallbacks.items():
cb(self,dom,event,detail,opaque)
return 0
except AttributeError:
pass
def _dispatchDomainEventLifecycleCallback(self, dom, event, detail, cbData):
"""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, cbData):
"""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, offset, cbData):
"""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, action, cbData):
"""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, srcPath, devAlias,
action, cbData):
"""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, srcPath,
devAlias, action, reason,
cbData):
"""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, phase, localAddr,
remoteAddr, authScheme, subject,
cbData):
"""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 dispatchDomainEventBlockPullCallback(self, dom, path, type, status, cbData):
"""Dispatches events to python user domain blockJob event callbacks
"""
try:
cb = cbData["cb"]
opaque = cbData["opaque"]
cb(self, virDomain(self, _obj=dom), path, type, status, opaque)
return 0
except AttributeError:
pass
def _dispatchDomainEventDiskChangeCallback(self, dom, oldSrcPath, newSrcPath, devAlias, reason, cbData):
"""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, devAlias, reason, cbData):
"""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, reason, cbData):
"""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, reason, cbData):
"""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, actual, cbData):
"""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, reason, cbData):
"""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, devAlias, cbData):
"""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 domainEventDeregisterAny(self, callbackID):
"""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', conn=self)
del self.domainEventCallbackID[callbackID]
except AttributeError:
pass
def domainEventRegisterAny(self, dom, eventID, cb, opaque):
"""Adds a Domain Event Callback. Registering for a domain
callback will enable delivery of the events """
if not hasattr(self, 'domainEventCallbackID'):
self.domainEventCallbackID = {}
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', conn=self)
self.domainEventCallbackID[ret] = opaque
return ret
def listAllDomains(self, flags=0):
"""List all domains and returns a list of domain objects"""
ret = libvirtmod.virConnectListAllDomains(self._o, flags)
if ret is None:
raise libvirtError("virConnectListAllDomains() failed", conn=self)
retlist = list()
for domptr in ret:
retlist.append(virDomain(self, _obj=domptr))
return retlist
def listAllStoragePools(self, flags=0):
"""Returns a list of storage pool objects"""
ret = libvirtmod.virConnectListAllStoragePools(self._o, flags)
if ret is None:
raise libvirtError("virConnectListAllStoragePools() failed", conn=self)
retlist = list()
for poolptr in ret:
retlist.append(virStoragePool(self, _obj=poolptr))
return retlist
def listAllNetworks(self, flags=0):
"""Returns a list of network objects"""
ret = libvirtmod.virConnectListAllNetworks(self._o, flags)
if ret is None:
raise libvirtError("virConnectListAllNetworks() failed", conn=self)
retlist = list()
for netptr in ret:
retlist.append(virNetwork(self, _obj=netptr))
return retlist
def listAllInterfaces(self, flags=0):
"""Returns a list of interface objects"""
ret = libvirtmod.virConnectListAllInterfaces(self._o, flags)
if ret is None:
raise libvirtError("virConnectListAllInterfaces() failed", conn=self)
retlist = list()
for ifaceptr in ret:
retlist.append(virInterface(self, _obj=ifaceptr))
return retlist
def listAllDevices(self, flags=0):
"""Returns a list of host node device objects"""
ret = libvirtmod.virConnectListAllNodeDevices(self._o, flags)
if ret is None:
raise libvirtError("virConnectListAllNodeDevices() failed", conn=self)
retlist = list()
for devptr in ret:
retlist.append(virNodeDevice(self, _obj=devptr))
return retlist
def listAllNWFilters(self, flags=0):
"""Returns a list of network filter objects"""
ret = libvirtmod.virConnectListAllNWFilters(self._o, flags)
if ret is None:
raise libvirtError("virConnectListAllNWFilters() failed", conn=self)
retlist = list()
for filter_ptr in ret:
retlist.append(virNWFilter(self, _obj=filter_ptr))
return retlist
def listAllSecrets(self, flags=0):
"""Returns a list of secret objects"""
ret = libvirtmod.virConnectListAllSecrets(self._o, flags)
if ret is None:
raise libvirtError("virConnectListAllSecrets() failed", conn=self)
retlist = list()
for secret_ptr in ret:
retlist.append(virSecret(self, _obj=secret_ptr))
return retlist
def _dispatchCloseCallback(self, reason, cbData):
"""Dispatches events to python user close callback"""
cb = cbData["cb"]
opaque = cbData["opaque"]
cb(self, reason, opaque)
return 0
def unregisterCloseCallback(self):
"""Removes a close event callback"""
ret = libvirtmod.virConnectUnregisterCloseCallback(self._o)
if ret == -1: raise libvirtError ('virConnectUnregisterCloseCallback() failed', conn=self)
def registerCloseCallback(self, cb, opaque):
"""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', conn=self)
return ret
def createXMLWithFiles(self, xmlDesc, files, flags=0):
"""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', conn=self)
__tmp = virDomain(self,_obj=ret)
return __tmp
def listAllSnapshots(self, flags=0):
"""List all snapshots and returns a list of snapshot objects"""
ret = libvirtmod.virDomainListAllSnapshots(self._o, flags)
if ret is None:
raise libvirtError("virDomainListAllSnapshots() failed", conn=self)
retlist = list()
for snapptr in ret:
retlist.append(virDomainSnapshot(self, _obj=snapptr))
return retlist
def createWithFiles(self, files, flags=0):
"""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', dom=self)
return ret
def getConnect(self):
"""Get the connection that owns the domain that a snapshot was created for"""
return self.connect()
def getDomain(self):
"""Get the domain that a snapshot was created for"""
return self.domain()
def listAllChildren(self, flags=0):
"""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", conn=self)
retlist = list()
for snapptr in ret:
retlist.append(virDomainSnapshot(self, _obj=snapptr))
return retlist
def listAllVolumes(self, flags=0):
"""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", conn=self)
retlist = list()
for volptr in ret:
retlist.append(virStorageVol(self, _obj=volptr))
return retlist
def __del__(self):
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, cbData):
"""
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, cb, opaque):
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, opaque):
"""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(1024*64)
if got == -2:
raise libvirtError("cannot use recvAll with "
"nonblocking stream")
if len(got) == 0:
break
try:
ret = handler(self, got, opaque)
if type(ret) is int and ret < 0:
raise RuntimeError("recvAll handler returned %d" % ret)
except Exception, e:
try:
self.abort()
except:
pass
raise e
def sendAll(self, handler, opaque):
"""
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, 1024*64, opaque)
except:
try:
self.abort()
except:
pass
raise e
if got == "":
break
ret = self.send(got)
if ret == -2:
raise libvirtError("cannot use sendAll with "
"nonblocking stream")
def recv(self, nbytes):
"""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):
"""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, len(data))
if ret == -1: raise libvirtError ('virStreamSend() failed')
return ret
此差异已折叠。
此差异已折叠。
<?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='str *' 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&apos;ed set of virDomainQemuMonitorCommandFlags'/>
</function>
<function name='virDomainQemuAgentCommand' file='python-qemu'>
<info>Send a Guest Agent command to domain</info>
<return type='str *' 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>
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
......@@ -58,15 +58,6 @@ export LIBVIRT_LOCK_MANAGER_PLUGIN_DIR="$b/src/.libs"
export VIRTLOCKD_PATH="$b/src/virtlockd"
export LIBVIRTD_PATH="$b/daemon/libvirtd"
# For Python.
export PYTHON=@PYTHON@
if [ -z "$PYTHONPATH" ]; then
PYTHONPATH="$b/python:$b/python/.libs"
else
PYTHONPATH="$b/python:$b/python/.libs:$PYTHONPATH"
fi
export PYTHONPATH
# This is a cheap way to find some use-after-free and uninitialized
# read problems when using glibc.
random_val="$(awk 'BEGIN{srand(); print 1+int(255*rand())}' < /dev/null)"
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册