mirror of
https://gitlab.com/libvirt/libvirt-python.git
synced 2025-07-05 08:59:36 +03:00
examples: Convert to ArgumentParser
Replace getopt() and hand-rolled-parser with argparse.ArgumentParser. Fix wrong header comments copy-pasted from domstart.py Signed-off-by: Philipp Hahn <hahn@univention.de>
This commit is contained in:
committed by
Philipp Hahn
parent
9cf539a2a8
commit
06aba185a8
@ -2,6 +2,7 @@
|
||||
# consolecallback - provide a persistent console that survives guest reboots
|
||||
|
||||
import sys, os, logging, libvirt, tty, termios, atexit
|
||||
from argparse import ArgumentParser
|
||||
from typing import Optional # noqa F401
|
||||
|
||||
def reset_term() -> None:
|
||||
@ -64,18 +65,15 @@ def lifecycle_callback(connection: libvirt.virConnect, domain: libvirt.virDomain
|
||||
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]
|
||||
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", uri)
|
||||
logging.info("UUID: %s", uuid)
|
||||
logging.info("URI: %s", args.uri)
|
||||
logging.info("UUID: %s", args.uuid)
|
||||
|
||||
libvirt.virEventRegisterDefaultImpl()
|
||||
libvirt.registerErrorHandler(error_handler, None)
|
||||
@ -84,7 +82,7 @@ atexit.register(reset_term)
|
||||
attrs = termios.tcgetattr(0)
|
||||
tty.setraw(0)
|
||||
|
||||
console = Console(uri, uuid)
|
||||
console = Console(args.uri, args.uuid)
|
||||
console.stdin_watch = libvirt.virEventAddHandle(0, libvirt.VIR_EVENT_HANDLE_READABLE, stdin_callback, console)
|
||||
|
||||
while check_console(console):
|
||||
|
@ -1,37 +1,29 @@
|
||||
#!/usr/bin/env python3
|
||||
# netdhcpleases - print leases info for given virtual network
|
||||
"""
|
||||
Print leases info for a given virtual network
|
||||
"""
|
||||
|
||||
import libvirt
|
||||
import sys
|
||||
import time
|
||||
from argparse import ArgumentParser
|
||||
|
||||
def usage() -> None:
|
||||
print("Usage: %s [URI] NETWORK" % sys.argv[0])
|
||||
print(" Print leases info for a given virtual network")
|
||||
|
||||
uri = None
|
||||
network = None
|
||||
args = len(sys.argv)
|
||||
|
||||
if args == 2:
|
||||
network = sys.argv[1]
|
||||
elif args == 3:
|
||||
uri = sys.argv[1]
|
||||
network = sys.argv[2]
|
||||
else:
|
||||
usage()
|
||||
sys.exit(2)
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("uri", nargs="?", default=None)
|
||||
parser.add_argument("network")
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
conn = libvirt.open(uri)
|
||||
conn = libvirt.open(args.uri)
|
||||
except libvirt.libvirtError:
|
||||
print("Unable to open connection to libvirt")
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
net = conn.networkLookupByName(network)
|
||||
net = conn.networkLookupByName(args.network)
|
||||
except libvirt.libvirtError:
|
||||
print("Network %s not found" % network)
|
||||
print("Network %s not found" % args.network)
|
||||
sys.exit(0)
|
||||
|
||||
leases = net.DHCPLeases()
|
||||
|
@ -1,16 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
# dominfo - print some information about a domain
|
||||
"""
|
||||
Print information about the domain DOMAIN
|
||||
"""
|
||||
|
||||
import libvirt
|
||||
import sys
|
||||
import os
|
||||
import libxml2
|
||||
import pdb
|
||||
from argparse import ArgumentParser
|
||||
from typing import Any
|
||||
|
||||
def usage() -> None:
|
||||
print('Usage: %s DOMAIN' % sys.argv[0])
|
||||
print(' Print information about the domain DOMAIN')
|
||||
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("domain")
|
||||
args = parser.parse_args()
|
||||
|
||||
|
||||
def print_section(title: str) -> None:
|
||||
print("\n%s" % title)
|
||||
@ -28,11 +33,6 @@ def print_xml(key: str, ctx, path: str) -> str:
|
||||
print_entry(key, value)
|
||||
return value
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
usage()
|
||||
sys.exit(2)
|
||||
|
||||
name = sys.argv[1]
|
||||
|
||||
# Connect to libvirt
|
||||
try:
|
||||
@ -42,10 +42,10 @@ except libvirt.libvirtError:
|
||||
sys.exit(1)
|
||||
|
||||
try:
|
||||
dom = conn.lookupByName(name)
|
||||
dom = conn.lookupByName(args.domain)
|
||||
# Annoyiingly, libvirt prints its own error message here
|
||||
except libvirt.libvirtError:
|
||||
print("Domain %s is not running" % name)
|
||||
print("Domain %s is not running" % args.domain)
|
||||
sys.exit(0)
|
||||
|
||||
info = dom.info()
|
||||
|
@ -1,8 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
# domipaddrs - print domain interfaces along with their MAC and IP addresses
|
||||
"""
|
||||
Print domain interfaces along with their MAC and IP addresses
|
||||
"""
|
||||
|
||||
import libvirt
|
||||
import sys
|
||||
from argparse import ArgumentParser
|
||||
|
||||
IPTYPE = {
|
||||
libvirt.VIR_IP_ADDR_TYPE_IPV4: "ipv4",
|
||||
@ -33,29 +36,20 @@ def print_dom_ifaces(dom: libvirt.virDomain) -> None:
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uri = None
|
||||
name = None
|
||||
args = len(sys.argv)
|
||||
|
||||
if args == 2:
|
||||
name = sys.argv[1]
|
||||
elif args == 3:
|
||||
uri = sys.argv[1]
|
||||
name = sys.argv[2]
|
||||
else:
|
||||
print("Usage: %s [URI] DOMAIN" % sys.argv[0])
|
||||
print(" Print domain interfaces along with their MAC and IP addresses")
|
||||
sys.exit(2)
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("uri", nargs="?", default=None)
|
||||
parser.add_argument("domain")
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
conn = libvirt.open(uri)
|
||||
conn = libvirt.open(args.uri)
|
||||
except libvirt.libvirtError:
|
||||
raise SystemExit("Unable to open connection to libvirt")
|
||||
|
||||
try:
|
||||
dom = conn.lookupByName(name)
|
||||
dom = conn.lookupByName(args.domain)
|
||||
except libvirt.libvirtError:
|
||||
print("Domain %s not found" % name)
|
||||
print("Domain %s not found" % args.domain)
|
||||
sys.exit(0)
|
||||
|
||||
print_dom_ifaces(dom)
|
||||
|
@ -1,24 +1,22 @@
|
||||
#!/usr/bin/env python3
|
||||
# domstart - make sure a given domU is running, if not start it
|
||||
"""
|
||||
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 sys
|
||||
import os
|
||||
import libxml2
|
||||
import pdb
|
||||
from argparse import ArgumentParser
|
||||
|
||||
def usage() -> None:
|
||||
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)
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("dir")
|
||||
args = parser.parse_args()
|
||||
|
||||
dir = sys.argv[1]
|
||||
imgs = os.listdir(dir)
|
||||
imgs = os.listdir(args.dir)
|
||||
|
||||
try:
|
||||
conn = libvirt.open(None)
|
||||
@ -27,7 +25,7 @@ except libvirt.libvirtError:
|
||||
sys.exit(1)
|
||||
|
||||
for img in imgs:
|
||||
file = os.path.join(dir, img)
|
||||
file = os.path.join(args.dir, img)
|
||||
print("Restoring %s ... " % img)
|
||||
ret = conn.restore(file)
|
||||
if ret == 0:
|
||||
|
@ -1,22 +1,20 @@
|
||||
#!/usr/bin/env python3
|
||||
# domstart - make sure a given domU is running, if not start it
|
||||
"""
|
||||
Save all currently running domU's into DIR.
|
||||
DIR must exist and be writable by this process.
|
||||
"""
|
||||
|
||||
import libvirt
|
||||
import sys
|
||||
import os
|
||||
import libxml2
|
||||
import pdb
|
||||
from argparse import ArgumentParser
|
||||
|
||||
def usage() -> None:
|
||||
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]
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("dir")
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
conn = libvirt.open(None)
|
||||
@ -30,7 +28,7 @@ for id in doms:
|
||||
continue
|
||||
dom = conn.lookupByID(id)
|
||||
print("Saving %s[%d] ... " % (dom.name(), id))
|
||||
path = os.path.join(dir, dom.name())
|
||||
path = os.path.join(args.dir, dom.name())
|
||||
ret = dom.save(path)
|
||||
if ret == 0:
|
||||
print("done")
|
||||
|
@ -1,11 +1,15 @@
|
||||
#!/usr/bin/env python3
|
||||
# domstart - make sure a given domU is running, if not start it
|
||||
"""
|
||||
Check that the domain described by DOMAIN.XML is running.
|
||||
If the domain is not running, create it.
|
||||
"""
|
||||
|
||||
import libvirt
|
||||
import sys
|
||||
import os
|
||||
import libxml2
|
||||
import pdb
|
||||
from argparse import ArgumentParser
|
||||
from typing import Tuple
|
||||
|
||||
# Parse the XML description of domU from FNAME
|
||||
@ -20,18 +24,12 @@ def read_domain(fname: str) -> Tuple[str, str]:
|
||||
name = doc.xpathNewContext().xpathEval("/domain/name")[0].content
|
||||
return (name, xmldesc)
|
||||
|
||||
def usage() -> None:
|
||||
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)
|
||||
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(sys.argv[1])
|
||||
(name, xmldesc) = read_domain(args.file)
|
||||
|
||||
try:
|
||||
conn = libvirt.open(None)
|
||||
|
@ -1,20 +1,18 @@
|
||||
#!/usr/bin/env python3
|
||||
# esxlist - list active domains of an ESX host and print some info.
|
||||
# also demonstrates how to use the libvirt.openAuth() method
|
||||
"""
|
||||
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
|
||||
from argparse import ArgumentParser
|
||||
from typing import Any, List
|
||||
|
||||
|
||||
def usage() -> None:
|
||||
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
|
||||
@ -73,15 +71,12 @@ def print_xml(key: str, ctx, path: str) -> str:
|
||||
return value
|
||||
|
||||
|
||||
if len(sys.argv) != 2:
|
||||
usage()
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
hostname = sys.argv[1]
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("hostname")
|
||||
args = parser.parse_args()
|
||||
|
||||
# Connect to libvirt
|
||||
uri = "esx://%s/?no_verify=1" % hostname
|
||||
uri = "esx://%s/?no_verify=1" % args.hostname
|
||||
|
||||
# The auth argument is a list that contains 3 items:
|
||||
# - a list of supported credential types
|
||||
@ -101,7 +96,7 @@ auth = [[libvirt.VIR_CRED_AUTHNAME, libvirt.VIR_CRED_NOECHOPROMPT],
|
||||
try:
|
||||
conn = libvirt.openAuth(uri, auth, 0)
|
||||
except libvirt.libvirtError:
|
||||
print("Failed to open connection to %s" % hostname)
|
||||
print("Failed to open connection to %s" % args.hostname)
|
||||
sys.exit(1)
|
||||
|
||||
state_names = { libvirt.VIR_DOMAIN_RUNNING : "running",
|
||||
|
@ -7,14 +7,13 @@
|
||||
##############################################################################
|
||||
|
||||
import atexit
|
||||
import sys
|
||||
import getopt
|
||||
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]
|
||||
@ -725,53 +724,29 @@ def myConnectionCloseCallback(conn: libvirt.virConnect, reason: int, opaque: _T)
|
||||
run = False
|
||||
|
||||
|
||||
def usage() -> None:
|
||||
print("usage: %s [-hdl] [uri]" % (os.path.basename(__file__),))
|
||||
print(" uri will default to qemu:///system")
|
||||
print(" --help, -h Print this help message")
|
||||
print(" --debug, -d Print debug output")
|
||||
print(" --loop=TYPE, -l Choose event-loop-implementation (native, poll, asyncio)")
|
||||
print(" --timeout=SECS Quit after SECS seconds running")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], "hdl:", ["help", "debug", "loop=", "timeout="])
|
||||
except getopt.GetoptError as err:
|
||||
# print help information and exit:
|
||||
print(str(err)) # will print something like "option -a not recognized"
|
||||
usage()
|
||||
sys.exit(2)
|
||||
timeout = None
|
||||
for o, a in opts:
|
||||
if o in ("-h", "--help"):
|
||||
usage()
|
||||
sys.exit()
|
||||
if o in ("-d", "--debug"):
|
||||
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
|
||||
if o in ("-l", "--loop"):
|
||||
global event_impl
|
||||
event_impl = a
|
||||
if o in ("--timeout"):
|
||||
timeout = int(a)
|
||||
|
||||
if len(args) >= 1:
|
||||
uri = args[0]
|
||||
else:
|
||||
uri = "qemu:///system"
|
||||
|
||||
print("Using uri '%s' and event loop '%s'" % (uri, event_impl))
|
||||
print("Using uri '%s' and event loop '%s'" % (args.uri, args.loop))
|
||||
|
||||
# Run a background thread with the event loop
|
||||
if event_impl == "poll":
|
||||
if args.loop == "poll":
|
||||
virEventLoopPollStart()
|
||||
elif event_impl == "asyncio":
|
||||
elif args.loop == "asyncio":
|
||||
virEventLoopAIOStart()
|
||||
else:
|
||||
virEventLoopNativeStart()
|
||||
|
||||
vc = libvirt.openReadOnly(uri)
|
||||
vc = libvirt.openReadOnly(args.uri)
|
||||
|
||||
# Close connection on exit (to test cleanup paths)
|
||||
def exit() -> None:
|
||||
@ -839,7 +814,7 @@ def main() -> None:
|
||||
# run the event loop in your main thread if your app is
|
||||
# totally event based.
|
||||
count = 0
|
||||
while run and (timeout is None or count < timeout):
|
||||
while run and (args.timeout is None or count < args.timeout):
|
||||
count = count + 1
|
||||
time.sleep(1)
|
||||
|
||||
|
@ -1,26 +1,22 @@
|
||||
#!/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
|
||||
import sys
|
||||
import getopt
|
||||
import os
|
||||
from argparse import ArgumentParser
|
||||
|
||||
uri = "qemu:///system"
|
||||
customXMLuri = "guest-cpu.python.libvirt.org"
|
||||
connectRetryTimeout = 5
|
||||
|
||||
def usage():
|
||||
print("usage: "+os.path.basename(sys.argv[0])+" [-h] [uri]")
|
||||
print(" uri will default to qemu:///system")
|
||||
print(" --help, -h Print(this help message")
|
||||
print("")
|
||||
print("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")
|
||||
|
||||
class workerData:
|
||||
def __init__(self):
|
||||
self.doms = list()
|
||||
@ -140,21 +136,10 @@ def main():
|
||||
time.sleep(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], "h", ["help"])
|
||||
except getopt.GetoptError as err:
|
||||
print(str(err))
|
||||
usage()
|
||||
sys.exit(2)
|
||||
for o, a in opts:
|
||||
if o in ("-h", "--help"):
|
||||
usage()
|
||||
sys.exit()
|
||||
parser = ArgumentParser(description=__doc__)
|
||||
parser.add_argument("uri", nargs="?", default=uri)
|
||||
args = parser.parse_args()
|
||||
|
||||
if len(args) > 1:
|
||||
usage()
|
||||
sys.exit(1)
|
||||
elif len(args) == 1:
|
||||
uri = args[0]
|
||||
uri = args.uri
|
||||
|
||||
main()
|
||||
|
@ -1,74 +1,45 @@
|
||||
#!/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
|
||||
import sys
|
||||
import getopt
|
||||
import os
|
||||
from argparse import ArgumentParser
|
||||
|
||||
customXMLuri = "guest-cpu.python.libvirt.org"
|
||||
|
||||
def usage():
|
||||
print("usage: "+os.path.basename(sys.argv[0])+" [-hcl] domain count [uri]")
|
||||
print(" uri will default to qemu:///system")
|
||||
print(" --help, -h Print(this help message")
|
||||
print(" --config, -c Modify persistent domain configuration")
|
||||
print(" --live, -l Modify live domain configuration")
|
||||
print("")
|
||||
print("Sets the vCPU count via the guest agent and sets the metadata element " +
|
||||
"used by guest-vcpu-daemon.py example")
|
||||
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()
|
||||
|
||||
uri = "qemu:///system"
|
||||
flags = 0
|
||||
live = False
|
||||
config = False
|
||||
flags = (libvirt.VIR_DOMAIN_AFFECT_CONFIG if args.config else 0) | (libvirt.VIR_DOMAIN_AFFECT_LIVE if args.live else 0)
|
||||
|
||||
try:
|
||||
opts, args = getopt.getopt(sys.argv[1:], "hcl", ["help", "config", "live"])
|
||||
except getopt.GetoptError as err:
|
||||
# print help information and exit:
|
||||
print(str(err)) # will print something like "option -a not recognized"
|
||||
usage()
|
||||
sys.exit(2)
|
||||
for o, a in opts:
|
||||
if o in ("-h", "--help"):
|
||||
usage()
|
||||
sys.exit()
|
||||
if o in ("-c", "--config"):
|
||||
config = True
|
||||
flags |= libvirt.VIR_DOMAIN_AFFECT_CONFIG
|
||||
if o in ("-l", "--live"):
|
||||
live = True
|
||||
flags |= libvirt.VIR_DOMAIN_AFFECT_LIVE
|
||||
conn = libvirt.open(args.uri)
|
||||
dom = conn.lookupByName(args.domain)
|
||||
|
||||
if len(args) < 2:
|
||||
usage()
|
||||
sys.exit(1)
|
||||
elif len(args) >= 3:
|
||||
uri = args[2]
|
||||
|
||||
domain = args[0]
|
||||
count = int(args[1])
|
||||
|
||||
conn = libvirt.open(uri)
|
||||
dom = conn.lookupByName(domain)
|
||||
|
||||
if flags == 0 or config:
|
||||
if flags == 0 or args.config:
|
||||
confvcpus = dom.vcpusFlags(libvirt.VIR_DOMAIN_AFFECT_CONFIG)
|
||||
|
||||
if confvcpus < count:
|
||||
if confvcpus < args.count:
|
||||
print("Persistent domain configuration has only " + str(confvcpus) + " vcpus configured")
|
||||
sys.exit(1)
|
||||
|
||||
if flags == 0 or live:
|
||||
if flags == 0 or args.live:
|
||||
livevcpus = dom.vcpusFlags(libvirt.VIR_DOMAIN_AFFECT_LIVE)
|
||||
|
||||
if livevcpus < count:
|
||||
if livevcpus < args.count:
|
||||
print("Live domain configuration has only " + str(livevcpus) + " vcpus configured")
|
||||
sys.exit(1)
|
||||
|
||||
if flags == 0 or live:
|
||||
dom.setVcpusFlags(count, libvirt.VIR_DOMAIN_AFFECT_LIVE | libvirt.VIR_DOMAIN_VCPU_GUEST)
|
||||
if flags == 0 or args.live:
|
||||
dom.setVcpusFlags(args.count, libvirt.VIR_DOMAIN_AFFECT_LIVE | libvirt.VIR_DOMAIN_VCPU_GUEST)
|
||||
|
||||
meta = "<ncpus count='" + str(count) + "'/>"
|
||||
meta = "<ncpus count='" + str(args.count) + "'/>"
|
||||
|
||||
dom.setMetadata(libvirt.VIR_DOMAIN_METADATA_ELEMENT, meta, "guestvcpudaemon", customXMLuri, flags)
|
||||
|
@ -1,10 +1,15 @@
|
||||
#!/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, sys, os
|
||||
from argparse import ArgumentParser
|
||||
|
||||
def bytesWriteHandler(stream: libvirt.virStream, buf: bytes, opaque: int) -> int:
|
||||
fd = opaque
|
||||
@ -94,24 +99,22 @@ def upload(vol: libvirt.virStorageVol, st: libvirt.virStream, filename: str) ->
|
||||
os.close(fd)
|
||||
|
||||
# main
|
||||
if len(sys.argv) != 5:
|
||||
print("Usage: ", sys.argv[0], " URI --upload/--download VOLUME FILE")
|
||||
print("Either uploads local FILE to libvirt VOLUME, or downloads libvirt ")
|
||||
print("VOLUME into local FILE while preserving FILE/VOLUME sparseness")
|
||||
sys.exit(1)
|
||||
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(sys.argv[1])
|
||||
vol = conn.storageVolLookupByKey(sys.argv[3])
|
||||
|
||||
conn = libvirt.open(args.uri)
|
||||
vol = conn.storageVolLookupByKey(args.volume)
|
||||
|
||||
st = conn.newStream()
|
||||
|
||||
if sys.argv[2] == "--download":
|
||||
download(vol, st, sys.argv[4])
|
||||
elif sys.argv[2] == "--upload":
|
||||
upload(vol, st, sys.argv[4])
|
||||
else:
|
||||
print("Unknown operation: %s " % sys.argv[1])
|
||||
sys.exit(1)
|
||||
args.operation(vol, st, args.file)
|
||||
|
||||
st.finish()
|
||||
conn.close()
|
||||
|
Reference in New Issue
Block a user