forked from autotest/virt-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
virsh.py
1840 lines (1473 loc) · 57.1 KB
/
virsh.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Utility classes and functions to handle connection to a libvirt host system
Suggested usage: import autotest.client.virt.virsh
The entire contents of callables in this module (minus the names defined in
NOCLOSE below), will become methods of the Virsh and VirshPersistent classes.
A Closure class is used to wrap the module functions, lambda does not
properly store instance state in this implementation.
Because none of the methods have a 'self' parameter defined, the classes
are defined to be dict-like, and get passed in to the methods as a the
special **dargs parameter. All virsh module functions _MUST_ include a
special **dargs (variable keyword arguments) to accept non-default
keyword arguments.
The standard set of keyword arguments to all functions/modules is declared
in the VirshBase class. Only the 'virsh_exec' key is guaranteed to always
be present, the remainder may or may not be provided. Therefor, virsh
functions/methods should use the dict.get() method to retrieve with a default
for non-existant keys.
@copyright: 2012 Red Hat Inc.
"""
import signal, logging, urlparse, re
from autotest.client import utils, os_dep
from autotest.client.shared import error
from virttest import aexpect, propcan, remote
# list of symbol names NOT to wrap as Virsh class methods
# Everything else from globals() will become a method of Virsh class
NOCLOSE = globals().keys() + [
'NOCLOSE', 'SCREENSHOT_ERROR_COUNT', 'VIRSH_COMMAND_CACHE',
'VIRSH_EXEC', 'VirshBase', 'VirshClosure', 'VirshSession', 'Virsh',
'VirshPersistent',
]
# Needs to be in-scope for Virsh* class screenshot method and module function
SCREENSHOT_ERROR_COUNT = 0
# Cache of virsh commands, used by has_help_command() and help_command()
VIRSH_COMMAND_CACHE = None
# This is used both inside and outside classes
try:
VIRSH_EXEC = os_dep.command("virsh")
except ValueError:
logging.warning("Virsh executable not set or found on path, "
"virsh module will not function normally")
VIRSH_EXEC = '/bin/true'
class VirshBase(propcan.PropCanBase):
"""
Base Class storing libvirt Connection & state to a host
"""
__slots__ = ('uri', 'ignore_status', 'debug', 'virsh_exec')
def __init__(self, *args, **dargs):
"""
Initialize instance with virsh_exec always set to something
"""
init_dict = dict(*args, **dargs)
init_dict['virsh_exec'] = init_dict.get('virsh_exec', VIRSH_EXEC)
init_dict['uri'] = init_dict.get('uri', None)
super(VirshBase, self).__init__(init_dict)
def set_ignore_status(self, ignore_status):
"""
Enforce setting ignore_status as a boolean
"""
if bool(ignore_status):
self.dict_set('ignore_status', True)
else:
self.dict_set('ignore_status', False)
def set_debug(self, debug):
"""
Accessor method for 'debug' property that logs message on change
"""
if not self.INITIALIZED:
self.dict_set('debug', debug)
else:
current_setting = self.dict_get('debug')
desired_setting = bool(debug)
if not current_setting and desired_setting:
self.dict_set('debug', True)
logging.debug("Virsh debugging enabled")
# current and desired could both be True
if current_setting and not desired_setting:
self.dict_set('debug', False)
logging.debug("Virsh debugging disabled")
def get_uri(self):
"""
Accessor method for 'uri' property that must exist
"""
# self.get() would call get_uri() recursivly
try:
return self.dict_get('uri')
except KeyError:
return None
class VirshSession(aexpect.ShellSession):
"""
A virsh shell session, used with Virsh instances.
"""
# No way to get virsh sub-command "exit" status
# Check output against list of known error-status strings
ERROR_REGEX_LIST = ['error:\s*.+$', '.*failed.*']
def __init__(self, virsh_exec=None, uri=None, a_id=None,
prompt=r"virsh\s*\#\s*", remote_ip=None,
remote_user=None, remote_pwd=None):
"""
Initialize virsh session server, or client if id set.
@param: virsh_exec: path to virsh executable
@param: uri: uri of libvirt instance to connect to
@param: id: ID of an already running server, if accessing a running
server, or None if starting a new one.
@param: prompt: Regular expression describing the shell's prompt line.
@param: remote_ip: Hostname/IP of remote system to ssh into (if any)
@param: remote_user: Username to ssh in as (if any)
@param: remote_pwd: Password to use, or None for host/pubkey
"""
self.uri = uri
self.remote_ip = remote_ip
self.remote_user = remote_user
self.remote_pwd = remote_pwd
# Special handling if setting up a remote session
if a_id is None and remote_ip is not None and uri is not None:
if remote_pwd:
pref_auth = "-o PreferredAuthentications=password"
else:
pref_auth = "-o PreferredAuthentications=hostbased,publickey"
# ssh_cmd != None flags this as remote session
ssh_cmd = ("ssh -o UserKnownHostsFile=/dev/null %s -p %s %s@%s"
% (pref_auth, 22, self.remote_user, self.remote_ip))
self.virsh_exec = ( "%s \"%s -c '%s'\""
% (ssh_cmd, virsh_exec, self.uri) )
else: # setting up a local session or re-using a session
if self.uri:
self.virsh_exec += " -c '%s'" % self.uri
else:
self.virsh_exec = virsh_exec
ssh_cmd = None # flags not-remote session
# aexpect tries to auto close session because no clients connected yet
aexpect.ShellSession.__init__(self, self.virsh_exec, a_id,
prompt=prompt, auto_close=False)
if ssh_cmd is not None: # this is a remote session
# Handle ssh / password prompts
remote.handle_prompts(self, self.remote_user, self.remote_pwd,
prompt, debug=True)
# fail if libvirtd is not running
if self.cmd_status('list', timeout=60) != 0:
logging.debug("Persistent virsh session is not responding, "
"libvirtd may be dead.")
raise aexpect.ShellStatusError(virsh_exec, 'list')
def cmd_status_output(self, cmd, timeout=60, internal_timeout=None,
print_func=None):
"""
Send a virsh command and return its exit status and output.
@param cmd: virsh command to send (must not contain newline characters)
@param timeout: The duration (in seconds) to wait for the prompt to
return
@param internal_timeout: The timeout to pass to read_nonblocking
@param print_func: A function to be used to print the data being read
(should take a string parameter)
@return: A tuple (status, output) where status is the exit status and
output is the output of cmd
@raise ShellTimeoutError: Raised if timeout expires
@raise ShellProcessTerminatedError: Raised if the shell process
terminates while waiting for output
@raise ShellStatusError: Raised if the exit status cannot be obtained
@raise ShellError: Raised if an unknown error occurs
"""
out = self.cmd_output(cmd, timeout, internal_timeout, print_func)
for line in out.splitlines():
if self.match_patterns(line, self.ERROR_REGEX_LIST) is not None:
return 1, out
return 0, out
def cmd_result(self, cmd, ignore_status=False):
"""Mimic utils.run()"""
exit_status, stdout = self.cmd_status_output(cmd)
stderr = '' # no way to retrieve this separately
result = utils.CmdResult(cmd, stdout, stderr, exit_status)
if not ignore_status and exit_status:
raise error.CmdError(cmd, result,
"Virsh Command returned non-zero exit status")
return result
# Work around for inconsistent builtin closure local reference problem
# across different versions of python
class VirshClosure(object):
"""
Callable that uses dict-like 'self' argument to augment **dargs
"""
def __init__(self, reference_function, dict_like_instance):
"""
Initialize callable for reference_function on dict_like_instance
"""
if not issubclass(dict_like_instance.__class__, dict):
raise ValueError("dict_like_instance %s must be dict or subclass"
% dict_like_instance.__class__.__name__)
self.reference_function = reference_function
self.dict_like_instance = dict_like_instance
def __call__(self, *args, **dargs):
"""
Call reference_function with dict_like_instance augmented by **dargs
@param: *args: Passthrough to reference_function
@param: **dargs: Updates dict_like_instance copy before call
"""
dargs.update(self.dict_like_instance)
return self.reference_function(*args, **dargs)
class Virsh(VirshBase):
"""
Execute libvirt operations, using a new virsh shell each time.
"""
__slots__ = VirshBase.__slots__
def __init__(self, *args, **dargs):
"""
Initialize Virsh instance with persistent options
@param: *args: Initial property keys/values
@param: **dargs: Initial property keys/values
"""
super(Virsh, self).__init__(*args, **dargs)
# Define the instance callables from the contents of this module
# to avoid using class methods and hand-written aliases
for sym, ref in globals().items():
if sym not in NOCLOSE and callable(ref):
# Adding methods, not properties, so avoid special __slots__
# handling. __getattribute__ will still find these.
self.super_set(sym, VirshClosure(ref, self))
class VirshPersistent(Virsh):
"""
Execute libvirt operations using persistent virsh session.
"""
__slots__ = Virsh.__slots__ + ('session_id', )
# Help detect leftover sessions
SESSION_COUNTER = 0
def __init__(self, *args, **dargs):
super(VirshPersistent, self).__init__(*args, **dargs)
if self.get('session_id') is None:
# set_uri does not call when INITIALIZED = False
# and no session_id passed to super __init__
self.new_session()
def __exit__(self, exc_type, exc_value, traceback):
"""
Clean up any leftover sessions
"""
self.close_session()
super(VirshPersistent, self).__exit__(exc_type, exc_value, traceback)
def __del__(self):
"""
Clean up any leftover sessions
"""
self.__exit__(None, None, None)
def close_session(self):
"""
If a persistent session exists, close it down.
"""
try:
session_id = self.dict_get('session_id')
if session_id:
try:
existing = VirshSession(a_id=session_id)
# except clause exits function
self.dict_del('session_id')
except aexpect.ShellStatusError:
# session was already closed
self.dict_del('session_id')
return # don't check is_alive or update counter
if existing.is_alive():
# try nicely first
existing.close()
if existing.is_alive():
# Be mean, incase it's hung
existing.close(sig=signal.SIGTERM)
# Keep count:
self.__class__.SESSION_COUNTER -= 1
self.dict_del('session_id')
except KeyError:
# Allow other exceptions to be raised
pass # session was closed already
def new_session(self):
"""
Open new session, closing any existing
"""
# Accessors may call this method, avoid recursion
virsh_exec = self.dict_get('virsh_exec') # Must exist, can't be None
uri = self.dict_get('uri') # Must exist, can be None
self.close_session()
# Always create new session
new_session = VirshSession(virsh_exec, uri, a_id=None)
# Keep count
self.__class__.SESSION_COUNTER += 1
session_id = new_session.get_id()
self.dict_set('session_id', session_id)
def set_uri(self, uri):
"""
Accessor method for 'uri' property, create new session on change
"""
if not self.INITIALIZED:
# Allow __init__ to call new_session
self.dict_set('uri', uri)
else:
# If the uri is changing
if self.dict_get('uri') != uri:
self.dict_set('uri', uri)
self.new_session()
# otherwise do nothing
class VirshConnectBack(VirshPersistent):
"""
Persistent virsh session connected back from a remote host
"""
__slots__ = Virsh.__slots__ + ('remote_ip', 'remote_pwd', 'remote_user')
def new_session(self):
"""
Open new remote session, closing any existing
"""
# Accessors may call this method, avoid recursion
virsh_exec = self.dict_get('virsh_exec') # Must exist, can't be None
uri = self.dict_get('uri') # Must exist, can be None
remote_ip = self.dict_get('remote_ip')
try:
remote_user = self.dict_get('remote_user')
except KeyError:
remote_user = 'root'
try:
remote_pwd = self.dict_get('remote_pwd')
except KeyError:
remote_pwd = None
super(VirshConnectBack, self).close_session()
new_session = VirshSession(virsh_exec, uri, a_id=None,
remote_ip=remote_ip,
remote_user=remote_user,
remote_pwd=remote_pwd)
# Keep count
self.__class__.SESSION_COUNTER += 1
session_id = new_session.get_id()
self.dict_set('session_id', session_id)
@staticmethod
def kosher_args(remote_ip, uri):
"""
Convenience static method to help validate argument sanity before use
@param: remote_ip: ip/hostname of remote libvirt helper-system
@param: uri: fully qualified libvirt uri of local system, from remote.
@returns: True/False if checks pass or not
"""
if remote_ip is None or uri is None:
return False
all_false = [
# remote_ip checks
bool(remote_ip.count("EXAMPLE.COM")),
bool(remote_ip.count("localhost")),
bool(remote_ip.count("127.")),
# uri checks
uri is None,
uri is "",
bool(uri.count("default")),
bool(uri.count(':///')),
bool(uri.count("localhost")),
bool(uri.count("127."))
]
return True not in all_false
##### virsh module functions follow (See module docstring for API) #####
def command(cmd, **dargs):
"""
Interface to cmd function as 'cmd' symbol is polluted
@param: cmd: Command line to append to virsh command
@param: dargs: standardized virsh function API keywords
@return: CmdResult object
@raises: CmdError if non-zero exit status and ignore_status=False
"""
virsh_exec = dargs.get('virsh_exec', VIRSH_EXEC)
uri = dargs.get('uri', None)
debug = dargs.get('debug', False)
ignore_status = dargs.get('ignore_status', True) # Caller deals with errors
session_id = dargs.get('session_id', None)
# Check if this is a VirshPersistent method call
if session_id:
# Retrieve existing session
session = VirshSession(a_id=session_id)
logging.debug("Reusing session %s", session_id)
else:
session = None
if debug:
logging.debug("Running virsh command: %s", cmd)
if session:
# Utilize persistant virsh session
ret = session.cmd_result(cmd, ignore_status)
# Mark return value with session it came from
ret.from_session_id = session_id
else:
# Normal call to run virsh command
if uri:
# uri argument IS being used
uri_arg = " -c '%s' " % uri
else:
uri_arg = " " # No uri argument being used
cmd = "%s%s%s" % (virsh_exec, uri_arg, cmd)
# Raise exception if ignore_status == False
ret = utils.run(cmd, verbose=debug, ignore_status=ignore_status)
# Mark return as not coming from persistant virsh session
ret.from_session_id = None
# Always log debug info, if persistant session or not
if debug:
logging.debug("status: %s", ret.exit_status)
logging.debug("stdout: %s", ret.stdout.strip())
logging.debug("stderr: %s", ret.stderr.strip())
# Return CmdResult instance when ignore_status is True
return ret
def domname(dom_id_or_uuid, **dargs):
"""
Convert a domain id or UUID to domain name
@param: dom_id_or_uuid: a domain id or UUID.
@param: dargs: standardized virsh function API keywords
@return: CmdResult object
"""
return command("domname --domain %s" % dom_id_or_uuid, **dargs)
def qemu_monitor_command(vm_name, cmd, **dargs):
"""
This helps to execute the qemu monitor command through virsh command.
@param: vm_name: Name of monitor domain
@param: cmd: monitor command to execute
@param: dargs: standardized virsh function API keywords
"""
cmd_qemu_monitor = "qemu-monitor-command %s --hmp \'%s\'" % (vm_name, cmd)
return command(cmd_qemu_monitor, **dargs)
def setvcpus(vm_name, count, extra="", **dargs):
"""
Change the number of virtual CPUs in the guest domain.
@oaram vm_name: name of vm to affect
@param count: value for vcpu parameter
@param options: any extra command options.
@param dargs: standardized virsh function API keywords
@return: CmdResult object from command
"""
cmd = "setvcpus %s %s %s" % (vm_name, count, extra)
return command(cmd, **dargs)
def vcpupin(vm_name, vcpu, cpu, **dargs):
"""
Changes the cpu affinity for respective vcpu.
@param: vm_name: name of domain
@param: vcpu: virtual CPU to modify
@param: cpu: physical CPU specification (string)
@param: dargs: standardized virsh function API keywords
@return: True operation was successful
"""
dargs['ignore_status'] = False
try:
cmd_vcpupin = "vcpupin %s %s %s" % (vm_name, vcpu, cpu)
command(cmd_vcpupin, **dargs)
except error.CmdError, detail:
logging.error("Virsh vcpupin VM %s failed:\n%s", vm_name, detail)
return False
def vcpuinfo(vm_name, **dargs):
"""
Retrieves the vcpuinfo command result if values not "N/A"
@param: vm_name: name of domain
@param: dargs: standardized virsh function API keywords
@return: CmdResult object
"""
# Guarantee cmdresult object created
dargs['ignore_status'] = True
cmdresult = command("vcpuinfo %s" % vm_name, **dargs)
if cmdresult.exit_status == 0:
# Non-running vm makes virsh exit(0) but have "N/A" info.
# on newer libvirt. Treat this as an error.
if re.search(r"\s*CPU:\s+N/A\s*", cmdresult.stdout.strip()):
cmdresult.exit_status = -1
cmdresult.stdout += "\n\nvirsh.vcpuinfo inject error: N/A values\n"
return cmdresult
def vcpucount_live(vm_name, **dargs):
"""
Prints the vcpucount of a given domain.
@param: vm_name: name of a domain
@param: dargs: standardized virsh function API keywords
@return: standard output from command
"""
cmd_vcpucount = "vcpucount --live --active %s" % vm_name
return command(cmd_vcpucount, **dargs).stdout.strip()
def freecell(extra="", **dargs):
"""
Prints the available amount of memory on the machine or within a NUMA cell.
@param: dargs: extra: extra argument string to pass to command
@param: dargs: standardized virsh function API keywords
@return: CmdResult object
"""
cmd_freecell = "freecell %s" % extra
return command(cmd_freecell, **dargs)
def nodeinfo(extra="", **dargs):
"""
Returns basic information about the node,like number and type of CPU,
and size of the physical memory.
@param: dargs: extra: extra argument string to pass to command
@param: dargs: standardized virsh function API keywords
@return: CmdResult object
"""
cmd_nodeinfo = "nodeinfo %s" % extra
return command(cmd_nodeinfo, **dargs)
def canonical_uri(option='', **dargs):
"""
Return the hypervisor canonical URI.
@param: option: additional option string to pass
@param: dargs: standardized virsh function API keywords
@return: standard output from command
"""
return command("uri %s" % option, **dargs).stdout.strip()
def hostname(option='', **dargs):
"""
Return the hypervisor hostname.
@param: option: additional option string to pass
@param: dargs: standardized virsh function API keywords
@return: standard output from command
"""
return command("hostname %s" % option, **dargs).stdout.strip()
def version(option='', **dargs):
"""
Return the major version info about what this built from.
@param: option: additional option string to pass
@param: dargs: standardized virsh function API keywords
@return: standard output from command
"""
return command("version %s" % option, **dargs).stdout.strip()
def dom_list(options="", **dargs):
"""
Return the list of domains.
@param: options: options to pass to list command
@return: CmdResult object
"""
return command("list %s" % options, **dargs)
def reboot(name, options="", **dargs):
"""
Run a reboot command in the target domain.
@param: name: Name of domain.
@param: options: options: options to pass to reboot command
@return: CmdResult object
"""
return command("reboot --domain %s %s" % (name, options), **dargs)
def managedsave(name, options="", **dargs):
"""
Managed save of a domain state.
@param: name: Name of domain to save
@param: options: options: options to pass to list command
@return: CmdResult object
"""
return command("managedsave --domain %s %s" % (name, options), **dargs)
def managedsave_remove(name, **dargs):
"""
Remove managed save of a domain
@param: name: name of managed-saved domain to remove
@return: CmdResult object
"""
return command("managedsave-remove --domain %s" % name, **dargs)
def driver(**dargs):
"""
Return the driver by asking libvirt
@param: dargs: standardized virsh function API keywords
@return: VM driver name
"""
# libvirt schme composed of driver + command
# ref: http://libvirt.org/uri.html
scheme = urlparse.urlsplit( canonical_uri(**dargs) )[0]
# extract just the driver, whether or not there is a '+'
return scheme.split('+', 2)[0]
def domstate(name, **dargs):
"""
Return the state about a running domain.
@param name: VM name
@param: dargs: standardized virsh function API keywords
@return: CmdResult object
"""
return command("domstate %s" % name, **dargs)
def domid(vm_name, **dargs):
"""
Return VM's ID.
@param vm_name: VM name or uuid
@param: dargs: standardized virsh function API keywords
@return: CmdResult instance
"""
return command("domid %s" % (vm_name), **dargs)
def dominfo(vm_name, **dargs):
"""
Return the VM information.
@param: vm_name: VM's name or id,uuid.
@param: dargs: standardized virsh function API keywords
@return: CmdResult instance
"""
return command("dominfo %s" % (vm_name), **dargs)
def domuuid(name, **dargs):
"""
Return the Converted domain name or id to the domain UUID.
@param name: VM name
@param: dargs: standardized virsh function API keywords
@return: CmdResult instance
"""
return command("domuuid %s" % name, **dargs)
def screenshot(name, filename, **dargs):
"""
Capture a screenshot of VM's console and store it in file on host
@param: name: VM name
@param: filename: name of host file
@param: dargs: standardized virsh function API keywords
@return: filename
"""
global SCREENSHOT_ERROR_COUNT
dargs['ignore_status'] = False
try:
command("screenshot %s %s" % (name, filename), **dargs)
except error.CmdError, detail:
if SCREENSHOT_ERROR_COUNT < 1:
logging.error("Error taking VM %s screenshot. You might have to "
"set take_regular_screendumps=no on your "
"tests.cfg config file \n%s. This will be the "
"only logged error message.", name, detail)
SCREENSHOT_ERROR_COUNT += 1
return filename
def domblkstat(name, device, option, **dargs):
"""
Store state of VM into named file.
@param: name: VM's name.
@param: device: VM's device.
@param: option: command domblkstat option.
@param: dargs: standardized virsh function API keywords
@return: CmdResult instance
"""
return command("domblkstat %s %s %s" % (name, device, option), **dargs)
def dumpxml(name, to_file="", **dargs):
"""
Return the domain information as an XML dump.
@param: name: VM name
@param: to_file: optional file to write XML output to
@param: dargs: standardized virsh function API keywords
@return: standard output from command
"""
dargs['ignore_status'] = True
if to_file:
cmd = "dumpxml %s > %s" % (name, to_file)
else:
cmd = "dumpxml %s" % name
result = command(cmd, **dargs)
if result.exit_status:
raise error.CmdError(cmd, result,
"Virsh dumpxml returned non-zero exit status")
return result.stdout.strip()
def domifstat(name, interface, **dargs):
"""
Get network interface stats for a running domain.
@param: name: Name of domain
@param: interface: interface device
@return: CmdResult object
"""
return command("domifstat %s %s" % (name, interface), **dargs)
def domjobinfo(name, **dargs):
"""
Get domain job information.
@param: name: VM name
@param: dargs: standardized virsh function API keywords
@return: CmdResult instance
"""
return command("domjobinfo %s" % name, **dargs)
def edit(options, **dargs):
"""
Edit the XML configuration for a domain.
@param options: virsh edit options string.
@param dargs: standardized virsh function API keywords
@return: CmdResult object
"""
return command("edit %s" % options, **dargs)
def domjobabort(vm_name, **dargs):
"""
Aborts the currently running domain job.
@param vm_name: VM's name, id or uuid.
@param dargs: standardized virsh function API keywords
@return: result from command
"""
return command("domjobabort %s" % vm_name, **dargs)
def domxml_from_native(format, file, options=None, **dargs):
"""
Convert native guest configuration format to domain XML format.
@param format:The command's options. For exmple:qemu-argv.
@param file:Native infomation file.
@param options:extra param.
@param dargs: standardized virsh function API keywords.
@return: result from command
"""
cmd = "domxml-from-native %s %s %s" % (format, file, options)
return command(cmd, **dargs)
def domxml_to_native(format, file, options, **dargs):
"""
Convert domain XML config to a native guest configuration format.
@param format:The command's options. For exmple:qemu-argv.
@param file:XML config file.
@param options:extra param.
@param dargs: standardized virsh function API keywords
@return: result from command
"""
cmd = "domxml-to-native %s %s %s" % (format, file, options)
return command(cmd, **dargs)
def vncdisplay(vm_name, **dargs):
"""
Output the IP address and port number for the VNC display.
@param vm_name: VM's name or id,uuid.
@param dargs: standardized virsh function API keywords.
@return: result from command
"""
return command("vncdisplay %s" % vm_name, **dargs)
def is_alive(name, **dargs):
"""
Return True if the domain is started/alive.
@param: name: VM name
@param: dargs: standardized virsh function API keywords
@return: True operation was successful
"""
return not is_dead(name, **dargs)
def is_dead(name, **dargs):
"""
Return True if the domain is undefined or not started/dead.
@param: name: VM name
@param: dargs: standardized virsh function API keywords
@return: True operation was successful
"""
dargs['ignore_status'] = False
try:
state = domstate(name, **dargs).stdout.strip()
except error.CmdError:
return True
if state in ('running', 'idle', 'no state', 'paused'):
return False
else:
return True
def suspend(name, **dargs):
"""
True on successful suspend of VM - kept in memory and not scheduled.
@param: name: VM name
@param: dargs: standardized virsh function API keywords
@return: CmdResult object
"""
return command("suspend %s" % (name), **dargs)
def resume(name, **dargs):
"""
True on successful moving domain out of suspend
@param: name: VM name
@param: dargs: standardized virsh function API keywords
@return: CmdResult object
"""
return command("resume %s" % (name), **dargs)
def dommemstat(name, extra="", **dargs):
"""
Store state of VM into named file.
@param: name: VM name
@param: extra: extra options to pass to command
@param: dargs: standardized virsh function API keywords
@return: CmdResult instance
"""
return command("dommemstat %s %s" % (name, extra), **dargs)
def dump(name, path, option="", **dargs):
"""
Dump the core of a domain to a file for analysis.
@param: name: VM name
@param: path: absolute path to state file
@param: option: command's option.
@param: dargs: standardized virsh function API keywords
@return: CmdResult instance
"""
return command("dump %s %s %s" % (name, path, option), **dargs)
def save(option, path, **dargs):
"""
Store state of VM into named file.
@param: option: save command's first option, vm'name, id or uuid.
@param: path: absolute path to state file
@param: dargs: standardized virsh function API keywords
@return: CmdResult instance
"""
return command("save %s %s" % (option, path), **dargs)
def restore(path, **dargs):
"""
Load state of VM from named file and remove file.
@param: path: absolute path to state file.
@param: dargs: standardized virsh function API keywords
"""
return command("restore %s" % path, **dargs)
def start(name, **dargs):
"""
True on successful start of (previously defined) inactive domain.
@param: name: VM name
@param: dargs: standardized virsh function API keywords
@return: True operation was successful
"""
if is_alive(name, **dargs):
return True
dargs['ignore_status'] = False
try:
command("start %s" % (name), **dargs)
return True
except error.CmdError, detail:
logging.error("Start VM %s failed:\n%s", name, detail)
return False
def shutdown(name, **dargs):
"""
True on successful domain shutdown.
@param: name: VM name
@param: dargs: standardized virsh function API keywords
@return: CmdResult object
"""
return command("shutdown %s" % (name), **dargs)
def destroy(name, **dargs):
"""
True on successful domain destruction