1 /*
2  * libvirt-domain.c: entry points for virDomainPtr APIs
3  *
4  * Copyright (C) 2006-2015 Red Hat, Inc.
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library.  If not, see
18  * <http://www.gnu.org/licenses/>.
19  */
20 
21 #include <config.h>
22 #include <sys/stat.h>
23 
24 #include "datatypes.h"
25 #include "viralloc.h"
26 #include "virfile.h"
27 #include "virlog.h"
28 #include "virtypedparam.h"
29 #include "virutil.h"
30 
31 VIR_LOG_INIT("libvirt.domain");
32 
33 #define VIR_FROM_THIS VIR_FROM_DOMAIN
34 
35 
36 /**
37  * virConnectListDomains:
38  * @conn: pointer to the hypervisor connection
39  * @ids: array to collect the list of IDs of active domains
40  * @maxids: size of @ids
41  *
42  * Collect the list of active domains, and store their IDs in array @ids
43  *
44  * The use of this function is discouraged. Instead, use
45  * virConnectListAllDomains().
46  *
47  * Returns the number of domains found or -1 in case of error.  Note that
48  * this command is inherently racy; a domain can be started between a
49  * call to virConnectNumOfDomains() and this call; you are only guaranteed
50  * that all currently active domains were listed if the return is less
51  * than @maxids.
52  */
53 int
virConnectListDomains(virConnectPtr conn,int * ids,int maxids)54 virConnectListDomains(virConnectPtr conn, int *ids, int maxids)
55 {
56     VIR_DEBUG("conn=%p, ids=%p, maxids=%d", conn, ids, maxids);
57 
58     virResetLastError();
59 
60     virCheckConnectReturn(conn, -1);
61     virCheckNonNullArrayArgGoto(ids, maxids, error);
62     virCheckNonNegativeArgGoto(maxids, error);
63 
64     if (conn->driver->connectListDomains) {
65         int ret = conn->driver->connectListDomains(conn, ids, maxids);
66         if (ret < 0)
67             goto error;
68         return ret;
69     }
70 
71     virReportUnsupportedError();
72  error:
73     virDispatchError(conn);
74     return -1;
75 }
76 
77 
78 /**
79  * virConnectNumOfDomains:
80  * @conn: pointer to the hypervisor connection
81  *
82  * Provides the number of active domains.
83  *
84  * Returns the number of domain found or -1 in case of error
85  */
86 int
virConnectNumOfDomains(virConnectPtr conn)87 virConnectNumOfDomains(virConnectPtr conn)
88 {
89     VIR_DEBUG("conn=%p", conn);
90 
91     virResetLastError();
92 
93     virCheckConnectReturn(conn, -1);
94 
95     if (conn->driver->connectNumOfDomains) {
96         int ret = conn->driver->connectNumOfDomains(conn);
97         if (ret < 0)
98             goto error;
99         return ret;
100     }
101 
102     virReportUnsupportedError();
103  error:
104     virDispatchError(conn);
105     return -1;
106 }
107 
108 
109 /**
110  * virDomainGetConnect:
111  * @dom: pointer to a domain
112  *
113  * Provides the connection pointer associated with a domain.  The
114  * reference counter on the connection is not increased by this
115  * call.
116  *
117  * Returns the virConnectPtr or NULL in case of failure.
118  */
119 virConnectPtr
virDomainGetConnect(virDomainPtr dom)120 virDomainGetConnect(virDomainPtr dom)
121 {
122     VIR_DOMAIN_DEBUG(dom);
123 
124     virResetLastError();
125 
126     virCheckDomainReturn(dom, NULL);
127 
128     return dom->conn;
129 }
130 
131 
132 /**
133  * virDomainCreateXML:
134  * @conn: pointer to the hypervisor connection
135  * @xmlDesc: string containing an XML description of the domain
136  * @flags: bitwise-OR of supported virDomainCreateFlags
137  *
138  * Launch a new guest domain, based on an XML description similar
139  * to the one returned by virDomainGetXMLDesc()
140  * This function may require privileged access to the hypervisor.
141  * The domain is not persistent, so its definition will disappear when it
142  * is destroyed, or if the host is restarted (see virDomainDefineXML() to
143  * define persistent domains).
144  *
145  * If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain
146  * will be started, but its CPUs will remain paused. The CPUs
147  * can later be manually started using virDomainResume.
148  *
149  * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest
150  * domain will be automatically destroyed when the virConnectPtr
151  * object is finally released. This will also happen if the
152  * client application crashes / loses its connection to the
153  * libvirtd daemon. Any domains marked for auto destroy will
154  * block attempts at migration. Hypervisors may also block save-to-file,
155  * or snapshots.
156  *
157  * virDomainFree should be used to free the resources after the
158  * domain object is no longer needed.
159  *
160  * Returns a new domain object or NULL in case of failure
161  */
162 virDomainPtr
virDomainCreateXML(virConnectPtr conn,const char * xmlDesc,unsigned int flags)163 virDomainCreateXML(virConnectPtr conn, const char *xmlDesc,
164                    unsigned int flags)
165 {
166     VIR_DEBUG("conn=%p, xmlDesc=%s, flags=0x%x", conn, NULLSTR(xmlDesc), flags);
167 
168     virResetLastError();
169 
170     virCheckConnectReturn(conn, NULL);
171     virCheckNonNullArgGoto(xmlDesc, error);
172     virCheckReadOnlyGoto(conn->flags, error);
173 
174     if (conn->driver->domainCreateXML) {
175         virDomainPtr ret;
176         ret = conn->driver->domainCreateXML(conn, xmlDesc, flags);
177         if (!ret)
178             goto error;
179         return ret;
180     }
181 
182     virReportUnsupportedError();
183  error:
184     virDispatchError(conn);
185     return NULL;
186 }
187 
188 
189 /**
190  * virDomainCreateXMLWithFiles:
191  * @conn: pointer to the hypervisor connection
192  * @xmlDesc: string containing an XML description of the domain
193  * @nfiles: number of file descriptors passed
194  * @files: list of file descriptors passed
195  * @flags: bitwise-OR of supported virDomainCreateFlags
196  *
197  * Launch a new guest domain, based on an XML description similar
198  * to the one returned by virDomainGetXMLDesc()
199  * This function may require privileged access to the hypervisor.
200  * The domain is not persistent, so its definition will disappear when it
201  * is destroyed, or if the host is restarted (see virDomainDefineXML() to
202  * define persistent domains).
203  *
204  * @files provides an array of file descriptors which will be
205  * made available to the 'init' process of the guest. The file
206  * handles exposed to the guest will be renumbered to start
207  * from 3 (ie immediately following stderr). This is only
208  * supported for guests which use container based virtualization
209  * technology.
210  *
211  * If the VIR_DOMAIN_START_PAUSED flag is set, the guest domain
212  * will be started, but its CPUs will remain paused. The CPUs
213  * can later be manually started using virDomainResume.
214  *
215  * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest
216  * domain will be automatically destroyed when the virConnectPtr
217  * object is finally released. This will also happen if the
218  * client application crashes / loses its connection to the
219  * libvirtd daemon. Any domains marked for auto destroy will
220  * block attempts at migration. Hypervisors may also block
221  * save-to-file, or snapshots.
222  *
223  * virDomainFree should be used to free the resources after the
224  * domain object is no longer needed.
225  *
226  * Returns a new domain object or NULL in case of failure
227  */
228 virDomainPtr
virDomainCreateXMLWithFiles(virConnectPtr conn,const char * xmlDesc,unsigned int nfiles,int * files,unsigned int flags)229 virDomainCreateXMLWithFiles(virConnectPtr conn, const char *xmlDesc,
230                             unsigned int nfiles,
231                             int *files,
232                             unsigned int flags)
233 {
234     VIR_DEBUG("conn=%p, xmlDesc=%s, nfiles=%u, files=%p, flags=0x%x",
235               conn, NULLSTR(xmlDesc), nfiles, files, flags);
236 
237     virResetLastError();
238 
239     virCheckConnectReturn(conn, NULL);
240     virCheckNonNullArgGoto(xmlDesc, error);
241     virCheckReadOnlyGoto(conn->flags, error);
242 
243     if (conn->driver->domainCreateXMLWithFiles) {
244         virDomainPtr ret;
245         ret = conn->driver->domainCreateXMLWithFiles(conn, xmlDesc,
246                                                      nfiles, files,
247                                                      flags);
248         if (!ret)
249             goto error;
250         return ret;
251     }
252 
253     virReportUnsupportedError();
254  error:
255     virDispatchError(conn);
256     return NULL;
257 }
258 
259 
260 /**
261  * virDomainCreateLinux:
262  * @conn: pointer to the hypervisor connection
263  * @xmlDesc: string containing an XML description of the domain
264  * @flags: extra flags; not used yet, so callers should always pass 0
265  *
266  * Deprecated after 0.4.6.
267  * Renamed to virDomainCreateXML() providing identical functionality.
268  * This existing name will be left indefinitely for API compatibility.
269  *
270  * Returns a new domain object or NULL in case of failure
271  */
272 virDomainPtr
virDomainCreateLinux(virConnectPtr conn,const char * xmlDesc,unsigned int flags)273 virDomainCreateLinux(virConnectPtr conn, const char *xmlDesc,
274                      unsigned int flags)
275 {
276     return virDomainCreateXML(conn, xmlDesc, flags);
277 }
278 
279 
280 /**
281  * virDomainLookupByID:
282  * @conn: pointer to the hypervisor connection
283  * @id: the domain ID number
284  *
285  * Try to find a domain based on the hypervisor ID number
286  * Note that this won't work for inactive domains which have an ID of -1,
287  * in that case a lookup based on the Name or UUID need to be done instead.
288  *
289  * virDomainFree should be used to free the resources after the
290  * domain object is no longer needed.
291  *
292  * Returns a new domain object or NULL in case of failure.  If the
293  * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised.
294  */
295 virDomainPtr
virDomainLookupByID(virConnectPtr conn,int id)296 virDomainLookupByID(virConnectPtr conn, int id)
297 {
298     VIR_DEBUG("conn=%p, id=%d", conn, id);
299 
300     virResetLastError();
301 
302     virCheckConnectReturn(conn, NULL);
303     virCheckNonNegativeArgGoto(id, error);
304 
305     if (conn->driver->domainLookupByID) {
306         virDomainPtr ret;
307         ret = conn->driver->domainLookupByID(conn, id);
308         if (!ret)
309             goto error;
310         return ret;
311     }
312 
313     virReportUnsupportedError();
314 
315  error:
316     virDispatchError(conn);
317     return NULL;
318 }
319 
320 
321 /**
322  * virDomainLookupByUUID:
323  * @conn: pointer to the hypervisor connection
324  * @uuid: the raw UUID for the domain
325  *
326  * Try to lookup a domain on the given hypervisor based on its UUID.
327  *
328  * virDomainFree should be used to free the resources after the
329  * domain object is no longer needed.
330  *
331  * Returns a new domain object or NULL in case of failure.  If the
332  * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised.
333  */
334 virDomainPtr
virDomainLookupByUUID(virConnectPtr conn,const unsigned char * uuid)335 virDomainLookupByUUID(virConnectPtr conn, const unsigned char *uuid)
336 {
337     VIR_UUID_DEBUG(conn, uuid);
338 
339     virResetLastError();
340 
341     virCheckConnectReturn(conn, NULL);
342     virCheckNonNullArgGoto(uuid, error);
343 
344     if (conn->driver->domainLookupByUUID) {
345         virDomainPtr ret;
346         ret = conn->driver->domainLookupByUUID(conn, uuid);
347         if (!ret)
348             goto error;
349         return ret;
350     }
351 
352     virReportUnsupportedError();
353 
354  error:
355     virDispatchError(conn);
356     return NULL;
357 }
358 
359 
360 /**
361  * virDomainLookupByUUIDString:
362  * @conn: pointer to the hypervisor connection
363  * @uuidstr: the string UUID for the domain
364  *
365  * Try to lookup a domain on the given hypervisor based on its UUID.
366  *
367  * virDomainFree should be used to free the resources after the
368  * domain object is no longer needed.
369  *
370  * Returns a new domain object or NULL in case of failure.  If the
371  * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised.
372  */
373 virDomainPtr
virDomainLookupByUUIDString(virConnectPtr conn,const char * uuidstr)374 virDomainLookupByUUIDString(virConnectPtr conn, const char *uuidstr)
375 {
376     unsigned char uuid[VIR_UUID_BUFLEN];
377     VIR_DEBUG("conn=%p, uuidstr=%s", conn, NULLSTR(uuidstr));
378 
379     virResetLastError();
380 
381     virCheckConnectReturn(conn, NULL);
382     virCheckNonNullArgGoto(uuidstr, error);
383 
384     if (virUUIDParse(uuidstr, uuid) < 0) {
385         virReportInvalidArg(uuidstr, "%s", _("Invalid UUID"));
386         goto error;
387     }
388 
389     return virDomainLookupByUUID(conn, &uuid[0]);
390 
391  error:
392     virDispatchError(conn);
393     return NULL;
394 }
395 
396 
397 /**
398  * virDomainLookupByName:
399  * @conn: pointer to the hypervisor connection
400  * @name: name for the domain
401  *
402  * Try to lookup a domain on the given hypervisor based on its name.
403  *
404  * virDomainFree should be used to free the resources after the
405  * domain object is no longer needed.
406  *
407  * Returns a new domain object or NULL in case of failure.  If the
408  * domain cannot be found, then VIR_ERR_NO_DOMAIN error is raised.
409  */
410 virDomainPtr
virDomainLookupByName(virConnectPtr conn,const char * name)411 virDomainLookupByName(virConnectPtr conn, const char *name)
412 {
413     VIR_DEBUG("conn=%p, name=%s", conn, NULLSTR(name));
414 
415     virResetLastError();
416 
417     virCheckConnectReturn(conn, NULL);
418     virCheckNonNullArgGoto(name, error);
419 
420     if (conn->driver->domainLookupByName) {
421         virDomainPtr dom;
422         dom = conn->driver->domainLookupByName(conn, name);
423         if (!dom)
424             goto error;
425         return dom;
426     }
427 
428     virReportUnsupportedError();
429 
430  error:
431     virDispatchError(conn);
432     return NULL;
433 }
434 
435 
436 /**
437  * virDomainDestroy:
438  * @domain: a domain object
439  *
440  * Destroy the domain object. The running instance is shutdown if not down
441  * already and all resources used by it are given back to the hypervisor. This
442  * does not free the associated virDomainPtr object.
443  * This function may require privileged access.
444  *
445  * virDomainDestroy first requests that a guest terminate
446  * (e.g. SIGTERM), then waits for it to comply. After a reasonable
447  * timeout, if the guest still exists, virDomainDestroy will
448  * forcefully terminate the guest (e.g. SIGKILL) if necessary (which
449  * may produce undesirable results, for example unflushed disk cache
450  * in the guest). To avoid this possibility, it's recommended to
451  * instead call virDomainDestroyFlags, sending the
452  * VIR_DOMAIN_DESTROY_GRACEFUL flag.
453  *
454  * If the domain is transient and has any snapshot metadata (see
455  * virDomainSnapshotNum()), then that metadata will automatically
456  * be deleted when the domain quits.
457  *
458  * Returns 0 in case of success and -1 in case of failure.
459  */
460 int
virDomainDestroy(virDomainPtr domain)461 virDomainDestroy(virDomainPtr domain)
462 {
463     virConnectPtr conn;
464 
465     VIR_DOMAIN_DEBUG(domain);
466 
467     virResetLastError();
468 
469     virCheckDomainReturn(domain, -1);
470     conn = domain->conn;
471 
472     virCheckReadOnlyGoto(conn->flags, error);
473 
474     if (conn->driver->domainDestroy) {
475         int ret;
476         ret = conn->driver->domainDestroy(domain);
477         if (ret < 0)
478             goto error;
479         return ret;
480     }
481 
482     virReportUnsupportedError();
483 
484  error:
485     virDispatchError(conn);
486     return -1;
487 }
488 
489 
490 /**
491  * virDomainDestroyFlags:
492  * @domain: a domain object
493  * @flags: bitwise-OR of virDomainDestroyFlagsValues
494  *
495  * Destroy the domain object. The running instance is shutdown if not down
496  * already and all resources used by it are given back to the hypervisor.
497  * This does not free the associated virDomainPtr object.
498  * This function may require privileged access.
499  *
500  * Calling this function with no @flags set (equal to zero) is
501  * equivalent to calling virDomainDestroy, and after a reasonable
502  * timeout will forcefully terminate the guest (e.g. SIGKILL) if
503  * necessary (which may produce undesirable results, for example
504  * unflushed disk cache in the guest). Including
505  * VIR_DOMAIN_DESTROY_GRACEFUL in the flags will prevent the forceful
506  * termination of the guest, and virDomainDestroyFlags will instead
507  * return an error if the guest doesn't terminate by the end of the
508  * timeout; at that time, the management application can decide if
509  * calling again without VIR_DOMAIN_DESTROY_GRACEFUL is appropriate.
510  *
511  * Another alternative which may produce cleaner results for the
512  * guest's disks is to use virDomainShutdown() instead, but that
513  * depends on guest support (some hypervisor/guest combinations may
514  * ignore the shutdown request).
515  *
516  *
517  * Returns 0 in case of success and -1 in case of failure.
518  */
519 int
virDomainDestroyFlags(virDomainPtr domain,unsigned int flags)520 virDomainDestroyFlags(virDomainPtr domain,
521                       unsigned int flags)
522 {
523     virConnectPtr conn;
524 
525     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
526 
527     virResetLastError();
528 
529     virCheckDomainReturn(domain, -1);
530     conn = domain->conn;
531 
532     virCheckReadOnlyGoto(conn->flags, error);
533 
534     if (conn->driver->domainDestroyFlags) {
535         int ret;
536         ret = conn->driver->domainDestroyFlags(domain, flags);
537         if (ret < 0)
538             goto error;
539         return ret;
540     }
541 
542     virReportUnsupportedError();
543 
544  error:
545     virDispatchError(conn);
546     return -1;
547 }
548 
549 
550 /**
551  * virDomainFree:
552  * @domain: a domain object
553  *
554  * Free the domain object. The running instance is kept alive.
555  * The data structure is freed and should not be used thereafter.
556  *
557  * Returns 0 in case of success and -1 in case of failure.
558  */
559 int
virDomainFree(virDomainPtr domain)560 virDomainFree(virDomainPtr domain)
561 {
562     VIR_DOMAIN_DEBUG(domain);
563 
564     virResetLastError();
565 
566     virCheckDomainReturn(domain, -1);
567 
568     virObjectUnref(domain);
569     return 0;
570 }
571 
572 
573 /**
574  * virDomainRef:
575  * @domain: the domain to hold a reference on
576  *
577  * Increment the reference count on the domain. For each
578  * additional call to this method, there shall be a corresponding
579  * call to virDomainFree to release the reference count, once
580  * the caller no longer needs the reference to this object.
581  *
582  * This method is typically useful for applications where multiple
583  * threads are using a connection, and it is required that the
584  * connection remain open until all threads have finished using
585  * it. ie, each new thread using a domain would increment
586  * the reference count.
587  *
588  * Returns 0 in case of success and -1 in case of failure.
589  */
590 int
virDomainRef(virDomainPtr domain)591 virDomainRef(virDomainPtr domain)
592 {
593     VIR_DOMAIN_DEBUG(domain);
594 
595     virResetLastError();
596 
597     virCheckDomainReturn(domain, -1);
598 
599     virObjectRef(domain);
600     return 0;
601 }
602 
603 
604 /**
605  * virDomainSuspend:
606  * @domain: a domain object
607  *
608  * Suspends an active domain, the process is frozen without further access
609  * to CPU resources and I/O but the memory used by the domain at the
610  * hypervisor level will stay allocated. Use virDomainResume() to reactivate
611  * the domain.
612  * This function may require privileged access.
613  * Moreover, suspend may not be supported if domain is in some
614  * special state like VIR_DOMAIN_PMSUSPENDED.
615  *
616  * Returns 0 in case of success and -1 in case of failure.
617  */
618 int
virDomainSuspend(virDomainPtr domain)619 virDomainSuspend(virDomainPtr domain)
620 {
621     virConnectPtr conn;
622 
623     VIR_DOMAIN_DEBUG(domain);
624 
625     virResetLastError();
626 
627     virCheckDomainReturn(domain, -1);
628     conn = domain->conn;
629 
630     virCheckReadOnlyGoto(conn->flags, error);
631 
632     if (conn->driver->domainSuspend) {
633         int ret;
634         ret = conn->driver->domainSuspend(domain);
635         if (ret < 0)
636             goto error;
637         return ret;
638     }
639 
640     virReportUnsupportedError();
641 
642  error:
643     virDispatchError(domain->conn);
644     return -1;
645 }
646 
647 
648 /**
649  * virDomainResume:
650  * @domain: a domain object
651  *
652  * Resume a suspended domain, the process is restarted from the state where
653  * it was frozen by calling virDomainSuspend().
654  * This function may require privileged access
655  * Moreover, resume may not be supported if domain is in some
656  * special state like VIR_DOMAIN_PMSUSPENDED.
657  *
658  * Returns 0 in case of success and -1 in case of failure.
659  */
660 int
virDomainResume(virDomainPtr domain)661 virDomainResume(virDomainPtr domain)
662 {
663     virConnectPtr conn;
664 
665     VIR_DOMAIN_DEBUG(domain);
666 
667     virResetLastError();
668 
669     virCheckDomainReturn(domain, -1);
670     conn = domain->conn;
671 
672     virCheckReadOnlyGoto(conn->flags, error);
673 
674     if (conn->driver->domainResume) {
675         int ret;
676         ret = conn->driver->domainResume(domain);
677         if (ret < 0)
678             goto error;
679         return ret;
680     }
681 
682     virReportUnsupportedError();
683 
684  error:
685     virDispatchError(domain->conn);
686     return -1;
687 }
688 
689 
690 /**
691  * virDomainPMSuspendForDuration:
692  * @dom: a domain object
693  * @target: a value from virNodeSuspendTarget
694  * @duration: duration in seconds to suspend, or 0 for indefinite
695  * @flags: extra flags; not used yet, so callers should always pass 0
696  *
697  * Attempt to have the guest enter the given @target power management
698  * suspension level.  If @duration is non-zero, also schedule the guest to
699  * resume normal operation after that many seconds, if nothing else has
700  * resumed it earlier.  Some hypervisors require that @duration be 0, for
701  * an indefinite suspension.
702  *
703  * Dependent on hypervisor used, this may require a
704  * guest agent to be available, e.g. QEMU.
705  *
706  * Beware that at least for QEMU, the domain's process will be terminated
707  * when VIR_NODE_SUSPEND_TARGET_DISK is used and a new process will be
708  * launched when libvirt is asked to wake up the domain. As a result of
709  * this, any runtime changes, such as device hotplug or memory settings,
710  * are lost unless such changes were made with VIR_DOMAIN_AFFECT_CONFIG
711  * flag.
712  *
713  * Returns: 0 on success,
714  *          -1 on failure.
715  */
716 int
virDomainPMSuspendForDuration(virDomainPtr dom,unsigned int target,unsigned long long duration,unsigned int flags)717 virDomainPMSuspendForDuration(virDomainPtr dom,
718                               unsigned int target,
719                               unsigned long long duration,
720                               unsigned int flags)
721 {
722     virConnectPtr conn;
723 
724     VIR_DOMAIN_DEBUG(dom, "target=%u duration=%llu flags=0x%x",
725                      target, duration, flags);
726 
727     virResetLastError();
728 
729     virCheckDomainReturn(dom, -1);
730     conn = dom->conn;
731 
732     virCheckReadOnlyGoto(conn->flags, error);
733 
734     if (conn->driver->domainPMSuspendForDuration) {
735         int ret;
736         ret = conn->driver->domainPMSuspendForDuration(dom, target,
737                                                        duration, flags);
738         if (ret < 0)
739             goto error;
740         return ret;
741     }
742 
743     virReportUnsupportedError();
744 
745  error:
746     virDispatchError(conn);
747     return -1;
748 }
749 
750 
751 /**
752  * virDomainPMWakeup:
753  * @dom: a domain object
754  * @flags: extra flags; not used yet, so callers should always pass 0
755  *
756  * Inject a wakeup into the guest that previously used
757  * virDomainPMSuspendForDuration, rather than waiting for the
758  * previously requested duration (if any) to elapse.
759  *
760  * Returns: 0 on success,
761  *          -1 on failure.
762  */
763 int
virDomainPMWakeup(virDomainPtr dom,unsigned int flags)764 virDomainPMWakeup(virDomainPtr dom,
765                   unsigned int flags)
766 {
767     virConnectPtr conn;
768 
769     VIR_DOMAIN_DEBUG(dom, "flags=0x%x", flags);
770 
771     virResetLastError();
772 
773     virCheckDomainReturn(dom, -1);
774     conn = dom->conn;
775 
776     virCheckReadOnlyGoto(conn->flags, error);
777 
778     if (conn->driver->domainPMWakeup) {
779         int ret;
780         ret = conn->driver->domainPMWakeup(dom, flags);
781         if (ret < 0)
782             goto error;
783         return ret;
784     }
785 
786     virReportUnsupportedError();
787 
788  error:
789     virDispatchError(conn);
790     return -1;
791 }
792 
793 
794 /**
795  * virDomainSave:
796  * @domain: a domain object
797  * @to: path for the output file
798  *
799  * This method will suspend a domain and save its memory contents to
800  * a file on disk. After the call, if successful, the domain is not
801  * listed as running anymore (this ends the life of a transient domain).
802  * Use virDomainRestore() to restore a domain after saving.
803  *
804  * See virDomainSaveFlags() for more control.  Also, a save file can
805  * be inspected or modified slightly with virDomainSaveImageGetXMLDesc()
806  * and virDomainSaveImageDefineXML().
807  *
808  * Returns 0 in case of success and -1 in case of failure.
809  */
810 int
virDomainSave(virDomainPtr domain,const char * to)811 virDomainSave(virDomainPtr domain, const char *to)
812 {
813     virConnectPtr conn;
814 
815     VIR_DOMAIN_DEBUG(domain, "to=%s", to);
816 
817     virResetLastError();
818 
819     virCheckDomainReturn(domain, -1);
820     conn = domain->conn;
821 
822     virCheckReadOnlyGoto(conn->flags, error);
823     virCheckNonNullArgGoto(to, error);
824 
825     if (conn->driver->domainSave) {
826         int ret;
827         char *absolute_to;
828 
829         /* We must absolutize the file path as the save is done out of process */
830         if (!(absolute_to = g_canonicalize_filename(to, NULL))) {
831             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
832                            _("could not build absolute output file path"));
833             goto error;
834         }
835 
836         ret = conn->driver->domainSave(domain, absolute_to);
837 
838         VIR_FREE(absolute_to);
839 
840         if (ret < 0)
841             goto error;
842         return ret;
843     }
844 
845     virReportUnsupportedError();
846 
847  error:
848     virDispatchError(domain->conn);
849     return -1;
850 }
851 
852 
853 /**
854  * virDomainSaveFlags:
855  * @domain: a domain object
856  * @to: path for the output file
857  * @dxml: (optional) XML config for adjusting guest xml used on restore
858  * @flags: bitwise-OR of virDomainSaveRestoreFlags
859  *
860  * This method will suspend a domain and save its memory contents to
861  * a file on disk. After the call, if successful, the domain is not
862  * listed as running anymore (this ends the life of a transient domain).
863  * Use virDomainRestore() to restore a domain after saving.
864  *
865  * If the hypervisor supports it, @dxml can be used to alter
866  * host-specific portions of the domain XML that will be used when
867  * restoring an image.  For example, it is possible to alter the
868  * backing filename that is associated with a disk device, in order to
869  * prepare for file renaming done as part of backing up the disk
870  * device while the domain is stopped.
871  *
872  * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will
873  * attempt to bypass the file system cache while creating the file, or
874  * fail if it cannot do so for the given system; this can allow less
875  * pressure on file system cache, but also risks slowing saves to NFS.
876  *
877  * Normally, the saved state file will remember whether the domain was
878  * running or paused, and restore defaults to the same state.
879  * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in
880  * @flags will override what state gets saved into the file.  These
881  * two flags are mutually exclusive.
882  *
883  * A save file can be inspected or modified slightly with
884  * virDomainSaveImageGetXMLDesc() and virDomainSaveImageDefineXML().
885  *
886  * Some hypervisors may prevent this operation if there is a current
887  * block job running; in that case, use virDomainBlockJobAbort()
888  * to stop the block job first.
889  *
890  * Returns 0 in case of success and -1 in case of failure.
891  */
892 int
virDomainSaveFlags(virDomainPtr domain,const char * to,const char * dxml,unsigned int flags)893 virDomainSaveFlags(virDomainPtr domain, const char *to,
894                    const char *dxml, unsigned int flags)
895 {
896     virConnectPtr conn;
897 
898     VIR_DOMAIN_DEBUG(domain, "to=%s, dxml=%s, flags=0x%x",
899                      to, NULLSTR(dxml), flags);
900 
901     virResetLastError();
902 
903     virCheckDomainReturn(domain, -1);
904     conn = domain->conn;
905 
906     virCheckReadOnlyGoto(conn->flags, error);
907     virCheckNonNullArgGoto(to, error);
908 
909     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING,
910                              VIR_DOMAIN_SAVE_PAUSED,
911                              error);
912 
913     if (conn->driver->domainSaveFlags) {
914         int ret;
915         char *absolute_to;
916 
917         /* We must absolutize the file path as the save is done out of process */
918         if (!(absolute_to = g_canonicalize_filename(to, NULL))) {
919             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
920                            _("could not build absolute output file path"));
921             goto error;
922         }
923 
924         ret = conn->driver->domainSaveFlags(domain, absolute_to, dxml, flags);
925 
926         VIR_FREE(absolute_to);
927 
928         if (ret < 0)
929             goto error;
930         return ret;
931     }
932 
933     virReportUnsupportedError();
934 
935  error:
936     virDispatchError(domain->conn);
937     return -1;
938 }
939 
940 
941 /**
942  * virDomainRestore:
943  * @conn: pointer to the hypervisor connection
944  * @from: path to the input file
945  *
946  * This method will restore a domain saved to disk by virDomainSave().
947  *
948  * See virDomainRestoreFlags() for more control.
949  *
950  * Returns 0 in case of success and -1 in case of failure.
951  */
952 int
virDomainRestore(virConnectPtr conn,const char * from)953 virDomainRestore(virConnectPtr conn, const char *from)
954 {
955     VIR_DEBUG("conn=%p, from=%s", conn, NULLSTR(from));
956 
957     virResetLastError();
958 
959     virCheckConnectReturn(conn, -1);
960     virCheckReadOnlyGoto(conn->flags, error);
961     virCheckNonNullArgGoto(from, error);
962 
963     if (conn->driver->domainRestore) {
964         int ret;
965         char *absolute_from;
966 
967         /* We must absolutize the file path as the restore is done out of process */
968         if (!(absolute_from = g_canonicalize_filename(from, NULL))) {
969             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
970                            _("could not build absolute input file path"));
971             goto error;
972         }
973 
974         ret = conn->driver->domainRestore(conn, absolute_from);
975 
976         VIR_FREE(absolute_from);
977 
978         if (ret < 0)
979             goto error;
980         return ret;
981     }
982 
983     virReportUnsupportedError();
984 
985  error:
986     virDispatchError(conn);
987     return -1;
988 }
989 
990 
991 /**
992  * virDomainRestoreFlags:
993  * @conn: pointer to the hypervisor connection
994  * @from: path to the input file
995  * @dxml: (optional) XML config for adjusting guest xml used on restore
996  * @flags: bitwise-OR of virDomainSaveRestoreFlags
997  *
998  * This method will restore a domain saved to disk by virDomainSave().
999  *
1000  * If the hypervisor supports it, @dxml can be used to alter
1001  * host-specific portions of the domain XML that will be used when
1002  * restoring an image.  For example, it is possible to alter the
1003  * backing filename that is associated with a disk device, in order to
1004  * prepare for file renaming done as part of backing up the disk
1005  * device while the domain is stopped.
1006  *
1007  * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will
1008  * attempt to bypass the file system cache while restoring the file, or
1009  * fail if it cannot do so for the given system; this can allow less
1010  * pressure on file system cache, but also risks slowing restores from NFS.
1011  *
1012  * Normally, the saved state file will remember whether the domain was
1013  * running or paused, and restore defaults to the same state.
1014  * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in
1015  * @flags will override the default read from the file.  These two
1016  * flags are mutually exclusive.
1017  *
1018  * Returns 0 in case of success and -1 in case of failure.
1019  */
1020 int
virDomainRestoreFlags(virConnectPtr conn,const char * from,const char * dxml,unsigned int flags)1021 virDomainRestoreFlags(virConnectPtr conn, const char *from, const char *dxml,
1022                       unsigned int flags)
1023 {
1024     VIR_DEBUG("conn=%p, from=%s, dxml=%s, flags=0x%x",
1025               conn, NULLSTR(from), NULLSTR(dxml), flags);
1026 
1027     virResetLastError();
1028 
1029     virCheckConnectReturn(conn, -1);
1030     virCheckReadOnlyGoto(conn->flags, error);
1031     virCheckNonNullArgGoto(from, error);
1032 
1033     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING,
1034                              VIR_DOMAIN_SAVE_PAUSED,
1035                              error);
1036 
1037     if (conn->driver->domainRestoreFlags) {
1038         int ret;
1039         char *absolute_from;
1040 
1041         /* We must absolutize the file path as the restore is done out of process */
1042         if (!(absolute_from = g_canonicalize_filename(from, NULL))) {
1043             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1044                            _("could not build absolute input file path"));
1045             goto error;
1046         }
1047 
1048         ret = conn->driver->domainRestoreFlags(conn, absolute_from, dxml,
1049                                                flags);
1050 
1051         VIR_FREE(absolute_from);
1052 
1053         if (ret < 0)
1054             goto error;
1055         return ret;
1056     }
1057 
1058     virReportUnsupportedError();
1059 
1060  error:
1061     virDispatchError(conn);
1062     return -1;
1063 }
1064 
1065 
1066 /**
1067  * virDomainSaveImageGetXMLDesc:
1068  * @conn: pointer to the hypervisor connection
1069  * @file: path to saved state file
1070  * @flags: bitwise-OR of supported virDomainSaveImageXMLFlags
1071  *
1072  * This method will extract the XML describing the domain at the time
1073  * a saved state file was created.  @file must be a file created
1074  * previously by virDomainSave() or virDomainSaveFlags().
1075  *
1076  * No security-sensitive data will be included unless @flags contains
1077  * VIR_DOMAIN_SAVE_IMAGE_XML_SECURE.
1078  *
1079  * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of
1080  * error.  The caller must free() the returned value.
1081  */
1082 char *
virDomainSaveImageGetXMLDesc(virConnectPtr conn,const char * file,unsigned int flags)1083 virDomainSaveImageGetXMLDesc(virConnectPtr conn, const char *file,
1084                              unsigned int flags)
1085 {
1086     VIR_DEBUG("conn=%p, file=%s, flags=0x%x",
1087               conn, NULLSTR(file), flags);
1088 
1089     virResetLastError();
1090 
1091     virCheckConnectReturn(conn, NULL);
1092     virCheckNonNullArgGoto(file, error);
1093     virCheckReadOnlyGoto(conn->flags, error);
1094 
1095     if (conn->driver->domainSaveImageGetXMLDesc) {
1096         char *ret;
1097         char *absolute_file;
1098 
1099         /* We must absolutize the file path as the read is done out of process */
1100         if (!(absolute_file = g_canonicalize_filename(file, NULL))) {
1101             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1102                            _("could not build absolute input file path"));
1103             goto error;
1104         }
1105 
1106         ret = conn->driver->domainSaveImageGetXMLDesc(conn, absolute_file,
1107                                                       flags);
1108 
1109         VIR_FREE(absolute_file);
1110 
1111         if (!ret)
1112             goto error;
1113         return ret;
1114     }
1115 
1116     virReportUnsupportedError();
1117 
1118  error:
1119     virDispatchError(conn);
1120     return NULL;
1121 }
1122 
1123 
1124 /**
1125  * virDomainSaveImageDefineXML:
1126  * @conn: pointer to the hypervisor connection
1127  * @file: path to saved state file
1128  * @dxml: XML config for adjusting guest xml used on restore
1129  * @flags: bitwise-OR of virDomainSaveRestoreFlags
1130  *
1131  * This updates the definition of a domain stored in a saved state
1132  * file.  @file must be a file created previously by virDomainSave()
1133  * or virDomainSaveFlags().
1134  *
1135  * @dxml can be used to alter host-specific portions of the domain XML
1136  * that will be used when restoring an image.  For example, it is
1137  * possible to alter the backing filename that is associated with a
1138  * disk device, to match renaming done as part of backing up the disk
1139  * device while the domain is stopped.
1140  *
1141  * Normally, the saved state file will remember whether the domain was
1142  * running or paused, and restore defaults to the same state.
1143  * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in
1144  * @flags will override the default saved into the file; omitting both
1145  * leaves the file's default unchanged.  These two flags are mutually
1146  * exclusive.
1147  *
1148  * Returns 0 in case of success and -1 in case of failure.
1149  */
1150 int
virDomainSaveImageDefineXML(virConnectPtr conn,const char * file,const char * dxml,unsigned int flags)1151 virDomainSaveImageDefineXML(virConnectPtr conn, const char *file,
1152                             const char *dxml, unsigned int flags)
1153 {
1154     VIR_DEBUG("conn=%p, file=%s, dxml=%s, flags=0x%x",
1155               conn, NULLSTR(file), NULLSTR(dxml), flags);
1156 
1157     virResetLastError();
1158 
1159     virCheckConnectReturn(conn, -1);
1160     virCheckReadOnlyGoto(conn->flags, error);
1161     virCheckNonNullArgGoto(file, error);
1162     virCheckNonNullArgGoto(dxml, error);
1163 
1164     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING,
1165                              VIR_DOMAIN_SAVE_PAUSED,
1166                              error);
1167 
1168     if (conn->driver->domainSaveImageDefineXML) {
1169         int ret;
1170         char *absolute_file;
1171 
1172         /* We must absolutize the file path as the read is done out of process */
1173         if (!(absolute_file = g_canonicalize_filename(file, NULL))) {
1174             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1175                            _("could not build absolute input file path"));
1176             goto error;
1177         }
1178 
1179         ret = conn->driver->domainSaveImageDefineXML(conn, absolute_file,
1180                                                      dxml, flags);
1181 
1182         VIR_FREE(absolute_file);
1183 
1184         if (ret < 0)
1185             goto error;
1186         return ret;
1187     }
1188 
1189     virReportUnsupportedError();
1190 
1191  error:
1192     virDispatchError(conn);
1193     return -1;
1194 }
1195 
1196 
1197 /**
1198  * virDomainCoreDump:
1199  * @domain: a domain object
1200  * @to: path for the core file
1201  * @flags: bitwise-OR of virDomainCoreDumpFlags
1202  *
1203  * This method will dump the core of a domain on a given file for analysis.
1204  * Note that for remote Xen Daemon the file path will be interpreted in
1205  * the remote host. Hypervisors may require  the user to manually ensure
1206  * proper permissions on the file named by @to.
1207  *
1208  * If @flags includes VIR_DUMP_CRASH, then leave the guest shut off with
1209  * a crashed state after the dump completes.  If @flags includes
1210  * VIR_DUMP_LIVE, then make the core dump while continuing to allow
1211  * the guest to run; otherwise, the guest is suspended during the dump.
1212  * VIR_DUMP_RESET flag forces reset of the guest after dump.
1213  * The above three flags are mutually exclusive.
1214  *
1215  * Additionally, if @flags includes VIR_DUMP_BYPASS_CACHE, then libvirt
1216  * will attempt to bypass the file system cache while creating the file,
1217  * or fail if it cannot do so for the given system; this can allow less
1218  * pressure on file system cache, but also risks slowing saves to NFS.
1219  *
1220  * For more control over the output format, see virDomainCoreDumpWithFormat().
1221  *
1222  * Returns 0 in case of success and -1 in case of failure.
1223  */
1224 int
virDomainCoreDump(virDomainPtr domain,const char * to,unsigned int flags)1225 virDomainCoreDump(virDomainPtr domain, const char *to, unsigned int flags)
1226 {
1227     virConnectPtr conn;
1228 
1229     VIR_DOMAIN_DEBUG(domain, "to=%s, flags=0x%x", to, flags);
1230 
1231     virResetLastError();
1232 
1233     virCheckDomainReturn(domain, -1);
1234     conn = domain->conn;
1235 
1236     virCheckReadOnlyGoto(conn->flags, error);
1237     virCheckNonNullArgGoto(to, error);
1238 
1239     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_LIVE, error);
1240     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_RESET, error);
1241     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_LIVE, VIR_DUMP_RESET, error);
1242 
1243     if (conn->driver->domainCoreDump) {
1244         int ret;
1245         char *absolute_to;
1246 
1247         /* We must absolutize the file path as the save is done out of process */
1248         if (!(absolute_to = g_canonicalize_filename(to, NULL))) {
1249             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1250                            _("could not build absolute core file path"));
1251             goto error;
1252         }
1253 
1254         ret = conn->driver->domainCoreDump(domain, absolute_to, flags);
1255 
1256         VIR_FREE(absolute_to);
1257 
1258         if (ret < 0)
1259             goto error;
1260         return ret;
1261     }
1262 
1263     virReportUnsupportedError();
1264 
1265  error:
1266     virDispatchError(domain->conn);
1267     return -1;
1268 }
1269 
1270 /**
1271  * virDomainCoreDumpWithFormat:
1272  * @domain: a domain object
1273  * @to: path for the core file
1274  * @dumpformat: format of domain memory's dump (one of virDomainCoreDumpFormat enum)
1275  * @flags: bitwise-OR of virDomainCoreDumpFlags
1276  *
1277  * This method will dump the core of a domain on a given file for analysis.
1278  * Note that for remote Xen Daemon the file path will be interpreted in
1279  * the remote host. Hypervisors may require  the user to manually ensure
1280  * proper permissions on the file named by @to.
1281  *
1282  * @dumpformat controls which format the dump will have; use of
1283  * VIR_DOMAIN_CORE_DUMP_FORMAT_RAW mirrors what virDomainCoreDump() will
1284  * perform.  Not all hypervisors are able to support all formats.
1285  *
1286  * If @flags includes VIR_DUMP_CRASH, then leave the guest shut off with
1287  * a crashed state after the dump completes.  If @flags includes
1288  * VIR_DUMP_LIVE, then make the core dump while continuing to allow
1289  * the guest to run; otherwise, the guest is suspended during the dump.
1290  * VIR_DUMP_RESET flag forces reset of the guest after dump.
1291  * The above three flags are mutually exclusive.
1292  *
1293  * Additionally, if @flags includes VIR_DUMP_BYPASS_CACHE, then libvirt
1294  * will attempt to bypass the file system cache while creating the file,
1295  * or fail if it cannot do so for the given system; this can allow less
1296  * pressure on file system cache, but also risks slowing saves to NFS.
1297  *
1298  * Returns 0 in case of success and -1 in case of failure.
1299  */
1300 int
virDomainCoreDumpWithFormat(virDomainPtr domain,const char * to,unsigned int dumpformat,unsigned int flags)1301 virDomainCoreDumpWithFormat(virDomainPtr domain, const char *to,
1302                             unsigned int dumpformat, unsigned int flags)
1303 {
1304     virConnectPtr conn;
1305 
1306     VIR_DOMAIN_DEBUG(domain, "to=%s, dumpformat=%u, flags=0x%x",
1307                      to, dumpformat, flags);
1308 
1309     virResetLastError();
1310 
1311     virCheckDomainReturn(domain, -1);
1312     conn = domain->conn;
1313 
1314     virCheckReadOnlyGoto(conn->flags, error);
1315     virCheckNonNullArgGoto(to, error);
1316 
1317     if (dumpformat >= VIR_DOMAIN_CORE_DUMP_FORMAT_LAST) {
1318         virReportInvalidArg(flags, _("dumpformat '%d' is not supported"),
1319                             dumpformat);
1320         goto error;
1321     }
1322 
1323     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_LIVE, error);
1324     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_CRASH, VIR_DUMP_RESET, error);
1325     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DUMP_LIVE, VIR_DUMP_RESET, error);
1326 
1327     if (conn->driver->domainCoreDumpWithFormat) {
1328         int ret;
1329         char *absolute_to;
1330 
1331         /* We must absolutize the file path as the save is done out of process */
1332         if (!(absolute_to = g_canonicalize_filename(to, NULL))) {
1333             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
1334                            _("could not build absolute core file path"));
1335             goto error;
1336         }
1337 
1338         ret = conn->driver->domainCoreDumpWithFormat(domain, absolute_to,
1339                                                      dumpformat, flags);
1340 
1341         VIR_FREE(absolute_to);
1342 
1343         if (ret < 0)
1344             goto error;
1345         return ret;
1346     }
1347 
1348     virReportUnsupportedError();
1349 
1350  error:
1351     virDispatchError(domain->conn);
1352     return -1;
1353 }
1354 
1355 
1356 /**
1357  * virDomainScreenshot:
1358  * @domain: a domain object
1359  * @stream: stream to use as output
1360  * @screen: monitor ID to take screenshot from
1361  * @flags: extra flags; not used yet, so callers should always pass 0
1362  *
1363  * Take a screenshot of current domain console as a stream. The image format
1364  * is hypervisor specific. Moreover, some hypervisors supports multiple
1365  * displays per domain. These can be distinguished by @screen argument.
1366  *
1367  * This call sets up a stream; subsequent use of stream API is necessary
1368  * to transfer actual data, determine how much data is successfully
1369  * transferred, and detect any errors.
1370  *
1371  * The screen ID is the sequential number of screen. In case of multiple
1372  * graphics cards, heads are enumerated before devices, e.g. having
1373  * two graphics cards, both with four heads, screen ID 5 addresses
1374  * the second head on the second card.
1375  *
1376  * Returns a string representing the mime-type of the image format, or
1377  * NULL upon error. The caller must free() the returned value.
1378  */
1379 char *
virDomainScreenshot(virDomainPtr domain,virStreamPtr stream,unsigned int screen,unsigned int flags)1380 virDomainScreenshot(virDomainPtr domain,
1381                     virStreamPtr stream,
1382                     unsigned int screen,
1383                     unsigned int flags)
1384 {
1385     VIR_DOMAIN_DEBUG(domain, "stream=%p, flags=0x%x", stream, flags);
1386 
1387     virResetLastError();
1388 
1389     virCheckDomainReturn(domain, NULL);
1390     virCheckStreamGoto(stream, error);
1391     virCheckReadOnlyGoto(domain->conn->flags, error);
1392 
1393     if (domain->conn != stream->conn) {
1394         virReportInvalidArg(stream,
1395                             _("stream must match connection of domain '%s'"),
1396                             domain->name);
1397         goto error;
1398     }
1399 
1400     if (domain->conn->driver->domainScreenshot) {
1401         char *ret;
1402         ret = domain->conn->driver->domainScreenshot(domain, stream,
1403                                                      screen, flags);
1404 
1405         if (ret == NULL)
1406             goto error;
1407         return ret;
1408     }
1409 
1410     virReportUnsupportedError();
1411 
1412  error:
1413     virDispatchError(domain->conn);
1414     return NULL;
1415 }
1416 
1417 
1418 /**
1419  * virDomainShutdown:
1420  * @domain: a domain object
1421  *
1422  * Shutdown a domain, the domain object is still usable thereafter, but
1423  * the domain OS is being stopped. Note that the guest OS may ignore the
1424  * request. Additionally, the hypervisor may check and support the domain
1425  * 'on_poweroff' XML setting resulting in a domain that reboots instead of
1426  * shutting down. For guests that react to a shutdown request, the differences
1427  * from virDomainDestroy() are that the guests disk storage will be in a
1428  * stable state rather than having the (virtual) power cord pulled, and
1429  * this command returns as soon as the shutdown request is issued rather
1430  * than blocking until the guest is no longer running.
1431  *
1432  * If the domain is transient and has any snapshot metadata (see
1433  * virDomainSnapshotNum()), then that metadata will automatically
1434  * be deleted when the domain quits.
1435  *
1436  * Returns 0 in case of success and -1 in case of failure.
1437  */
1438 int
virDomainShutdown(virDomainPtr domain)1439 virDomainShutdown(virDomainPtr domain)
1440 {
1441     virConnectPtr conn;
1442 
1443     VIR_DOMAIN_DEBUG(domain);
1444 
1445     virResetLastError();
1446 
1447     virCheckDomainReturn(domain, -1);
1448     conn = domain->conn;
1449 
1450     virCheckReadOnlyGoto(conn->flags, error);
1451 
1452     if (conn->driver->domainShutdown) {
1453         int ret;
1454         ret = conn->driver->domainShutdown(domain);
1455         if (ret < 0)
1456             goto error;
1457         return ret;
1458     }
1459 
1460     virReportUnsupportedError();
1461 
1462  error:
1463     virDispatchError(domain->conn);
1464     return -1;
1465 }
1466 
1467 
1468 /**
1469  * virDomainShutdownFlags:
1470  * @domain: a domain object
1471  * @flags: bitwise-OR of virDomainShutdownFlagValues
1472  *
1473  * Shutdown a domain, the domain object is still usable thereafter but
1474  * the domain OS is being stopped. Note that the guest OS may ignore the
1475  * request. Additionally, the hypervisor may check and support the domain
1476  * 'on_poweroff' XML setting resulting in a domain that reboots instead of
1477  * shutting down. For guests that react to a shutdown request, the differences
1478  * from virDomainDestroy() are that the guest's disk storage will be in a
1479  * stable state rather than having the (virtual) power cord pulled, and
1480  * this command returns as soon as the shutdown request is issued rather
1481  * than blocking until the guest is no longer running.
1482  *
1483  * If the domain is transient and has any snapshot metadata (see
1484  * virDomainSnapshotNum()), then that metadata will automatically
1485  * be deleted when the domain quits.
1486  *
1487  * If @flags is set to zero, then the hypervisor will choose the
1488  * method of shutdown it considers best. To have greater control
1489  * pass one or more of the virDomainShutdownFlagValues. The order
1490  * in which the hypervisor tries each shutdown method is undefined,
1491  * and a hypervisor is not required to support all methods.
1492  *
1493  * To use guest agent (VIR_DOMAIN_SHUTDOWN_GUEST_AGENT) the domain XML
1494  * must have <channel> configured.
1495  *
1496  * Returns 0 in case of success and -1 in case of failure.
1497  */
1498 int
virDomainShutdownFlags(virDomainPtr domain,unsigned int flags)1499 virDomainShutdownFlags(virDomainPtr domain, unsigned int flags)
1500 {
1501     virConnectPtr conn;
1502 
1503     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
1504 
1505     virResetLastError();
1506 
1507     virCheckDomainReturn(domain, -1);
1508     conn = domain->conn;
1509 
1510     virCheckReadOnlyGoto(conn->flags, error);
1511 
1512     if (conn->driver->domainShutdownFlags) {
1513         int ret;
1514         ret = conn->driver->domainShutdownFlags(domain, flags);
1515         if (ret < 0)
1516             goto error;
1517         return ret;
1518     }
1519 
1520     virReportUnsupportedError();
1521 
1522  error:
1523     virDispatchError(domain->conn);
1524     return -1;
1525 }
1526 
1527 
1528 /**
1529  * virDomainReboot:
1530  * @domain: a domain object
1531  * @flags: bitwise-OR of virDomainRebootFlagValues
1532  *
1533  * Reboot a domain, the domain object is still usable thereafter, but
1534  * the domain OS is being stopped for a restart.
1535  * Note that the guest OS may ignore the request.
1536  * Additionally, the hypervisor may check and support the domain
1537  * 'on_reboot' XML setting resulting in a domain that shuts down instead
1538  * of rebooting.
1539  *
1540  * If @flags is set to zero, then the hypervisor will choose the
1541  * method of shutdown it considers best. To have greater control
1542  * pass one or more of the virDomainRebootFlagValues. The order
1543  * in which the hypervisor tries each shutdown method is undefined,
1544  * and a hypervisor is not required to support all methods.
1545  *
1546  * To use guest agent (VIR_DOMAIN_REBOOT_GUEST_AGENT) the domain XML
1547  * must have <channel> configured.
1548  *
1549  * Due to implementation limitations in some drivers (the qemu driver,
1550  * for instance) it is not advised to migrate or save a guest that is
1551  * rebooting as a result of this API. Migrating such a guest can lead
1552  * to a plain shutdown on the destination.
1553  *
1554  * Returns 0 in case of success and -1 in case of failure.
1555  */
1556 int
virDomainReboot(virDomainPtr domain,unsigned int flags)1557 virDomainReboot(virDomainPtr domain, unsigned int flags)
1558 {
1559     virConnectPtr conn;
1560 
1561     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
1562 
1563     virResetLastError();
1564 
1565     virCheckDomainReturn(domain, -1);
1566     conn = domain->conn;
1567 
1568     virCheckReadOnlyGoto(conn->flags, error);
1569 
1570     if (conn->driver->domainReboot) {
1571         int ret;
1572         ret = conn->driver->domainReboot(domain, flags);
1573         if (ret < 0)
1574             goto error;
1575         return ret;
1576     }
1577 
1578     virReportUnsupportedError();
1579 
1580  error:
1581     virDispatchError(domain->conn);
1582     return -1;
1583 }
1584 
1585 
1586 /**
1587  * virDomainReset:
1588  * @domain: a domain object
1589  * @flags: extra flags; not used yet, so callers should always pass 0
1590  *
1591  * Reset a domain immediately without any guest OS shutdown.
1592  * Reset emulates the power reset button on a machine, where all
1593  * hardware sees the RST line set and reinitializes internal state.
1594  *
1595  * Note that there is a risk of data loss caused by reset without any
1596  * guest OS shutdown.
1597  *
1598  * Returns 0 in case of success and -1 in case of failure.
1599  */
1600 int
virDomainReset(virDomainPtr domain,unsigned int flags)1601 virDomainReset(virDomainPtr domain, unsigned int flags)
1602 {
1603     virConnectPtr conn;
1604 
1605     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
1606 
1607     virResetLastError();
1608 
1609     virCheckDomainReturn(domain, -1);
1610     conn = domain->conn;
1611 
1612     virCheckReadOnlyGoto(conn->flags, error);
1613 
1614     if (conn->driver->domainReset) {
1615         int ret;
1616         ret = conn->driver->domainReset(domain, flags);
1617         if (ret < 0)
1618             goto error;
1619         return ret;
1620     }
1621 
1622     virReportUnsupportedError();
1623 
1624  error:
1625     virDispatchError(domain->conn);
1626     return -1;
1627 }
1628 
1629 
1630 /**
1631  * virDomainGetName:
1632  * @domain: a domain object
1633  *
1634  * Get the public name for that domain
1635  *
1636  * Returns a pointer to the name or NULL, the string need not be deallocated
1637  * its lifetime will be the same as the domain object.
1638  */
1639 const char *
virDomainGetName(virDomainPtr domain)1640 virDomainGetName(virDomainPtr domain)
1641 {
1642     VIR_DEBUG("domain=%p", domain);
1643 
1644     virResetLastError();
1645 
1646     virCheckDomainReturn(domain, NULL);
1647 
1648     return domain->name;
1649 }
1650 
1651 
1652 /**
1653  * virDomainGetUUID:
1654  * @domain: a domain object
1655  * @uuid: pointer to a VIR_UUID_BUFLEN bytes array
1656  *
1657  * Get the UUID for a domain
1658  *
1659  * Returns -1 in case of error, 0 in case of success
1660  */
1661 int
virDomainGetUUID(virDomainPtr domain,unsigned char * uuid)1662 virDomainGetUUID(virDomainPtr domain, unsigned char *uuid)
1663 {
1664     VIR_DOMAIN_DEBUG(domain, "uuid=%p", uuid);
1665 
1666     virResetLastError();
1667 
1668     virCheckDomainReturn(domain, -1);
1669     virCheckNonNullArgGoto(uuid, error);
1670 
1671     memcpy(uuid, &domain->uuid[0], VIR_UUID_BUFLEN);
1672 
1673     return 0;
1674 
1675  error:
1676     virDispatchError(domain->conn);
1677     return -1;
1678 }
1679 
1680 
1681 /**
1682  * virDomainGetUUIDString:
1683  * @domain: a domain object
1684  * @buf: pointer to a VIR_UUID_STRING_BUFLEN bytes array
1685  *
1686  * Get the UUID for a domain as string. For more information about
1687  * UUID see RFC4122.
1688  *
1689  * Returns -1 in case of error, 0 in case of success
1690  */
1691 int
virDomainGetUUIDString(virDomainPtr domain,char * buf)1692 virDomainGetUUIDString(virDomainPtr domain, char *buf)
1693 {
1694     VIR_DOMAIN_DEBUG(domain, "buf=%p", buf);
1695 
1696     virResetLastError();
1697 
1698     virCheckDomainReturn(domain, -1);
1699     virCheckNonNullArgGoto(buf, error);
1700 
1701     virUUIDFormat(domain->uuid, buf);
1702     return 0;
1703 
1704  error:
1705     virDispatchError(domain->conn);
1706     return -1;
1707 }
1708 
1709 
1710 /**
1711  * virDomainGetID:
1712  * @domain: a domain object
1713  *
1714  * Get the hypervisor ID number for the domain
1715  *
1716  * Returns the domain ID number or (unsigned int) -1 in case of error
1717  */
1718 unsigned int
virDomainGetID(virDomainPtr domain)1719 virDomainGetID(virDomainPtr domain)
1720 {
1721     VIR_DOMAIN_DEBUG(domain);
1722 
1723     virResetLastError();
1724 
1725     virCheckDomainReturn(domain, (unsigned int)-1);
1726 
1727     return domain->id;
1728 }
1729 
1730 
1731 /**
1732  * virDomainGetOSType:
1733  * @domain: a domain object
1734  *
1735  * Get the type of domain operation system.
1736  *
1737  * Returns the new string or NULL in case of error, the string must be
1738  *         freed by the caller.
1739  */
1740 char *
virDomainGetOSType(virDomainPtr domain)1741 virDomainGetOSType(virDomainPtr domain)
1742 {
1743     virConnectPtr conn;
1744 
1745     VIR_DOMAIN_DEBUG(domain);
1746 
1747     virResetLastError();
1748 
1749     virCheckDomainReturn(domain, NULL);
1750     conn = domain->conn;
1751 
1752     if (conn->driver->domainGetOSType) {
1753         char *ret;
1754         ret = conn->driver->domainGetOSType(domain);
1755         if (!ret)
1756             goto error;
1757         return ret;
1758     }
1759 
1760     virReportUnsupportedError();
1761 
1762  error:
1763     virDispatchError(domain->conn);
1764     return NULL;
1765 }
1766 
1767 
1768 /**
1769  * virDomainGetMaxMemory:
1770  * @domain: a domain object or NULL
1771  *
1772  * Retrieve the maximum amount of physical memory allocated to a
1773  * domain. If domain is NULL, then this get the amount of memory reserved
1774  * to Domain0 i.e. the domain where the application runs.
1775  *
1776  * Returns the memory size in kibibytes (blocks of 1024 bytes), or 0 in
1777  * case of error.
1778  */
1779 unsigned long
virDomainGetMaxMemory(virDomainPtr domain)1780 virDomainGetMaxMemory(virDomainPtr domain)
1781 {
1782     virConnectPtr conn;
1783 
1784     VIR_DOMAIN_DEBUG(domain);
1785 
1786     virResetLastError();
1787 
1788     virCheckDomainReturn(domain, 0);
1789     conn = domain->conn;
1790 
1791     if (conn->driver->domainGetMaxMemory) {
1792         unsigned long long ret;
1793         ret = conn->driver->domainGetMaxMemory(domain);
1794         if (ret == 0)
1795             goto error;
1796         if ((unsigned long) ret != ret) {
1797             virReportError(VIR_ERR_OVERFLOW, _("result too large: %llu"),
1798                            ret);
1799             goto error;
1800         }
1801         return ret;
1802     }
1803 
1804     virReportUnsupportedError();
1805 
1806  error:
1807     virDispatchError(domain->conn);
1808     return 0;
1809 }
1810 
1811 
1812 /**
1813  * virDomainSetMaxMemory:
1814  * @domain: a domain object or NULL
1815  * @memory: the memory size in kibibytes (blocks of 1024 bytes)
1816  *
1817  * Dynamically change the maximum amount of physical memory allocated to a
1818  * domain. If domain is NULL, then this change the amount of memory reserved
1819  * to Domain0 i.e. the domain where the application runs.
1820  * This function may require privileged access to the hypervisor.
1821  *
1822  * This command is hypervisor-specific for whether active, persistent,
1823  * or both configurations are changed; for more control, use
1824  * virDomainSetMemoryFlags().
1825  *
1826  * Returns 0 in case of success and -1 in case of failure.
1827  */
1828 int
virDomainSetMaxMemory(virDomainPtr domain,unsigned long memory)1829 virDomainSetMaxMemory(virDomainPtr domain, unsigned long memory)
1830 {
1831     virConnectPtr conn;
1832 
1833     VIR_DOMAIN_DEBUG(domain, "memory=%lu", memory);
1834 
1835     virResetLastError();
1836 
1837     virCheckDomainReturn(domain, -1);
1838     conn = domain->conn;
1839 
1840     virCheckReadOnlyGoto(conn->flags, error);
1841     virCheckNonZeroArgGoto(memory, error);
1842 
1843     if (virMemoryMaxValue(true) / 1024 <= memory) {
1844         virReportError(VIR_ERR_OVERFLOW, _("input too large: %lu"),
1845                        memory);
1846         goto error;
1847     }
1848 
1849     if (conn->driver->domainSetMaxMemory) {
1850         int ret;
1851         ret = conn->driver->domainSetMaxMemory(domain, memory);
1852         if (ret < 0)
1853             goto error;
1854         return ret;
1855     }
1856 
1857     virReportUnsupportedError();
1858 
1859  error:
1860     virDispatchError(domain->conn);
1861     return -1;
1862 }
1863 
1864 
1865 /**
1866  * virDomainSetMemory:
1867  * @domain: a domain object or NULL
1868  * @memory: the memory size in kibibytes (blocks of 1024 bytes)
1869  *
1870  * Dynamically change the target amount of physical memory allocated to a
1871  * domain. If domain is NULL, then this change the amount of memory reserved
1872  * to Domain0 i.e. the domain where the application runs.
1873  * This function may require privileged access to the hypervisor.
1874  *
1875  * This command is hypervisor-specific for whether active, persistent,
1876  * or both configurations are changed; for more control, use
1877  * virDomainSetMemoryFlags().
1878  *
1879  * Returns 0 in case of success and -1 in case of failure.
1880  */
1881 int
virDomainSetMemory(virDomainPtr domain,unsigned long memory)1882 virDomainSetMemory(virDomainPtr domain, unsigned long memory)
1883 {
1884     virConnectPtr conn;
1885 
1886     VIR_DOMAIN_DEBUG(domain, "memory=%lu", memory);
1887 
1888     virResetLastError();
1889 
1890     virCheckDomainReturn(domain, -1);
1891     conn = domain->conn;
1892 
1893     virCheckReadOnlyGoto(conn->flags, error);
1894     virCheckNonZeroArgGoto(memory, error);
1895 
1896     if (virMemoryMaxValue(true) / 1024 <= memory) {
1897         virReportError(VIR_ERR_OVERFLOW, _("input too large: %lu"),
1898                        memory);
1899         goto error;
1900     }
1901 
1902     if (conn->driver->domainSetMemory) {
1903         int ret;
1904         ret = conn->driver->domainSetMemory(domain, memory);
1905         if (ret < 0)
1906             goto error;
1907         return ret;
1908     }
1909 
1910     virReportUnsupportedError();
1911 
1912  error:
1913     virDispatchError(domain->conn);
1914     return -1;
1915 }
1916 
1917 
1918 /**
1919  * virDomainSetMemoryFlags:
1920  * @domain: a domain object or NULL
1921  * @memory: the memory size in kibibytes (blocks of 1024 bytes)
1922  * @flags: bitwise-OR of virDomainMemoryModFlags
1923  *
1924  * Dynamically change the target amount of physical memory allocated to a
1925  * domain. If domain is NULL, then this change the amount of memory reserved
1926  * to Domain0 i.e. the domain where the application runs.
1927  * This function may require privileged access to the hypervisor.
1928  *
1929  * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
1930  * Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects
1931  * a running domain and will fail if domain is not active.
1932  * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
1933  * and will fail for transient domains. If neither flag is specified
1934  * (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain
1935  * modifies persistent setup, while an active domain is hypervisor-dependent
1936  * on whether just live or both live and persistent state is changed.
1937  * If VIR_DOMAIN_MEM_MAXIMUM is set, the change affects domain's maximum memory
1938  * size rather than current memory size.
1939  * Not all hypervisors can support all flag combinations.
1940  *
1941  * Returns 0 in case of success, -1 in case of failure.
1942  */
1943 int
virDomainSetMemoryFlags(virDomainPtr domain,unsigned long memory,unsigned int flags)1944 virDomainSetMemoryFlags(virDomainPtr domain, unsigned long memory,
1945                         unsigned int flags)
1946 {
1947     virConnectPtr conn;
1948 
1949     VIR_DOMAIN_DEBUG(domain, "memory=%lu, flags=0x%x", memory, flags);
1950 
1951     virResetLastError();
1952 
1953     virCheckDomainReturn(domain, -1);
1954     conn = domain->conn;
1955 
1956     virCheckReadOnlyGoto(conn->flags, error);
1957     virCheckNonZeroArgGoto(memory, error);
1958 
1959     if (virMemoryMaxValue(true) / 1024 <= memory) {
1960         virReportError(VIR_ERR_OVERFLOW, _("input too large: %lu"),
1961                        memory);
1962         goto error;
1963     }
1964 
1965     if (conn->driver->domainSetMemoryFlags) {
1966         int ret;
1967         ret = conn->driver->domainSetMemoryFlags(domain, memory, flags);
1968         if (ret < 0)
1969             goto error;
1970         return ret;
1971     }
1972 
1973     virReportUnsupportedError();
1974 
1975  error:
1976     virDispatchError(domain->conn);
1977     return -1;
1978 }
1979 
1980 
1981 /**
1982  * virDomainSetMemoryStatsPeriod:
1983  * @domain: a domain object or NULL
1984  * @period: the period in seconds for stats collection
1985  * @flags: bitwise-OR of virDomainMemoryModFlags
1986  *
1987  * Dynamically change the domain memory balloon driver statistics collection
1988  * period. Use 0 to disable and a positive value to enable.
1989  *
1990  * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
1991  * Both flags may be set. If VIR_DOMAIN_AFFECT_LIVE is set, the change affects
1992  * a running domain and will fail if domain is not active.
1993  * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
1994  * and will fail for transient domains. If neither flag is specified
1995  * (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain
1996  * modifies persistent setup, while an active domain is hypervisor-dependent
1997  * on whether just live or both live and persistent state is changed.
1998  *
1999  * Not all hypervisors can support all flag combinations.
2000  *
2001  * Returns 0 in case of success, -1 in case of failure.
2002  */
2003 int
virDomainSetMemoryStatsPeriod(virDomainPtr domain,int period,unsigned int flags)2004 virDomainSetMemoryStatsPeriod(virDomainPtr domain, int period,
2005                               unsigned int flags)
2006 {
2007     virConnectPtr conn;
2008 
2009     VIR_DOMAIN_DEBUG(domain, "period=%d, flags=0x%x", period, flags);
2010 
2011     virResetLastError();
2012 
2013     virCheckDomainReturn(domain, -1);
2014     conn = domain->conn;
2015 
2016     virCheckReadOnlyGoto(conn->flags, error);
2017 
2018     /* This must be positive to set the balloon collection period */
2019     virCheckNonNegativeArgGoto(period, error);
2020 
2021     if (conn->driver->domainSetMemoryStatsPeriod) {
2022         int ret;
2023         ret = conn->driver->domainSetMemoryStatsPeriod(domain, period, flags);
2024         if (ret < 0)
2025             goto error;
2026         return ret;
2027     }
2028 
2029     virReportUnsupportedError();
2030 
2031  error:
2032     virDispatchError(domain->conn);
2033     return -1;
2034 }
2035 
2036 
2037 /**
2038  * virDomainSetMemoryParameters:
2039  * @domain: pointer to domain object
2040  * @params: pointer to memory parameter objects
2041  * @nparams: number of memory parameter (this value can be the same or
2042  *          less than the number of parameters supported)
2043  * @flags: bitwise-OR of virDomainModificationImpact
2044  *
2045  * Change all or a subset of the memory tunables.
2046  * This function may require privileged access to the hypervisor.
2047  *
2048  * Possible values for all *_limit memory tunables are in range from 0 to
2049  * VIR_DOMAIN_MEMORY_PARAM_UNLIMITED.
2050  *
2051  * Returns -1 in case of error, 0 in case of success.
2052  */
2053 int
virDomainSetMemoryParameters(virDomainPtr domain,virTypedParameterPtr params,int nparams,unsigned int flags)2054 virDomainSetMemoryParameters(virDomainPtr domain,
2055                              virTypedParameterPtr params,
2056                              int nparams, unsigned int flags)
2057 {
2058     virConnectPtr conn;
2059 
2060     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=0x%x",
2061                      params, nparams, flags);
2062     VIR_TYPED_PARAMS_DEBUG(params, nparams);
2063 
2064     virResetLastError();
2065 
2066     virCheckDomainReturn(domain, -1);
2067     conn = domain->conn;
2068 
2069     virCheckReadOnlyGoto(conn->flags, error);
2070     virCheckNonNullArgGoto(params, error);
2071     virCheckPositiveArgGoto(nparams, error);
2072 
2073     if (virTypedParameterValidateSet(conn, params, nparams) < 0)
2074         goto error;
2075 
2076     if (conn->driver->domainSetMemoryParameters) {
2077         int ret;
2078         ret = conn->driver->domainSetMemoryParameters(domain, params, nparams, flags);
2079         if (ret < 0)
2080             goto error;
2081         return ret;
2082     }
2083 
2084     virReportUnsupportedError();
2085 
2086  error:
2087     virDispatchError(domain->conn);
2088     return -1;
2089 }
2090 
2091 
2092 /**
2093  * virDomainGetMemoryParameters:
2094  * @domain: pointer to domain object
2095  * @params: pointer to memory parameter object
2096  *          (return value, allocated by the caller)
2097  * @nparams: pointer to number of memory parameters; input and output
2098  * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
2099  *
2100  * Get all memory parameters.  On input, @nparams gives the size of the
2101  * @params array; on output, @nparams gives how many slots were filled
2102  * with parameter information, which might be less but will not exceed
2103  * the input value.
2104  *
2105  * As a special case, calling with @params as NULL and @nparams as 0 on
2106  * input will cause @nparams on output to contain the number of parameters
2107  * supported by the hypervisor. The caller should then allocate @params
2108  * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
2109  * again.
2110  *
2111  * Here is a sample code snippet:
2112  *
2113  *   if (virDomainGetMemoryParameters(dom, NULL, &nparams, 0) == 0 &&
2114  *       nparams != 0) {
2115  *       if ((params = malloc(sizeof(*params) * nparams)) == NULL)
2116  *           goto error;
2117  *       memset(params, 0, sizeof(*params) * nparams);
2118  *       if (virDomainGetMemoryParameters(dom, params, &nparams, 0))
2119  *           goto error;
2120  *   }
2121  *
2122  * This function may require privileged access to the hypervisor. This function
2123  * expects the caller to allocate the @params.
2124  *
2125  * Returns -1 in case of error, 0 in case of success.
2126  */
2127 int
virDomainGetMemoryParameters(virDomainPtr domain,virTypedParameterPtr params,int * nparams,unsigned int flags)2128 virDomainGetMemoryParameters(virDomainPtr domain,
2129                              virTypedParameterPtr params,
2130                              int *nparams, unsigned int flags)
2131 {
2132     virConnectPtr conn;
2133     int rc;
2134 
2135     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=0x%x",
2136                      params, (nparams) ? *nparams : -1, flags);
2137 
2138     virResetLastError();
2139 
2140     virCheckDomainReturn(domain, -1);
2141     virCheckNonNullArgGoto(nparams, error);
2142     virCheckNonNegativeArgGoto(*nparams, error);
2143     if (*nparams != 0)
2144         virCheckNonNullArgGoto(params, error);
2145 
2146     rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
2147                                   VIR_DRV_FEATURE_TYPED_PARAM_STRING);
2148     if (rc < 0)
2149         goto error;
2150     if (rc)
2151         flags |= VIR_TYPED_PARAM_STRING_OKAY;
2152 
2153     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE,
2154                              VIR_DOMAIN_AFFECT_CONFIG,
2155                              error);
2156 
2157     conn = domain->conn;
2158 
2159     if (conn->driver->domainGetMemoryParameters) {
2160         int ret;
2161         ret = conn->driver->domainGetMemoryParameters(domain, params, nparams, flags);
2162         if (ret < 0)
2163             goto error;
2164         return ret;
2165     }
2166     virReportUnsupportedError();
2167 
2168  error:
2169     virDispatchError(domain->conn);
2170     return -1;
2171 }
2172 
2173 
2174 /**
2175  * virDomainSetNumaParameters:
2176  * @domain: pointer to domain object
2177  * @params: pointer to numa parameter objects
2178  * @nparams: number of numa parameters (this value can be the same or
2179  *          less than the number of parameters supported)
2180  * @flags: bitwise-OR of virDomainModificationImpact
2181  *
2182  * Change all or a subset of the numa tunables.
2183  * This function may require privileged access to the hypervisor.
2184  *
2185  * Returns -1 in case of error, 0 in case of success.
2186  */
2187 int
virDomainSetNumaParameters(virDomainPtr domain,virTypedParameterPtr params,int nparams,unsigned int flags)2188 virDomainSetNumaParameters(virDomainPtr domain,
2189                            virTypedParameterPtr params,
2190                            int nparams, unsigned int flags)
2191 {
2192     virConnectPtr conn;
2193 
2194     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=0x%x",
2195                      params, nparams, flags);
2196     VIR_TYPED_PARAMS_DEBUG(params, nparams);
2197 
2198     virResetLastError();
2199 
2200     virCheckDomainReturn(domain, -1);
2201     virCheckReadOnlyGoto(domain->conn->flags, error);
2202     virCheckNonNullArgGoto(params, error);
2203     virCheckPositiveArgGoto(nparams, error);
2204     if (virTypedParameterValidateSet(domain->conn, params, nparams) < 0)
2205         goto error;
2206 
2207     conn = domain->conn;
2208 
2209     if (conn->driver->domainSetNumaParameters) {
2210         int ret;
2211         ret = conn->driver->domainSetNumaParameters(domain, params, nparams,
2212                                                     flags);
2213         if (ret < 0)
2214             goto error;
2215         return ret;
2216     }
2217 
2218     virReportUnsupportedError();
2219 
2220  error:
2221     virDispatchError(domain->conn);
2222     return -1;
2223 }
2224 
2225 
2226 /**
2227  * virDomainGetNumaParameters:
2228  * @domain: pointer to domain object
2229  * @params: pointer to numa parameter object
2230  *          (return value, allocated by the caller)
2231  * @nparams: pointer to number of numa parameters
2232  * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
2233  *
2234  * Get all numa parameters.  On input, @nparams gives the size of the
2235  * @params array; on output, @nparams gives how many slots were filled
2236  * with parameter information, which might be less but will not exceed
2237  * the input value.
2238  *
2239  * As a special case, calling with @params as NULL and @nparams as 0 on
2240  * input will cause @nparams on output to contain the number of parameters
2241  * supported by the hypervisor. The caller should then allocate @params
2242  * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
2243  * again.
2244  *
2245  * See virDomainGetMemoryParameters() for an equivalent usage example.
2246  *
2247  * This function may require privileged access to the hypervisor. This function
2248  * expects the caller to allocate the @params.
2249  *
2250  * Returns -1 in case of error, 0 in case of success.
2251  */
2252 int
virDomainGetNumaParameters(virDomainPtr domain,virTypedParameterPtr params,int * nparams,unsigned int flags)2253 virDomainGetNumaParameters(virDomainPtr domain,
2254                            virTypedParameterPtr params,
2255                            int *nparams, unsigned int flags)
2256 {
2257     virConnectPtr conn;
2258     int rc;
2259 
2260     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=0x%x",
2261                      params, (nparams) ? *nparams : -1, flags);
2262 
2263     virResetLastError();
2264 
2265     virCheckDomainReturn(domain, -1);
2266     virCheckNonNullArgGoto(nparams, error);
2267     virCheckNonNegativeArgGoto(*nparams, error);
2268     if (*nparams != 0)
2269         virCheckNonNullArgGoto(params, error);
2270 
2271     rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
2272                                   VIR_DRV_FEATURE_TYPED_PARAM_STRING);
2273     if (rc < 0)
2274         goto error;
2275     if (rc)
2276         flags |= VIR_TYPED_PARAM_STRING_OKAY;
2277 
2278     conn = domain->conn;
2279 
2280     if (conn->driver->domainGetNumaParameters) {
2281         int ret;
2282         ret = conn->driver->domainGetNumaParameters(domain, params, nparams,
2283                                                     flags);
2284         if (ret < 0)
2285             goto error;
2286         return ret;
2287     }
2288     virReportUnsupportedError();
2289 
2290  error:
2291     virDispatchError(domain->conn);
2292     return -1;
2293 }
2294 
2295 
2296 /**
2297  * virDomainSetBlkioParameters:
2298  * @domain: pointer to domain object
2299  * @params: pointer to blkio parameter objects
2300  * @nparams: number of blkio parameters (this value can be the same or
2301  *          less than the number of parameters supported)
2302  * @flags: bitwise-OR of virDomainModificationImpact
2303  *
2304  * Change all or a subset of the blkio tunables.
2305  * This function may require privileged access to the hypervisor.
2306  *
2307  * Returns -1 in case of error, 0 in case of success.
2308  */
2309 int
virDomainSetBlkioParameters(virDomainPtr domain,virTypedParameterPtr params,int nparams,unsigned int flags)2310 virDomainSetBlkioParameters(virDomainPtr domain,
2311                             virTypedParameterPtr params,
2312                             int nparams, unsigned int flags)
2313 {
2314     virConnectPtr conn;
2315 
2316     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=0x%x",
2317                      params, nparams, flags);
2318     VIR_TYPED_PARAMS_DEBUG(params, nparams);
2319 
2320     virResetLastError();
2321 
2322     virCheckDomainReturn(domain, -1);
2323     conn = domain->conn;
2324 
2325     virCheckReadOnlyGoto(conn->flags, error);
2326     virCheckNonNullArgGoto(params, error);
2327     virCheckNonNegativeArgGoto(nparams, error);
2328 
2329     if (virTypedParameterValidateSet(conn, params, nparams) < 0)
2330         goto error;
2331 
2332     if (conn->driver->domainSetBlkioParameters) {
2333         int ret;
2334         ret = conn->driver->domainSetBlkioParameters(domain, params, nparams, flags);
2335         if (ret < 0)
2336             goto error;
2337         return ret;
2338     }
2339 
2340     virReportUnsupportedError();
2341 
2342  error:
2343     virDispatchError(domain->conn);
2344     return -1;
2345 }
2346 
2347 
2348 /**
2349  * virDomainGetBlkioParameters:
2350  * @domain: pointer to domain object
2351  * @params: pointer to blkio parameter object
2352  *          (return value, allocated by the caller)
2353  * @nparams: pointer to number of blkio parameters; input and output
2354  * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
2355  *
2356  * Get all blkio parameters.  On input, @nparams gives the size of the
2357  * @params array; on output, @nparams gives how many slots were filled
2358  * with parameter information, which might be less but will not exceed
2359  * the input value.
2360  *
2361  * As a special case, calling with @params as NULL and @nparams as 0 on
2362  * input will cause @nparams on output to contain the number of parameters
2363  * supported by the hypervisor. The caller should then allocate @params
2364  * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
2365  * again.
2366  *
2367  * See virDomainGetMemoryParameters() for an equivalent usage example.
2368  *
2369  * This function may require privileged access to the hypervisor. This function
2370  * expects the caller to allocate the @params.
2371  *
2372  * Returns -1 in case of error, 0 in case of success.
2373  */
2374 int
virDomainGetBlkioParameters(virDomainPtr domain,virTypedParameterPtr params,int * nparams,unsigned int flags)2375 virDomainGetBlkioParameters(virDomainPtr domain,
2376                             virTypedParameterPtr params,
2377                             int *nparams, unsigned int flags)
2378 {
2379     virConnectPtr conn;
2380     int rc;
2381 
2382     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=0x%x",
2383                      params, (nparams) ? *nparams : -1, flags);
2384 
2385     virResetLastError();
2386 
2387     virCheckDomainReturn(domain, -1);
2388     virCheckNonNullArgGoto(nparams, error);
2389     virCheckNonNegativeArgGoto(*nparams, error);
2390     if (*nparams != 0)
2391         virCheckNonNullArgGoto(params, error);
2392 
2393     rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
2394                                   VIR_DRV_FEATURE_TYPED_PARAM_STRING);
2395     if (rc < 0)
2396         goto error;
2397     if (rc)
2398         flags |= VIR_TYPED_PARAM_STRING_OKAY;
2399 
2400     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE,
2401                              VIR_DOMAIN_AFFECT_CONFIG,
2402                              error);
2403 
2404     conn = domain->conn;
2405 
2406     if (conn->driver->domainGetBlkioParameters) {
2407         int ret;
2408         ret = conn->driver->domainGetBlkioParameters(domain, params, nparams, flags);
2409         if (ret < 0)
2410             goto error;
2411         return ret;
2412     }
2413     virReportUnsupportedError();
2414 
2415  error:
2416     virDispatchError(domain->conn);
2417     return -1;
2418 }
2419 
2420 
2421 /**
2422  * virDomainGetInfo:
2423  * @domain: a domain object
2424  * @info: pointer to a virDomainInfo structure allocated by the user
2425  *
2426  * Extract information about a domain. Note that if the connection
2427  * used to get the domain is limited only a partial set of the information
2428  * can be extracted.
2429  *
2430  * Returns 0 in case of success and -1 in case of failure.
2431  */
2432 int
virDomainGetInfo(virDomainPtr domain,virDomainInfoPtr info)2433 virDomainGetInfo(virDomainPtr domain, virDomainInfoPtr info)
2434 {
2435     virConnectPtr conn;
2436 
2437     VIR_DOMAIN_DEBUG(domain, "info=%p", info);
2438 
2439     virResetLastError();
2440 
2441     if (info)
2442         memset(info, 0, sizeof(*info));
2443 
2444     virCheckDomainReturn(domain, -1);
2445     virCheckNonNullArgGoto(info, error);
2446 
2447     conn = domain->conn;
2448 
2449     if (conn->driver->domainGetInfo) {
2450         int ret;
2451         ret = conn->driver->domainGetInfo(domain, info);
2452         if (ret < 0)
2453             goto error;
2454         return ret;
2455     }
2456 
2457     virReportUnsupportedError();
2458 
2459  error:
2460     virDispatchError(domain->conn);
2461     return -1;
2462 }
2463 
2464 
2465 /**
2466  * virDomainGetState:
2467  * @domain: a domain object
2468  * @state: returned state of the domain (one of virDomainState)
2469  * @reason: returned reason which led to @state (one of virDomain*Reason
2470  * corresponding to the current state); it is allowed to be NULL
2471  * @flags: extra flags; not used yet, so callers should always pass 0
2472  *
2473  * Extract domain state. Each state can be accompanied with a reason (if known)
2474  * which led to the state.
2475  *
2476  * Returns 0 in case of success and -1 in case of failure.
2477  */
2478 int
virDomainGetState(virDomainPtr domain,int * state,int * reason,unsigned int flags)2479 virDomainGetState(virDomainPtr domain,
2480                   int *state,
2481                   int *reason,
2482                   unsigned int flags)
2483 {
2484     virConnectPtr conn;
2485 
2486     VIR_DOMAIN_DEBUG(domain, "state=%p, reason=%p, flags=0x%x",
2487                      state, reason, flags);
2488 
2489     virResetLastError();
2490 
2491     virCheckDomainReturn(domain, -1);
2492     virCheckNonNullArgGoto(state, error);
2493 
2494     conn = domain->conn;
2495     if (conn->driver->domainGetState) {
2496         int ret;
2497         ret = conn->driver->domainGetState(domain, state, reason, flags);
2498         if (ret < 0)
2499             goto error;
2500         return ret;
2501     }
2502 
2503     virReportUnsupportedError();
2504 
2505  error:
2506     virDispatchError(domain->conn);
2507     return -1;
2508 }
2509 
2510 
2511 /**
2512  * virDomainGetControlInfo:
2513  * @domain: a domain object
2514  * @info: pointer to a virDomainControlInfo structure allocated by the user
2515  * @flags: extra flags; not used yet, so callers should always pass 0
2516  *
2517  * Extract details about current state of control interface to a domain.
2518  *
2519  * Returns 0 in case of success and -1 in case of failure.
2520  */
2521 int
virDomainGetControlInfo(virDomainPtr domain,virDomainControlInfoPtr info,unsigned int flags)2522 virDomainGetControlInfo(virDomainPtr domain,
2523                         virDomainControlInfoPtr info,
2524                         unsigned int flags)
2525 {
2526     virConnectPtr conn;
2527 
2528     VIR_DOMAIN_DEBUG(domain, "info=%p, flags=0x%x", info, flags);
2529 
2530     virResetLastError();
2531 
2532     virCheckDomainReturn(domain, -1);
2533     virCheckNonNullArgGoto(info, error);
2534 
2535     conn = domain->conn;
2536     if (conn->driver->domainGetControlInfo) {
2537         int ret;
2538         ret = conn->driver->domainGetControlInfo(domain, info, flags);
2539         if (ret < 0)
2540             goto error;
2541         return ret;
2542     }
2543 
2544     virReportUnsupportedError();
2545 
2546  error:
2547     virDispatchError(domain->conn);
2548     return -1;
2549 }
2550 
2551 
2552 /**
2553  * virDomainGetXMLDesc:
2554  * @domain: a domain object
2555  * @flags: bitwise-OR of virDomainXMLFlags
2556  *
2557  * Provide an XML description of the domain. The description may be reused
2558  * later to relaunch the domain with virDomainCreateXML().
2559  *
2560  * No security-sensitive data will be included unless @flags contains
2561  * VIR_DOMAIN_XML_SECURE; this flag is rejected on read-only
2562  * connections.  If @flags includes VIR_DOMAIN_XML_INACTIVE, then the
2563  * XML represents the configuration that will be used on the next boot
2564  * of a persistent domain; otherwise, the configuration represents the
2565  * currently running domain.  If @flags contains
2566  * VIR_DOMAIN_XML_UPDATE_CPU, then the portion of the domain XML
2567  * describing CPU capabilities is modified to match actual
2568  * capabilities of the host.
2569  *
2570  * If @flags contains VIR_DOMAIN_XML_MIGRATABLE, the XML is altered to
2571  * assist in migrations, since the source and destination may be
2572  * running different libvirt versions.  This may include trimming
2573  * redundant or default information that might confuse an older
2574  * recipient, or exposing internal details that aid a newer recipient;
2575  * this flag is rejected on read-only connections, and the resulting
2576  * XML might not validate against the schema, so it is mainly for
2577  * internal use.
2578  *
2579  * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case
2580  * of error. The caller must free() the returned value.
2581  */
2582 char *
virDomainGetXMLDesc(virDomainPtr domain,unsigned int flags)2583 virDomainGetXMLDesc(virDomainPtr domain, unsigned int flags)
2584 {
2585     virConnectPtr conn;
2586 
2587     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
2588 
2589     virResetLastError();
2590 
2591     virCheckDomainReturn(domain, NULL);
2592     conn = domain->conn;
2593 
2594     if ((conn->flags & VIR_CONNECT_RO) &&
2595         (flags & (VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_MIGRATABLE))) {
2596         virReportError(VIR_ERR_OPERATION_DENIED, "%s",
2597                        _("virDomainGetXMLDesc with secure flag"));
2598         goto error;
2599     }
2600 
2601     if (conn->driver->domainGetXMLDesc) {
2602         char *ret;
2603         ret = conn->driver->domainGetXMLDesc(domain, flags);
2604         if (!ret)
2605             goto error;
2606         return ret;
2607     }
2608 
2609     virReportUnsupportedError();
2610 
2611  error:
2612     virDispatchError(domain->conn);
2613     return NULL;
2614 }
2615 
2616 
2617 /**
2618  * virConnectDomainXMLFromNative:
2619  * @conn: a connection object
2620  * @nativeFormat: configuration format importing from
2621  * @nativeConfig: the configuration data to import
2622  * @flags: extra flags; not used yet, so callers should always pass 0
2623  *
2624  * Reads native configuration data  describing a domain, and
2625  * generates libvirt domain XML. The format of the native
2626  * data is hypervisor dependent.
2627  *
2628  * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case
2629  * of error. The caller must free() the returned value.
2630  */
2631 char *
virConnectDomainXMLFromNative(virConnectPtr conn,const char * nativeFormat,const char * nativeConfig,unsigned int flags)2632 virConnectDomainXMLFromNative(virConnectPtr conn,
2633                               const char *nativeFormat,
2634                               const char *nativeConfig,
2635                               unsigned int flags)
2636 {
2637     VIR_DEBUG("conn=%p, format=%s, config=%s, flags=0x%x",
2638               conn, NULLSTR(nativeFormat), NULLSTR(nativeConfig), flags);
2639 
2640     virResetLastError();
2641 
2642     virCheckConnectReturn(conn, NULL);
2643     virCheckReadOnlyGoto(conn->flags, error);
2644 
2645     virCheckNonNullArgGoto(nativeFormat, error);
2646     virCheckNonNullArgGoto(nativeConfig, error);
2647 
2648     if (conn->driver->connectDomainXMLFromNative) {
2649         char *ret;
2650         ret = conn->driver->connectDomainXMLFromNative(conn,
2651                                                        nativeFormat,
2652                                                        nativeConfig,
2653                                                        flags);
2654         if (!ret)
2655             goto error;
2656         return ret;
2657     }
2658 
2659     virReportUnsupportedError();
2660 
2661  error:
2662     virDispatchError(conn);
2663     return NULL;
2664 }
2665 
2666 
2667 /**
2668  * virConnectDomainXMLToNative:
2669  * @conn: a connection object
2670  * @nativeFormat: configuration format exporting to
2671  * @domainXml: the domain configuration to export
2672  * @flags: extra flags; not used yet, so callers should always pass 0
2673  *
2674  * Reads a domain XML configuration document, and generates
2675  * a native configuration file describing the domain.
2676  * The format of the native data is hypervisor dependent.
2677  *
2678  * Returns a 0 terminated UTF-8 encoded native config datafile, or
2679  * NULL in case of error. The caller must free() the returned value.
2680  */
2681 char *
virConnectDomainXMLToNative(virConnectPtr conn,const char * nativeFormat,const char * domainXml,unsigned int flags)2682 virConnectDomainXMLToNative(virConnectPtr conn,
2683                             const char *nativeFormat,
2684                             const char *domainXml,
2685                             unsigned int flags)
2686 {
2687     VIR_DEBUG("conn=%p, format=%s, xml=%s, flags=0x%x",
2688               conn, NULLSTR(nativeFormat), NULLSTR(domainXml), flags);
2689 
2690     virResetLastError();
2691 
2692     virCheckConnectReturn(conn, NULL);
2693     virCheckReadOnlyGoto(conn->flags, error);
2694 
2695     virCheckNonNullArgGoto(nativeFormat, error);
2696     virCheckNonNullArgGoto(domainXml, error);
2697 
2698     if (conn->driver->connectDomainXMLToNative) {
2699         char *ret;
2700         ret = conn->driver->connectDomainXMLToNative(conn,
2701                                                      nativeFormat,
2702                                                      domainXml,
2703                                                      flags);
2704         if (!ret)
2705             goto error;
2706         return ret;
2707     }
2708 
2709     virReportUnsupportedError();
2710 
2711  error:
2712     virDispatchError(conn);
2713     return NULL;
2714 }
2715 
2716 
2717 /*
2718  * Sequence v1:
2719  *
2720  *  Dst: Prepare
2721  *        - Get ready to accept incoming VM
2722  *        - Generate optional cookie to pass to src
2723  *
2724  *  Src: Perform
2725  *        - Start migration and wait for send completion
2726  *        - Kill off VM if successful, resume if failed
2727  *
2728  *  Dst: Finish
2729  *        - Wait for recv completion and check status
2730  *        - Kill off VM if unsuccessful
2731  *
2732  */
2733 static virDomainPtr
virDomainMigrateVersion1(virDomainPtr domain,virConnectPtr dconn,unsigned long flags,const char * dname,const char * uri,unsigned long bandwidth)2734 virDomainMigrateVersion1(virDomainPtr domain,
2735                          virConnectPtr dconn,
2736                          unsigned long flags,
2737                          const char *dname,
2738                          const char *uri,
2739                          unsigned long bandwidth)
2740 {
2741     g_autofree char *uri_out = NULL;
2742     g_autofree char *cookie = NULL;
2743     int cookielen = 0, ret;
2744     virDomainInfo info;
2745     unsigned int destflags;
2746 
2747     VIR_DOMAIN_DEBUG(domain,
2748                      "dconn=%p, flags=0x%lx, dname=%s, uri=%s, bandwidth=%lu",
2749                      dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth);
2750 
2751     ret = virDomainGetInfo(domain, &info);
2752     if (ret == 0 && info.state == VIR_DOMAIN_PAUSED)
2753         flags |= VIR_MIGRATE_PAUSED;
2754 
2755     destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR |
2756                           VIR_MIGRATE_AUTO_CONVERGE);
2757 
2758     /* Prepare the migration.
2759      *
2760      * The destination host may return a cookie, or leave cookie as
2761      * NULL.
2762      *
2763      * The destination host MUST set uri_out if uri_in is NULL.
2764      *
2765      * If uri_in is non-NULL, then the destination host may modify
2766      * the URI by setting uri_out.  If it does not wish to modify
2767      * the URI, it should leave uri_out as NULL.
2768      */
2769     if (dconn->driver->domainMigratePrepare
2770         (dconn, &cookie, &cookielen, uri, &uri_out, destflags, dname,
2771          bandwidth) == -1)
2772         return NULL;
2773 
2774     if (uri == NULL && uri_out == NULL) {
2775         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2776                        _("domainMigratePrepare did not set uri"));
2777         return NULL;
2778     }
2779     if (uri_out)
2780         uri = uri_out; /* Did domainMigratePrepare change URI? */
2781 
2782     /* Perform the migration.  The driver isn't supposed to return
2783      * until the migration is complete.
2784      */
2785     if (domain->conn->driver->domainMigratePerform
2786         (domain, cookie, cookielen, uri, flags, dname, bandwidth) == -1)
2787         return NULL;
2788 
2789     /* Get the destination domain and return it or error.
2790      * 'domain' no longer actually exists at this point
2791      * (or so we hope), but we still use the object in memory
2792      * in order to get the name.
2793      */
2794     dname = dname ? dname : domain->name;
2795     if (dconn->driver->domainMigrateFinish)
2796         return dconn->driver->domainMigrateFinish
2797             (dconn, dname, cookie, cookielen, uri, destflags);
2798 
2799     return virDomainLookupByName(dconn, dname);
2800 }
2801 
2802 
2803 /*
2804  * Sequence v2:
2805  *
2806  *  Src: DumpXML
2807  *        - Generate XML to pass to dst
2808  *
2809  *  Dst: Prepare
2810  *        - Get ready to accept incoming VM
2811  *        - Generate optional cookie to pass to src
2812  *
2813  *  Src: Perform
2814  *        - Start migration and wait for send completion
2815  *        - Kill off VM if successful, resume if failed
2816  *
2817  *  Dst: Finish
2818  *        - Wait for recv completion and check status
2819  *        - Kill off VM if unsuccessful
2820  *
2821  */
2822 static virDomainPtr
virDomainMigrateVersion2(virDomainPtr domain,virConnectPtr dconn,unsigned long flags,const char * dname,const char * uri,unsigned long bandwidth)2823 virDomainMigrateVersion2(virDomainPtr domain,
2824                          virConnectPtr dconn,
2825                          unsigned long flags,
2826                          const char *dname,
2827                          const char *uri,
2828                          unsigned long bandwidth)
2829 {
2830     virDomainPtr ddomain = NULL;
2831     g_autofree char *uri_out = NULL;
2832     g_autofree char *cookie = NULL;
2833     g_autofree char *dom_xml = NULL;
2834     int cookielen = 0, ret;
2835     virDomainInfo info;
2836     virErrorPtr orig_err = NULL;
2837     unsigned int getxml_flags = 0;
2838     int cancelled;
2839     unsigned long destflags;
2840 
2841     VIR_DOMAIN_DEBUG(domain,
2842                      "dconn=%p, flags=0x%lx, dname=%s, uri=%s, bandwidth=%lu",
2843                      dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth);
2844 
2845     /* Prepare the migration.
2846      *
2847      * The destination host may return a cookie, or leave cookie as
2848      * NULL.
2849      *
2850      * The destination host MUST set uri_out if uri_in is NULL.
2851      *
2852      * If uri_in is non-NULL, then the destination host may modify
2853      * the URI by setting uri_out.  If it does not wish to modify
2854      * the URI, it should leave uri_out as NULL.
2855      */
2856 
2857     /* In version 2 of the protocol, the prepare step is slightly
2858      * different.  We fetch the domain XML of the source domain
2859      * and pass it to Prepare2.
2860      */
2861     if (!domain->conn->driver->domainGetXMLDesc) {
2862         virReportUnsupportedError();
2863         return NULL;
2864     }
2865 
2866     ret = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
2867                                    VIR_DRV_FEATURE_XML_MIGRATABLE);
2868     if (ret < 0)
2869         return NULL;
2870     if (ret)
2871         getxml_flags |= VIR_DOMAIN_XML_MIGRATABLE;
2872     else
2873         getxml_flags |= VIR_DOMAIN_XML_SECURE | VIR_DOMAIN_XML_UPDATE_CPU;
2874 
2875     dom_xml = domain->conn->driver->domainGetXMLDesc(domain, getxml_flags);
2876     if (!dom_xml)
2877         return NULL;
2878 
2879     ret = virDomainGetInfo(domain, &info);
2880     if (ret == 0 && info.state == VIR_DOMAIN_PAUSED)
2881         flags |= VIR_MIGRATE_PAUSED;
2882 
2883     destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR |
2884                           VIR_MIGRATE_AUTO_CONVERGE);
2885 
2886     VIR_DEBUG("Prepare2 %p flags=0x%lx", dconn, destflags);
2887     ret = dconn->driver->domainMigratePrepare2
2888         (dconn, &cookie, &cookielen, uri, &uri_out, destflags, dname,
2889          bandwidth, dom_xml);
2890     if (ret == -1)
2891         goto done;
2892 
2893     if (uri == NULL && uri_out == NULL) {
2894         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
2895                        _("domainMigratePrepare2 did not set uri"));
2896         cancelled = 1;
2897         /* Make sure Finish doesn't overwrite the error */
2898         virErrorPreserveLast(&orig_err);
2899         goto finish;
2900     }
2901     if (uri_out)
2902         uri = uri_out; /* Did domainMigratePrepare2 change URI? */
2903 
2904     /* Perform the migration.  The driver isn't supposed to return
2905      * until the migration is complete.
2906      */
2907     VIR_DEBUG("Perform %p", domain->conn);
2908     ret = domain->conn->driver->domainMigratePerform
2909         (domain, cookie, cookielen, uri, flags, dname, bandwidth);
2910 
2911     /* Perform failed. Make sure Finish doesn't overwrite the error */
2912     if (ret < 0)
2913         virErrorPreserveLast(&orig_err);
2914 
2915     /* If Perform returns < 0, then we need to cancel the VM
2916      * startup on the destination
2917      */
2918     cancelled = ret < 0 ? 1 : 0;
2919 
2920  finish:
2921     /* In version 2 of the migration protocol, we pass the
2922      * status code from the sender to the destination host,
2923      * so it can do any cleanup if the migration failed.
2924      */
2925     dname = dname ? dname : domain->name;
2926     VIR_DEBUG("Finish2 %p ret=%d", dconn, ret);
2927     ddomain = dconn->driver->domainMigrateFinish2
2928         (dconn, dname, cookie, cookielen, uri, destflags, cancelled);
2929     if (cancelled && ddomain)
2930         VIR_ERROR(_("finish step ignored that migration was cancelled"));
2931 
2932  done:
2933     virErrorRestore(&orig_err);
2934     return ddomain;
2935 }
2936 
2937 
2938 /*
2939  * Sequence v3:
2940  *
2941  *  Src: Begin
2942  *        - Generate XML to pass to dst
2943  *        - Generate optional cookie to pass to dst
2944  *
2945  *  Dst: Prepare
2946  *        - Get ready to accept incoming VM
2947  *        - Generate optional cookie to pass to src
2948  *
2949  *  Src: Perform
2950  *        - Start migration and wait for send completion
2951  *        - Generate optional cookie to pass to dst
2952  *
2953  *  Dst: Finish
2954  *        - Wait for recv completion and check status
2955  *        - Kill off VM if failed, resume if success
2956  *        - Generate optional cookie to pass to src
2957  *
2958  *  Src: Confirm
2959  *        - Kill off VM if success, resume if failed
2960  *
2961   * If useParams is true, params and nparams contain migration parameters and
2962   * we know it's safe to call the API which supports extensible parameters.
2963   * Otherwise, we have to use xmlin, dname, uri, and bandwidth and pass them
2964   * to the old-style APIs.
2965  */
2966 static virDomainPtr
virDomainMigrateVersion3Full(virDomainPtr domain,virConnectPtr dconn,const char * xmlin,const char * dname,const char * uri,unsigned long long bandwidth,virTypedParameterPtr params,int nparams,bool useParams,unsigned int flags)2967 virDomainMigrateVersion3Full(virDomainPtr domain,
2968                              virConnectPtr dconn,
2969                              const char *xmlin,
2970                              const char *dname,
2971                              const char *uri,
2972                              unsigned long long bandwidth,
2973                              virTypedParameterPtr params,
2974                              int nparams,
2975                              bool useParams,
2976                              unsigned int flags)
2977 {
2978     virDomainPtr ddomain = NULL;
2979     g_autofree char *uri_out = NULL;
2980     g_autofree char *cookiein = NULL;
2981     g_autofree char *cookieout = NULL;
2982     g_autofree char *dom_xml = NULL;
2983     int cookieinlen = 0;
2984     int cookieoutlen = 0;
2985     int ret;
2986     virDomainInfo info;
2987     virErrorPtr orig_err = NULL;
2988     int cancelled = 1;
2989     unsigned long protection = 0;
2990     bool notify_source = true;
2991     unsigned int destflags;
2992     int state;
2993     virTypedParameterPtr tmp;
2994 
2995     VIR_DOMAIN_DEBUG(domain,
2996                      "dconn=%p, xmlin=%s, dname=%s, uri=%s, bandwidth=%llu, "
2997                      "params=%p, nparams=%d, useParams=%d, flags=0x%x",
2998                      dconn, NULLSTR(xmlin), NULLSTR(dname), NULLSTR(uri),
2999                      bandwidth, params, nparams, useParams, flags);
3000     VIR_TYPED_PARAMS_DEBUG(params, nparams);
3001 
3002     if ((!useParams &&
3003          (!domain->conn->driver->domainMigrateBegin3 ||
3004           !domain->conn->driver->domainMigratePerform3 ||
3005           !domain->conn->driver->domainMigrateConfirm3 ||
3006           !dconn->driver->domainMigratePrepare3 ||
3007           !dconn->driver->domainMigrateFinish3)) ||
3008         (useParams &&
3009          (!domain->conn->driver->domainMigrateBegin3Params ||
3010           !domain->conn->driver->domainMigratePerform3Params ||
3011           !domain->conn->driver->domainMigrateConfirm3Params ||
3012           !dconn->driver->domainMigratePrepare3Params ||
3013           !dconn->driver->domainMigrateFinish3Params))) {
3014         virReportUnsupportedError();
3015         return NULL;
3016     }
3017 
3018     if (virTypedParamsCopy(&tmp, params, nparams) < 0)
3019         return NULL;
3020     params = tmp;
3021 
3022     ret = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3023                                    VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION);
3024     if (ret < 0)
3025         goto done;
3026     if (ret)
3027         protection = VIR_MIGRATE_CHANGE_PROTECTION;
3028 
3029     VIR_DEBUG("Begin3 %p", domain->conn);
3030     if (useParams) {
3031         dom_xml = domain->conn->driver->domainMigrateBegin3Params
3032             (domain, params, nparams, &cookieout, &cookieoutlen,
3033              flags | protection);
3034     } else {
3035         dom_xml = domain->conn->driver->domainMigrateBegin3
3036             (domain, xmlin, &cookieout, &cookieoutlen,
3037              flags | protection, dname, bandwidth);
3038     }
3039     if (!dom_xml)
3040         goto done;
3041 
3042     if (useParams) {
3043         /* If source is new enough to support extensible migration parameters,
3044          * it's certainly new enough to support virDomainGetState. */
3045         ret = virDomainGetState(domain, &state, NULL, 0);
3046     } else {
3047         ret = virDomainGetInfo(domain, &info);
3048         state = info.state;
3049     }
3050     if (ret == 0 && state == VIR_DOMAIN_PAUSED)
3051         flags |= VIR_MIGRATE_PAUSED;
3052 
3053     destflags = flags & ~(VIR_MIGRATE_ABORT_ON_ERROR |
3054                           VIR_MIGRATE_AUTO_CONVERGE);
3055 
3056     VIR_DEBUG("Prepare3 %p flags=0x%x", dconn, destflags);
3057     cookiein = g_steal_pointer(&cookieout);
3058     cookieinlen = cookieoutlen;
3059     cookieoutlen = 0;
3060     if (useParams) {
3061         if (virTypedParamsReplaceString(&params, &nparams,
3062                                         VIR_MIGRATE_PARAM_DEST_XML,
3063                                         dom_xml) < 0)
3064             goto done;
3065         ret = dconn->driver->domainMigratePrepare3Params
3066             (dconn, params, nparams, cookiein, cookieinlen,
3067              &cookieout, &cookieoutlen, &uri_out, destflags);
3068     } else {
3069         ret = dconn->driver->domainMigratePrepare3
3070             (dconn, cookiein, cookieinlen, &cookieout, &cookieoutlen,
3071              uri, &uri_out, destflags, dname, bandwidth, dom_xml);
3072     }
3073     if (ret == -1) {
3074         if (protection) {
3075             /* Begin already started a migration job so we need to cancel it by
3076              * calling Confirm while making sure it doesn't overwrite the error
3077              */
3078             virErrorPreserveLast(&orig_err);
3079             goto confirm;
3080         } else {
3081             goto done;
3082         }
3083     }
3084 
3085     /* Did domainMigratePrepare3 change URI? */
3086     if (uri_out) {
3087         uri = uri_out;
3088         if (useParams &&
3089             virTypedParamsReplaceString(&params, &nparams,
3090                                         VIR_MIGRATE_PARAM_URI,
3091                                         uri_out) < 0) {
3092             virErrorPreserveLast(&orig_err);
3093             goto finish;
3094         }
3095     } else if (!uri &&
3096                virTypedParamsGetString(params, nparams,
3097                                        VIR_MIGRATE_PARAM_URI, &uri) <= 0) {
3098         virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3099                        _("domainMigratePrepare3 did not set uri"));
3100         virErrorPreserveLast(&orig_err);
3101         goto finish;
3102     }
3103 
3104     if (flags & VIR_MIGRATE_OFFLINE) {
3105         VIR_DEBUG("Offline migration, skipping Perform phase");
3106         VIR_FREE(cookieout);
3107         cookieoutlen = 0;
3108         cancelled = 0;
3109         goto finish;
3110     }
3111 
3112     /* Perform the migration.  The driver isn't supposed to return
3113      * until the migration is complete. The src VM should remain
3114      * running, but in paused state until the destination can
3115      * confirm migration completion.
3116      */
3117     VIR_DEBUG("Perform3 %p uri=%s", domain->conn, uri);
3118     VIR_FREE(cookiein);
3119     cookiein = g_steal_pointer(&cookieout);
3120     cookieinlen = cookieoutlen;
3121     cookieoutlen = 0;
3122     /* dconnuri not relevant in non-P2P modes, so left NULL here */
3123     if (useParams) {
3124         ret = domain->conn->driver->domainMigratePerform3Params
3125             (domain, NULL, params, nparams, cookiein, cookieinlen,
3126              &cookieout, &cookieoutlen, flags | protection);
3127     } else {
3128         ret = domain->conn->driver->domainMigratePerform3
3129             (domain, NULL, cookiein, cookieinlen,
3130              &cookieout, &cookieoutlen, NULL,
3131              uri, flags | protection, dname, bandwidth);
3132     }
3133 
3134     /* Perform failed. Make sure Finish doesn't overwrite the error */
3135     if (ret < 0) {
3136         virErrorPreserveLast(&orig_err);
3137         /* Perform failed so we don't need to call confirm to let source know
3138          * about the failure.
3139          */
3140         notify_source = false;
3141     }
3142 
3143     /* If Perform returns < 0, then we need to cancel the VM
3144      * startup on the destination
3145      */
3146     cancelled = ret < 0 ? 1 : 0;
3147 
3148  finish:
3149     /*
3150      * The status code from the source is passed to the destination.
3151      * The dest can cleanup if the source indicated it failed to
3152      * send all migration data. Returns NULL for ddomain if
3153      * the dest was unable to complete migration.
3154      */
3155     VIR_DEBUG("Finish3 %p ret=%d", dconn, ret);
3156     VIR_FREE(cookiein);
3157     cookiein = g_steal_pointer(&cookieout);
3158     cookieinlen = cookieoutlen;
3159     cookieoutlen = 0;
3160     if (useParams) {
3161         if (virTypedParamsGetString(params, nparams,
3162                                     VIR_MIGRATE_PARAM_DEST_NAME, NULL) <= 0 &&
3163             virTypedParamsReplaceString(&params, &nparams,
3164                                         VIR_MIGRATE_PARAM_DEST_NAME,
3165                                         domain->name) < 0) {
3166             ddomain = NULL;
3167         } else {
3168             ddomain = dconn->driver->domainMigrateFinish3Params
3169                 (dconn, params, nparams, cookiein, cookieinlen,
3170                  &cookieout, &cookieoutlen, destflags, cancelled);
3171         }
3172     } else {
3173         dname = dname ? dname : domain->name;
3174         ddomain = dconn->driver->domainMigrateFinish3
3175             (dconn, dname, cookiein, cookieinlen, &cookieout, &cookieoutlen,
3176              NULL, uri, destflags, cancelled);
3177     }
3178 
3179     if (cancelled) {
3180         if (ddomain) {
3181             VIR_ERROR(_("finish step ignored that migration was cancelled"));
3182         } else {
3183             /* If Finish reported a useful error, use it instead of the
3184              * original "migration unexpectedly failed" error.
3185              *
3186              * This is ugly but we can't do better with the APIs we have. We
3187              * only replace the error if Finish was called with cancelled == 1
3188              * and reported a real error (old libvirt would report an error
3189              * from RPC instead of MIGRATE_FINISH_OK), which only happens when
3190              * the domain died on destination. To further reduce a possibility
3191              * of false positives we also check that Perform returned
3192              * VIR_ERR_OPERATION_FAILED.
3193              */
3194             if (orig_err &&
3195                 orig_err->domain == VIR_FROM_QEMU &&
3196                 orig_err->code == VIR_ERR_OPERATION_FAILED) {
3197                 virErrorPtr err = virGetLastError();
3198                 if (err &&
3199                     err->domain == VIR_FROM_QEMU &&
3200                     err->code != VIR_ERR_MIGRATE_FINISH_OK) {
3201                     virFreeError(orig_err);
3202                     orig_err = NULL;
3203                 }
3204             }
3205         }
3206     }
3207 
3208     /* If ddomain is NULL, then we were unable to start
3209      * the guest on the target, and must restart on the
3210      * source. There is a small chance that the ddomain
3211      * is NULL due to an RPC failure, in which case
3212      * ddomain could in fact be running on the dest.
3213      * The lock manager plugins should take care of
3214      * safety in this scenario.
3215      */
3216     cancelled = ddomain == NULL ? 1 : 0;
3217 
3218     /* If finish3 set an error, and we don't have an earlier
3219      * one we need to preserve it in case confirm3 overwrites
3220      */
3221     if (!orig_err)
3222         virErrorPreserveLast(&orig_err);
3223 
3224  confirm:
3225     /*
3226      * If cancelled, then src VM will be restarted, else it will be killed.
3227      * Don't do this if migration failed on source and thus it was already
3228      * cancelled there.
3229      */
3230     if (notify_source) {
3231         VIR_DEBUG("Confirm3 %p ret=%d domain=%p", domain->conn, ret, domain);
3232         VIR_FREE(cookiein);
3233         cookiein = g_steal_pointer(&cookieout);
3234         cookieinlen = cookieoutlen;
3235         cookieoutlen = 0;
3236         if (useParams) {
3237             ret = domain->conn->driver->domainMigrateConfirm3Params
3238                 (domain, params, nparams, cookiein, cookieinlen,
3239                  flags | protection, cancelled);
3240         } else {
3241             ret = domain->conn->driver->domainMigrateConfirm3
3242                 (domain, cookiein, cookieinlen,
3243                  flags | protection, cancelled);
3244         }
3245         /* If Confirm3 returns -1, there's nothing more we can
3246          * do, but fortunately worst case is that there is a
3247          * domain left in 'paused' state on source.
3248          */
3249         if (ret < 0) {
3250             VIR_WARN("Guest %s probably left in 'paused' state on source",
3251                      domain->name);
3252         }
3253     }
3254 
3255  done:
3256     virErrorRestore(&orig_err);
3257     virTypedParamsFree(params, nparams);
3258     return ddomain;
3259 }
3260 
3261 
3262 static virDomainPtr
virDomainMigrateVersion3(virDomainPtr domain,virConnectPtr dconn,const char * xmlin,unsigned long flags,const char * dname,const char * uri,unsigned long bandwidth)3263 virDomainMigrateVersion3(virDomainPtr domain,
3264                          virConnectPtr dconn,
3265                          const char *xmlin,
3266                          unsigned long flags,
3267                          const char *dname,
3268                          const char *uri,
3269                          unsigned long bandwidth)
3270 {
3271     return virDomainMigrateVersion3Full(domain, dconn, xmlin, dname, uri,
3272                                         bandwidth, NULL, 0, false, flags);
3273 }
3274 
3275 
3276 static virDomainPtr
virDomainMigrateVersion3Params(virDomainPtr domain,virConnectPtr dconn,virTypedParameterPtr params,int nparams,unsigned int flags)3277 virDomainMigrateVersion3Params(virDomainPtr domain,
3278                                virConnectPtr dconn,
3279                                virTypedParameterPtr params,
3280                                int nparams,
3281                                unsigned int flags)
3282 {
3283     return virDomainMigrateVersion3Full(domain, dconn, NULL, NULL, NULL, 0,
3284                                         params, nparams, true, flags);
3285 }
3286 
3287 int
virDomainMigrateCheckNotLocal(const char * dconnuri)3288 virDomainMigrateCheckNotLocal(const char *dconnuri)
3289 {
3290     g_autoptr(virURI) tempuri = NULL;
3291 
3292     if (!(tempuri = virURIParse(dconnuri)))
3293         return -1;
3294 
3295     /*
3296      * If someone migrates explicitly to a unix socket, then they have to know
3297      * what they are doing and it most probably was not a mistake.
3298      */
3299     if ((tempuri->server && STRPREFIX(tempuri->server, "localhost")) ||
3300         (!tempuri->server && !virURICheckUnixSocket(tempuri))) {
3301         virReportInvalidArg(dconnuri, "%s",
3302                             _("Attempt to migrate guest to the same host"));
3303         return -1;
3304     }
3305 
3306     return 0;
3307 }
3308 
3309 
3310 static int
virDomainMigrateUnmanagedProto2(virDomainPtr domain,const char * dconnuri,virTypedParameterPtr params,int nparams,unsigned int flags)3311 virDomainMigrateUnmanagedProto2(virDomainPtr domain,
3312                                 const char *dconnuri,
3313                                 virTypedParameterPtr params,
3314                                 int nparams,
3315                                 unsigned int flags)
3316 {
3317     /* uri parameter is added for direct case */
3318     const char *compatParams[] = { VIR_MIGRATE_PARAM_DEST_NAME,
3319                                    VIR_MIGRATE_PARAM_BANDWIDTH,
3320                                    VIR_MIGRATE_PARAM_URI };
3321     const char *uri = NULL;
3322     const char *miguri = NULL;
3323     const char *dname = NULL;
3324     unsigned long long bandwidth = 0;
3325 
3326     if (!virTypedParamsCheck(params, nparams, compatParams,
3327                              G_N_ELEMENTS(compatParams))) {
3328         virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3329                        _("Some parameters are not supported by migration "
3330                          "protocol 2"));
3331         return -1;
3332     }
3333 
3334     if (virTypedParamsGetString(params, nparams,
3335                                 VIR_MIGRATE_PARAM_URI, &miguri) < 0 ||
3336         virTypedParamsGetString(params, nparams,
3337                                 VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 ||
3338         virTypedParamsGetULLong(params, nparams,
3339                                 VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) {
3340         return -1;
3341     }
3342 
3343     if (flags & VIR_MIGRATE_PEER2PEER) {
3344         if (miguri) {
3345             virReportError(VIR_ERR_INTERNAL_ERROR, "%s",
3346                            _("Unable to override peer2peer migration URI"));
3347             return -1;
3348         }
3349         uri = dconnuri;
3350     } else {
3351         uri = miguri;
3352     }
3353 
3354     return domain->conn->driver->domainMigratePerform
3355             (domain, NULL, 0, uri, flags, dname, bandwidth);
3356 }
3357 
3358 
3359 static int
virDomainMigrateUnmanagedProto3(virDomainPtr domain,const char * dconnuri,virTypedParameterPtr params,int nparams,unsigned int flags)3360 virDomainMigrateUnmanagedProto3(virDomainPtr domain,
3361                                 const char *dconnuri,
3362                                 virTypedParameterPtr params,
3363                                 int nparams,
3364                                 unsigned int flags)
3365 {
3366     const char *compatParams[] = { VIR_MIGRATE_PARAM_URI,
3367                                    VIR_MIGRATE_PARAM_DEST_NAME,
3368                                    VIR_MIGRATE_PARAM_DEST_XML,
3369                                    VIR_MIGRATE_PARAM_BANDWIDTH };
3370     const char *miguri = NULL;
3371     const char *dname = NULL;
3372     const char *xmlin = NULL;
3373     unsigned long long bandwidth = 0;
3374 
3375     if (!virTypedParamsCheck(params, nparams, compatParams,
3376                              G_N_ELEMENTS(compatParams))) {
3377         virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3378                        _("Some parameters are not supported by migration "
3379                          "protocol 3"));
3380         return -1;
3381     }
3382 
3383     if (virTypedParamsGetString(params, nparams,
3384                                 VIR_MIGRATE_PARAM_URI, &miguri) < 0 ||
3385         virTypedParamsGetString(params, nparams,
3386                                 VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 ||
3387         virTypedParamsGetString(params, nparams,
3388                                 VIR_MIGRATE_PARAM_DEST_XML, &xmlin) < 0 ||
3389         virTypedParamsGetULLong(params, nparams,
3390                                 VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) {
3391         return -1;
3392     }
3393 
3394     return domain->conn->driver->domainMigratePerform3
3395             (domain, xmlin, NULL, 0, NULL, NULL, dconnuri,
3396              miguri, flags, dname, bandwidth);
3397 }
3398 
3399 
3400 /*
3401  * In normal migration, the libvirt client coordinates communication
3402  * between the 2 libvirtd instances on source & dest hosts.
3403  *
3404  * This function encapsulates 2 alternatives to the above case.
3405  *
3406  * 1. peer-2-peer migration, the libvirt client only talks to the source
3407  * libvirtd instance. The source libvirtd then opens its own
3408  * connection to the destination and coordinates migration itself.
3409  *
3410  * 2. direct migration, where there is no requirement for a libvirtd instance
3411  * on the dest host. Eg, XenD can talk direct to XenD, so libvirtd on dest
3412  * does not need to be involved at all, or even running.
3413  */
3414 static int
virDomainMigrateUnmanagedParams(virDomainPtr domain,const char * dconnuri,virTypedParameterPtr params,int nparams,unsigned int flags)3415 virDomainMigrateUnmanagedParams(virDomainPtr domain,
3416                                 const char *dconnuri,
3417                                 virTypedParameterPtr params,
3418                                 int nparams,
3419                                 unsigned int flags)
3420 {
3421     int rc;
3422 
3423     VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparams=%d, flags=0x%x",
3424                      NULLSTR(dconnuri), params, nparams, flags);
3425     VIR_TYPED_PARAMS_DEBUG(params, nparams);
3426 
3427     if ((flags & VIR_MIGRATE_PEER2PEER) &&
3428         virDomainMigrateCheckNotLocal(dconnuri) < 0)
3429         return -1;
3430 
3431     if (flags & VIR_MIGRATE_PEER2PEER) {
3432         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3433                                       VIR_DRV_FEATURE_MIGRATION_PARAMS);
3434         if (rc < 0)
3435             return -1;
3436         if (rc) {
3437             VIR_DEBUG("Using migration protocol 3 with extensible parameters");
3438             if (!domain->conn->driver->domainMigratePerform3Params) {
3439                 virReportUnsupportedError();
3440                 return -1;
3441             }
3442             return domain->conn->driver->domainMigratePerform3Params
3443                     (domain, dconnuri, params, nparams,
3444                      NULL, 0, NULL, NULL, flags);
3445         }
3446     }
3447 
3448     rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3449                                   VIR_DRV_FEATURE_MIGRATION_V3);
3450     if (rc < 0)
3451         return -1;
3452     if (rc) {
3453         VIR_DEBUG("Using migration protocol 3");
3454         if (!domain->conn->driver->domainMigratePerform3) {
3455             virReportUnsupportedError();
3456             return -1;
3457         }
3458         return virDomainMigrateUnmanagedProto3(domain, dconnuri,
3459                                                params, nparams, flags);
3460     } else {
3461         VIR_DEBUG("Using migration protocol 2");
3462         if (!domain->conn->driver->domainMigratePerform) {
3463             virReportUnsupportedError();
3464             return -1;
3465         }
3466         return virDomainMigrateUnmanagedProto2(domain, dconnuri,
3467                                                params, nparams, flags);
3468     }
3469 }
3470 
3471 
3472 static int
virDomainMigrateUnmanaged(virDomainPtr domain,const char * xmlin,unsigned int flags,const char * dname,const char * dconnuri,const char * miguri,unsigned long long bandwidth)3473 virDomainMigrateUnmanaged(virDomainPtr domain,
3474                           const char *xmlin,
3475                           unsigned int flags,
3476                           const char *dname,
3477                           const char *dconnuri,
3478                           const char *miguri,
3479                           unsigned long long bandwidth)
3480 {
3481     int ret = -1;
3482     virTypedParameterPtr params = NULL;
3483     int nparams = 0;
3484     int maxparams = 0;
3485 
3486     if (miguri &&
3487         virTypedParamsAddString(&params, &nparams, &maxparams,
3488                                 VIR_MIGRATE_PARAM_URI, miguri) < 0)
3489         goto cleanup;
3490     if (dname &&
3491         virTypedParamsAddString(&params, &nparams, &maxparams,
3492                                 VIR_MIGRATE_PARAM_DEST_NAME, dname) < 0)
3493         goto cleanup;
3494     if (xmlin &&
3495         virTypedParamsAddString(&params, &nparams, &maxparams,
3496                                 VIR_MIGRATE_PARAM_DEST_XML, xmlin) < 0)
3497         goto cleanup;
3498     if (virTypedParamsAddULLong(&params, &nparams, &maxparams,
3499                                 VIR_MIGRATE_PARAM_BANDWIDTH, bandwidth) < 0)
3500         goto cleanup;
3501 
3502     ret = virDomainMigrateUnmanagedParams(domain, dconnuri, params,
3503                                           nparams, flags);
3504 
3505  cleanup:
3506     virTypedParamsFree(params, nparams);
3507 
3508     return ret;
3509 }
3510 
3511 
3512 /**
3513  * virDomainMigrate:
3514  * @domain: a domain object
3515  * @dconn: destination host (a connection object)
3516  * @flags: bitwise-OR of virDomainMigrateFlags
3517  * @dname: (optional) rename domain to this at destination
3518  * @uri: (optional) dest hostname/URI as seen from the source host
3519  * @bandwidth: (optional) specify migration bandwidth limit in MiB/s
3520  *
3521  * Migrate the domain object from its current host to the destination
3522  * host given by dconn (a connection to the destination host).
3523  *
3524  * This function is similar to virDomainMigrate3, but it only supports a fixed
3525  * set of parameters: @dname corresponds to VIR_MIGRATE_PARAM_DEST_NAME, @uri
3526  * is VIR_MIGRATE_PARAM_URI, and @bandwidth is VIR_MIGRATE_PARAM_BANDWIDTH.
3527  *
3528  * virDomainFree should be used to free the resources after the
3529  * returned domain object is no longer needed.
3530  *
3531  * Returns the new domain object if the migration was successful,
3532  *   or NULL in case of error.  Note that the new domain object
3533  *   exists in the scope of the destination connection (dconn).
3534  */
3535 virDomainPtr
virDomainMigrate(virDomainPtr domain,virConnectPtr dconn,unsigned long flags,const char * dname,const char * uri,unsigned long bandwidth)3536 virDomainMigrate(virDomainPtr domain,
3537                  virConnectPtr dconn,
3538                  unsigned long flags,
3539                  const char *dname,
3540                  const char *uri,
3541                  unsigned long bandwidth)
3542 {
3543     virDomainPtr ddomain = NULL;
3544     int rc_src;
3545     int rc_dst;
3546     int rc;
3547 
3548     VIR_DOMAIN_DEBUG(domain,
3549                      "dconn=%p, flags=0x%lx, dname=%s, uri=%s, bandwidth=%lu",
3550                      dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth);
3551 
3552     virResetLastError();
3553 
3554     /* First checkout the source */
3555     virCheckDomainReturn(domain, NULL);
3556     virCheckReadOnlyGoto(domain->conn->flags, error);
3557 
3558     /* Now checkout the destination */
3559     virCheckConnectGoto(dconn, error);
3560     virCheckReadOnlyGoto(dconn->flags, error);
3561 
3562     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_NON_SHARED_DISK,
3563                              VIR_MIGRATE_NON_SHARED_INC,
3564                              error);
3565 
3566     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_TUNNELLED,
3567                              VIR_MIGRATE_PARALLEL,
3568                              error);
3569 
3570     if (flags & VIR_MIGRATE_OFFLINE) {
3571         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3572                                       VIR_DRV_FEATURE_MIGRATION_OFFLINE);
3573         if (rc <= 0) {
3574             if (rc == 0)
3575                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3576                                _("offline migration is not supported by "
3577                                  "the source host"));
3578             goto error;
3579         }
3580 
3581         rc = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
3582                                       VIR_DRV_FEATURE_MIGRATION_OFFLINE);
3583         if (rc <= 0) {
3584             if (rc == 0)
3585                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3586                                _("offline migration is not supported by "
3587                                  "the destination host"));
3588             goto error;
3589         }
3590     }
3591 
3592     if (flags & VIR_MIGRATE_PEER2PEER) {
3593         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3594                                       VIR_DRV_FEATURE_MIGRATION_P2P);
3595         if (rc < 0)
3596             goto error;
3597         if (rc) {
3598             g_autofree char *dstURI = NULL;
3599             if (uri == NULL) {
3600                 dstURI = virConnectGetURI(dconn);
3601                 if (!dstURI)
3602                     return NULL;
3603             }
3604 
3605             VIR_DEBUG("Using peer2peer migration");
3606             if (virDomainMigrateUnmanaged(domain, NULL, flags, dname,
3607                                           uri ? uri : dstURI, NULL, bandwidth) < 0)
3608                 goto error;
3609 
3610             ddomain = virDomainLookupByName(dconn, dname ? dname : domain->name);
3611         } else {
3612             /* This driver does not support peer to peer migration */
3613             virReportUnsupportedError();
3614             goto error;
3615         }
3616     } else {
3617         /* Change protection requires support only on source side, and
3618          * is only needed in v3 migration, which automatically re-adds
3619          * the flag for just the source side.  We mask it out for
3620          * non-peer2peer to allow migration from newer source to an
3621          * older destination that rejects the flag.  */
3622         if (flags & VIR_MIGRATE_CHANGE_PROTECTION) {
3623             rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3624                                           VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION);
3625             if (rc <= 0) {
3626                 if (rc == 0)
3627                     virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3628                                    _("cannot enforce change protection"));
3629                 goto error;
3630             }
3631         }
3632         flags &= ~VIR_MIGRATE_CHANGE_PROTECTION;
3633         if (flags & VIR_MIGRATE_TUNNELLED) {
3634             virReportError(VIR_ERR_OPERATION_INVALID, "%s",
3635                            _("cannot perform tunnelled migration without using peer2peer flag"));
3636             goto error;
3637         }
3638 
3639         /* Check that migration is supported by both drivers. */
3640         rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3641                                           VIR_DRV_FEATURE_MIGRATION_V3);
3642         if (rc_src < 0)
3643             goto error;
3644         rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
3645                                           VIR_DRV_FEATURE_MIGRATION_V3);
3646         if (rc_dst < 0)
3647             goto error;
3648         if (rc_src && rc_dst) {
3649             VIR_DEBUG("Using migration protocol 3");
3650             ddomain = virDomainMigrateVersion3(domain, dconn, NULL,
3651                                                flags, dname, uri, bandwidth);
3652             goto done;
3653         }
3654 
3655         rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3656                                           VIR_DRV_FEATURE_MIGRATION_V2);
3657         if (rc_src < 0)
3658             goto error;
3659         rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
3660                                           VIR_DRV_FEATURE_MIGRATION_V2);
3661         if (rc_dst < 0)
3662             goto error;
3663         if (rc_src && rc_dst) {
3664             VIR_DEBUG("Using migration protocol 2");
3665             ddomain = virDomainMigrateVersion2(domain, dconn, flags,
3666                                                dname, uri, bandwidth);
3667             goto done;
3668         }
3669 
3670         rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3671                                           VIR_DRV_FEATURE_MIGRATION_V1);
3672         if (rc_src < 0)
3673             goto error;
3674         rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
3675                                           VIR_DRV_FEATURE_MIGRATION_V1);
3676         if (rc_dst < 0)
3677             goto error;
3678         if (rc_src && rc_dst) {
3679             VIR_DEBUG("Using migration protocol 1");
3680             ddomain = virDomainMigrateVersion1(domain, dconn, flags,
3681                                                dname, uri, bandwidth);
3682             goto done;
3683         }
3684 
3685         /* This driver does not support any migration method */
3686         virReportUnsupportedError();
3687         goto error;
3688     }
3689 
3690  done:
3691     if (ddomain == NULL)
3692         goto error;
3693 
3694     return ddomain;
3695 
3696  error:
3697     virDispatchError(domain->conn);
3698     return NULL;
3699 }
3700 
3701 
3702 /**
3703  * virDomainMigrate2:
3704  * @domain: a domain object
3705  * @dconn: destination host (a connection object)
3706  * @flags: bitwise-OR of virDomainMigrateFlags
3707  * @dxml: (optional) XML config for launching guest on target
3708  * @dname: (optional) rename domain to this at destination
3709  * @uri: (optional) dest hostname/URI as seen from the source host
3710  * @bandwidth: (optional) specify migration bandwidth limit in MiB/s
3711  *
3712  * Migrate the domain object from its current host to the destination
3713  * host given by dconn (a connection to the destination host).
3714  *
3715  * This function is similar to virDomainMigrate3, but it only supports a fixed
3716  * set of parameters: @dxml corresponds to VIR_MIGRATE_PARAM_DEST_XML, @dname
3717  * is VIR_MIGRATE_PARAM_DEST_NAME, @uri is VIR_MIGRATE_PARAM_URI, and
3718  * @bandwidth is VIR_MIGRATE_PARAM_BANDWIDTH.
3719  *
3720  * virDomainFree should be used to free the resources after the
3721  * returned domain object is no longer needed.
3722  *
3723  * Returns the new domain object if the migration was successful,
3724  *   or NULL in case of error.  Note that the new domain object
3725  *   exists in the scope of the destination connection (dconn).
3726  */
3727 virDomainPtr
virDomainMigrate2(virDomainPtr domain,virConnectPtr dconn,const char * dxml,unsigned long flags,const char * dname,const char * uri,unsigned long bandwidth)3728 virDomainMigrate2(virDomainPtr domain,
3729                   virConnectPtr dconn,
3730                   const char *dxml,
3731                   unsigned long flags,
3732                   const char *dname,
3733                   const char *uri,
3734                   unsigned long bandwidth)
3735 {
3736     virDomainPtr ddomain = NULL;
3737     int rc_src;
3738     int rc_dst;
3739     int rc;
3740 
3741     VIR_DOMAIN_DEBUG(domain,
3742                      "dconn=%p, flags=0x%lx, dname=%s, uri=%s, bandwidth=%lu",
3743                      dconn, flags, NULLSTR(dname), NULLSTR(uri), bandwidth);
3744 
3745     virResetLastError();
3746 
3747     /* First checkout the source */
3748     virCheckDomainReturn(domain, NULL);
3749     virCheckReadOnlyGoto(domain->conn->flags, error);
3750 
3751     /* Now checkout the destination */
3752     virCheckConnectGoto(dconn, error);
3753     virCheckReadOnlyGoto(dconn->flags, error);
3754 
3755     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_NON_SHARED_DISK,
3756                              VIR_MIGRATE_NON_SHARED_INC,
3757                              error);
3758 
3759     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_TUNNELLED,
3760                              VIR_MIGRATE_PARALLEL,
3761                              error);
3762 
3763     if (flags & VIR_MIGRATE_OFFLINE) {
3764         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3765                                       VIR_DRV_FEATURE_MIGRATION_OFFLINE);
3766         if (rc <= 0) {
3767             if (rc == 0)
3768                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3769                                _("offline migration is not supported by "
3770                                  "the source host"));
3771             goto error;
3772         }
3773         rc = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
3774                                       VIR_DRV_FEATURE_MIGRATION_OFFLINE);
3775         if (rc <= 0) {
3776             if (rc == 0)
3777                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3778                                _("offline migration is not supported by "
3779                                  "the destination host"));
3780             goto error;
3781         }
3782     }
3783 
3784     if (flags & VIR_MIGRATE_PEER2PEER) {
3785         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3786                                       VIR_DRV_FEATURE_MIGRATION_P2P);
3787         if (rc < 0)
3788             goto error;
3789         if (rc) {
3790             g_autofree char *dstURI = virConnectGetURI(dconn);
3791             if (!dstURI)
3792                 return NULL;
3793 
3794             VIR_DEBUG("Using peer2peer migration");
3795             if (virDomainMigrateUnmanaged(domain, dxml, flags, dname,
3796                                           dstURI, uri, bandwidth) < 0)
3797                 goto error;
3798 
3799             ddomain = virDomainLookupByName(dconn, dname ? dname : domain->name);
3800         } else {
3801             /* This driver does not support peer to peer migration */
3802             virReportUnsupportedError();
3803             goto error;
3804         }
3805     } else {
3806         /* Change protection requires support only on source side, and
3807          * is only needed in v3 migration, which automatically re-adds
3808          * the flag for just the source side.  We mask it out for
3809          * non-peer2peer to allow migration from newer source to an
3810          * older destination that rejects the flag.  */
3811         if (flags & VIR_MIGRATE_CHANGE_PROTECTION) {
3812             rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3813                                           VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION);
3814             if (rc <= 0) {
3815                 if (rc == 0)
3816                     virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3817                                    _("cannot enforce change protection"));
3818                 goto error;
3819             }
3820         }
3821         flags &= ~VIR_MIGRATE_CHANGE_PROTECTION;
3822         if (flags & VIR_MIGRATE_TUNNELLED) {
3823             virReportError(VIR_ERR_OPERATION_INVALID, "%s",
3824                            _("cannot perform tunnelled migration without using peer2peer flag"));
3825             goto error;
3826         }
3827 
3828         /* Check that migration is supported by both drivers. */
3829         rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3830                                           VIR_DRV_FEATURE_MIGRATION_V3);
3831         if (rc_src < 0)
3832             goto error;
3833         rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
3834                                           VIR_DRV_FEATURE_MIGRATION_V3);
3835         if (rc_dst < 0)
3836             goto error;
3837         if (rc_src && rc_dst) {
3838             VIR_DEBUG("Using migration protocol 3");
3839             ddomain = virDomainMigrateVersion3(domain, dconn, dxml,
3840                                                flags, dname, uri, bandwidth);
3841             goto done;
3842         }
3843 
3844         rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3845                                           VIR_DRV_FEATURE_MIGRATION_V2);
3846         if (rc_src < 0)
3847             goto error;
3848         rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
3849                                           VIR_DRV_FEATURE_MIGRATION_V2);
3850         if (rc_dst < 0)
3851             goto error;
3852         if (rc_src && rc_dst) {
3853             VIR_DEBUG("Using migration protocol 2");
3854             if (dxml) {
3855                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3856                                _("Unable to change target guest XML during migration"));
3857                 goto error;
3858             }
3859             ddomain = virDomainMigrateVersion2(domain, dconn, flags,
3860                                                dname, uri, bandwidth);
3861             goto done;
3862         }
3863 
3864         rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3865                                           VIR_DRV_FEATURE_MIGRATION_V1);
3866         if (rc_src < 0)
3867             goto error;
3868         rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
3869                                           VIR_DRV_FEATURE_MIGRATION_V1);
3870         if (rc_dst < 0)
3871             goto error;
3872         if (rc_src && rc_dst) {
3873             VIR_DEBUG("Using migration protocol 1");
3874             if (dxml) {
3875                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3876                                _("Unable to change target guest XML during migration"));
3877                 goto error;
3878             }
3879             ddomain = virDomainMigrateVersion1(domain, dconn, flags,
3880                                                dname, uri, bandwidth);
3881             goto done;
3882         }
3883 
3884         /* This driver does not support any migration method */
3885         virReportUnsupportedError();
3886         goto error;
3887     }
3888 
3889  done:
3890     if (ddomain == NULL)
3891         goto error;
3892 
3893     return ddomain;
3894 
3895  error:
3896     virDispatchError(domain->conn);
3897     return NULL;
3898 }
3899 
3900 
3901 /**
3902  * virDomainMigrate3:
3903  * @domain: a domain object
3904  * @dconn: destination host (a connection object)
3905  * @params: (optional) migration parameters
3906  * @nparams: (optional) number of migration parameters in @params
3907  * @flags: bitwise-OR of virDomainMigrateFlags
3908  *
3909  * Migrate the domain object from its current host to the destination host
3910  * given by dconn (a connection to the destination host).
3911  *
3912  * See VIR_MIGRATE_PARAM_* and virDomainMigrateFlags for detailed description
3913  * of accepted migration parameters and flags.
3914  *
3915  * See virDomainMigrateFlags documentation for description of individual flags.
3916  *
3917  * VIR_MIGRATE_TUNNELLED and VIR_MIGRATE_PEER2PEER are not supported by this
3918  * API, use virDomainMigrateToURI3 instead.
3919  *
3920  * There are many limitations on migration imposed by the underlying
3921  * technology - for example it may not be possible to migrate between
3922  * different processors even with the same architecture, or between
3923  * different types of hypervisor.
3924  *
3925  * virDomainFree should be used to free the resources after the
3926  * returned domain object is no longer needed.
3927  *
3928  * Returns the new domain object if the migration was successful,
3929  *   or NULL in case of error.  Note that the new domain object
3930  *   exists in the scope of the destination connection (dconn).
3931  */
3932 virDomainPtr
virDomainMigrate3(virDomainPtr domain,virConnectPtr dconn,virTypedParameterPtr params,unsigned int nparams,unsigned int flags)3933 virDomainMigrate3(virDomainPtr domain,
3934                   virConnectPtr dconn,
3935                   virTypedParameterPtr params,
3936                   unsigned int nparams,
3937                   unsigned int flags)
3938 {
3939     virDomainPtr ddomain = NULL;
3940     const char *compatParams[] = { VIR_MIGRATE_PARAM_URI,
3941                                    VIR_MIGRATE_PARAM_DEST_NAME,
3942                                    VIR_MIGRATE_PARAM_DEST_XML,
3943                                    VIR_MIGRATE_PARAM_BANDWIDTH };
3944     const char *uri = NULL;
3945     const char *dname = NULL;
3946     const char *dxml = NULL;
3947     unsigned long long bandwidth = 0;
3948     int rc_src;
3949     int rc_dst;
3950     int rc;
3951 
3952     VIR_DOMAIN_DEBUG(domain, "dconn=%p, params=%p, nparms=%u flags=0x%x",
3953                      dconn, params, nparams, flags);
3954     VIR_TYPED_PARAMS_DEBUG(params, nparams);
3955 
3956     virResetLastError();
3957 
3958     /* First checkout the source */
3959     virCheckDomainReturn(domain, NULL);
3960     virCheckReadOnlyGoto(domain->conn->flags, error);
3961 
3962     /* Now checkout the destination */
3963     virCheckReadOnlyGoto(dconn->flags, error);
3964 
3965     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_NON_SHARED_DISK,
3966                              VIR_MIGRATE_NON_SHARED_INC,
3967                              error);
3968 
3969     if (flags & VIR_MIGRATE_PEER2PEER) {
3970         virReportInvalidArg(flags, "%s",
3971                             _("use virDomainMigrateToURI3 for peer-to-peer "
3972                               "migration"));
3973         goto error;
3974     }
3975     if (flags & VIR_MIGRATE_TUNNELLED) {
3976         virReportInvalidArg(flags, "%s",
3977                             _("cannot perform tunnelled migration "
3978                               "without using peer2peer flag"));
3979         goto error;
3980     }
3981 
3982     if (flags & VIR_MIGRATE_OFFLINE) {
3983         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
3984                                       VIR_DRV_FEATURE_MIGRATION_OFFLINE);
3985         if (rc <= 0) {
3986             if (rc == 0)
3987                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3988                                _("offline migration is not supported by "
3989                                  "the source host"));
3990             goto error;
3991         }
3992 
3993         rc = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
3994                                       VIR_DRV_FEATURE_MIGRATION_OFFLINE);
3995         if (rc <= 0) {
3996             if (rc == 0)
3997                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
3998                                _("offline migration is not supported by "
3999                                  "the destination host"));
4000             goto error;
4001         }
4002     }
4003 
4004     /* Change protection requires support only on source side, and
4005      * is only needed in v3 migration, which automatically re-adds
4006      * the flag for just the source side.  We mask it out to allow
4007      * migration from newer source to an older destination that
4008      * rejects the flag.  */
4009     if (flags & VIR_MIGRATE_CHANGE_PROTECTION) {
4010         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
4011                                       VIR_DRV_FEATURE_MIGRATE_CHANGE_PROTECTION);
4012         if (rc <= 0) {
4013             if (rc == 0)
4014                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
4015                                _("cannot enforce change protection"));
4016             goto error;
4017         }
4018     }
4019     flags &= ~VIR_MIGRATE_CHANGE_PROTECTION;
4020 
4021     /* Prefer extensible API but fall back to older migration APIs if params
4022      * only contains parameters which were supported by the older API. */
4023     rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
4024                                       VIR_DRV_FEATURE_MIGRATION_PARAMS);
4025     if (rc_src < 0)
4026         goto error;
4027     rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
4028                                       VIR_DRV_FEATURE_MIGRATION_PARAMS);
4029     if (rc_dst < 0)
4030         goto error;
4031     if (rc_src && rc_dst) {
4032         VIR_DEBUG("Using migration protocol 3 with extensible parameters");
4033         ddomain = virDomainMigrateVersion3Params(domain, dconn, params,
4034                                                  nparams, flags);
4035         goto done;
4036     }
4037 
4038     if (!virTypedParamsCheck(params, nparams, compatParams,
4039                              G_N_ELEMENTS(compatParams))) {
4040         virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
4041                        _("Migration APIs with extensible parameters are not "
4042                          "supported but extended parameters were passed"));
4043         goto error;
4044     }
4045 
4046     if (virTypedParamsGetString(params, nparams,
4047                                 VIR_MIGRATE_PARAM_URI, &uri) < 0 ||
4048         virTypedParamsGetString(params, nparams,
4049                                 VIR_MIGRATE_PARAM_DEST_NAME, &dname) < 0 ||
4050         virTypedParamsGetString(params, nparams,
4051                                 VIR_MIGRATE_PARAM_DEST_XML, &dxml) < 0 ||
4052         virTypedParamsGetULLong(params, nparams,
4053                                 VIR_MIGRATE_PARAM_BANDWIDTH, &bandwidth) < 0) {
4054         goto error;
4055     }
4056 
4057     rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
4058                                       VIR_DRV_FEATURE_MIGRATION_V3);
4059     if (rc_src < 0)
4060         goto error;
4061     rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
4062                                       VIR_DRV_FEATURE_MIGRATION_V3);
4063     if (rc_dst < 0)
4064         goto error;
4065     if (rc_src && rc_dst) {
4066         VIR_DEBUG("Using migration protocol 3");
4067         ddomain = virDomainMigrateVersion3(domain, dconn, dxml, flags,
4068                                            dname, uri, bandwidth);
4069         goto done;
4070     }
4071 
4072     rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
4073                                       VIR_DRV_FEATURE_MIGRATION_V2);
4074     if (rc_src < 0)
4075         goto error;
4076     rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
4077                                       VIR_DRV_FEATURE_MIGRATION_V2);
4078     if (rc_dst < 0)
4079         goto error;
4080     if (rc_src && rc_dst) {
4081         VIR_DEBUG("Using migration protocol 2");
4082         if (dxml) {
4083             virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
4084                            _("Unable to change target guest XML during "
4085                              "migration"));
4086             goto error;
4087         }
4088         ddomain = virDomainMigrateVersion2(domain, dconn, flags,
4089                                            dname, uri, bandwidth);
4090         goto done;
4091     }
4092 
4093     rc_src = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
4094                                       VIR_DRV_FEATURE_MIGRATION_V1);
4095     if (rc_src < 0)
4096         goto error;
4097     rc_dst = VIR_DRV_SUPPORTS_FEATURE(dconn->driver, dconn,
4098                                       VIR_DRV_FEATURE_MIGRATION_V1);
4099     if (rc_dst < 0)
4100         goto error;
4101     if (rc_src && rc_dst) {
4102         VIR_DEBUG("Using migration protocol 1");
4103         if (dxml) {
4104             virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
4105                            _("Unable to change target guest XML during "
4106                              "migration"));
4107             goto error;
4108         }
4109         ddomain = virDomainMigrateVersion1(domain, dconn, flags,
4110                                            dname, uri, bandwidth);
4111         goto done;
4112     }
4113 
4114     /* This driver does not support any migration method */
4115     virReportUnsupportedError();
4116     goto error;
4117 
4118  done:
4119     if (ddomain == NULL)
4120         goto error;
4121 
4122     return ddomain;
4123 
4124  error:
4125     virDispatchError(domain->conn);
4126     return NULL;
4127 }
4128 
4129 
4130 static
virDomainMigrateUnmanagedCheckCompat(virDomainPtr domain,unsigned int flags)4131 int virDomainMigrateUnmanagedCheckCompat(virDomainPtr domain,
4132                                          unsigned int flags)
4133 {
4134     int rc;
4135 
4136     VIR_EXCLUSIVE_FLAGS_RET(VIR_MIGRATE_NON_SHARED_DISK,
4137                             VIR_MIGRATE_NON_SHARED_INC,
4138                             -1);
4139 
4140     if (flags & VIR_MIGRATE_OFFLINE) {
4141         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
4142                                       VIR_DRV_FEATURE_MIGRATION_OFFLINE);
4143 
4144         if (rc <= 0) {
4145             if (rc == 0)
4146                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
4147                                _("offline migration is not supported by "
4148                                  "the source host"));
4149             return -1;
4150         }
4151     }
4152 
4153     if (flags & VIR_MIGRATE_PEER2PEER) {
4154         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
4155                                       VIR_DRV_FEATURE_MIGRATION_P2P);
4156 
4157         if (rc <= 0) {
4158             if (rc == 0)
4159                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
4160                                _("p2p migration is not supported by "
4161                                  "the source host"));
4162             return -1;
4163         }
4164     } else {
4165         rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
4166                                       VIR_DRV_FEATURE_MIGRATION_DIRECT);
4167         if (rc <= 0) {
4168             if (rc == 0)
4169                 virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
4170                                _("direct migration is not supported by "
4171                                  "the source host"));
4172             return -1;
4173         }
4174     }
4175 
4176     return 0;
4177 }
4178 
4179 
4180 /**
4181  * virDomainMigrateToURI:
4182  * @domain: a domain object
4183  * @duri: mandatory URI for the destination host
4184  * @flags: bitwise-OR of virDomainMigrateFlags
4185  * @dname: (optional) rename domain to this at destination
4186  * @bandwidth: (optional) specify migration bandwidth limit in MiB/s
4187  *
4188  * Migrate the domain object from its current host to the destination
4189  * host given by duri.
4190  *
4191  * This function is similar to virDomainMigrateToURI3, but it only supports a
4192  * fixed set of parameters: @dname corresponds to VIR_MIGRATE_PARAM_DEST_NAME,
4193  * and @bandwidth corresponds to VIR_MIGRATE_PARAM_BANDWIDTH.
4194  *
4195  * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag.
4196  *
4197  * If the VIR_MIGRATE_PEER2PEER flag IS set, the @duri parameter must be a
4198  * valid libvirt connection URI, by which the source libvirt driver can connect
4199  * to the destination libvirt. In other words, @duri corresponds to @dconnuri
4200  * of virDomainMigrateToURI3.
4201  *
4202  * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the @duri parameter takes a
4203  * hypervisor specific URI used to initiate the migration. In this case @duri
4204  * corresponds to VIR_MIGRATE_PARAM_URI of virDomainMigrateToURI3.
4205  *
4206  * Returns 0 if the migration succeeded, -1 upon error.
4207  */
4208 int
virDomainMigrateToURI(virDomainPtr domain,const char * duri,unsigned long flags,const char * dname,unsigned long bandwidth)4209 virDomainMigrateToURI(virDomainPtr domain,
4210                       const char *duri,
4211                       unsigned long flags,
4212                       const char *dname,
4213                       unsigned long bandwidth)
4214 {
4215     const char *dconnuri = NULL;
4216     const char *miguri = NULL;
4217 
4218     VIR_DOMAIN_DEBUG(domain, "duri=%s, flags=0x%lx, dname=%s, bandwidth=%lu",
4219                      NULLSTR(duri), flags, NULLSTR(dname), bandwidth);
4220 
4221     virResetLastError();
4222 
4223     /* First checkout the source */
4224     virCheckDomainReturn(domain, -1);
4225     virCheckReadOnlyGoto(domain->conn->flags, error);
4226     virCheckNonNullArgGoto(duri, error);
4227 
4228     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_TUNNELLED,
4229                              VIR_MIGRATE_PARALLEL,
4230                              error);
4231 
4232     if (virDomainMigrateUnmanagedCheckCompat(domain, flags) < 0)
4233         goto error;
4234 
4235     if (flags & VIR_MIGRATE_PEER2PEER)
4236         dconnuri = duri;
4237     else
4238         miguri = duri;
4239 
4240     if (virDomainMigrateUnmanaged(domain, NULL, flags,
4241                                   dname, dconnuri, miguri, bandwidth) < 0)
4242         goto error;
4243 
4244     return 0;
4245 
4246  error:
4247     virDispatchError(domain->conn);
4248     return -1;
4249 }
4250 
4251 
4252 /**
4253  * virDomainMigrateToURI2:
4254  * @domain: a domain object
4255  * @dconnuri: (optional) URI for target libvirtd if @flags includes VIR_MIGRATE_PEER2PEER
4256  * @miguri: (optional) URI for invoking the migration, not if @flags includs VIR_MIGRATE_TUNNELLED
4257  * @dxml: (optional) XML config for launching guest on target
4258  * @flags: bitwise-OR of virDomainMigrateFlags
4259  * @dname: (optional) rename domain to this at destination
4260  * @bandwidth: (optional) specify migration bandwidth limit in MiB/s
4261  *
4262  * Migrate the domain object from its current host to the destination
4263  * host given by @dconnuri.
4264  *
4265  * This function is similar to virDomainMigrateToURI3, but it only supports a
4266  * fixed set of parameters: @miguri corresponds to VIR_MIGRATE_PARAM_URI, @dxml
4267  * is VIR_MIGRATE_PARAM_DEST_XML, @dname is VIR_MIGRATE_PARAM_DEST_NAME, and
4268  * @bandwidth corresponds to VIR_MIGRATE_PARAM_BANDWIDTH.
4269  *
4270  * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag.
4271  *
4272  * If the VIR_MIGRATE_PEER2PEER flag IS set, the @dconnuri parameter must be a
4273  * valid libvirt connection URI, by which the source libvirt driver can connect
4274  * to the destination libvirt. In other words, @dconnuri has the same semantics
4275  * as in virDomainMigrateToURI3.
4276  *
4277  * If the VIR_MIGRATE_PEER2PEER flag is NOT set, the @dconnuri must be NULL
4278  * and the @miguri parameter takes a hypervisor specific URI used to initiate
4279  * the migration. In this case @miguri corresponds to VIR_MIGRATE_PARAM_URI of
4280  * virDomainMigrateToURI3.
4281  *
4282  * Returns 0 if the migration succeeded, -1 upon error.
4283  */
4284 int
virDomainMigrateToURI2(virDomainPtr domain,const char * dconnuri,const char * miguri,const char * dxml,unsigned long flags,const char * dname,unsigned long bandwidth)4285 virDomainMigrateToURI2(virDomainPtr domain,
4286                        const char *dconnuri,
4287                        const char *miguri,
4288                        const char *dxml,
4289                        unsigned long flags,
4290                        const char *dname,
4291                        unsigned long bandwidth)
4292 {
4293     VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, miguri=%s, dxml=%s, "
4294                      "flags=0x%lx, dname=%s, bandwidth=%lu",
4295                      NULLSTR(dconnuri), NULLSTR(miguri), NULLSTR(dxml),
4296                      flags, NULLSTR(dname), bandwidth);
4297 
4298     virResetLastError();
4299 
4300     /* First checkout the source */
4301     virCheckDomainReturn(domain, -1);
4302     virCheckReadOnlyGoto(domain->conn->flags, error);
4303 
4304     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_TUNNELLED,
4305                              VIR_MIGRATE_PARALLEL,
4306                              error);
4307 
4308     if (virDomainMigrateUnmanagedCheckCompat(domain, flags) < 0)
4309         goto error;
4310 
4311     if (flags & VIR_MIGRATE_PEER2PEER)
4312         virCheckNonNullArgGoto(dconnuri, error);
4313     else
4314         dconnuri = NULL;
4315 
4316     if (virDomainMigrateUnmanaged(domain, dxml, flags,
4317                                   dname, dconnuri, miguri, bandwidth) < 0)
4318         goto error;
4319 
4320     return 0;
4321 
4322  error:
4323     virDispatchError(domain->conn);
4324     return -1;
4325 }
4326 
4327 
4328 /**
4329  * virDomainMigrateToURI3:
4330  * @domain: a domain object
4331  * @dconnuri: (optional) URI for target libvirtd if @flags includes VIR_MIGRATE_PEER2PEER
4332  * @params: (optional) migration parameters
4333  * @nparams: (optional) number of migration parameters in @params
4334  * @flags: bitwise-OR of virDomainMigrateFlags
4335  *
4336  * Migrate the domain object from its current host to the destination host
4337  * given by URI.
4338  *
4339  * See VIR_MIGRATE_PARAM_* and virDomainMigrateFlags for detailed description
4340  * of accepted migration parameters and flags.
4341  *
4342  * The operation of this API hinges on the VIR_MIGRATE_PEER2PEER flag.
4343  *
4344  * If the VIR_MIGRATE_PEER2PEER flag is set, the @dconnuri parameter must be a
4345  * valid libvirt connection URI, by which the source libvirt daemon can connect
4346  * to the destination libvirt.
4347  *
4348  * If the VIR_MIGRATE_PEER2PEER flag is NOT set, then @dconnuri must be NULL
4349  * and VIR_MIGRATE_PARAM_URI migration parameter must be filled in with
4350  * hypervisor specific URI used to initiate the migration. The uri_transports
4351  * element of the hypervisor capabilities XML includes supported URI schemes.
4352  * This is called "direct" migration. Not all hypervisors support this mode of
4353  * migration, so if the VIR_MIGRATE_PEER2PEER flag is not set, then it may be
4354  * necessary to use the alternative virDomainMigrate3 API providing an explicit
4355  * virConnectPtr for the destination host.
4356  *
4357  * There are many limitations on migration imposed by the underlying
4358  * technology - for example it may not be possible to migrate between
4359  * different processors even with the same architecture, or between
4360  * different types of hypervisor.
4361  *
4362  * Returns 0 if the migration succeeded, -1 upon error.
4363  */
4364 int
virDomainMigrateToURI3(virDomainPtr domain,const char * dconnuri,virTypedParameterPtr params,unsigned int nparams,unsigned int flags)4365 virDomainMigrateToURI3(virDomainPtr domain,
4366                        const char *dconnuri,
4367                        virTypedParameterPtr params,
4368                        unsigned int nparams,
4369                        unsigned int flags)
4370 {
4371     VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparms=%u flags=0x%x",
4372                      NULLSTR(dconnuri), params, nparams, flags);
4373     VIR_TYPED_PARAMS_DEBUG(params, nparams);
4374 
4375     virResetLastError();
4376 
4377     /* First checkout the source */
4378     virCheckDomainReturn(domain, -1);
4379     virCheckReadOnlyGoto(domain->conn->flags, error);
4380 
4381     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MIGRATE_TUNNELLED,
4382                              VIR_MIGRATE_PARALLEL,
4383                              error);
4384 
4385     if (virDomainMigrateUnmanagedCheckCompat(domain, flags) < 0)
4386         goto error;
4387 
4388     if (flags & VIR_MIGRATE_PEER2PEER)
4389         virCheckNonNullArgGoto(dconnuri, error);
4390     else
4391         dconnuri = NULL;
4392 
4393     if (virDomainMigrateUnmanagedParams(domain, dconnuri,
4394                                         params, nparams, flags) < 0)
4395         goto error;
4396 
4397     return 0;
4398 
4399  error:
4400     virDispatchError(domain->conn);
4401     return -1;
4402 }
4403 
4404 
4405 /*
4406  * Not for public use.  This function is part of the internal
4407  * implementation of migration in the remote case.
4408  */
4409 int
virDomainMigratePrepare(virConnectPtr dconn,char ** cookie,int * cookielen,const char * uri_in,char ** uri_out,unsigned long flags,const char * dname,unsigned long bandwidth)4410 virDomainMigratePrepare(virConnectPtr dconn,
4411                         char **cookie,
4412                         int *cookielen,
4413                         const char *uri_in,
4414                         char **uri_out,
4415                         unsigned long flags,
4416                         const char *dname,
4417                         unsigned long bandwidth)
4418 {
4419     VIR_DEBUG("dconn=%p, cookie=%p, cookielen=%p, uri_in=%s, uri_out=%p, "
4420               "flags=0x%lx, dname=%s, bandwidth=%lu", dconn, cookie, cookielen,
4421               NULLSTR(uri_in), uri_out, flags, NULLSTR(dname), bandwidth);
4422 
4423     virResetLastError();
4424 
4425     virCheckConnectReturn(dconn, -1);
4426     virCheckReadOnlyGoto(dconn->flags, error);
4427 
4428     if (dconn->driver->domainMigratePrepare) {
4429         int ret;
4430         ret = dconn->driver->domainMigratePrepare(dconn, cookie, cookielen,
4431                                                   uri_in, uri_out,
4432                                                   flags, dname, bandwidth);
4433         if (ret < 0)
4434             goto error;
4435         return ret;
4436     }
4437 
4438     virReportUnsupportedError();
4439 
4440  error:
4441     virDispatchError(dconn);
4442     return -1;
4443 }
4444 
4445 
4446 /*
4447  * Not for public use.  This function is part of the internal
4448  * implementation of migration in the remote case.
4449  */
4450 int
virDomainMigratePerform(virDomainPtr domain,const char * cookie,int cookielen,const char * uri,unsigned long flags,const char * dname,unsigned long bandwidth)4451 virDomainMigratePerform(virDomainPtr domain,
4452                         const char *cookie,
4453                         int cookielen,
4454                         const char *uri,
4455                         unsigned long flags,
4456                         const char *dname,
4457                         unsigned long bandwidth)
4458 {
4459     virConnectPtr conn;
4460 
4461     VIR_DOMAIN_DEBUG(domain, "cookie=%p, cookielen=%d, uri=%s, flags=0x%lx, "
4462                      "dname=%s, bandwidth=%lu", cookie, cookielen, uri, flags,
4463                      NULLSTR(dname), bandwidth);
4464 
4465     virResetLastError();
4466 
4467     virCheckDomainReturn(domain, -1);
4468     conn = domain->conn;
4469 
4470     virCheckReadOnlyGoto(conn->flags, error);
4471 
4472     if (conn->driver->domainMigratePerform) {
4473         int ret;
4474         ret = conn->driver->domainMigratePerform(domain, cookie, cookielen,
4475                                                  uri,
4476                                                  flags, dname, bandwidth);
4477         if (ret < 0)
4478             goto error;
4479         return ret;
4480     }
4481 
4482     virReportUnsupportedError();
4483 
4484  error:
4485     virDispatchError(domain->conn);
4486     return -1;
4487 }
4488 
4489 
4490 /*
4491  * Not for public use.  This function is part of the internal
4492  * implementation of migration in the remote case.
4493  */
4494 virDomainPtr
virDomainMigrateFinish(virConnectPtr dconn,const char * dname,const char * cookie,int cookielen,const char * uri,unsigned long flags)4495 virDomainMigrateFinish(virConnectPtr dconn,
4496                        const char *dname,
4497                        const char *cookie,
4498                        int cookielen,
4499                        const char *uri,
4500                        unsigned long flags)
4501 {
4502     VIR_DEBUG("dconn=%p, dname=%s, cookie=%p, cookielen=%d, uri=%s, "
4503               "flags=0x%lx", dconn, NULLSTR(dname), cookie, cookielen,
4504               NULLSTR(uri), flags);
4505 
4506     virResetLastError();
4507 
4508     virCheckConnectReturn(dconn, NULL);
4509     virCheckReadOnlyGoto(dconn->flags, error);
4510 
4511     if (dconn->driver->domainMigrateFinish) {
4512         virDomainPtr ret;
4513         ret = dconn->driver->domainMigrateFinish(dconn, dname,
4514                                                  cookie, cookielen,
4515                                                  uri, flags);
4516         if (!ret)
4517             goto error;
4518         return ret;
4519     }
4520 
4521     virReportUnsupportedError();
4522 
4523  error:
4524     virDispatchError(dconn);
4525     return NULL;
4526 }
4527 
4528 
4529 /*
4530  * Not for public use.  This function is part of the internal
4531  * implementation of migration in the remote case.
4532  */
4533 int
virDomainMigratePrepare2(virConnectPtr dconn,char ** cookie,int * cookielen,const char * uri_in,char ** uri_out,unsigned long flags,const char * dname,unsigned long bandwidth,const char * dom_xml)4534 virDomainMigratePrepare2(virConnectPtr dconn,
4535                          char **cookie,
4536                          int *cookielen,
4537                          const char *uri_in,
4538                          char **uri_out,
4539                          unsigned long flags,
4540                          const char *dname,
4541                          unsigned long bandwidth,
4542                          const char *dom_xml)
4543 {
4544     VIR_DEBUG("dconn=%p, cookie=%p, cookielen=%p, uri_in=%s, uri_out=%p,"
4545               "flags=0x%lx, dname=%s, bandwidth=%lu, dom_xml=%s", dconn,
4546               cookie, cookielen, NULLSTR(uri_in), uri_out, flags, NULLSTR(dname),
4547               bandwidth, NULLSTR(dom_xml));
4548 
4549     virResetLastError();
4550 
4551     virCheckConnectReturn(dconn, -1);
4552     virCheckReadOnlyGoto(dconn->flags, error);
4553 
4554     if (dconn->driver->domainMigratePrepare2) {
4555         int ret;
4556         ret = dconn->driver->domainMigratePrepare2(dconn, cookie, cookielen,
4557                                                    uri_in, uri_out,
4558                                                    flags, dname, bandwidth,
4559                                                    dom_xml);
4560         if (ret < 0)
4561             goto error;
4562         return ret;
4563     }
4564 
4565     virReportUnsupportedError();
4566 
4567  error:
4568     virDispatchError(dconn);
4569     return -1;
4570 }
4571 
4572 
4573 /*
4574  * Not for public use.  This function is part of the internal
4575  * implementation of migration in the remote case.
4576  */
4577 virDomainPtr
virDomainMigrateFinish2(virConnectPtr dconn,const char * dname,const char * cookie,int cookielen,const char * uri,unsigned long flags,int retcode)4578 virDomainMigrateFinish2(virConnectPtr dconn,
4579                         const char *dname,
4580                         const char *cookie,
4581                         int cookielen,
4582                         const char *uri,
4583                         unsigned long flags,
4584                         int retcode)
4585 {
4586     VIR_DEBUG("dconn=%p, dname=%s, cookie=%p, cookielen=%d, uri=%s, "
4587               "flags=0x%lx, retcode=%d", dconn, NULLSTR(dname), cookie,
4588               cookielen, NULLSTR(uri), flags, retcode);
4589 
4590     virResetLastError();
4591 
4592     virCheckConnectReturn(dconn, NULL);
4593     virCheckReadOnlyGoto(dconn->flags, error);
4594 
4595     if (dconn->driver->domainMigrateFinish2) {
4596         virDomainPtr ret;
4597         ret = dconn->driver->domainMigrateFinish2(dconn, dname,
4598                                                   cookie, cookielen,
4599                                                   uri, flags,
4600                                                   retcode);
4601         if (!ret && !retcode)
4602             goto error;
4603         return ret;
4604     }
4605 
4606     virReportUnsupportedError();
4607 
4608  error:
4609     virDispatchError(dconn);
4610     return NULL;
4611 }
4612 
4613 
4614 /*
4615  * Not for public use.  This function is part of the internal
4616  * implementation of migration in the remote case.
4617  */
4618 int
virDomainMigratePrepareTunnel(virConnectPtr conn,virStreamPtr st,unsigned long flags,const char * dname,unsigned long bandwidth,const char * dom_xml)4619 virDomainMigratePrepareTunnel(virConnectPtr conn,
4620                               virStreamPtr st,
4621                               unsigned long flags,
4622                               const char *dname,
4623                               unsigned long bandwidth,
4624                               const char *dom_xml)
4625 {
4626     VIR_DEBUG("conn=%p, stream=%p, flags=0x%lx, dname=%s, "
4627               "bandwidth=%lu, dom_xml=%s", conn, st, flags,
4628               NULLSTR(dname), bandwidth, NULLSTR(dom_xml));
4629 
4630     virResetLastError();
4631 
4632     virCheckConnectReturn(conn, -1);
4633     virCheckReadOnlyGoto(conn->flags, error);
4634 
4635     if (conn != st->conn) {
4636         virReportInvalidArg(conn, "%s",
4637                             _("conn must match stream connection"));
4638         goto error;
4639     }
4640 
4641     if (conn->driver->domainMigratePrepareTunnel) {
4642         int rv = conn->driver->domainMigratePrepareTunnel(conn, st,
4643                                                           flags, dname,
4644                                                           bandwidth, dom_xml);
4645         if (rv < 0)
4646             goto error;
4647         return rv;
4648     }
4649 
4650     virReportUnsupportedError();
4651 
4652  error:
4653     virDispatchError(conn);
4654     return -1;
4655 }
4656 
4657 
4658 /*
4659  * Not for public use.  This function is part of the internal
4660  * implementation of migration in the remote case.
4661  */
4662 char *
virDomainMigrateBegin3(virDomainPtr domain,const char * xmlin,char ** cookieout,int * cookieoutlen,unsigned long flags,const char * dname,unsigned long bandwidth)4663 virDomainMigrateBegin3(virDomainPtr domain,
4664                        const char *xmlin,
4665                        char **cookieout,
4666                        int *cookieoutlen,
4667                        unsigned long flags,
4668                        const char *dname,
4669                        unsigned long bandwidth)
4670 {
4671     virConnectPtr conn;
4672 
4673     VIR_DOMAIN_DEBUG(domain, "xmlin=%s cookieout=%p, cookieoutlen=%p, "
4674                      "flags=0x%lx, dname=%s, bandwidth=%lu",
4675                      NULLSTR(xmlin), cookieout, cookieoutlen, flags,
4676                      NULLSTR(dname), bandwidth);
4677 
4678     virResetLastError();
4679 
4680     virCheckDomainReturn(domain, NULL);
4681     conn = domain->conn;
4682 
4683     virCheckReadOnlyGoto(conn->flags, error);
4684 
4685     if (conn->driver->domainMigrateBegin3) {
4686         char *xml;
4687         xml = conn->driver->domainMigrateBegin3(domain, xmlin,
4688                                                 cookieout, cookieoutlen,
4689                                                 flags, dname, bandwidth);
4690         VIR_DEBUG("xml %s", NULLSTR(xml));
4691         if (!xml)
4692             goto error;
4693         return xml;
4694     }
4695 
4696     virReportUnsupportedError();
4697 
4698  error:
4699     virDispatchError(domain->conn);
4700     return NULL;
4701 }
4702 
4703 
4704 /*
4705  * Not for public use.  This function is part of the internal
4706  * implementation of migration in the remote case.
4707  */
4708 int
virDomainMigratePrepare3(virConnectPtr dconn,const char * cookiein,int cookieinlen,char ** cookieout,int * cookieoutlen,const char * uri_in,char ** uri_out,unsigned long flags,const char * dname,unsigned long bandwidth,const char * dom_xml)4709 virDomainMigratePrepare3(virConnectPtr dconn,
4710                          const char *cookiein,
4711                          int cookieinlen,
4712                          char **cookieout,
4713                          int *cookieoutlen,
4714                          const char *uri_in,
4715                          char **uri_out,
4716                          unsigned long flags,
4717                          const char *dname,
4718                          unsigned long bandwidth,
4719                          const char *dom_xml)
4720 {
4721     VIR_DEBUG("dconn=%p, cookiein=%p, cookieinlen=%d, cookieout=%p, "
4722               "cookieoutlen=%p, uri_in=%s, uri_out=%p, flags=0x%lx, dname=%s, "
4723               "bandwidth=%lu, dom_xml=%s",
4724               dconn, cookiein, cookieinlen, cookieout, cookieoutlen, NULLSTR(uri_in),
4725               uri_out, flags, NULLSTR(dname), bandwidth, NULLSTR(dom_xml));
4726 
4727     virResetLastError();
4728 
4729     virCheckConnectReturn(dconn, -1);
4730     virCheckReadOnlyGoto(dconn->flags, error);
4731 
4732     if (dconn->driver->domainMigratePrepare3) {
4733         int ret;
4734         ret = dconn->driver->domainMigratePrepare3(dconn,
4735                                                    cookiein, cookieinlen,
4736                                                    cookieout, cookieoutlen,
4737                                                    uri_in, uri_out,
4738                                                    flags, dname, bandwidth,
4739                                                    dom_xml);
4740         if (ret < 0)
4741             goto error;
4742         return ret;
4743     }
4744 
4745     virReportUnsupportedError();
4746 
4747  error:
4748     virDispatchError(dconn);
4749     return -1;
4750 }
4751 
4752 
4753 /*
4754  * Not for public use.  This function is part of the internal
4755  * implementation of migration in the remote case.
4756  */
4757 int
virDomainMigratePrepareTunnel3(virConnectPtr conn,virStreamPtr st,const char * cookiein,int cookieinlen,char ** cookieout,int * cookieoutlen,unsigned long flags,const char * dname,unsigned long bandwidth,const char * dom_xml)4758 virDomainMigratePrepareTunnel3(virConnectPtr conn,
4759                                virStreamPtr st,
4760                                const char *cookiein,
4761                                int cookieinlen,
4762                                char **cookieout,
4763                                int *cookieoutlen,
4764                                unsigned long flags,
4765                                const char *dname,
4766                                unsigned long bandwidth,
4767                                const char *dom_xml)
4768 {
4769     VIR_DEBUG("conn=%p, stream=%p, cookiein=%p, cookieinlen=%d, cookieout=%p, "
4770               "cookieoutlen=%p, flags=0x%lx, dname=%s, bandwidth=%lu, "
4771               "dom_xml=%s",
4772               conn, st, cookiein, cookieinlen, cookieout, cookieoutlen, flags,
4773               NULLSTR(dname), bandwidth, NULLSTR(dom_xml));
4774 
4775     virResetLastError();
4776 
4777     virCheckConnectReturn(conn, -1);
4778     virCheckReadOnlyGoto(conn->flags, error);
4779 
4780     if (conn != st->conn) {
4781         virReportInvalidArg(conn, "%s",
4782                             _("conn must match stream connection"));
4783         goto error;
4784     }
4785 
4786     if (conn->driver->domainMigratePrepareTunnel3) {
4787         int rv = conn->driver->domainMigratePrepareTunnel3(conn, st,
4788                                                            cookiein, cookieinlen,
4789                                                            cookieout, cookieoutlen,
4790                                                            flags, dname,
4791                                                            bandwidth, dom_xml);
4792         if (rv < 0)
4793             goto error;
4794         return rv;
4795     }
4796 
4797     virReportUnsupportedError();
4798 
4799  error:
4800     virDispatchError(conn);
4801     return -1;
4802 }
4803 
4804 
4805 /*
4806  * Not for public use.  This function is part of the internal
4807  * implementation of migration in the remote case.
4808  */
4809 int
virDomainMigratePerform3(virDomainPtr domain,const char * xmlin,const char * cookiein,int cookieinlen,char ** cookieout,int * cookieoutlen,const char * dconnuri,const char * uri,unsigned long flags,const char * dname,unsigned long bandwidth)4810 virDomainMigratePerform3(virDomainPtr domain,
4811                          const char *xmlin,
4812                          const char *cookiein,
4813                          int cookieinlen,
4814                          char **cookieout,
4815                          int *cookieoutlen,
4816                          const char *dconnuri,
4817                          const char *uri,
4818                          unsigned long flags,
4819                          const char *dname,
4820                          unsigned long bandwidth)
4821 {
4822     virConnectPtr conn;
4823 
4824     VIR_DOMAIN_DEBUG(domain, "xmlin=%s cookiein=%p, cookieinlen=%d, "
4825                      "cookieout=%p, cookieoutlen=%p, dconnuri=%s, "
4826                      "uri=%s, flags=0x%lx, dname=%s, bandwidth=%lu",
4827                      NULLSTR(xmlin), cookiein, cookieinlen,
4828                      cookieout, cookieoutlen, NULLSTR(dconnuri),
4829                      NULLSTR(uri), flags, NULLSTR(dname), bandwidth);
4830 
4831     virResetLastError();
4832 
4833     virCheckDomainReturn(domain, -1);
4834     conn = domain->conn;
4835 
4836     virCheckReadOnlyGoto(conn->flags, error);
4837 
4838     if (conn->driver->domainMigratePerform3) {
4839         int ret;
4840         ret = conn->driver->domainMigratePerform3(domain, xmlin,
4841                                                   cookiein, cookieinlen,
4842                                                   cookieout, cookieoutlen,
4843                                                   dconnuri, uri,
4844                                                   flags, dname, bandwidth);
4845         if (ret < 0)
4846             goto error;
4847         return ret;
4848     }
4849 
4850     virReportUnsupportedError();
4851 
4852  error:
4853     virDispatchError(domain->conn);
4854     return -1;
4855 }
4856 
4857 
4858 /*
4859  * Not for public use.  This function is part of the internal
4860  * implementation of migration in the remote case.
4861  */
4862 virDomainPtr
virDomainMigrateFinish3(virConnectPtr dconn,const char * dname,const char * cookiein,int cookieinlen,char ** cookieout,int * cookieoutlen,const char * dconnuri,const char * uri,unsigned long flags,int cancelled)4863 virDomainMigrateFinish3(virConnectPtr dconn,
4864                         const char *dname,
4865                         const char *cookiein,
4866                         int cookieinlen,
4867                         char **cookieout,
4868                         int *cookieoutlen,
4869                         const char *dconnuri,
4870                         const char *uri,
4871                         unsigned long flags,
4872                         int cancelled)
4873 {
4874     VIR_DEBUG("dconn=%p, dname=%s, cookiein=%p, cookieinlen=%d, cookieout=%p,"
4875               "cookieoutlen=%p, dconnuri=%s, uri=%s, flags=0x%lx, retcode=%d",
4876               dconn, NULLSTR(dname), cookiein, cookieinlen, cookieout,
4877               cookieoutlen, NULLSTR(dconnuri), NULLSTR(uri), flags, cancelled);
4878 
4879     virResetLastError();
4880 
4881     virCheckConnectReturn(dconn, NULL);
4882     virCheckReadOnlyGoto(dconn->flags, error);
4883 
4884     if (dconn->driver->domainMigrateFinish3) {
4885         virDomainPtr ret;
4886         ret = dconn->driver->domainMigrateFinish3(dconn, dname,
4887                                                   cookiein, cookieinlen,
4888                                                   cookieout, cookieoutlen,
4889                                                   dconnuri, uri, flags,
4890                                                   cancelled);
4891         if (!ret && !cancelled)
4892             goto error;
4893         return ret;
4894     }
4895 
4896     virReportUnsupportedError();
4897 
4898  error:
4899     virDispatchError(dconn);
4900     return NULL;
4901 }
4902 
4903 
4904 /*
4905  * Not for public use.  This function is part of the internal
4906  * implementation of migration in the remote case.
4907  */
4908 int
virDomainMigrateConfirm3(virDomainPtr domain,const char * cookiein,int cookieinlen,unsigned long flags,int cancelled)4909 virDomainMigrateConfirm3(virDomainPtr domain,
4910                          const char *cookiein,
4911                          int cookieinlen,
4912                          unsigned long flags,
4913                          int cancelled)
4914 {
4915     virConnectPtr conn;
4916 
4917     VIR_DOMAIN_DEBUG(domain,
4918                      "cookiein=%p, cookieinlen=%d, flags=0x%lx, cancelled=%d",
4919                      cookiein, cookieinlen, flags, cancelled);
4920 
4921     virResetLastError();
4922 
4923     virCheckDomainReturn(domain, -1);
4924     conn = domain->conn;
4925 
4926     virCheckReadOnlyGoto(conn->flags, error);
4927 
4928     if (conn->driver->domainMigrateConfirm3) {
4929         int ret;
4930         ret = conn->driver->domainMigrateConfirm3(domain,
4931                                                   cookiein, cookieinlen,
4932                                                   flags, cancelled);
4933         if (ret < 0)
4934             goto error;
4935         return ret;
4936     }
4937 
4938     virReportUnsupportedError();
4939 
4940  error:
4941     virDispatchError(domain->conn);
4942     return -1;
4943 }
4944 
4945 
4946 /*
4947  * Not for public use.  This function is part of the internal
4948  * implementation of migration in the remote case.
4949  */
4950 char *
virDomainMigrateBegin3Params(virDomainPtr domain,virTypedParameterPtr params,int nparams,char ** cookieout,int * cookieoutlen,unsigned int flags)4951 virDomainMigrateBegin3Params(virDomainPtr domain,
4952                              virTypedParameterPtr params,
4953                              int nparams,
4954                              char **cookieout,
4955                              int *cookieoutlen,
4956                              unsigned int flags)
4957 {
4958     virConnectPtr conn;
4959 
4960     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, "
4961                      "cookieout=%p, cookieoutlen=%p, flags=0x%x",
4962                      params, nparams, cookieout, cookieoutlen, flags);
4963     VIR_TYPED_PARAMS_DEBUG(params, nparams);
4964 
4965     virResetLastError();
4966 
4967     virCheckDomainReturn(domain, NULL);
4968     conn = domain->conn;
4969 
4970     virCheckReadOnlyGoto(conn->flags, error);
4971 
4972     if (conn->driver->domainMigrateBegin3Params) {
4973         char *xml;
4974         xml = conn->driver->domainMigrateBegin3Params(domain, params, nparams,
4975                                                       cookieout, cookieoutlen,
4976                                                       flags);
4977         VIR_DEBUG("xml %s", NULLSTR(xml));
4978         if (!xml)
4979             goto error;
4980         return xml;
4981     }
4982 
4983     virReportUnsupportedError();
4984 
4985  error:
4986     virDispatchError(domain->conn);
4987     return NULL;
4988 }
4989 
4990 
4991 /*
4992  * Not for public use.  This function is part of the internal
4993  * implementation of migration in the remote case.
4994  */
4995 int
virDomainMigratePrepare3Params(virConnectPtr dconn,virTypedParameterPtr params,int nparams,const char * cookiein,int cookieinlen,char ** cookieout,int * cookieoutlen,char ** uri_out,unsigned int flags)4996 virDomainMigratePrepare3Params(virConnectPtr dconn,
4997                                virTypedParameterPtr params,
4998                                int nparams,
4999                                const char *cookiein,
5000                                int cookieinlen,
5001                                char **cookieout,
5002                                int *cookieoutlen,
5003                                char **uri_out,
5004                                unsigned int flags)
5005 {
5006     VIR_DEBUG("dconn=%p, params=%p, nparams=%d, cookiein=%p, cookieinlen=%d, "
5007               "cookieout=%p, cookieoutlen=%p, uri_out=%p, flags=0x%x",
5008               dconn, params, nparams, cookiein, cookieinlen,
5009               cookieout, cookieoutlen, uri_out, flags);
5010     VIR_TYPED_PARAMS_DEBUG(params, nparams);
5011 
5012     virResetLastError();
5013 
5014     virCheckConnectReturn(dconn, -1);
5015     virCheckReadOnlyGoto(dconn->flags, error);
5016 
5017     if (dconn->driver->domainMigratePrepare3Params) {
5018         int ret;
5019         ret = dconn->driver->domainMigratePrepare3Params(dconn, params, nparams,
5020                                                          cookiein, cookieinlen,
5021                                                          cookieout, cookieoutlen,
5022                                                          uri_out, flags);
5023         if (ret < 0)
5024             goto error;
5025         return ret;
5026     }
5027 
5028     virReportUnsupportedError();
5029 
5030  error:
5031     virDispatchError(dconn);
5032     return -1;
5033 }
5034 
5035 
5036 /*
5037  * Not for public use.  This function is part of the internal
5038  * implementation of migration in the remote case.
5039  */
5040 int
virDomainMigratePrepareTunnel3Params(virConnectPtr conn,virStreamPtr st,virTypedParameterPtr params,int nparams,const char * cookiein,int cookieinlen,char ** cookieout,int * cookieoutlen,unsigned int flags)5041 virDomainMigratePrepareTunnel3Params(virConnectPtr conn,
5042                                      virStreamPtr st,
5043                                      virTypedParameterPtr params,
5044                                      int nparams,
5045                                      const char *cookiein,
5046                                      int cookieinlen,
5047                                      char **cookieout,
5048                                      int *cookieoutlen,
5049                                      unsigned int flags)
5050 {
5051     VIR_DEBUG("conn=%p, stream=%p, params=%p, nparams=%d, cookiein=%p, "
5052               "cookieinlen=%d, cookieout=%p, cookieoutlen=%p, flags=0x%x",
5053               conn, st, params, nparams, cookiein, cookieinlen,
5054               cookieout, cookieoutlen, flags);
5055     VIR_TYPED_PARAMS_DEBUG(params, nparams);
5056 
5057     virResetLastError();
5058 
5059     virCheckConnectReturn(conn, -1);
5060     virCheckReadOnlyGoto(conn->flags, error);
5061 
5062     if (conn != st->conn) {
5063         virReportInvalidArg(conn, "%s",
5064                             _("conn must match stream connection"));
5065         goto error;
5066     }
5067 
5068     if (conn->driver->domainMigratePrepareTunnel3Params) {
5069         int rv;
5070         rv = conn->driver->domainMigratePrepareTunnel3Params(
5071                 conn, st, params, nparams, cookiein, cookieinlen,
5072                 cookieout, cookieoutlen, flags);
5073         if (rv < 0)
5074             goto error;
5075         return rv;
5076     }
5077 
5078     virReportUnsupportedError();
5079 
5080  error:
5081     virDispatchError(conn);
5082     return -1;
5083 }
5084 
5085 
5086 /*
5087  * Not for public use.  This function is part of the internal
5088  * implementation of migration in the remote case.
5089  */
5090 int
virDomainMigratePerform3Params(virDomainPtr domain,const char * dconnuri,virTypedParameterPtr params,int nparams,const char * cookiein,int cookieinlen,char ** cookieout,int * cookieoutlen,unsigned int flags)5091 virDomainMigratePerform3Params(virDomainPtr domain,
5092                                const char *dconnuri,
5093                                virTypedParameterPtr params,
5094                                int nparams,
5095                                const char *cookiein,
5096                                int cookieinlen,
5097                                char **cookieout,
5098                                int *cookieoutlen,
5099                                unsigned int flags)
5100 {
5101     virConnectPtr conn;
5102 
5103     VIR_DOMAIN_DEBUG(domain, "dconnuri=%s, params=%p, nparams=%d, cookiein=%p, "
5104                      "cookieinlen=%d, cookieout=%p, cookieoutlen=%p, flags=0x%x",
5105                      NULLSTR(dconnuri), params, nparams, cookiein,
5106                      cookieinlen, cookieout, cookieoutlen, flags);
5107     VIR_TYPED_PARAMS_DEBUG(params, nparams);
5108 
5109     virResetLastError();
5110 
5111     virCheckDomainReturn(domain, -1);
5112     conn = domain->conn;
5113 
5114     virCheckReadOnlyGoto(conn->flags, error);
5115 
5116     if (conn->driver->domainMigratePerform3Params) {
5117         int ret;
5118         ret = conn->driver->domainMigratePerform3Params(
5119                 domain, dconnuri, params, nparams, cookiein, cookieinlen,
5120                 cookieout, cookieoutlen, flags);
5121         if (ret < 0)
5122             goto error;
5123         return ret;
5124     }
5125 
5126     virReportUnsupportedError();
5127 
5128  error:
5129     virDispatchError(domain->conn);
5130     return -1;
5131 }
5132 
5133 
5134 /*
5135  * Not for public use.  This function is part of the internal
5136  * implementation of migration in the remote case.
5137  */
5138 virDomainPtr
virDomainMigrateFinish3Params(virConnectPtr dconn,virTypedParameterPtr params,int nparams,const char * cookiein,int cookieinlen,char ** cookieout,int * cookieoutlen,unsigned int flags,int cancelled)5139 virDomainMigrateFinish3Params(virConnectPtr dconn,
5140                               virTypedParameterPtr params,
5141                               int nparams,
5142                               const char *cookiein,
5143                               int cookieinlen,
5144                               char **cookieout,
5145                               int *cookieoutlen,
5146                               unsigned int flags,
5147                               int cancelled)
5148 {
5149     VIR_DEBUG("dconn=%p, params=%p, nparams=%d, cookiein=%p, cookieinlen=%d, "
5150               "cookieout=%p, cookieoutlen=%p, flags=0x%x, cancelled=%d",
5151               dconn, params, nparams, cookiein, cookieinlen, cookieout,
5152               cookieoutlen, flags, cancelled);
5153     VIR_TYPED_PARAMS_DEBUG(params, nparams);
5154 
5155     virResetLastError();
5156 
5157     virCheckConnectReturn(dconn, NULL);
5158     virCheckReadOnlyGoto(dconn->flags, error);
5159 
5160     if (dconn->driver->domainMigrateFinish3Params) {
5161         virDomainPtr ret;
5162         ret = dconn->driver->domainMigrateFinish3Params(
5163                 dconn, params, nparams, cookiein, cookieinlen,
5164                 cookieout, cookieoutlen, flags, cancelled);
5165         if (!ret && !cancelled)
5166             goto error;
5167         return ret;
5168     }
5169 
5170     virReportUnsupportedError();
5171 
5172  error:
5173     virDispatchError(dconn);
5174     return NULL;
5175 }
5176 
5177 
5178 /*
5179  * Not for public use.  This function is part of the internal
5180  * implementation of migration in the remote case.
5181  */
5182 int
virDomainMigrateConfirm3Params(virDomainPtr domain,virTypedParameterPtr params,int nparams,const char * cookiein,int cookieinlen,unsigned int flags,int cancelled)5183 virDomainMigrateConfirm3Params(virDomainPtr domain,
5184                                virTypedParameterPtr params,
5185                                int nparams,
5186                                const char *cookiein,
5187                                int cookieinlen,
5188                                unsigned int flags,
5189                                int cancelled)
5190 {
5191     virConnectPtr conn;
5192 
5193     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, cookiein=%p, "
5194                      "cookieinlen=%d, flags=0x%x, cancelled=%d",
5195                      params, nparams, cookiein, cookieinlen, flags, cancelled);
5196     VIR_TYPED_PARAMS_DEBUG(params, nparams);
5197 
5198     virResetLastError();
5199 
5200     virCheckDomainReturn(domain, -1);
5201     conn = domain->conn;
5202 
5203     virCheckReadOnlyGoto(conn->flags, error);
5204 
5205     if (conn->driver->domainMigrateConfirm3Params) {
5206         int ret;
5207         ret = conn->driver->domainMigrateConfirm3Params(
5208                 domain, params, nparams,
5209                 cookiein, cookieinlen, flags, cancelled);
5210         if (ret < 0)
5211             goto error;
5212         return ret;
5213     }
5214 
5215     virReportUnsupportedError();
5216 
5217  error:
5218     virDispatchError(domain->conn);
5219     return -1;
5220 }
5221 
5222 
5223 /**
5224  * virDomainGetSchedulerType:
5225  * @domain: pointer to domain object
5226  * @nparams: pointer to number of scheduler parameters, can be NULL
5227  *           (return value)
5228  *
5229  * Get the scheduler type and the number of scheduler parameters.
5230  *
5231  * Returns NULL in case of error. The caller must free the returned string.
5232  */
5233 char *
virDomainGetSchedulerType(virDomainPtr domain,int * nparams)5234 virDomainGetSchedulerType(virDomainPtr domain, int *nparams)
5235 {
5236     virConnectPtr conn;
5237     char *schedtype;
5238 
5239     VIR_DOMAIN_DEBUG(domain, "nparams=%p", nparams);
5240 
5241     virResetLastError();
5242 
5243     virCheckDomainReturn(domain, NULL);
5244     conn = domain->conn;
5245 
5246     if (conn->driver->domainGetSchedulerType) {
5247         schedtype = conn->driver->domainGetSchedulerType(domain, nparams);
5248         if (!schedtype)
5249             goto error;
5250         return schedtype;
5251     }
5252 
5253     virReportUnsupportedError();
5254 
5255  error:
5256     virDispatchError(domain->conn);
5257     return NULL;
5258 }
5259 
5260 
5261 /**
5262  * virDomainGetSchedulerParameters:
5263  * @domain: pointer to domain object
5264  * @params: pointer to scheduler parameter objects
5265  *          (return value)
5266  * @nparams: pointer to number of scheduler parameter objects
5267  *          (this value should generally be as large as the returned value
5268  *           nparams of virDomainGetSchedulerType()); input and output
5269  *
5270  * Get all scheduler parameters.  On input, @nparams gives the size of the
5271  * @params array; on output, @nparams gives how many slots were filled
5272  * with parameter information, which might be less but will not exceed
5273  * the input value.  @nparams cannot be 0.
5274  *
5275  * It is hypervisor specific whether this returns the live or
5276  * persistent state; for more control, use
5277  * virDomainGetSchedulerParametersFlags().
5278  *
5279  * Returns -1 in case of error, 0 in case of success.
5280  */
5281 int
virDomainGetSchedulerParameters(virDomainPtr domain,virTypedParameterPtr params,int * nparams)5282 virDomainGetSchedulerParameters(virDomainPtr domain,
5283                                 virTypedParameterPtr params, int *nparams)
5284 {
5285     virConnectPtr conn;
5286 
5287     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p", params, nparams);
5288 
5289     virResetLastError();
5290 
5291     virCheckDomainReturn(domain, -1);
5292 
5293     virCheckNonNullArgGoto(params, error);
5294     virCheckNonNullArgGoto(nparams, error);
5295     virCheckPositiveArgGoto(*nparams, error);
5296 
5297     conn = domain->conn;
5298 
5299     if (conn->driver->domainGetSchedulerParameters) {
5300         int ret;
5301         ret = conn->driver->domainGetSchedulerParameters(domain, params, nparams);
5302         if (ret < 0)
5303             goto error;
5304         return ret;
5305     }
5306 
5307     virReportUnsupportedError();
5308 
5309  error:
5310     virDispatchError(domain->conn);
5311     return -1;
5312 }
5313 
5314 
5315 /**
5316  * virDomainGetSchedulerParametersFlags:
5317  * @domain: pointer to domain object
5318  * @params: pointer to scheduler parameter object
5319  *          (return value)
5320  * @nparams: pointer to number of scheduler parameter
5321  *          (this value should be same than the returned value
5322  *           nparams of virDomainGetSchedulerType()); input and output
5323  * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
5324  *
5325  * Get all scheduler parameters.  On input, @nparams gives the size of the
5326  * @params array; on output, @nparams gives how many slots were filled
5327  * with parameter information, which might be less but will not exceed
5328  * the input value.  @nparams cannot be 0.
5329  *
5330  * The value of @flags can be exactly VIR_DOMAIN_AFFECT_CURRENT,
5331  * VIR_DOMAIN_AFFECT_LIVE, or VIR_DOMAIN_AFFECT_CONFIG.
5332  *
5333  * Here is a sample code snippet:
5334  *
5335  *   char *ret = virDomainGetSchedulerType(dom, &nparams);
5336  *   if (ret && nparams != 0) {
5337  *       if ((params = malloc(sizeof(*params) * nparams)) == NULL)
5338  *           goto error;
5339  *       memset(params, 0, sizeof(*params) * nparams);
5340  *       if (virDomainGetSchedulerParametersFlags(dom, params, &nparams, 0))
5341  *           goto error;
5342  *   }
5343  *
5344  * Returns -1 in case of error, 0 in case of success.
5345  */
5346 int
virDomainGetSchedulerParametersFlags(virDomainPtr domain,virTypedParameterPtr params,int * nparams,unsigned int flags)5347 virDomainGetSchedulerParametersFlags(virDomainPtr domain,
5348                                      virTypedParameterPtr params, int *nparams,
5349                                      unsigned int flags)
5350 {
5351     virConnectPtr conn;
5352     int rc;
5353 
5354     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p, flags=0x%x",
5355                      params, nparams, flags);
5356 
5357     virResetLastError();
5358 
5359     virCheckDomainReturn(domain, -1);
5360 
5361     virCheckNonNullArgGoto(params, error);
5362     virCheckNonNullArgGoto(nparams, error);
5363     virCheckPositiveArgGoto(*nparams, error);
5364 
5365     rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
5366                                   VIR_DRV_FEATURE_TYPED_PARAM_STRING);
5367     if (rc < 0)
5368         goto error;
5369     if (rc)
5370         flags |= VIR_TYPED_PARAM_STRING_OKAY;
5371 
5372     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE,
5373                              VIR_DOMAIN_AFFECT_CONFIG,
5374                              error);
5375 
5376     conn = domain->conn;
5377 
5378     if (conn->driver->domainGetSchedulerParametersFlags) {
5379         int ret;
5380         ret = conn->driver->domainGetSchedulerParametersFlags(domain, params,
5381                                                               nparams, flags);
5382         if (ret < 0)
5383             goto error;
5384         return ret;
5385     }
5386 
5387     virReportUnsupportedError();
5388 
5389  error:
5390     virDispatchError(domain->conn);
5391     return -1;
5392 }
5393 
5394 
5395 /**
5396  * virDomainSetSchedulerParameters:
5397  * @domain: pointer to domain object
5398  * @params: pointer to scheduler parameter objects
5399  * @nparams: number of scheduler parameter objects
5400  *          (this value can be the same or less than the returned value
5401  *           nparams of virDomainGetSchedulerType)
5402  *
5403  * Change all or a subset or the scheduler parameters.  It is
5404  * hypervisor-specific whether this sets live, persistent, or both
5405  * settings; for more control, use
5406  * virDomainSetSchedulerParametersFlags.
5407  *
5408  * Returns -1 in case of error, 0 in case of success.
5409  */
5410 int
virDomainSetSchedulerParameters(virDomainPtr domain,virTypedParameterPtr params,int nparams)5411 virDomainSetSchedulerParameters(virDomainPtr domain,
5412                                 virTypedParameterPtr params, int nparams)
5413 {
5414     virConnectPtr conn;
5415 
5416     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d", params, nparams);
5417     VIR_TYPED_PARAMS_DEBUG(params, nparams);
5418 
5419     virResetLastError();
5420 
5421     virCheckDomainReturn(domain, -1);
5422     conn = domain->conn;
5423 
5424     virCheckReadOnlyGoto(conn->flags, error);
5425     virCheckNonNullArgGoto(params, error);
5426     virCheckNonNegativeArgGoto(nparams, error);
5427 
5428     if (virTypedParameterValidateSet(conn, params, nparams) < 0)
5429         goto error;
5430 
5431     if (conn->driver->domainSetSchedulerParameters) {
5432         int ret;
5433         ret = conn->driver->domainSetSchedulerParameters(domain, params, nparams);
5434         if (ret < 0)
5435             goto error;
5436         return ret;
5437     }
5438 
5439     virReportUnsupportedError();
5440 
5441  error:
5442     virDispatchError(domain->conn);
5443     return -1;
5444 }
5445 
5446 
5447 /**
5448  * virDomainSetSchedulerParametersFlags:
5449  * @domain: pointer to domain object
5450  * @params: pointer to scheduler parameter objects
5451  * @nparams: number of scheduler parameter objects
5452  *          (this value can be the same or less than the returned value
5453  *           nparams of virDomainGetSchedulerType)
5454  * @flags: bitwise-OR of virDomainModificationImpact
5455  *
5456  * Change a subset or all scheduler parameters.  The value of @flags
5457  * should be either VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of
5458  * values from VIR_DOMAIN_AFFECT_LIVE and
5459  * VIR_DOMAIN_AFFECT_CURRENT, although hypervisors vary in which
5460  * flags are supported.
5461  *
5462  * Returns -1 in case of error, 0 in case of success.
5463  */
5464 int
virDomainSetSchedulerParametersFlags(virDomainPtr domain,virTypedParameterPtr params,int nparams,unsigned int flags)5465 virDomainSetSchedulerParametersFlags(virDomainPtr domain,
5466                                      virTypedParameterPtr params,
5467                                      int nparams,
5468                                      unsigned int flags)
5469 {
5470     virConnectPtr conn;
5471 
5472     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d, flags=0x%x",
5473                      params, nparams, flags);
5474     VIR_TYPED_PARAMS_DEBUG(params, nparams);
5475 
5476     virResetLastError();
5477 
5478     virCheckDomainReturn(domain, -1);
5479     conn = domain->conn;
5480 
5481     virCheckReadOnlyGoto(conn->flags, error);
5482     virCheckNonNullArgGoto(params, error);
5483     virCheckNonNegativeArgGoto(nparams, error);
5484 
5485     if (virTypedParameterValidateSet(conn, params, nparams) < 0)
5486         goto error;
5487 
5488     if (conn->driver->domainSetSchedulerParametersFlags) {
5489         int ret;
5490         ret = conn->driver->domainSetSchedulerParametersFlags(domain,
5491                                                               params,
5492                                                               nparams,
5493                                                               flags);
5494         if (ret < 0)
5495             goto error;
5496         return ret;
5497     }
5498 
5499     virReportUnsupportedError();
5500 
5501  error:
5502     virDispatchError(domain->conn);
5503     return -1;
5504 }
5505 
5506 
5507 /**
5508  * virDomainBlockStats:
5509  * @dom: pointer to the domain object
5510  * @disk: path to the block device, or device shorthand
5511  * @stats: block device stats (returned)
5512  * @size: size of stats structure
5513  *
5514  * This function returns block device (disk) stats for block
5515  * devices attached to the domain.
5516  *
5517  * The @disk parameter is either the device target shorthand (the
5518  * <target dev='...'/> sub-element, such as "vda"), or (since 0.9.8)
5519  * an unambiguous source name of the block device (the <source
5520  * file='...'/> sub-element, such as "/path/to/image").  Valid names
5521  * can be found by calling virDomainGetXMLDesc() and inspecting
5522  * elements within //domain/devices/disk. Some drivers might also
5523  * accept the empty string for the @disk parameter, and then yield
5524  * summary stats for the entire domain.
5525  *
5526  * Domains may have more than one block device.  To get stats for
5527  * each you should make multiple calls to this function.
5528  *
5529  * Individual fields within the stats structure may be returned
5530  * as -1, which indicates that the hypervisor does not support
5531  * that particular statistic.
5532  *
5533  * Returns: 0 in case of success or -1 in case of failure.
5534  */
5535 int
virDomainBlockStats(virDomainPtr dom,const char * disk,virDomainBlockStatsPtr stats,size_t size)5536 virDomainBlockStats(virDomainPtr dom, const char *disk,
5537                     virDomainBlockStatsPtr stats, size_t size)
5538 {
5539     virConnectPtr conn;
5540     virDomainBlockStatsStruct stats2 = { -1, -1, -1, -1, -1 };
5541 
5542     VIR_DOMAIN_DEBUG(dom, "disk=%s, stats=%p, size=%zi", disk, stats, size);
5543 
5544     virResetLastError();
5545 
5546     virCheckDomainReturn(dom, -1);
5547     virCheckNonNullArgGoto(disk, error);
5548     virCheckNonNullArgGoto(stats, error);
5549     if (size > sizeof(stats2)) {
5550         virReportInvalidArg(size,
5551                             _("size must not exceed %zu"),
5552                             sizeof(stats2));
5553         goto error;
5554     }
5555     conn = dom->conn;
5556 
5557     if (conn->driver->domainBlockStats) {
5558         if (conn->driver->domainBlockStats(dom, disk, &stats2) == -1)
5559             goto error;
5560 
5561         memcpy(stats, &stats2, size);
5562         return 0;
5563     }
5564 
5565     virReportUnsupportedError();
5566 
5567  error:
5568     virDispatchError(dom->conn);
5569     return -1;
5570 }
5571 
5572 
5573 /**
5574  * virDomainBlockStatsFlags:
5575  * @dom: pointer to domain object
5576  * @disk: path to the block device, or device shorthand
5577  * @params: pointer to block stats parameter object
5578  *          (return value, allocated by the caller)
5579  * @nparams: pointer to number of block stats; input and output
5580  * @flags: bitwise-OR of virTypedParameterFlags
5581  *
5582  * This function is to get block stats parameters for block
5583  * devices attached to the domain.
5584  *
5585  * The @disk parameter is either the device target shorthand (the
5586  * <target dev='...'/> sub-element, such as "vda"), or (since 0.9.8)
5587  * an unambiguous source name of the block device (the <source
5588  * file='...'/> sub-element, such as "/path/to/image").  Valid names
5589  * can be found by calling virDomainGetXMLDesc() and inspecting
5590  * elements within //domain/devices/disk. Some drivers might also
5591  * accept the empty string for the @disk parameter, and then yield
5592  * summary stats for the entire domain.
5593  *
5594  * Domains may have more than one block device.  To get stats for
5595  * each you should make multiple calls to this function.
5596  *
5597  * On input, @nparams gives the size of the @params array; on output,
5598  * @nparams gives how many slots were filled with parameter
5599  * information, which might be less but will not exceed the input
5600  * value.
5601  *
5602  * As a special case, calling with @params as NULL and @nparams as 0 on
5603  * input will cause @nparams on output to contain the number of parameters
5604  * supported by the hypervisor. (Note that block devices of different types
5605  * might support different parameters, so it might be necessary to compute
5606  * @nparams for each block device). The caller should then allocate @params
5607  * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
5608  * again. See virDomainGetMemoryParameters() for more details.
5609  *
5610  * Returns -1 in case of error, 0 in case of success.
5611  */
5612 int
virDomainBlockStatsFlags(virDomainPtr dom,const char * disk,virTypedParameterPtr params,int * nparams,unsigned int flags)5613 virDomainBlockStatsFlags(virDomainPtr dom,
5614                          const char *disk,
5615                          virTypedParameterPtr params,
5616                          int *nparams,
5617                          unsigned int flags)
5618 {
5619     virConnectPtr conn;
5620     int rc;
5621 
5622     VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=0x%x",
5623                      disk, params, nparams ? *nparams : -1, flags);
5624 
5625     virResetLastError();
5626 
5627     virCheckDomainReturn(dom, -1);
5628     virCheckNonNullArgGoto(disk, error);
5629     virCheckNonNullArgGoto(nparams, error);
5630     virCheckNonNegativeArgGoto(*nparams, error);
5631     if (*nparams != 0)
5632         virCheckNonNullArgGoto(params, error);
5633 
5634     rc = VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn,
5635                                   VIR_DRV_FEATURE_TYPED_PARAM_STRING);
5636     if (rc < 0)
5637         goto error;
5638     if (rc)
5639         flags |= VIR_TYPED_PARAM_STRING_OKAY;
5640     conn = dom->conn;
5641 
5642     if (conn->driver->domainBlockStatsFlags) {
5643         int ret;
5644         ret = conn->driver->domainBlockStatsFlags(dom, disk, params, nparams, flags);
5645         if (ret < 0)
5646             goto error;
5647         return ret;
5648     }
5649     virReportUnsupportedError();
5650 
5651  error:
5652     virDispatchError(dom->conn);
5653     return -1;
5654 }
5655 
5656 
5657 /**
5658  * virDomainInterfaceStats:
5659  * @dom: pointer to the domain object
5660  * @device: the interface name or MAC address
5661  * @stats: network interface stats (returned)
5662  * @size: size of stats structure
5663  *
5664  * This function returns network interface stats for interfaces
5665  * attached to the domain.
5666  *
5667  * The @device parameter is the network interface either by name or MAC
5668  * address.
5669  *
5670  * Domains may have more than one network interface.  To get stats for
5671  * each you should make multiple calls to this function.
5672  *
5673  * Individual fields within the stats structure may be returned
5674  * as -1, which indicates that the hypervisor does not support
5675  * that particular statistic.
5676  *
5677  * The returned stats are from domain's point of view.
5678  *
5679  * Returns: 0 in case of success or -1 in case of failure.
5680  */
5681 int
virDomainInterfaceStats(virDomainPtr dom,const char * device,virDomainInterfaceStatsPtr stats,size_t size)5682 virDomainInterfaceStats(virDomainPtr dom, const char *device,
5683                         virDomainInterfaceStatsPtr stats, size_t size)
5684 {
5685     virConnectPtr conn;
5686     virDomainInterfaceStatsStruct stats2 = { -1, -1, -1, -1,
5687                                              -1, -1, -1, -1 };
5688 
5689     VIR_DOMAIN_DEBUG(dom, "device=%s, stats=%p, size=%zi",
5690                      device, stats, size);
5691 
5692     virResetLastError();
5693 
5694     virCheckDomainReturn(dom, -1);
5695     virCheckNonNullArgGoto(device, error);
5696     virCheckNonNullArgGoto(stats, error);
5697     if (size > sizeof(stats2)) {
5698         virReportInvalidArg(size,
5699                             _("size must not exceed %zu"),
5700                             sizeof(stats2));
5701         goto error;
5702     }
5703 
5704     conn = dom->conn;
5705 
5706     if (conn->driver->domainInterfaceStats) {
5707         if (conn->driver->domainInterfaceStats(dom, device, &stats2) == -1)
5708             goto error;
5709 
5710         memcpy(stats, &stats2, size);
5711         return 0;
5712     }
5713 
5714     virReportUnsupportedError();
5715 
5716  error:
5717     virDispatchError(dom->conn);
5718     return -1;
5719 }
5720 
5721 
5722 /**
5723  * virDomainSetInterfaceParameters:
5724  * @domain: pointer to domain object
5725  * @device: the interface name or mac address
5726  * @params: pointer to interface parameter objects
5727  * @nparams: number of interface parameter (this value can be the same or
5728  *          less than the number of parameters supported)
5729  * @flags: bitwise-OR of virDomainModificationImpact
5730  *
5731  * Change a subset or all parameters of interface; currently this
5732  * includes bandwidth parameters.  The value of @flags should be
5733  * either VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of values
5734  * VIR_DOMAIN_AFFECT_LIVE and VIR_DOMAIN_AFFECT_CONFIG, although
5735  * hypervisors vary in which flags are supported.
5736  *
5737  * This function may require privileged access to the hypervisor.
5738  *
5739  * Returns -1 in case of error, 0 in case of success.
5740  */
5741 int
virDomainSetInterfaceParameters(virDomainPtr domain,const char * device,virTypedParameterPtr params,int nparams,unsigned int flags)5742 virDomainSetInterfaceParameters(virDomainPtr domain,
5743                                 const char *device,
5744                                 virTypedParameterPtr params,
5745                                 int nparams, unsigned int flags)
5746 {
5747     virConnectPtr conn;
5748 
5749     VIR_DOMAIN_DEBUG(domain, "device=%s, params=%p, nparams=%d, flags=0x%x",
5750                      device, params, nparams, flags);
5751     VIR_TYPED_PARAMS_DEBUG(params, nparams);
5752 
5753     virResetLastError();
5754 
5755     virCheckDomainReturn(domain, -1);
5756     conn = domain->conn;
5757 
5758     virCheckReadOnlyGoto(conn->flags, error);
5759     virCheckNonNullArgGoto(params, error);
5760     virCheckPositiveArgGoto(nparams, error);
5761 
5762     if (virTypedParameterValidateSet(conn, params, nparams) < 0)
5763         goto error;
5764 
5765     if (conn->driver->domainSetInterfaceParameters) {
5766         int ret;
5767         ret = conn->driver->domainSetInterfaceParameters(domain, device,
5768                                                          params, nparams,
5769                                                          flags);
5770         if (ret < 0)
5771             goto error;
5772         return ret;
5773     }
5774 
5775     virReportUnsupportedError();
5776 
5777  error:
5778     virDispatchError(domain->conn);
5779     return -1;
5780 }
5781 
5782 
5783 /**
5784  * virDomainGetInterfaceParameters:
5785  * @domain: pointer to domain object
5786  * @device: the interface name or mac address
5787  * @params: pointer to interface parameter objects
5788  *          (return value, allocated by the caller)
5789  * @nparams: pointer to number of interface parameter; input and output
5790  * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
5791  *
5792  * Get all interface parameters. On input, @nparams gives the size of
5793  * the @params array; on output, @nparams gives how many slots were
5794  * filled with parameter information, which might be less but will not
5795  * exceed the input value.
5796  *
5797  * As a special case, calling with @params as NULL and @nparams as 0 on
5798  * input will cause @nparams on output to contain the number of parameters
5799  * supported by the hypervisor. The caller should then allocate @params
5800  * array, i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the
5801  * API again. See virDomainGetMemoryParameters() for an equivalent usage
5802  * example.
5803  *
5804  * This function may require privileged access to the hypervisor. This function
5805  * expects the caller to allocate the @params.
5806  *
5807  * Returns -1 in case of error, 0 in case of success.
5808  */
5809 int
virDomainGetInterfaceParameters(virDomainPtr domain,const char * device,virTypedParameterPtr params,int * nparams,unsigned int flags)5810 virDomainGetInterfaceParameters(virDomainPtr domain,
5811                                 const char *device,
5812                                 virTypedParameterPtr params,
5813                                 int *nparams, unsigned int flags)
5814 {
5815     virConnectPtr conn;
5816     int rc;
5817 
5818     VIR_DOMAIN_DEBUG(domain, "device=%s, params=%p, nparams=%d, flags=0x%x",
5819                      device, params, (nparams) ? *nparams : -1, flags);
5820 
5821     virResetLastError();
5822 
5823     virCheckDomainReturn(domain, -1);
5824     virCheckNonNullArgGoto(nparams, error);
5825     virCheckNonNegativeArgGoto(*nparams, error);
5826     if (*nparams != 0)
5827         virCheckNonNullArgGoto(params, error);
5828 
5829     rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
5830                                   VIR_DRV_FEATURE_TYPED_PARAM_STRING);
5831     if (rc < 0)
5832         goto error;
5833     if (rc)
5834         flags |= VIR_TYPED_PARAM_STRING_OKAY;
5835 
5836     conn = domain->conn;
5837 
5838     if (conn->driver->domainGetInterfaceParameters) {
5839         int ret;
5840         ret = conn->driver->domainGetInterfaceParameters(domain, device,
5841                                                          params, nparams,
5842                                                          flags);
5843         if (ret < 0)
5844             goto error;
5845         return ret;
5846     }
5847     virReportUnsupportedError();
5848 
5849  error:
5850     virDispatchError(domain->conn);
5851     return -1;
5852 }
5853 
5854 
5855 /**
5856  * virDomainMemoryStats:
5857  * @dom: pointer to the domain object
5858  * @stats: nr_stats-sized array of stat structures (returned)
5859  * @nr_stats: number of memory statistics requested
5860  * @flags: extra flags; not used yet, so callers should always pass 0
5861  *
5862  * This function provides memory statistics for the domain.
5863  *
5864  * Up to 'nr_stats' elements of 'stats' will be populated with memory statistics
5865  * from the domain.  Only statistics supported by the domain, the driver, and
5866  * this version of libvirt will be returned.
5867  *
5868  * Memory Statistics:
5869  *
5870  * VIR_DOMAIN_MEMORY_STAT_SWAP_IN:
5871  *     The total amount of data read from swap space (in kb).
5872  * VIR_DOMAIN_MEMORY_STAT_SWAP_OUT:
5873  *     The total amount of memory written out to swap space (in kb).
5874  * VIR_DOMAIN_MEMORY_STAT_MAJOR_FAULT:
5875  *     The number of page faults that required disk IO to service.
5876  * VIR_DOMAIN_MEMORY_STAT_MINOR_FAULT:
5877  *     The number of page faults serviced without disk IO.
5878  * VIR_DOMAIN_MEMORY_STAT_UNUSED:
5879  *     The amount of memory which is not being used for any purpose (in kb).
5880  * VIR_DOMAIN_MEMORY_STAT_AVAILABLE:
5881  *     The total amount of memory available to the domain's OS (in kb).
5882  * VIR_DOMAIN_MEMORY_STAT_USABLE:
5883  *     How much the balloon can be inflated without pushing the guest system
5884  *     to swap, corresponds to 'Available' in /proc/meminfo
5885  * VIR_DOMAIN_MEMORY_STAT_ACTUAL_BALLOON:
5886  *     Current balloon value (in kb).
5887  * VIR_DOMAIN_MEMORY_STAT_LAST_UPDATE
5888  *     Timestamp of the last statistic
5889  * VIR_DOMAIN_MEMORY_STAT_DISK_CACHES
5890  *     Memory that can be reclaimed without additional I/O, typically disk
5891  *     caches (in kb).
5892  * VIR_DOMAIN_MEMORY_STAT_HUGETLB_PGALLOC
5893  *     The number of successful huge page allocations from inside the domain
5894  * VIR_DOMAIN_MEMORY_STAT_HUGETLB_PGFAIL
5895  *     The number of failed huge page allocations from inside the domain
5896  *
5897  * Returns: The number of stats provided or -1 in case of failure.
5898  */
5899 int
virDomainMemoryStats(virDomainPtr dom,virDomainMemoryStatPtr stats,unsigned int nr_stats,unsigned int flags)5900 virDomainMemoryStats(virDomainPtr dom, virDomainMemoryStatPtr stats,
5901                      unsigned int nr_stats, unsigned int flags)
5902 {
5903     virConnectPtr conn;
5904 
5905     VIR_DOMAIN_DEBUG(dom, "stats=%p, nr_stats=%u, flags=0x%x",
5906                      stats, nr_stats, flags);
5907 
5908     virResetLastError();
5909 
5910     virCheckDomainReturn(dom, -1);
5911 
5912     if (!stats || nr_stats == 0)
5913         return 0;
5914 
5915     if (nr_stats > VIR_DOMAIN_MEMORY_STAT_NR)
5916         nr_stats = VIR_DOMAIN_MEMORY_STAT_NR;
5917 
5918     conn = dom->conn;
5919     if (conn->driver->domainMemoryStats) {
5920         int ret = conn->driver->domainMemoryStats(dom, stats, nr_stats, flags);
5921         if (ret == -1)
5922             goto error;
5923         return ret;
5924     }
5925 
5926     virReportUnsupportedError();
5927 
5928  error:
5929     virDispatchError(dom->conn);
5930     return -1;
5931 }
5932 
5933 
5934 /**
5935  * virDomainBlockPeek:
5936  * @dom: pointer to the domain object
5937  * @disk: path to the block device, or device shorthand
5938  * @offset: offset within block device
5939  * @size: size to read
5940  * @buffer: return buffer (must be at least size bytes)
5941  * @flags: extra flags; not used yet, so callers should always pass 0
5942  *
5943  * This function allows you to read the contents of a domain's
5944  * disk device.
5945  *
5946  * Typical uses for this are to determine if the domain has
5947  * written a Master Boot Record (indicating that the domain
5948  * has completed installation), or to try to work out the state
5949  * of the domain's filesystems.
5950  *
5951  * (Note that in the local case you might try to open the
5952  * block device or file directly, but that won't work in the
5953  * remote case, nor if you don't have sufficient permission.
5954  * Hence the need for this call).
5955  *
5956  * The @disk parameter is either an unambiguous source name of the
5957  * block device (the <source file='...'/> sub-element, such as
5958  * "/path/to/image"), or (since 0.9.5) the device target shorthand
5959  * (the <target dev='...'/> sub-element, such as "vda").  Valid names
5960  * can be found by calling virDomainGetXMLDesc() and inspecting
5961  * elements within //domain/devices/disk.
5962  *
5963  * 'offset' and 'size' represent an area which must lie entirely
5964  * within the device or file.  'size' may be 0 to test if the
5965  * call would succeed.
5966  *
5967  * 'buffer' is the return buffer and must be at least 'size' bytes.
5968  *
5969  * NB. The remote driver imposes a 64K byte limit on 'size'.
5970  * For your program to be able to work reliably over a remote
5971  * connection you should split large requests to <= 65536 bytes.
5972  * However, with 0.9.13 this RPC limit has been raised to 1M byte.
5973  * Starting with version 1.0.6 the RPC limit has been raised again.
5974  * Now large requests up to 16M byte are supported.
5975  *
5976  * Returns: 0 in case of success or -1 in case of failure.
5977  */
5978 int
virDomainBlockPeek(virDomainPtr dom,const char * disk,unsigned long long offset,size_t size,void * buffer,unsigned int flags)5979 virDomainBlockPeek(virDomainPtr dom,
5980                    const char *disk,
5981                    unsigned long long offset,
5982                    size_t size,
5983                    void *buffer,
5984                    unsigned int flags)
5985 {
5986     virConnectPtr conn;
5987 
5988     VIR_DOMAIN_DEBUG(dom, "disk=%s, offset=%lld, size=%zi, buffer=%p, flags=0x%x",
5989                      disk, offset, size, buffer, flags);
5990 
5991     virResetLastError();
5992 
5993     virCheckDomainReturn(dom, -1);
5994     conn = dom->conn;
5995 
5996     virCheckReadOnlyGoto(conn->flags, error);
5997     virCheckNonEmptyStringArgGoto(disk, error);
5998 
5999     /* Allow size == 0 as an access test. */
6000     if (size > 0)
6001         virCheckNonNullArgGoto(buffer, error);
6002 
6003     if (conn->driver->domainBlockPeek) {
6004         int ret;
6005         ret = conn->driver->domainBlockPeek(dom, disk, offset, size,
6006                                             buffer, flags);
6007         if (ret < 0)
6008             goto error;
6009         return ret;
6010     }
6011 
6012     virReportUnsupportedError();
6013 
6014  error:
6015     virDispatchError(dom->conn);
6016     return -1;
6017 }
6018 
6019 
6020 /**
6021  * virDomainBlockResize:
6022  * @dom: pointer to the domain object
6023  * @disk: path to the block image, or shorthand
6024  * @size: new size of the block image, see below for unit
6025  * @flags: bitwise-OR of virDomainBlockResizeFlags
6026  *
6027  * Resize a block device of domain while the domain is running.  If
6028  * @flags is 0, then @size is in kibibytes (blocks of 1024 bytes);
6029  * since 0.9.11, if @flags includes VIR_DOMAIN_BLOCK_RESIZE_BYTES,
6030  * @size is in bytes instead.  @size is taken directly as the new
6031  * size.  Depending on the file format, the hypervisor may round up
6032  * to the next alignment boundary.
6033  *
6034  * The @disk parameter is either an unambiguous source name of the
6035  * block device (the <source file='...'/> sub-element, such as
6036  * "/path/to/image"), or (since 0.9.5) the device target shorthand
6037  * (the <target dev='...'/> sub-element, such as "vda").  Valid names
6038  * can be found by calling virDomainGetXMLDesc() and inspecting
6039  * elements within //domain/devices/disk.
6040  *
6041  * Note that this call may fail if the underlying virtualization hypervisor
6042  * does not support it; this call requires privileged access to the
6043  * hypervisor.
6044  *
6045  * Returns: 0 in case of success or -1 in case of failure.
6046  */
6047 int
virDomainBlockResize(virDomainPtr dom,const char * disk,unsigned long long size,unsigned int flags)6048 virDomainBlockResize(virDomainPtr dom,
6049                      const char *disk,
6050                      unsigned long long size,
6051                      unsigned int flags)
6052 {
6053     virConnectPtr conn;
6054 
6055     VIR_DOMAIN_DEBUG(dom, "disk=%s, size=%llu, flags=0x%x", disk, size, flags);
6056 
6057     virResetLastError();
6058 
6059     virCheckDomainReturn(dom, -1);
6060     conn = dom->conn;
6061 
6062     virCheckReadOnlyGoto(conn->flags, error);
6063     virCheckNonNullArgGoto(disk, error);
6064 
6065     if (conn->driver->domainBlockResize) {
6066         int ret;
6067         ret = conn->driver->domainBlockResize(dom, disk, size, flags);
6068         if (ret < 0)
6069             goto error;
6070         return ret;
6071     }
6072 
6073     virReportUnsupportedError();
6074 
6075  error:
6076     virDispatchError(dom->conn);
6077     return -1;
6078 }
6079 
6080 
6081 /**
6082  * virDomainMemoryPeek:
6083  * @dom: pointer to the domain object
6084  * @start: start of memory to peek
6085  * @size: size of memory to peek
6086  * @buffer: return buffer (must be at least size bytes)
6087  * @flags: bitwise-OR of virDomainMemoryFlags
6088  *
6089  * This function allows you to read the contents of a domain's
6090  * memory.
6091  *
6092  * The memory which is read is controlled by the 'start', 'size'
6093  * and 'flags' parameters.
6094  *
6095  * If 'flags' is VIR_MEMORY_VIRTUAL then the 'start' and 'size'
6096  * parameters are interpreted as virtual memory addresses for
6097  * whichever task happens to be running on the domain at the
6098  * moment.  Although this sounds haphazard it is in fact what
6099  * you want in order to read Linux kernel state, because it
6100  * ensures that pointers in the kernel image can be interpreted
6101  * coherently.
6102  *
6103  * 'buffer' is the return buffer and must be at least 'size' bytes.
6104  * 'size' may be 0 to test if the call would succeed.
6105  *
6106  * NB. The remote driver imposes a 64K byte limit on 'size'.
6107  * For your program to be able to work reliably over a remote
6108  * connection you should split large requests to <= 65536 bytes.
6109  * However, with 0.9.13 this RPC limit has been raised to 1M byte.
6110  * Starting with version 1.0.6 the RPC limit has been raised again.
6111  * Now large requests up to 16M byte are supported.
6112  *
6113  * Returns: 0 in case of success or -1 in case of failure.
6114  */
6115 int
virDomainMemoryPeek(virDomainPtr dom,unsigned long long start,size_t size,void * buffer,unsigned int flags)6116 virDomainMemoryPeek(virDomainPtr dom,
6117                     unsigned long long start,
6118                     size_t size,
6119                     void *buffer,
6120                     unsigned int flags)
6121 {
6122     virConnectPtr conn;
6123 
6124     VIR_DOMAIN_DEBUG(dom, "start=%lld, size=%zi, buffer=%p, flags=0x%x",
6125                      start, size, buffer, flags);
6126 
6127     virResetLastError();
6128 
6129     virCheckDomainReturn(dom, -1);
6130     conn = dom->conn;
6131 
6132     virCheckReadOnlyGoto(conn->flags, error);
6133 
6134     /* Note on access to physical memory: A VIR_MEMORY_PHYSICAL flag is
6135      * a possibility.  However it isn't really useful unless the caller
6136      * can also access registers, particularly CR3 on x86 in order to
6137      * get the Page Table Directory.  Since registers are different on
6138      * every architecture, that would imply another call to get the
6139      * machine registers.
6140      *
6141      * The QEMU driver handles VIR_MEMORY_VIRTUAL, mapping it
6142      * to the qemu 'memsave' command which does the virtual to physical
6143      * mapping inside qemu.
6144      *
6145      * The QEMU driver also handles VIR_MEMORY_PHYSICAL, mapping it
6146      * to the qemu 'pmemsave' command.
6147      *
6148      * At time of writing there is no Xen driver.  However the Xen
6149      * hypervisor only lets you map physical pages from other domains,
6150      * and so the Xen driver would have to do the virtual to physical
6151      * mapping by chasing 2, 3 or 4-level page tables from the PTD.
6152      * There is example code in libxc (xc_translate_foreign_address)
6153      * which does this, although we cannot copy this code directly
6154      * because of incompatible licensing.
6155      */
6156 
6157     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_MEMORY_VIRTUAL, VIR_MEMORY_PHYSICAL, error);
6158 
6159     /* Allow size == 0 as an access test. */
6160     if (size > 0)
6161         virCheckNonNullArgGoto(buffer, error);
6162 
6163     if (conn->driver->domainMemoryPeek) {
6164         int ret;
6165         ret = conn->driver->domainMemoryPeek(dom, start, size,
6166                                              buffer, flags);
6167         if (ret < 0)
6168             goto error;
6169         return ret;
6170     }
6171 
6172     virReportUnsupportedError();
6173 
6174  error:
6175     virDispatchError(dom->conn);
6176     return -1;
6177 }
6178 
6179 
6180 /**
6181  * virDomainGetBlockInfo:
6182  * @domain: a domain object
6183  * @disk: path to the block device, or device shorthand
6184  * @info: pointer to a virDomainBlockInfo structure allocated by the user
6185  * @flags: extra flags; not used yet, so callers should always pass 0
6186  *
6187  * Extract information about a domain's block device.
6188  *
6189  * The @disk parameter is either an unambiguous source name of the
6190  * block device (the <source file='...'/> sub-element, such as
6191  * "/path/to/image"), or (since 0.9.5) the device target shorthand
6192  * (the <target dev='...'/> sub-element, such as "vda").  Valid names
6193  * can be found by calling virDomainGetXMLDesc() and inspecting
6194  * elements within //domain/devices/disk.
6195  *
6196  * For QEMU domains, the allocation and physical virDomainBlockInfo
6197  * values returned will generally be the same, except when using a
6198  * non raw, block backing device, such as qcow2 for an active domain.
6199  * When the persistent domain is not active, QEMU will return the
6200  * default which is the same value for allocation and physical.
6201  *
6202  * Active QEMU domains can return an allocation value which is more
6203  * representative of the currently used blocks by the device compared
6204  * to the physical size of the device. Applications can use/monitor
6205  * the allocation value with the understanding that if the domain
6206  * becomes inactive during an attempt to get the value, the default
6207  * values will be returned. Thus, the application should check
6208  * after the call for the domain being inactive if the values are
6209  * the same. Optionally, the application could be watching for a
6210  * shutdown event and then ignore any values received afterwards.
6211  * This can be an issue when a domain is being migrated and the
6212  * exact timing of the domain being made inactive and check of
6213  * the allocation value results the default being returned. For
6214  * a transient domain in the similar situation, this call will return
6215  * -1 and an error message indicating the "domain is not running".
6216  *
6217  * The following is some pseudo code illustrating the call sequence:
6218  *
6219  *   ...
6220  *   virDomainPtr dom;
6221  *   virDomainBlockInfo info;
6222  *   char *device;
6223  *   ...
6224  *   // Either get a list of all domains or a specific domain
6225  *   // via a virDomainLookupBy*() call.
6226  *   //
6227  *   // It's also required to fill in the device pointer, but that's
6228  *   // specific to the implementation. For the purposes of this example
6229  *   // a qcow2 backed device name string would need to be provided.
6230  *   ...
6231  *   // If the following call is made on a persistent domain with a
6232  *   // qcow2 block backed block device, then it's possible the returned
6233  *   // allocation equals the physical value. In that case, the domain
6234  *   // that may have been active prior to calling has become inactive,
6235  *   // such as is the case during a domain migration. Thus once we
6236  *   // get data returned, check for active domain when the values are
6237  *   // the same.
6238  *   if (virDomainGetBlockInfo(dom, device, &info, 0) < 0)
6239  *       goto failure;
6240  *   if (info.allocation == info.physical) {
6241  *       // If the domain is no longer active,
6242  *       // then the defaults are being returned.
6243  *       if (!virDomainIsActive())
6244  *               goto ignore_return;
6245  *   }
6246  *   // Do something with the allocation and physical values
6247  *   ...
6248  *
6249  * Returns 0 in case of success and -1 in case of failure.
6250  */
6251 int
virDomainGetBlockInfo(virDomainPtr domain,const char * disk,virDomainBlockInfoPtr info,unsigned int flags)6252 virDomainGetBlockInfo(virDomainPtr domain, const char *disk,
6253                       virDomainBlockInfoPtr info, unsigned int flags)
6254 {
6255     virConnectPtr conn;
6256 
6257     VIR_DOMAIN_DEBUG(domain, "info=%p, flags=0x%x", info, flags);
6258 
6259     virResetLastError();
6260 
6261     if (info)
6262         memset(info, 0, sizeof(*info));
6263 
6264     virCheckDomainReturn(domain, -1);
6265     virCheckNonEmptyStringArgGoto(disk, error);
6266     virCheckNonNullArgGoto(info, error);
6267 
6268     conn = domain->conn;
6269 
6270     if (conn->driver->domainGetBlockInfo) {
6271         int ret;
6272         ret = conn->driver->domainGetBlockInfo(domain, disk, info, flags);
6273         if (ret < 0)
6274             goto error;
6275         return ret;
6276     }
6277 
6278     virReportUnsupportedError();
6279 
6280  error:
6281     virDispatchError(domain->conn);
6282     return -1;
6283 }
6284 
6285 
6286 /**
6287  * virDomainDefineXML:
6288  * @conn: pointer to the hypervisor connection
6289  * @xml: the XML description for the domain, preferably in UTF-8
6290  *
6291  * Define a domain, but does not start it.
6292  * This definition is persistent, until explicitly undefined with
6293  * virDomainUndefine(). A previous definition for this domain with the same
6294  * UUID and name would be overridden if it already exists.
6295  *
6296  * virDomainFree should be used to free the resources after the
6297  * domain object is no longer needed.
6298  *
6299  * Returns NULL in case of error, a pointer to the domain otherwise
6300  */
6301 virDomainPtr
virDomainDefineXML(virConnectPtr conn,const char * xml)6302 virDomainDefineXML(virConnectPtr conn, const char *xml)
6303 {
6304     VIR_DEBUG("conn=%p, xml=%s", conn, NULLSTR(xml));
6305 
6306     virResetLastError();
6307 
6308     virCheckConnectReturn(conn, NULL);
6309     virCheckReadOnlyGoto(conn->flags, error);
6310     virCheckNonNullArgGoto(xml, error);
6311 
6312     if (conn->driver->domainDefineXML) {
6313         virDomainPtr ret;
6314         ret = conn->driver->domainDefineXML(conn, xml);
6315         if (!ret)
6316             goto error;
6317         return ret;
6318     }
6319 
6320     virReportUnsupportedError();
6321 
6322  error:
6323     virDispatchError(conn);
6324     return NULL;
6325 }
6326 
6327 
6328 /**
6329  * virDomainDefineXMLFlags:
6330  * @conn: pointer to the hypervisor connection
6331  * @xml: the XML description for the domain, preferably in UTF-8
6332  * @flags: bitwise OR of the virDomainDefineFlags constants
6333  *
6334  * Defines a domain, but does not start it.
6335  * This definition is persistent, until explicitly undefined with
6336  * virDomainUndefine(). A previous definition for this domain with the same
6337  * UUID and name would be overridden if it already exists.
6338  *
6339  * virDomainFree should be used to free the resources after the
6340  * domain object is no longer needed.
6341  *
6342  * Returns NULL in case of error, a pointer to the domain otherwise
6343  */
6344 virDomainPtr
virDomainDefineXMLFlags(virConnectPtr conn,const char * xml,unsigned int flags)6345 virDomainDefineXMLFlags(virConnectPtr conn, const char *xml, unsigned int flags)
6346 {
6347     VIR_DEBUG("conn=%p, xml=%s flags=0x%x", conn, NULLSTR(xml), flags);
6348 
6349     virResetLastError();
6350 
6351     virCheckConnectReturn(conn, NULL);
6352     virCheckReadOnlyGoto(conn->flags, error);
6353     virCheckNonNullArgGoto(xml, error);
6354 
6355     if (conn->driver->domainDefineXMLFlags) {
6356         virDomainPtr ret;
6357         ret = conn->driver->domainDefineXMLFlags(conn, xml, flags);
6358         if (!ret)
6359             goto error;
6360         return ret;
6361     }
6362 
6363     virReportUnsupportedError();
6364 
6365  error:
6366     virDispatchError(conn);
6367     return NULL;
6368 }
6369 
6370 
6371 /**
6372  * virDomainUndefine:
6373  * @domain: pointer to a defined domain
6374  *
6375  * Undefine a domain. If the domain is running, it's converted to
6376  * transient domain, without stopping it. If the domain is inactive,
6377  * the domain configuration is removed.
6378  *
6379  * If the domain has a managed save image (see
6380  * virDomainHasManagedSaveImage()), or if it is inactive and has any
6381  * snapshot metadata (see virDomainSnapshotNum()) or checkpoint
6382  * metadata (see virDomainListAllCheckpoints()), then the undefine
6383  * will fail. See virDomainUndefineFlags() for more control.
6384  *
6385  * Returns 0 in case of success, -1 in case of error
6386  */
6387 int
virDomainUndefine(virDomainPtr domain)6388 virDomainUndefine(virDomainPtr domain)
6389 {
6390     virConnectPtr conn;
6391 
6392     VIR_DOMAIN_DEBUG(domain);
6393 
6394     virResetLastError();
6395 
6396     virCheckDomainReturn(domain, -1);
6397     conn = domain->conn;
6398 
6399     virCheckReadOnlyGoto(conn->flags, error);
6400 
6401     if (conn->driver->domainUndefine) {
6402         int ret;
6403         ret = conn->driver->domainUndefine(domain);
6404         if (ret < 0)
6405             goto error;
6406         return ret;
6407     }
6408 
6409     virReportUnsupportedError();
6410 
6411  error:
6412     virDispatchError(domain->conn);
6413     return -1;
6414 }
6415 
6416 
6417 /**
6418  * virDomainUndefineFlags:
6419  * @domain: pointer to a defined domain
6420  * @flags: bitwise-OR of supported virDomainUndefineFlagsValues
6421  *
6422  * Undefine a domain. If the domain is running, it's converted to
6423  * transient domain, without stopping it. If the domain is inactive,
6424  * the domain configuration is removed.
6425  *
6426  * If the domain has a managed save image (see virDomainHasManagedSaveImage()),
6427  * then including VIR_DOMAIN_UNDEFINE_MANAGED_SAVE in @flags will also remove
6428  * that file, and omitting the flag will cause the undefine process to fail.
6429  *
6430  * If the domain is inactive and has any snapshot metadata (see
6431  * virDomainSnapshotNum()), then including
6432  * VIR_DOMAIN_UNDEFINE_SNAPSHOTS_METADATA in @flags will also remove
6433  * that metadata.  Omitting the flag will cause the undefine of an
6434  * inactive domain with snapshots to fail.  Active domains will retain
6435  * snapshot metadata until the (now-transient) domain halts,
6436  * regardless of whether this flag is present.  On hypervisors that
6437  * support snapshots, but where snapshots do not use libvirt metadata,
6438  * this flag has no effect.
6439  *
6440  * If the domain is inactive and has any checkpoint metadata (see
6441  * virDomainListAllCheckpoints()), then including
6442  * VIR_DOMAIN_UNDEFINE_CHECKPOINTS_METADATA in @flags will also remove
6443  * that metadata. Omitting the flag will cause the undefine of an
6444  * inactive domain with checkpoints to fail. Active domains will
6445  * retain checkpoint metadata until the (now-transient) domain halts,
6446  * regardless of whether this flag is present. On hypervisors that
6447  * support checkpoints, but where checkpoints do not use libvirt
6448  * metadata, this flag has no effect.
6449  *
6450  * If the domain has any nvram specified, the undefine process will fail
6451  * unless VIR_DOMAIN_UNDEFINE_KEEP_NVRAM is specified, or if
6452  * VIR_DOMAIN_UNDEFINE_NVRAM is specified to remove the nvram file.
6453  *
6454  * Returns 0 in case of success, -1 in case of error
6455  */
6456 int
virDomainUndefineFlags(virDomainPtr domain,unsigned int flags)6457 virDomainUndefineFlags(virDomainPtr domain,
6458                        unsigned int flags)
6459 {
6460     virConnectPtr conn;
6461 
6462     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
6463 
6464     virResetLastError();
6465 
6466     virCheckDomainReturn(domain, -1);
6467     conn = domain->conn;
6468 
6469     virCheckReadOnlyGoto(conn->flags, error);
6470 
6471     if (conn->driver->domainUndefineFlags) {
6472         int ret;
6473         ret = conn->driver->domainUndefineFlags(domain, flags);
6474         if (ret < 0)
6475             goto error;
6476         return ret;
6477     }
6478 
6479     virReportUnsupportedError();
6480 
6481  error:
6482     virDispatchError(domain->conn);
6483     return -1;
6484 }
6485 
6486 
6487 /**
6488  * virConnectNumOfDefinedDomains:
6489  * @conn: pointer to the hypervisor connection
6490  *
6491  * Provides the number of defined but inactive domains.
6492  *
6493  * Returns the number of domain found or -1 in case of error
6494  */
6495 int
virConnectNumOfDefinedDomains(virConnectPtr conn)6496 virConnectNumOfDefinedDomains(virConnectPtr conn)
6497 {
6498     VIR_DEBUG("conn=%p", conn);
6499 
6500     virResetLastError();
6501 
6502     virCheckConnectReturn(conn, -1);
6503 
6504     if (conn->driver->connectNumOfDefinedDomains) {
6505         int ret;
6506         ret = conn->driver->connectNumOfDefinedDomains(conn);
6507         if (ret < 0)
6508             goto error;
6509         return ret;
6510     }
6511 
6512     virReportUnsupportedError();
6513 
6514  error:
6515     virDispatchError(conn);
6516     return -1;
6517 }
6518 
6519 
6520 /**
6521  * virConnectListDefinedDomains:
6522  * @conn: pointer to the hypervisor connection
6523  * @names: pointer to an array to store the names
6524  * @maxnames: size of the array
6525  *
6526  * list the defined but inactive domains, stores the pointers to the names
6527  * in @names
6528  *
6529  * The use of this function is discouraged. Instead, use
6530  * virConnectListAllDomains().
6531  *
6532  * Returns the number of names provided in the array or -1 in case of error.
6533  * Note that this command is inherently racy; a domain can be defined between
6534  * a call to virConnectNumOfDefinedDomains() and this call; you are only
6535  * guaranteed that all currently defined domains were listed if the return
6536  * is less than @maxids.  The client must call free() on each returned name.
6537  */
6538 int
virConnectListDefinedDomains(virConnectPtr conn,char ** const names,int maxnames)6539 virConnectListDefinedDomains(virConnectPtr conn, char **const names,
6540                              int maxnames)
6541 {
6542     VIR_DEBUG("conn=%p, names=%p, maxnames=%d", conn, names, maxnames);
6543 
6544     virResetLastError();
6545 
6546     virCheckConnectReturn(conn, -1);
6547     virCheckNonNullArrayArgGoto(names, maxnames, error);
6548     virCheckNonNegativeArgGoto(maxnames, error);
6549 
6550     if (conn->driver->connectListDefinedDomains) {
6551         int ret;
6552         ret = conn->driver->connectListDefinedDomains(conn, names, maxnames);
6553         if (ret < 0)
6554             goto error;
6555         return ret;
6556     }
6557 
6558     virReportUnsupportedError();
6559 
6560  error:
6561     virDispatchError(conn);
6562     return -1;
6563 }
6564 
6565 
6566 /**
6567  * virConnectListAllDomains:
6568  * @conn: Pointer to the hypervisor connection.
6569  * @domains: Pointer to a variable to store the array containing domain objects
6570  *           or NULL if the list is not required (just returns number of guests).
6571  * @flags: bitwise-OR of virConnectListAllDomainsFlags
6572  *
6573  * Collect a possibly-filtered list of all domains, and return an allocated
6574  * array of information for each.  This API solves the race inherent in
6575  * virConnectListDomains() and virConnectListDefinedDomains().
6576  *
6577  * Normally, all domains are returned; however, @flags can be used to
6578  * filter the results for a smaller list of targeted domains.  The valid
6579  * flags are divided into groups, where each group contains bits that
6580  * describe mutually exclusive attributes of a domain, and where all bits
6581  * within a group describe all possible domains.  Some hypervisors might
6582  * reject explicit bits from a group where the hypervisor cannot make a
6583  * distinction (for example, not all hypervisors can tell whether domains
6584  * have snapshots).  For a group supported by a given hypervisor, the
6585  * behavior when no bits of a group are set is identical to the behavior
6586  * when all bits in that group are set.  When setting bits from more than
6587  * one group, it is possible to select an impossible combination (such
6588  * as an inactive transient domain), in that case a hypervisor may return
6589  * either 0 or an error.
6590  *
6591  * The first group of @flags is VIR_CONNECT_LIST_DOMAINS_ACTIVE (online
6592  * domains) and VIR_CONNECT_LIST_DOMAINS_INACTIVE (offline domains).
6593  *
6594  * The next group of @flags is VIR_CONNECT_LIST_DOMAINS_PERSISTENT (defined
6595  * domains) and VIR_CONNECT_LIST_DOMAINS_TRANSIENT (running but not defined).
6596  *
6597  * The next group of @flags covers various domain states:
6598  * VIR_CONNECT_LIST_DOMAINS_RUNNING, VIR_CONNECT_LIST_DOMAINS_PAUSED,
6599  * VIR_CONNECT_LIST_DOMAINS_SHUTOFF, and a catch-all for all other states
6600  * (such as crashed, this catch-all covers the possibility of adding new
6601  * states).
6602  *
6603  * The remaining groups cover boolean attributes commonly asked about
6604  * domains; they include VIR_CONNECT_LIST_DOMAINS_MANAGEDSAVE and
6605  * VIR_CONNECT_LIST_DOMAINS_NO_MANAGEDSAVE, for filtering based on whether
6606  * a managed save image exists; VIR_CONNECT_LIST_DOMAINS_AUTOSTART and
6607  * VIR_CONNECT_LIST_DOMAINS_NO_AUTOSTART, for filtering based on autostart;
6608  * VIR_CONNECT_LIST_DOMAINS_HAS_SNAPSHOT and
6609  * VIR_CONNECT_LIST_DOMAINS_NO_SNAPSHOT, for filtering based on whether
6610  * a domain has snapshots; VIR_CONNECT_LIST_DOMAINS_HAS_CHECKPOINT and
6611  * VIR_CONNECT_LIST_DOMAINS_NO_CHECKPOINT, for filtering based on whether
6612  * a domain has checkpoints.
6613  *
6614  * Example of usage:
6615  *
6616  *   virDomainPtr *domains;
6617  *   size_t i;
6618  *   int ret;
6619  *   unsigned int flags = VIR_CONNECT_LIST_DOMAINS_RUNNING |
6620  *                        VIR_CONNECT_LIST_DOMAINS_PERSISTENT;
6621  *   ret = virConnectListAllDomains(conn, &domains, flags);
6622  *   if (ret < 0)
6623  *       error();
6624  *   for (i = 0; i < ret; i++) {
6625  *        do_something_with_domain(domains[i]);
6626  *        //here or in a separate loop if needed
6627  *        virDomainFree(domains[i]);
6628  *   }
6629  *   free(domains);
6630  *
6631  * Returns the number of domains found or -1 and sets domains to NULL in case of
6632  * error.  On success, the array stored into @domains is guaranteed to have an
6633  * extra allocated element set to NULL but not included in the return count, to
6634  * make iteration easier. The caller is responsible for calling virDomainFree()
6635  * on each array element, then calling free() on @domains.
6636  */
6637 int
virConnectListAllDomains(virConnectPtr conn,virDomainPtr ** domains,unsigned int flags)6638 virConnectListAllDomains(virConnectPtr conn,
6639                          virDomainPtr **domains,
6640                          unsigned int flags)
6641 {
6642     VIR_DEBUG("conn=%p, domains=%p, flags=0x%x", conn, domains, flags);
6643 
6644     virResetLastError();
6645 
6646     if (domains)
6647         *domains = NULL;
6648 
6649     virCheckConnectReturn(conn, -1);
6650 
6651     if (conn->driver->connectListAllDomains) {
6652         int ret;
6653         ret = conn->driver->connectListAllDomains(conn, domains, flags);
6654         if (ret < 0)
6655             goto error;
6656         return ret;
6657     }
6658 
6659     virReportUnsupportedError();
6660 
6661  error:
6662     virDispatchError(conn);
6663     return -1;
6664 }
6665 
6666 
6667 /**
6668  * virDomainCreate:
6669  * @domain: pointer to a defined domain
6670  *
6671  * Launch a defined domain. If the call succeeds the domain moves from the
6672  * defined to the running domains pools.  The domain will be paused only
6673  * if restoring from managed state created from a paused domain.  For more
6674  * control, see virDomainCreateWithFlags().
6675  *
6676  * Returns 0 in case of success, -1 in case of error
6677  */
6678 int
virDomainCreate(virDomainPtr domain)6679 virDomainCreate(virDomainPtr domain)
6680 {
6681     virConnectPtr conn;
6682 
6683     VIR_DOMAIN_DEBUG(domain);
6684 
6685     virResetLastError();
6686 
6687     virCheckDomainReturn(domain, -1);
6688     conn = domain->conn;
6689 
6690     virCheckReadOnlyGoto(conn->flags, error);
6691 
6692     if (conn->driver->domainCreate) {
6693         int ret;
6694         ret = conn->driver->domainCreate(domain);
6695         if (ret < 0)
6696             goto error;
6697         return ret;
6698     }
6699 
6700     virReportUnsupportedError();
6701 
6702  error:
6703     virDispatchError(domain->conn);
6704     return -1;
6705 }
6706 
6707 
6708 /**
6709  * virDomainCreateWithFlags:
6710  * @domain: pointer to a defined domain
6711  * @flags: bitwise-OR of supported virDomainCreateFlags
6712  *
6713  * Launch a defined domain. If the call succeeds the domain moves from the
6714  * defined to the running domains pools.
6715  *
6716  * If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain
6717  * has a managed save image that requested paused state (see
6718  * virDomainManagedSave()) the guest domain will be started, but its
6719  * CPUs will remain paused. The CPUs can later be manually started
6720  * using virDomainResume().  In all other cases, the guest domain will
6721  * be running.
6722  *
6723  * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest
6724  * domain will be automatically destroyed when the virConnectPtr
6725  * object is finally released. This will also happen if the
6726  * client application crashes / loses its connection to the
6727  * libvirtd daemon. Any domains marked for auto destroy will
6728  * block attempts at migration. Hypervisors may also block save-to-file,
6729  * or snapshots.
6730  *
6731  * If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a
6732  * managed save file for this domain (created by virDomainManagedSave()),
6733  * then libvirt will attempt to bypass the file system cache while restoring
6734  * the file, or fail if it cannot do so for the given system; this can allow
6735  * less pressure on file system cache, but also risks slowing loads from NFS.
6736  *
6737  * If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save
6738  * file for this domain is discarded, and the domain boots from scratch.
6739  *
6740  * Returns 0 in case of success, -1 in case of error
6741  */
6742 int
virDomainCreateWithFlags(virDomainPtr domain,unsigned int flags)6743 virDomainCreateWithFlags(virDomainPtr domain, unsigned int flags)
6744 {
6745     virConnectPtr conn;
6746 
6747     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
6748 
6749     virResetLastError();
6750 
6751     virCheckDomainReturn(domain, -1);
6752     conn = domain->conn;
6753 
6754     virCheckReadOnlyGoto(conn->flags, error);
6755 
6756     if (conn->driver->domainCreateWithFlags) {
6757         int ret;
6758         ret = conn->driver->domainCreateWithFlags(domain, flags);
6759         if (ret < 0)
6760             goto error;
6761         return ret;
6762     }
6763 
6764     virReportUnsupportedError();
6765 
6766  error:
6767     virDispatchError(domain->conn);
6768     return -1;
6769 }
6770 
6771 
6772 /**
6773  * virDomainCreateWithFiles:
6774  * @domain: pointer to a defined domain
6775  * @nfiles: number of file descriptors passed
6776  * @files: list of file descriptors passed
6777  * @flags: bitwise-OR of supported virDomainCreateFlags
6778  *
6779  * Launch a defined domain. If the call succeeds the domain moves from the
6780  * defined to the running domains pools.
6781  *
6782  * @files provides an array of file descriptors which will be
6783  * made available to the 'init' process of the guest. The file
6784  * handles exposed to the guest will be renumbered to start
6785  * from 3 (ie immediately following stderr). This is only
6786  * supported for guests which use container based virtualization
6787  * technology.
6788  *
6789  * If the VIR_DOMAIN_START_PAUSED flag is set, or if the guest domain
6790  * has a managed save image that requested paused state (see
6791  * virDomainManagedSave()) the guest domain will be started, but its
6792  * CPUs will remain paused. The CPUs can later be manually started
6793  * using virDomainResume().  In all other cases, the guest domain will
6794  * be running.
6795  *
6796  * If the VIR_DOMAIN_START_AUTODESTROY flag is set, the guest
6797  * domain will be automatically destroyed when the virConnectPtr
6798  * object is finally released. This will also happen if the
6799  * client application crashes / loses its connection to the
6800  * libvirtd daemon. Any domains marked for auto destroy will
6801  * block attempts at migration, save-to-file, or snapshots.
6802  *
6803  * If the VIR_DOMAIN_START_BYPASS_CACHE flag is set, and there is a
6804  * managed save file for this domain (created by virDomainManagedSave()),
6805  * then libvirt will attempt to bypass the file system cache while restoring
6806  * the file, or fail if it cannot do so for the given system; this can allow
6807  * less pressure on file system cache, but also risks slowing loads from NFS.
6808  *
6809  * If the VIR_DOMAIN_START_FORCE_BOOT flag is set, then any managed save
6810  * file for this domain is discarded, and the domain boots from scratch.
6811  *
6812  * Returns 0 in case of success, -1 in case of error
6813  */
6814 int
virDomainCreateWithFiles(virDomainPtr domain,unsigned int nfiles,int * files,unsigned int flags)6815 virDomainCreateWithFiles(virDomainPtr domain, unsigned int nfiles,
6816                          int *files, unsigned int flags)
6817 {
6818     virConnectPtr conn;
6819 
6820     VIR_DOMAIN_DEBUG(domain, "nfiles=%u, files=%p, flags=0x%x",
6821                      nfiles, files, flags);
6822 
6823     virResetLastError();
6824 
6825     virCheckDomainReturn(domain, -1);
6826     conn = domain->conn;
6827 
6828     virCheckReadOnlyGoto(conn->flags, error);
6829 
6830     if (conn->driver->domainCreateWithFiles) {
6831         int ret;
6832         ret = conn->driver->domainCreateWithFiles(domain,
6833                                                   nfiles, files,
6834                                                   flags);
6835         if (ret < 0)
6836             goto error;
6837         return ret;
6838     }
6839 
6840     virReportUnsupportedError();
6841 
6842  error:
6843     virDispatchError(domain->conn);
6844     return -1;
6845 }
6846 
6847 
6848 /**
6849  * virDomainGetAutostart:
6850  * @domain: a domain object
6851  * @autostart: the value returned
6852  *
6853  * Provides a boolean value indicating whether the domain
6854  * configured to be automatically started when the host
6855  * machine boots.
6856  *
6857  * Returns -1 in case of error, 0 in case of success
6858  */
6859 int
virDomainGetAutostart(virDomainPtr domain,int * autostart)6860 virDomainGetAutostart(virDomainPtr domain,
6861                       int *autostart)
6862 {
6863     virConnectPtr conn;
6864 
6865     VIR_DOMAIN_DEBUG(domain, "autostart=%p", autostart);
6866 
6867     virResetLastError();
6868 
6869     virCheckDomainReturn(domain, -1);
6870     virCheckNonNullArgGoto(autostart, error);
6871 
6872     conn = domain->conn;
6873 
6874     if (conn->driver->domainGetAutostart) {
6875         int ret;
6876         ret = conn->driver->domainGetAutostart(domain, autostart);
6877         if (ret < 0)
6878             goto error;
6879         return ret;
6880     }
6881 
6882     virReportUnsupportedError();
6883 
6884  error:
6885     virDispatchError(domain->conn);
6886     return -1;
6887 }
6888 
6889 
6890 /**
6891  * virDomainSetAutostart:
6892  * @domain: a domain object
6893  * @autostart: whether the domain should be automatically started 0 or 1
6894  *
6895  * Configure the domain to be automatically started
6896  * when the host machine boots.
6897  *
6898  * Returns -1 in case of error, 0 in case of success
6899  */
6900 int
virDomainSetAutostart(virDomainPtr domain,int autostart)6901 virDomainSetAutostart(virDomainPtr domain,
6902                       int autostart)
6903 {
6904     virConnectPtr conn;
6905 
6906     VIR_DOMAIN_DEBUG(domain, "autostart=%d", autostart);
6907 
6908     virResetLastError();
6909 
6910     virCheckDomainReturn(domain, -1);
6911     conn = domain->conn;
6912 
6913     virCheckReadOnlyGoto(conn->flags, error);
6914 
6915     if (conn->driver->domainSetAutostart) {
6916         int ret;
6917         ret = conn->driver->domainSetAutostart(domain, autostart);
6918         if (ret < 0)
6919             goto error;
6920         return ret;
6921     }
6922 
6923     virReportUnsupportedError();
6924 
6925  error:
6926     virDispatchError(domain->conn);
6927     return -1;
6928 }
6929 
6930 
6931 /**
6932  * virDomainInjectNMI:
6933  * @domain: pointer to domain object, or NULL for Domain0
6934  * @flags: extra flags; not used yet, so callers should always pass 0
6935  *
6936  * Send NMI to the guest
6937  *
6938  * Returns 0 in case of success, -1 in case of failure.
6939  */
6940 int
virDomainInjectNMI(virDomainPtr domain,unsigned int flags)6941 virDomainInjectNMI(virDomainPtr domain, unsigned int flags)
6942 {
6943     virConnectPtr conn;
6944     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
6945 
6946     virResetLastError();
6947 
6948     virCheckDomainReturn(domain, -1);
6949     conn = domain->conn;
6950 
6951     virCheckReadOnlyGoto(conn->flags, error);
6952 
6953     if (conn->driver->domainInjectNMI) {
6954         int ret;
6955         ret = conn->driver->domainInjectNMI(domain, flags);
6956         if (ret < 0)
6957             goto error;
6958         return ret;
6959     }
6960 
6961     virReportUnsupportedError();
6962 
6963  error:
6964     virDispatchError(domain->conn);
6965     return -1;
6966 }
6967 
6968 
6969 /**
6970  * virDomainSendKey:
6971  * @domain:    pointer to domain object, or NULL for Domain0
6972  * @codeset:   the code set of keycodes, from virKeycodeSet
6973  * @holdtime:  the duration (in milliseconds) that the keys will be held
6974  * @keycodes:  array of keycodes
6975  * @nkeycodes: number of keycodes, up to VIR_DOMAIN_SEND_KEY_MAX_KEYS
6976  * @flags: extra flags; not used yet, so callers should always pass 0
6977  *
6978  * Send key(s) to the guest.
6979  *
6980  * Returns 0 in case of success, -1 in case of failure.
6981  */
6982 int
virDomainSendKey(virDomainPtr domain,unsigned int codeset,unsigned int holdtime,unsigned int * keycodes,int nkeycodes,unsigned int flags)6983 virDomainSendKey(virDomainPtr domain,
6984                  unsigned int codeset,
6985                  unsigned int holdtime,
6986                  unsigned int *keycodes,
6987                  int nkeycodes,
6988                  unsigned int flags)
6989 {
6990     virConnectPtr conn;
6991     VIR_DOMAIN_DEBUG(domain, "codeset=%u, holdtime=%u, nkeycodes=%u, flags=0x%x",
6992                      codeset, holdtime, nkeycodes, flags);
6993 
6994     virResetLastError();
6995 
6996     virCheckDomainReturn(domain, -1);
6997     conn = domain->conn;
6998 
6999     virCheckReadOnlyGoto(conn->flags, error);
7000     virCheckNonNullArgGoto(keycodes, error);
7001     virCheckPositiveArgGoto(nkeycodes, error);
7002 
7003     if (codeset >= VIR_KEYCODE_SET_LAST) {
7004         virReportInvalidArg(codeset,
7005                             _("Unsupported codeset '%d'"),
7006                             codeset);
7007         goto error;
7008     }
7009 
7010     if (nkeycodes > VIR_DOMAIN_SEND_KEY_MAX_KEYS) {
7011         virReportInvalidArg(nkeycodes,
7012                             _("nkeycodes must be <= %d"),
7013                             VIR_DOMAIN_SEND_KEY_MAX_KEYS);
7014         goto error;
7015     }
7016 
7017     if (conn->driver->domainSendKey) {
7018         int ret;
7019         ret = conn->driver->domainSendKey(domain, codeset, holdtime,
7020                                           keycodes, nkeycodes, flags);
7021         if (ret < 0)
7022             goto error;
7023         return ret;
7024     }
7025 
7026     virReportUnsupportedError();
7027 
7028  error:
7029     virDispatchError(domain->conn);
7030     return -1;
7031 }
7032 
7033 
7034 /**
7035  * virDomainSendProcessSignal:
7036  * @domain: pointer to domain object
7037  * @pid_value: a positive integer process ID, or negative integer process group ID
7038  * @signum: a signal from the virDomainProcessSignal enum
7039  * @flags: currently unused, pass 0
7040  *
7041  * Send a signal to the designated process in the guest
7042  *
7043  * The signal numbers must be taken from the virDomainProcessSignal
7044  * enum. These will be translated to the corresponding signal
7045  * number for the guest OS, by the guest agent delivering the
7046  * signal. If there is no mapping from virDomainProcessSignal to
7047  * the native OS signals, this API will report an error.
7048  *
7049  * If @pid_value is an integer greater than zero, it is
7050  * treated as a process ID. If @pid_value is an integer
7051  * less than zero, it is treated as a process group ID.
7052  * All the @pid_value numbers are from the container/guest
7053  * namespace. The value zero is not valid.
7054  *
7055  * Not all hypervisors will support sending signals to
7056  * arbitrary processes or process groups. If this API is
7057  * implemented the minimum requirement is to be able to
7058  * use @pid_value == 1 (i.e. kill init). No other value is
7059  * required to be supported.
7060  *
7061  * If the @signum is VIR_DOMAIN_PROCESS_SIGNAL_NOP then this
7062  * API will simply report whether the process is running in
7063  * the container/guest.
7064  *
7065  * Returns 0 in case of success, -1 in case of failure.
7066  */
7067 int
virDomainSendProcessSignal(virDomainPtr domain,long long pid_value,unsigned int signum,unsigned int flags)7068 virDomainSendProcessSignal(virDomainPtr domain,
7069                            long long pid_value,
7070                            unsigned int signum,
7071                            unsigned int flags)
7072 {
7073     virConnectPtr conn;
7074     VIR_DOMAIN_DEBUG(domain, "pid=%lld, signum=%u flags=0x%x",
7075                      pid_value, signum, flags);
7076 
7077     virResetLastError();
7078 
7079     virCheckDomainReturn(domain, -1);
7080     conn = domain->conn;
7081 
7082     virCheckNonZeroArgGoto(pid_value, error);
7083     virCheckReadOnlyGoto(conn->flags, error);
7084 
7085     if (conn->driver->domainSendProcessSignal) {
7086         int ret;
7087         ret = conn->driver->domainSendProcessSignal(domain,
7088                                                     pid_value,
7089                                                     signum,
7090                                                     flags);
7091         if (ret < 0)
7092             goto error;
7093         return ret;
7094     }
7095 
7096     virReportUnsupportedError();
7097 
7098  error:
7099     virDispatchError(domain->conn);
7100     return -1;
7101 }
7102 
7103 
7104 /**
7105  * virDomainSetVcpus:
7106  * @domain: pointer to domain object, or NULL for Domain0
7107  * @nvcpus: the new number of virtual CPUs for this domain
7108  *
7109  * Dynamically change the number of virtual CPUs used by the domain.
7110  * Note that this call may fail if the underlying virtualization hypervisor
7111  * does not support it or if growing the number is arbitrarily limited.
7112  * This function may require privileged access to the hypervisor.
7113  *
7114  * Note that if this call is executed before the guest has finished booting,
7115  * the guest may fail to process the change.
7116  *
7117  * This command only changes the runtime configuration of the domain,
7118  * so can only be called on an active domain.  It is hypervisor-dependent
7119  * whether it also affects persistent configuration; for more control,
7120  * use virDomainSetVcpusFlags().
7121  *
7122  * Returns 0 in case of success, -1 in case of failure.
7123  */
7124 int
virDomainSetVcpus(virDomainPtr domain,unsigned int nvcpus)7125 virDomainSetVcpus(virDomainPtr domain, unsigned int nvcpus)
7126 {
7127     virConnectPtr conn;
7128 
7129     VIR_DOMAIN_DEBUG(domain, "nvcpus=%u", nvcpus);
7130 
7131     virResetLastError();
7132 
7133     virCheckDomainReturn(domain, -1);
7134     conn = domain->conn;
7135 
7136     virCheckReadOnlyGoto(conn->flags, error);
7137     virCheckNonZeroArgGoto(nvcpus, error);
7138 
7139     if (conn->driver->domainSetVcpus) {
7140         int ret;
7141         ret = conn->driver->domainSetVcpus(domain, nvcpus);
7142         if (ret < 0)
7143             goto error;
7144         return ret;
7145     }
7146 
7147     virReportUnsupportedError();
7148 
7149  error:
7150     virDispatchError(domain->conn);
7151     return -1;
7152 }
7153 
7154 
7155 /**
7156  * virDomainSetVcpusFlags:
7157  * @domain: pointer to domain object, or NULL for Domain0
7158  * @nvcpus: the new number of virtual CPUs for this domain, must be at least 1
7159  * @flags: bitwise-OR of virDomainVcpuFlags
7160  *
7161  * Dynamically change the number of virtual CPUs used by the domain.
7162  * Note that this call may fail if the underlying virtualization hypervisor
7163  * does not support it or if growing the number is arbitrarily limited.
7164  * This function may require privileged access to the hypervisor.
7165  *
7166  * @flags may include VIR_DOMAIN_AFFECT_LIVE to affect a running
7167  * domain (which may fail if domain is not active), or
7168  * VIR_DOMAIN_AFFECT_CONFIG to affect the next boot via the XML
7169  * description of the domain.  Both flags may be set.
7170  * If neither flag is specified (that is, @flags is VIR_DOMAIN_AFFECT_CURRENT),
7171  * then an inactive domain modifies persistent setup, while an active domain
7172  * is hypervisor-dependent on whether just live or both live and persistent
7173  * state is changed.
7174  *
7175  * Note that if this call is executed before the guest has finished booting,
7176  * the guest may fail to process the change.
7177  *
7178  * If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then
7179  * VIR_DOMAIN_AFFECT_LIVE must be clear, and only the maximum virtual
7180  * CPU limit is altered; generally, this value must be less than or
7181  * equal to virConnectGetMaxVcpus().  Otherwise, this call affects the
7182  * current virtual CPU limit, which must be less than or equal to the
7183  * maximum limit. Note that hypervisors may not allow changing the maximum
7184  * vcpu count if processor topology is specified.
7185  *
7186  * If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of processors is
7187  * modified inside the guest instead of the hypervisor. This flag can only
7188  * be used with live guests and is incompatible with VIR_DOMAIN_VCPU_MAXIMUM.
7189  * The usage of this flag may require a guest agent configured.
7190  *
7191  * Not all hypervisors can support all flag combinations.
7192  *
7193  * Returns 0 in case of success, -1 in case of failure.
7194  */
7195 int
virDomainSetVcpusFlags(virDomainPtr domain,unsigned int nvcpus,unsigned int flags)7196 virDomainSetVcpusFlags(virDomainPtr domain, unsigned int nvcpus,
7197                        unsigned int flags)
7198 {
7199     virConnectPtr conn;
7200 
7201     VIR_DOMAIN_DEBUG(domain, "nvcpus=%u, flags=0x%x", nvcpus, flags);
7202 
7203     virResetLastError();
7204 
7205     virCheckDomainReturn(domain, -1);
7206     virCheckReadOnlyGoto(domain->conn->flags, error);
7207 
7208     VIR_REQUIRE_FLAG_GOTO(VIR_DOMAIN_VCPU_MAXIMUM,
7209                           VIR_DOMAIN_AFFECT_CONFIG,
7210                           error);
7211 
7212     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_VCPU_GUEST,
7213                              VIR_DOMAIN_AFFECT_CONFIG,
7214                              error);
7215 
7216     virCheckNonZeroArgGoto(nvcpus, error);
7217 
7218     conn = domain->conn;
7219 
7220     if (conn->driver->domainSetVcpusFlags) {
7221         int ret;
7222         ret = conn->driver->domainSetVcpusFlags(domain, nvcpus, flags);
7223         if (ret < 0)
7224             goto error;
7225         return ret;
7226     }
7227 
7228     virReportUnsupportedError();
7229 
7230  error:
7231     virDispatchError(domain->conn);
7232     return -1;
7233 }
7234 
7235 
7236 /**
7237  * virDomainGetVcpusFlags:
7238  * @domain: pointer to domain object, or NULL for Domain0
7239  * @flags: bitwise-OR of virDomainVcpuFlags
7240  *
7241  * Query the number of virtual CPUs used by the domain.  Note that
7242  * this call may fail if the underlying virtualization hypervisor does
7243  * not support it.  This function may require privileged access to the
7244  * hypervisor.
7245  *
7246  * If @flags includes VIR_DOMAIN_AFFECT_LIVE, this will query a
7247  * running domain (which will fail if domain is not active); if
7248  * it includes VIR_DOMAIN_AFFECT_CONFIG, this will query the XML
7249  * description of the domain.  It is an error to set both flags.
7250  * If neither flag is set (that is, VIR_DOMAIN_AFFECT_CURRENT),
7251  * then the configuration queried depends on whether the domain
7252  * is currently running.
7253  *
7254  * If @flags includes VIR_DOMAIN_VCPU_MAXIMUM, then the maximum
7255  * virtual CPU limit is queried.  Otherwise, this call queries the
7256  * current virtual CPU count.
7257  *
7258  * If @flags includes VIR_DOMAIN_VCPU_GUEST, then the state of the processors
7259  * is queried in the guest instead of the hypervisor. This flag is only usable
7260  * on live domains. Guest agent may be needed for this flag to be available.
7261  *
7262  * Returns the number of vCPUs in case of success, -1 in case of failure.
7263  */
7264 int
virDomainGetVcpusFlags(virDomainPtr domain,unsigned int flags)7265 virDomainGetVcpusFlags(virDomainPtr domain, unsigned int flags)
7266 {
7267     virConnectPtr conn;
7268 
7269     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
7270 
7271     virResetLastError();
7272 
7273     virCheckDomainReturn(domain, -1);
7274     conn = domain->conn;
7275 
7276     if (flags & VIR_DOMAIN_VCPU_GUEST)
7277         virCheckReadOnlyGoto(conn->flags, error);
7278 
7279     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE,
7280                              VIR_DOMAIN_AFFECT_CONFIG,
7281                              error);
7282 
7283     if (conn->driver->domainGetVcpusFlags) {
7284         int ret;
7285         ret = conn->driver->domainGetVcpusFlags(domain, flags);
7286         if (ret < 0)
7287             goto error;
7288         return ret;
7289     }
7290 
7291     virReportUnsupportedError();
7292 
7293  error:
7294     virDispatchError(domain->conn);
7295     return -1;
7296 }
7297 
7298 
7299 /**
7300  * virDomainPinVcpu:
7301  * @domain: pointer to domain object, or NULL for Domain0
7302  * @vcpu: virtual CPU number
7303  * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN)
7304  *      Each bit set to 1 means that corresponding CPU is usable.
7305  *      Bytes are stored in little-endian order: CPU0-7, 8-15...
7306  *      In each byte, lowest CPU number is least significant bit.
7307  * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in
7308  *      underlying virtualization system (Xen...).
7309  *      If maplen < size, missing bytes are set to zero.
7310  *      If maplen > size, failure code is returned.
7311  *
7312  * Dynamically change the real CPUs which can be allocated to a virtual CPU.
7313  * This function may require privileged access to the hypervisor.
7314  *
7315  * This command only changes the runtime configuration of the domain,
7316  * so can only be called on an active domain.
7317  *
7318  * Returns 0 in case of success, -1 in case of failure.
7319  */
7320 int
virDomainPinVcpu(virDomainPtr domain,unsigned int vcpu,unsigned char * cpumap,int maplen)7321 virDomainPinVcpu(virDomainPtr domain, unsigned int vcpu,
7322                  unsigned char *cpumap, int maplen)
7323 {
7324     virConnectPtr conn;
7325 
7326     VIR_DOMAIN_DEBUG(domain, "vcpu=%u, cpumap=%p, maplen=%d",
7327                      vcpu, cpumap, maplen);
7328 
7329     virResetLastError();
7330 
7331     virCheckDomainReturn(domain, -1);
7332     conn = domain->conn;
7333 
7334     virCheckReadOnlyGoto(conn->flags, error);
7335     virCheckNonNullArgGoto(cpumap, error);
7336     virCheckPositiveArgGoto(maplen, error);
7337 
7338     if (conn->driver->domainPinVcpu) {
7339         int ret;
7340         ret = conn->driver->domainPinVcpu(domain, vcpu, cpumap, maplen);
7341         if (ret < 0)
7342             goto error;
7343         return ret;
7344     }
7345 
7346     virReportUnsupportedError();
7347 
7348  error:
7349     virDispatchError(domain->conn);
7350     return -1;
7351 }
7352 
7353 
7354 /**
7355  * virDomainPinVcpuFlags:
7356  * @domain: pointer to domain object, or NULL for Domain0
7357  * @vcpu: virtual CPU number
7358  * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN)
7359  *      Each bit set to 1 means that corresponding CPU is usable.
7360  *      Bytes are stored in little-endian order: CPU0-7, 8-15...
7361  *      In each byte, lowest CPU number is least significant bit.
7362  * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in
7363  *      underlying virtualization system (Xen...).
7364  *      If maplen < size, missing bytes are set to zero.
7365  *      If maplen > size, failure code is returned.
7366  * @flags: bitwise-OR of virDomainModificationImpact
7367  *
7368  * Dynamically change the real CPUs which can be allocated to a virtual CPU.
7369  * This function may require privileged access to the hypervisor.
7370  *
7371  * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
7372  * Both flags may be set.
7373  * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain
7374  * and may fail if domain is not alive.
7375  * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
7376  * and will fail for transient domains. If neither flag is specified (that is,
7377  * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies
7378  * persistent setup, while an active domain is hypervisor-dependent on whether
7379  * just live or both live and persistent state is changed.
7380  * Not all hypervisors can support all flag combinations.
7381  *
7382  * See also virDomainGetVcpuPinInfo for querying this information.
7383  *
7384  * Returns 0 in case of success, -1 in case of failure.
7385  *
7386  */
7387 int
virDomainPinVcpuFlags(virDomainPtr domain,unsigned int vcpu,unsigned char * cpumap,int maplen,unsigned int flags)7388 virDomainPinVcpuFlags(virDomainPtr domain, unsigned int vcpu,
7389                       unsigned char *cpumap, int maplen, unsigned int flags)
7390 {
7391     virConnectPtr conn;
7392 
7393     VIR_DOMAIN_DEBUG(domain, "vcpu=%u, cpumap=%p, maplen=%d, flags=0x%x",
7394                      vcpu, cpumap, maplen, flags);
7395 
7396     virResetLastError();
7397 
7398     virCheckDomainReturn(domain, -1);
7399     conn = domain->conn;
7400 
7401     virCheckReadOnlyGoto(conn->flags, error);
7402     virCheckNonNullArgGoto(cpumap, error);
7403     virCheckPositiveArgGoto(maplen, error);
7404 
7405     if (conn->driver->domainPinVcpuFlags) {
7406         int ret;
7407         ret = conn->driver->domainPinVcpuFlags(domain, vcpu, cpumap, maplen, flags);
7408         if (ret < 0)
7409             goto error;
7410         return ret;
7411     }
7412 
7413     virReportUnsupportedError();
7414 
7415  error:
7416     virDispatchError(domain->conn);
7417     return -1;
7418 }
7419 
7420 
7421 /**
7422  * virDomainGetVcpuPinInfo:
7423  * @domain: pointer to domain object, or NULL for Domain0
7424  * @ncpumaps: the number of cpumap (listed first to match virDomainGetVcpus)
7425  * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this
7426  *     domain (in 8-bit bytes) (OUT)
7427  *     It's assumed there is <ncpumaps> cpumap in cpumaps array.
7428  *     The memory allocated to cpumaps must be (ncpumaps * maplen) bytes
7429  *     (ie: calloc(ncpumaps, maplen)).
7430  *     One cpumap inside cpumaps has the format described in
7431  *     virDomainPinVcpu() API.
7432  *     Must not be NULL.
7433  * @maplen: the number of bytes in one cpumap, from 1 up to size of CPU map.
7434  *     Must be positive.
7435  * @flags: bitwise-OR of virDomainModificationImpact
7436  *     Must not be VIR_DOMAIN_AFFECT_LIVE and
7437  *     VIR_DOMAIN_AFFECT_CONFIG concurrently.
7438  *
7439  * Query the CPU affinity setting of all virtual CPUs of domain, store it
7440  * in cpumaps.
7441  *
7442  * Returns the number of virtual CPUs in case of success,
7443  * -1 in case of failure.
7444  */
7445 int
virDomainGetVcpuPinInfo(virDomainPtr domain,int ncpumaps,unsigned char * cpumaps,int maplen,unsigned int flags)7446 virDomainGetVcpuPinInfo(virDomainPtr domain, int ncpumaps,
7447                         unsigned char *cpumaps, int maplen, unsigned int flags)
7448 {
7449     virConnectPtr conn;
7450 
7451     VIR_DOMAIN_DEBUG(domain, "ncpumaps=%d, cpumaps=%p, maplen=%d, flags=0x%x",
7452                      ncpumaps, cpumaps, maplen, flags);
7453 
7454     virResetLastError();
7455 
7456     virCheckDomainReturn(domain, -1);
7457     conn = domain->conn;
7458 
7459     virCheckNonNullArrayArgGoto(cpumaps, ncpumaps, error);
7460     virCheckPositiveArgGoto(ncpumaps, error);
7461     virCheckPositiveArgGoto(maplen, error);
7462 
7463     if (VIR_INT_MULTIPLY_OVERFLOW(ncpumaps, maplen)) {
7464         virReportError(VIR_ERR_OVERFLOW, _("input too large: %d * %d"),
7465                        ncpumaps, maplen);
7466         goto error;
7467     }
7468 
7469     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE,
7470                              VIR_DOMAIN_AFFECT_CONFIG,
7471                              error);
7472 
7473     if (conn->driver->domainGetVcpuPinInfo) {
7474         int ret;
7475         ret = conn->driver->domainGetVcpuPinInfo(domain, ncpumaps,
7476                                                  cpumaps, maplen, flags);
7477         if (ret < 0)
7478             goto error;
7479         return ret;
7480     }
7481 
7482     virReportUnsupportedError();
7483 
7484  error:
7485     virDispatchError(domain->conn);
7486     return -1;
7487 }
7488 
7489 
7490 /**
7491  * virDomainPinEmulator:
7492  * @domain: pointer to domain object, or NULL for Domain0
7493  * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN)
7494  *      Each bit set to 1 means that corresponding CPU is usable.
7495  *      Bytes are stored in little-endian order: CPU0-7, 8-15...
7496  *      In each byte, lowest CPU number is least significant bit.
7497  * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in
7498  *      underlying virtualization system (Xen...).
7499  *      If maplen < size, missing bytes are set to zero.
7500  *      If maplen > size, failure code is returned.
7501  * @flags: bitwise-OR of virDomainModificationImpact
7502  *
7503  * Dynamically change the real CPUs which can be allocated to all emulator
7504  * threads. This function may require privileged access to the hypervisor.
7505  *
7506  * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
7507  * Both flags may be set.
7508  * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain
7509  * and may fail if domain is not alive.
7510  * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
7511  * and will fail for transient domains. If neither flag is specified (that is,
7512  * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies
7513  * persistent setup, while an active domain is hypervisor-dependent on whether
7514  * just live or both live and persistent state is changed.
7515  * Not all hypervisors can support all flag combinations.
7516  *
7517  * See also virDomainGetEmulatorPinInfo for querying this information.
7518  *
7519  * Returns 0 in case of success, -1 in case of failure.
7520  *
7521  */
7522 int
virDomainPinEmulator(virDomainPtr domain,unsigned char * cpumap,int maplen,unsigned int flags)7523 virDomainPinEmulator(virDomainPtr domain, unsigned char *cpumap,
7524                      int maplen, unsigned int flags)
7525 {
7526     virConnectPtr conn;
7527 
7528     VIR_DOMAIN_DEBUG(domain, "cpumap=%p, maplen=%d, flags=0x%x",
7529                      cpumap, maplen, flags);
7530 
7531     virResetLastError();
7532 
7533     virCheckDomainReturn(domain, -1);
7534     conn = domain->conn;
7535 
7536     virCheckReadOnlyGoto(conn->flags, error);
7537 
7538     virCheckNonNullArgGoto(cpumap, error);
7539     virCheckPositiveArgGoto(maplen, error);
7540 
7541     if (conn->driver->domainPinEmulator) {
7542         int ret;
7543         ret = conn->driver->domainPinEmulator(domain, cpumap, maplen, flags);
7544         if (ret < 0)
7545             goto error;
7546         return ret;
7547     }
7548 
7549     virReportUnsupportedError();
7550 
7551  error:
7552     virDispatchError(domain->conn);
7553     return -1;
7554 }
7555 
7556 
7557 /**
7558  * virDomainGetEmulatorPinInfo:
7559  * @domain: pointer to domain object, or NULL for Domain0
7560  * @cpumap: pointer to a bit map of real CPUs for all emulator threads of
7561  *     this domain (in 8-bit bytes) (OUT)
7562  *     There is only one cpumap for all emulator threads.
7563  *     Must not be NULL.
7564  * @maplen: the number of bytes in one cpumap, from 1 up to size of CPU map.
7565  *     Must be positive.
7566  * @flags: bitwise-OR of virDomainModificationImpact
7567  *     Must not be VIR_DOMAIN_AFFECT_LIVE and
7568  *     VIR_DOMAIN_AFFECT_CONFIG concurrently.
7569  *
7570  * Query the CPU affinity setting of all emulator threads of domain, store
7571  * it in cpumap.
7572  *
7573  * Returns 1 in case of success,
7574  * 0 in case of no emulator threads are pined to pcpus,
7575  * -1 in case of failure.
7576  */
7577 int
virDomainGetEmulatorPinInfo(virDomainPtr domain,unsigned char * cpumap,int maplen,unsigned int flags)7578 virDomainGetEmulatorPinInfo(virDomainPtr domain, unsigned char *cpumap,
7579                             int maplen, unsigned int flags)
7580 {
7581     virConnectPtr conn;
7582 
7583     VIR_DOMAIN_DEBUG(domain, "cpumap=%p, maplen=%d, flags=0x%x",
7584                      cpumap, maplen, flags);
7585 
7586     virResetLastError();
7587 
7588     virCheckDomainReturn(domain, -1);
7589 
7590     virCheckNonNullArgGoto(cpumap, error);
7591     virCheckPositiveArgGoto(maplen, error);
7592 
7593     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE,
7594                              VIR_DOMAIN_AFFECT_CONFIG,
7595                              error);
7596 
7597     conn = domain->conn;
7598 
7599     if (conn->driver->domainGetEmulatorPinInfo) {
7600         int ret;
7601         ret = conn->driver->domainGetEmulatorPinInfo(domain, cpumap,
7602                                                      maplen, flags);
7603         if (ret < 0)
7604             goto error;
7605         return ret;
7606     }
7607 
7608     virReportUnsupportedError();
7609 
7610  error:
7611     virDispatchError(domain->conn);
7612     return -1;
7613 }
7614 
7615 
7616 /**
7617  * virDomainGetVcpus:
7618  * @domain: pointer to domain object, or NULL for Domain0
7619  * @info: pointer to an array of virVcpuInfo structures (OUT)
7620  * @maxinfo: number of structures in info array
7621  * @cpumaps: pointer to a bit map of real CPUs for all vcpus of this
7622  *      domain (in 8-bit bytes) (OUT)
7623  *      If cpumaps is NULL, then no cpumap information is returned by the API.
7624  *      It's assumed there is <maxinfo> cpumap in cpumaps array.
7625  *      The memory allocated to cpumaps must be (maxinfo * maplen) bytes
7626  *      (ie: calloc(maxinfo, maplen)).
7627  *      One cpumap inside cpumaps has the format described in
7628  *      virDomainPinVcpu() API.
7629  * @maplen: number of bytes in one cpumap, from 1 up to size of CPU map in
7630  *      underlying virtualization system (Xen...).
7631  *      Must be zero when cpumaps is NULL and positive when it is non-NULL.
7632  *
7633  * Extract information about virtual CPUs of domain, store it in info array
7634  * and also in cpumaps if this pointer isn't NULL.  This call may fail
7635  * on an inactive domain.
7636  *
7637  * See also virDomainGetVcpuPinInfo for querying just cpumaps, including on
7638  * an inactive domain.
7639  *
7640  * Returns the number of info filled in case of success, -1 in case of failure.
7641  */
7642 int
virDomainGetVcpus(virDomainPtr domain,virVcpuInfoPtr info,int maxinfo,unsigned char * cpumaps,int maplen)7643 virDomainGetVcpus(virDomainPtr domain, virVcpuInfoPtr info, int maxinfo,
7644                   unsigned char *cpumaps, int maplen)
7645 {
7646     virConnectPtr conn;
7647 
7648     VIR_DOMAIN_DEBUG(domain, "info=%p, maxinfo=%d, cpumaps=%p, maplen=%d",
7649                      info, maxinfo, cpumaps, maplen);
7650 
7651     virResetLastError();
7652 
7653     virCheckDomainReturn(domain, -1);
7654     virCheckNonNullArgGoto(info, error);
7655     virCheckPositiveArgGoto(maxinfo, error);
7656 
7657     /* Ensure that domainGetVcpus (aka remoteDomainGetVcpus) does not
7658        try to memcpy anything into a NULL pointer.  */
7659     if (cpumaps)
7660         virCheckPositiveArgGoto(maplen, error);
7661     else
7662         virCheckZeroArgGoto(maplen, error);
7663 
7664     if (cpumaps && VIR_INT_MULTIPLY_OVERFLOW(maxinfo, maplen)) {
7665         virReportError(VIR_ERR_OVERFLOW, _("input too large: %d * %d"),
7666                        maxinfo, maplen);
7667         goto error;
7668     }
7669 
7670     conn = domain->conn;
7671 
7672     if (conn->driver->domainGetVcpus) {
7673         int ret;
7674         ret = conn->driver->domainGetVcpus(domain, info, maxinfo,
7675                                            cpumaps, maplen);
7676         if (ret < 0)
7677             goto error;
7678         return ret;
7679     }
7680 
7681     virReportUnsupportedError();
7682 
7683  error:
7684     virDispatchError(domain->conn);
7685     return -1;
7686 }
7687 
7688 
7689 /**
7690  * virDomainGetMaxVcpus:
7691  * @domain: pointer to domain object
7692  *
7693  * Provides the maximum number of virtual CPUs supported for
7694  * the guest VM. If the guest is inactive, this is basically
7695  * the same as virConnectGetMaxVcpus(). If the guest is running
7696  * this will reflect the maximum number of virtual CPUs the
7697  * guest was booted with.  For more details, see virDomainGetVcpusFlags().
7698  *
7699  * Returns the maximum of virtual CPU or -1 in case of error.
7700  */
7701 int
virDomainGetMaxVcpus(virDomainPtr domain)7702 virDomainGetMaxVcpus(virDomainPtr domain)
7703 {
7704     virConnectPtr conn;
7705 
7706     VIR_DOMAIN_DEBUG(domain);
7707 
7708     virResetLastError();
7709 
7710     virCheckDomainReturn(domain, -1);
7711     conn = domain->conn;
7712 
7713     if (conn->driver->domainGetMaxVcpus) {
7714         int ret;
7715         ret = conn->driver->domainGetMaxVcpus(domain);
7716         if (ret < 0)
7717             goto error;
7718         return ret;
7719     }
7720 
7721     virReportUnsupportedError();
7722 
7723  error:
7724     virDispatchError(domain->conn);
7725     return -1;
7726 }
7727 
7728 
7729 /**
7730  * virDomainGetIOThreadInfo:
7731  * @dom: a domain object
7732  * @info: pointer to an array of virDomainIOThreadInfo structures (OUT)
7733  * @flags: bitwise-OR of virDomainModificationImpact
7734  *     Must not be VIR_DOMAIN_AFFECT_LIVE and
7735  *     VIR_DOMAIN_AFFECT_CONFIG concurrently.
7736  *
7737  * Fetch IOThreads of an active domain including the cpumap information to
7738  * determine on which CPU the IOThread has affinity to run.
7739  *
7740  * Returns the number of IOThreads or -1 in case of error.
7741  * On success, the array of information is stored into @info. The caller is
7742  * responsible for calling virDomainIOThreadInfoFree() on each array element,
7743  * then calling free() on @info. On error, @info is set to NULL.
7744  */
7745 int
virDomainGetIOThreadInfo(virDomainPtr dom,virDomainIOThreadInfoPtr ** info,unsigned int flags)7746 virDomainGetIOThreadInfo(virDomainPtr dom,
7747                          virDomainIOThreadInfoPtr **info,
7748                          unsigned int flags)
7749 {
7750     VIR_DOMAIN_DEBUG(dom, "info=%p flags=0x%x", info, flags);
7751 
7752     virResetLastError();
7753 
7754     virCheckDomainReturn(dom, -1);
7755     virCheckNonNullArgGoto(info, error);
7756     *info = NULL;
7757 
7758     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE,
7759                              VIR_DOMAIN_AFFECT_CONFIG,
7760                              error);
7761 
7762     if (dom->conn->driver->domainGetIOThreadInfo) {
7763         int ret;
7764         ret = dom->conn->driver->domainGetIOThreadInfo(dom, info, flags);
7765         if (ret < 0)
7766             goto error;
7767         return ret;
7768     }
7769 
7770     virReportUnsupportedError();
7771 
7772  error:
7773     virDispatchError(dom->conn);
7774     return -1;
7775 }
7776 
7777 
7778 /**
7779  * virDomainIOThreadInfoFree:
7780  * @info: pointer to a virDomainIOThreadInfo object
7781  *
7782  * Frees the memory used by @info.
7783  */
7784 void
virDomainIOThreadInfoFree(virDomainIOThreadInfoPtr info)7785 virDomainIOThreadInfoFree(virDomainIOThreadInfoPtr info)
7786 {
7787     if (!info)
7788         return;
7789 
7790     g_free(info->cpumap);
7791     g_free(info);
7792 }
7793 
7794 
7795 /**
7796  * virDomainPinIOThread:
7797  * @domain: a domain object
7798  * @iothread_id: the IOThread ID to set the CPU affinity
7799  * @cpumap: pointer to a bit map of real CPUs (in 8-bit bytes) (IN)
7800  *      Each bit set to 1 means that corresponding CPU is usable.
7801  *      Bytes are stored in little-endian order: CPU0-7, 8-15...
7802  *      In each byte, lowest CPU number is least significant bit.
7803  * @maplen: number of bytes in cpumap, from 1 up to size of CPU map in
7804  *      underlying virtualization system (Xen...).
7805  *      If maplen < size, missing bytes are set to zero.
7806  *      If maplen > size, failure code is returned.
7807  * @flags: bitwise-OR of virDomainModificationImpact
7808  *
7809  * Dynamically change the real CPUs which can be allocated to an IOThread.
7810  * This function may require privileged access to the hypervisor.
7811  *
7812  * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
7813  * Both flags may be set.
7814  * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain
7815  * and may fail if domain is not alive.
7816  * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
7817  * and will fail for transient domains. If neither flag is specified (that is,
7818  * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies
7819  * persistent setup, while an active domain is hypervisor-dependent on whether
7820  * just live or both live and persistent state is changed.
7821  * Not all hypervisors can support all flag combinations.
7822  *
7823  * See also virDomainGetIOThreadInfo for querying this information.
7824  *
7825  * Returns 0 in case of success, -1 in case of failure.
7826  */
7827 int
virDomainPinIOThread(virDomainPtr domain,unsigned int iothread_id,unsigned char * cpumap,int maplen,unsigned int flags)7828 virDomainPinIOThread(virDomainPtr domain,
7829                      unsigned int iothread_id,
7830                      unsigned char *cpumap,
7831                      int maplen,
7832                      unsigned int flags)
7833 {
7834     virConnectPtr conn;
7835 
7836     VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, cpumap=%p, maplen=%d",
7837                      iothread_id, cpumap, maplen);
7838 
7839     virResetLastError();
7840 
7841     virCheckDomainReturn(domain, -1);
7842     conn = domain->conn;
7843 
7844     virCheckReadOnlyGoto(conn->flags, error);
7845     virCheckNonNullArgGoto(cpumap, error);
7846     virCheckPositiveArgGoto(maplen, error);
7847 
7848     if (conn->driver->domainPinIOThread) {
7849         int ret;
7850         ret = conn->driver->domainPinIOThread(domain, iothread_id,
7851                                               cpumap, maplen, flags);
7852         if (ret < 0)
7853             goto error;
7854         return ret;
7855     }
7856 
7857     virReportUnsupportedError();
7858 
7859  error:
7860     virDispatchError(domain->conn);
7861     return -1;
7862 }
7863 
7864 
7865 /**
7866  * virDomainAddIOThread:
7867  * @domain: a domain object
7868  * @iothread_id: the specific IOThread ID value to add
7869  * @flags: bitwise-OR of virDomainModificationImpact
7870  *
7871  * Dynamically add an IOThread to the domain. It is left up to the
7872  * underlying virtual hypervisor to determine the valid range for an
7873  * @iothread_id and determining whether the @iothread_id already exists.
7874  *
7875  * Note that this call can fail if the underlying virtualization hypervisor
7876  * does not support it or if growing the number is arbitrarily limited.
7877  * This function requires privileged access to the hypervisor.
7878  *
7879  * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
7880  * Both flags may be set.
7881  * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain
7882  * and may fail if domain is not alive.
7883  * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
7884  * and will fail for transient domains. If neither flag is specified (that is,
7885  * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies
7886  * persistent setup, while an active domain is hypervisor-dependent on whether
7887  * just live or both live and persistent state is changed.
7888  *
7889  * Returns 0 in case of success, -1 in case of failure.
7890  */
7891 int
virDomainAddIOThread(virDomainPtr domain,unsigned int iothread_id,unsigned int flags)7892 virDomainAddIOThread(virDomainPtr domain,
7893                      unsigned int iothread_id,
7894                      unsigned int flags)
7895 {
7896     virConnectPtr conn;
7897 
7898     VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, flags=0x%x",
7899                      iothread_id, flags);
7900 
7901     virResetLastError();
7902 
7903     virCheckDomainReturn(domain, -1);
7904     virCheckReadOnlyGoto(domain->conn->flags, error);
7905 
7906     conn = domain->conn;
7907 
7908     if (conn->driver->domainAddIOThread) {
7909         int ret;
7910         ret = conn->driver->domainAddIOThread(domain, iothread_id, flags);
7911         if (ret < 0)
7912             goto error;
7913         return ret;
7914     }
7915 
7916     virReportUnsupportedError();
7917 
7918  error:
7919     virDispatchError(domain->conn);
7920     return -1;
7921 }
7922 
7923 
7924 /**
7925  * virDomainDelIOThread:
7926  * @domain: a domain object
7927  * @iothread_id: the specific IOThread ID value to delete
7928  * @flags: bitwise-OR of virDomainModificationImpact
7929  *
7930  * Dynamically delete an IOThread from the domain. The @iothread_id to be
7931  * deleted must not have a resource associated with it and can be any of
7932  * the currently valid IOThread ID's.
7933  *
7934  * Note that this call can fail if the underlying virtualization hypervisor
7935  * does not support it or if reducing the number is arbitrarily limited.
7936  * This function requires privileged access to the hypervisor.
7937  *
7938  * @flags may include VIR_DOMAIN_AFFECT_LIVE or VIR_DOMAIN_AFFECT_CONFIG.
7939  * Both flags may be set.
7940  * If VIR_DOMAIN_AFFECT_LIVE is set, the change affects a running domain
7941  * and may fail if domain is not alive.
7942  * If VIR_DOMAIN_AFFECT_CONFIG is set, the change affects persistent state,
7943  * and will fail for transient domains. If neither flag is specified (that is,
7944  * @flags is VIR_DOMAIN_AFFECT_CURRENT), then an inactive domain modifies
7945  * persistent setup, while an active domain is hypervisor-dependent on whether
7946  * just live or both live and persistent state is changed.
7947  *
7948  * Returns 0 in case of success, -1 in case of failure.
7949  */
7950 int
virDomainDelIOThread(virDomainPtr domain,unsigned int iothread_id,unsigned int flags)7951 virDomainDelIOThread(virDomainPtr domain,
7952                      unsigned int iothread_id,
7953                      unsigned int flags)
7954 {
7955     virConnectPtr conn;
7956 
7957     VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, flags=0x%x", iothread_id, flags);
7958 
7959     virResetLastError();
7960 
7961     virCheckDomainReturn(domain, -1);
7962     virCheckReadOnlyGoto(domain->conn->flags, error);
7963     virCheckNonZeroArgGoto(iothread_id, error);
7964 
7965     conn = domain->conn;
7966 
7967     if (conn->driver->domainDelIOThread) {
7968         int ret;
7969         ret = conn->driver->domainDelIOThread(domain, iothread_id, flags);
7970         if (ret < 0)
7971             goto error;
7972         return ret;
7973     }
7974 
7975     virReportUnsupportedError();
7976 
7977  error:
7978     virDispatchError(domain->conn);
7979     return -1;
7980 }
7981 
7982 
7983 /**
7984  * virDomainSetIOThreadParams:
7985  * @domain: a domain object
7986  * @iothread_id: the specific IOThread ID value to add
7987  * @params: pointer to IOThread parameter objects
7988  * @nparams: number of IOThread parameters
7989  * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
7990  *
7991  * Dynamically set IOThread parameters to the domain. It is left up to
7992  * the underlying virtual hypervisor to determine the valid range for an
7993  * @iothread_id, determining whether the @iothread_id already exists, and
7994  * determining the validity of the provided param values.
7995  *
7996  * See VIR_DOMAIN_IOTHREAD_* for detailed description of accepted IOThread
7997  * parameters.
7998  *
7999  * Since the purpose of this API is to dynamically modify the IOThread
8000  * @flags should only include the VIR_DOMAIN_AFFECT_CURRENT and/or
8001  * VIR_DOMAIN_AFFECT_LIVE virDomainMemoryModFlags. Setting other flags
8002  * may cause errors from the hypervisor.
8003  *
8004  * Note that this call can fail if the underlying virtualization hypervisor
8005  * does not support it or does not support setting the provided values.
8006  *
8007  * This function requires privileged access to the hypervisor.
8008  *
8009  * Returns 0 in case of success, -1 in case of failure.
8010  */
8011 int
virDomainSetIOThreadParams(virDomainPtr domain,unsigned int iothread_id,virTypedParameterPtr params,int nparams,unsigned int flags)8012 virDomainSetIOThreadParams(virDomainPtr domain,
8013                            unsigned int iothread_id,
8014                            virTypedParameterPtr params,
8015                            int nparams,
8016                            unsigned int flags)
8017 {
8018     virConnectPtr conn;
8019 
8020     VIR_DOMAIN_DEBUG(domain, "iothread_id=%u, params=%p, nparams=%d, flags=0x%x",
8021                      iothread_id, params, nparams, flags);
8022     VIR_TYPED_PARAMS_DEBUG(params, nparams);
8023 
8024     virResetLastError();
8025 
8026     virCheckDomainReturn(domain, -1);
8027     conn = domain->conn;
8028 
8029     virCheckReadOnlyGoto(conn->flags, error);
8030     virCheckNonNullArgGoto(params, error);
8031     virCheckPositiveArgGoto(nparams, error);
8032 
8033     if (virTypedParameterValidateSet(conn, params, nparams) < 0)
8034         goto error;
8035 
8036     if (conn->driver->domainSetIOThreadParams) {
8037         int ret;
8038         ret = conn->driver->domainSetIOThreadParams(domain, iothread_id,
8039                                                     params, nparams, flags);
8040         if (ret < 0)
8041             goto error;
8042         return ret;
8043     }
8044 
8045     virReportUnsupportedError();
8046 
8047  error:
8048     virDispatchError(domain->conn);
8049     return -1;
8050 }
8051 
8052 
8053 /**
8054  * virDomainGetSecurityLabel:
8055  * @domain: a domain object
8056  * @seclabel: pointer to a virSecurityLabel structure
8057  *
8058  * Extract security label of an active domain. The 'label' field
8059  * in the @seclabel argument will be initialized to the empty
8060  * string if the domain is not running under a security model.
8061  *
8062  * Returns 0 in case of success, -1 in case of failure
8063  */
8064 int
virDomainGetSecurityLabel(virDomainPtr domain,virSecurityLabelPtr seclabel)8065 virDomainGetSecurityLabel(virDomainPtr domain, virSecurityLabelPtr seclabel)
8066 {
8067     virConnectPtr conn;
8068 
8069     VIR_DOMAIN_DEBUG(domain, "seclabel=%p", seclabel);
8070 
8071     virResetLastError();
8072 
8073     virCheckDomainReturn(domain, -1);
8074     conn = domain->conn;
8075 
8076     virCheckNonNullArgGoto(seclabel, error);
8077 
8078     if (conn->driver->domainGetSecurityLabel) {
8079         int ret;
8080         ret = conn->driver->domainGetSecurityLabel(domain, seclabel);
8081         if (ret < 0)
8082             goto error;
8083         return ret;
8084     }
8085 
8086     virReportUnsupportedError();
8087 
8088  error:
8089     virDispatchError(domain->conn);
8090     return -1;
8091 }
8092 
8093 
8094 /**
8095  * virDomainGetSecurityLabelList:
8096  * @domain: a domain object
8097  * @seclabels: will be auto-allocated and filled with domains' security labels.
8098  * Caller must free memory on return.
8099  *
8100  * Extract the security labels of an active domain. The 'label' field
8101  * in the @seclabels argument will be initialized to the empty
8102  * string if the domain is not running under a security model.
8103  *
8104  * Returns number of elements in @seclabels on success, -1 in case of failure.
8105  */
8106 int
virDomainGetSecurityLabelList(virDomainPtr domain,virSecurityLabelPtr * seclabels)8107 virDomainGetSecurityLabelList(virDomainPtr domain,
8108                               virSecurityLabelPtr* seclabels)
8109 {
8110     virConnectPtr conn;
8111 
8112     VIR_DOMAIN_DEBUG(domain, "seclabels=%p", seclabels);
8113 
8114     virResetLastError();
8115 
8116     virCheckDomainReturn(domain, -1);
8117 
8118     virCheckNonNullArgGoto(seclabels, error);
8119 
8120     conn = domain->conn;
8121 
8122     if (conn->driver->domainGetSecurityLabelList) {
8123         int ret;
8124         ret = conn->driver->domainGetSecurityLabelList(domain, seclabels);
8125         if (ret < 0)
8126             goto error;
8127         return ret;
8128     }
8129 
8130     virReportUnsupportedError();
8131 
8132  error:
8133     virDispatchError(domain->conn);
8134     return -1;
8135 }
8136 
8137 
8138 /**
8139  * virDomainSetMetadata:
8140  * @domain: a domain object
8141  * @type: type of metadata, from virDomainMetadataType
8142  * @metadata: new metadata text
8143  * @key: XML namespace key, or NULL
8144  * @uri: XML namespace URI, or NULL
8145  * @flags: bitwise-OR of virDomainModificationImpact
8146  *
8147  * Sets the appropriate domain element given by @type to the
8148  * value of @metadata.  A @type of VIR_DOMAIN_METADATA_DESCRIPTION
8149  * is free-form text; VIR_DOMAIN_METADATA_TITLE is free-form, but no
8150  * newlines are permitted, and should be short (although the length is
8151  * not enforced). For these two options @key and @uri are irrelevant and
8152  * must be set to NULL.
8153  *
8154  * For type VIR_DOMAIN_METADATA_ELEMENT @metadata  must be well-formed
8155  * XML belonging to namespace defined by @uri with local name @key.
8156  *
8157  * Passing NULL for @metadata says to remove that element from the
8158  * domain XML (passing the empty string leaves the element present).
8159  *
8160  * The resulting metadata will be present in virDomainGetXMLDesc(),
8161  * as well as quick access through virDomainGetMetadata().
8162  *
8163  * @flags controls whether the live domain, persistent configuration,
8164  * or both will be modified.
8165  *
8166  * Returns 0 on success, -1 in case of failure.
8167  */
8168 int
virDomainSetMetadata(virDomainPtr domain,int type,const char * metadata,const char * key,const char * uri,unsigned int flags)8169 virDomainSetMetadata(virDomainPtr domain,
8170                      int type,
8171                      const char *metadata,
8172                      const char *key,
8173                      const char *uri,
8174                      unsigned int flags)
8175 {
8176     virConnectPtr conn;
8177 
8178     VIR_DOMAIN_DEBUG(domain,
8179                      "type=%d, metadata='%s', key='%s', uri='%s', flags=0x%x",
8180                      type, NULLSTR(metadata), NULLSTR(key), NULLSTR(uri),
8181                      flags);
8182 
8183     virResetLastError();
8184 
8185     virCheckDomainReturn(domain, -1);
8186     conn = domain->conn;
8187 
8188     virCheckReadOnlyGoto(conn->flags, error);
8189 
8190     switch (type) {
8191     case VIR_DOMAIN_METADATA_TITLE:
8192         if (metadata && strchr(metadata, '\n')) {
8193             virReportInvalidArg(metadata, "%s",
8194                                 _("metadata title can't contain "
8195                                   "newlines"));
8196             goto error;
8197         }
8198         G_GNUC_FALLTHROUGH;
8199     case VIR_DOMAIN_METADATA_DESCRIPTION:
8200         virCheckNullArgGoto(uri, error);
8201         virCheckNullArgGoto(key, error);
8202         break;
8203     case VIR_DOMAIN_METADATA_ELEMENT:
8204         virCheckNonNullArgGoto(uri, error);
8205         if (metadata)
8206             virCheckNonNullArgGoto(key, error);
8207         break;
8208     default:
8209         /* For future expansion */
8210         break;
8211     }
8212 
8213     if (conn->driver->domainSetMetadata) {
8214         int ret;
8215         ret = conn->driver->domainSetMetadata(domain, type, metadata, key, uri,
8216                                               flags);
8217         if (ret < 0)
8218             goto error;
8219         return ret;
8220     }
8221 
8222     virReportUnsupportedError();
8223 
8224  error:
8225     virDispatchError(domain->conn);
8226     return -1;
8227 }
8228 
8229 
8230 /**
8231  * virDomainGetMetadata:
8232  * @domain: a domain object
8233  * @type: type of metadata, from virDomainMetadataType
8234  * @uri: XML namespace identifier
8235  * @flags: bitwise-OR of virDomainModificationImpact
8236  *
8237  * Retrieves the appropriate domain element given by @type.
8238  * If VIR_DOMAIN_METADATA_ELEMENT is requested parameter @uri
8239  * must be set to the name of the namespace the requested elements
8240  * belong to, otherwise must be NULL.
8241  *
8242  * If an element of the domain XML is not present, the resulting
8243  * error will be VIR_ERR_NO_DOMAIN_METADATA.  This method forms
8244  * a shortcut for seeing information from virDomainSetMetadata()
8245  * without having to go through virDomainGetXMLDesc().
8246  *
8247  * @flags controls whether the live domain or persistent
8248  * configuration will be queried.
8249  *
8250  * Returns the metadata string on success (caller must free),
8251  * or NULL in case of failure.
8252  */
8253 char *
virDomainGetMetadata(virDomainPtr domain,int type,const char * uri,unsigned int flags)8254 virDomainGetMetadata(virDomainPtr domain,
8255                      int type,
8256                      const char *uri,
8257                      unsigned int flags)
8258 {
8259     virConnectPtr conn;
8260 
8261     VIR_DOMAIN_DEBUG(domain, "type=%d, uri='%s', flags=0x%x",
8262                      type, NULLSTR(uri), flags);
8263 
8264     virResetLastError();
8265 
8266     virCheckDomainReturn(domain, NULL);
8267 
8268     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE,
8269                              VIR_DOMAIN_AFFECT_CONFIG,
8270                              error);
8271 
8272     switch (type) {
8273     case VIR_DOMAIN_METADATA_TITLE:
8274     case VIR_DOMAIN_METADATA_DESCRIPTION:
8275         virCheckNullArgGoto(uri, error);
8276         break;
8277     case VIR_DOMAIN_METADATA_ELEMENT:
8278         virCheckNonNullArgGoto(uri, error);
8279         break;
8280     default:
8281         /* For future expansion */
8282         break;
8283     }
8284 
8285     conn = domain->conn;
8286 
8287     if (conn->driver->domainGetMetadata) {
8288         char *ret;
8289         if (!(ret = conn->driver->domainGetMetadata(domain, type, uri, flags)))
8290             goto error;
8291         return ret;
8292     }
8293 
8294     virReportUnsupportedError();
8295 
8296  error:
8297     virDispatchError(domain->conn);
8298     return NULL;
8299 }
8300 
8301 
8302 /**
8303  * virDomainAttachDevice:
8304  * @domain: pointer to domain object
8305  * @xml: pointer to XML description of one device
8306  *
8307  * Create a virtual device attachment to backend.  This function,
8308  * having hotplug semantics, is only allowed on an active domain.
8309  *
8310  * For compatibility, this method can also be used to change the media
8311  * in an existing CDROM/Floppy device, however, applications are
8312  * recommended to use the virDomainUpdateDeviceFlags method instead.
8313  *
8314  * Be aware that hotplug changes might not persist across a domain going
8315  * into S4 state (also known as hibernation) unless you also modify the
8316  * persistent domain definition.
8317  *
8318  * Returns 0 in case of success, -1 in case of failure.
8319  */
8320 int
virDomainAttachDevice(virDomainPtr domain,const char * xml)8321 virDomainAttachDevice(virDomainPtr domain, const char *xml)
8322 {
8323     virConnectPtr conn;
8324 
8325     VIR_DOMAIN_DEBUG(domain, "xml=%s", xml);
8326 
8327     virResetLastError();
8328 
8329     virCheckDomainReturn(domain, -1);
8330     conn = domain->conn;
8331 
8332     virCheckNonNullArgGoto(xml, error);
8333     virCheckReadOnlyGoto(conn->flags, error);
8334 
8335     if (conn->driver->domainAttachDevice) {
8336        int ret;
8337        ret = conn->driver->domainAttachDevice(domain, xml);
8338        if (ret < 0)
8339           goto error;
8340        return ret;
8341     }
8342 
8343     virReportUnsupportedError();
8344 
8345  error:
8346     virDispatchError(domain->conn);
8347     return -1;
8348 }
8349 
8350 
8351 /**
8352  * virDomainAttachDeviceFlags:
8353  * @domain: pointer to domain object
8354  * @xml: pointer to XML description of one device
8355  * @flags: bitwise-OR of virDomainDeviceModifyFlags
8356  *
8357  * Attach a virtual device to a domain, using the flags parameter
8358  * to control how the device is attached.  VIR_DOMAIN_AFFECT_CURRENT
8359  * specifies that the device allocation is made based on current domain
8360  * state.  VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be
8361  * allocated to the active domain instance only and is not added to the
8362  * persisted domain configuration.  VIR_DOMAIN_AFFECT_CONFIG
8363  * specifies that the device shall be allocated to the persisted domain
8364  * configuration only.  Note that the target hypervisor must return an
8365  * error if unable to satisfy flags.  E.g. the hypervisor driver will
8366  * return failure if LIVE is specified but it only supports modifying the
8367  * persisted device allocation.
8368  *
8369  * For compatibility, this method can also be used to change the media
8370  * in an existing CDROM/Floppy device, however, applications are
8371  * recommended to use the virDomainUpdateDeviceFlag method instead.
8372  *
8373  * Be aware that hotplug changes might not persist across a domain going
8374  * into S4 state (also known as hibernation) unless you also modify the
8375  * persistent domain definition.
8376  *
8377  * Returns 0 in case of success, -1 in case of failure.
8378  */
8379 int
virDomainAttachDeviceFlags(virDomainPtr domain,const char * xml,unsigned int flags)8380 virDomainAttachDeviceFlags(virDomainPtr domain,
8381                            const char *xml, unsigned int flags)
8382 {
8383     virConnectPtr conn;
8384 
8385     VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=0x%x", xml, flags);
8386 
8387     virResetLastError();
8388 
8389     virCheckDomainReturn(domain, -1);
8390     conn = domain->conn;
8391 
8392     virCheckNonNullArgGoto(xml, error);
8393     virCheckReadOnlyGoto(conn->flags, error);
8394 
8395     if (conn->driver->domainAttachDeviceFlags) {
8396         int ret;
8397         ret = conn->driver->domainAttachDeviceFlags(domain, xml, flags);
8398         if (ret < 0)
8399             goto error;
8400         return ret;
8401     }
8402 
8403     virReportUnsupportedError();
8404 
8405  error:
8406     virDispatchError(domain->conn);
8407     return -1;
8408 }
8409 
8410 
8411 /**
8412  * virDomainDetachDevice:
8413  * @domain: pointer to domain object
8414  * @xml: pointer to XML description of one device
8415  *
8416  * This is an equivalent of virDomainDetachDeviceFlags() when called with
8417  * @flags parameter set to VIR_DOMAIN_AFFECT_LIVE.
8418  *
8419  * See virDomainDetachDeviceFlags() for more details.
8420  *
8421  * Returns 0 in case of success, -1 in case of failure.
8422  */
8423 int
virDomainDetachDevice(virDomainPtr domain,const char * xml)8424 virDomainDetachDevice(virDomainPtr domain, const char *xml)
8425 {
8426     virConnectPtr conn;
8427 
8428     VIR_DOMAIN_DEBUG(domain, "xml=%s", xml);
8429 
8430     virResetLastError();
8431 
8432     virCheckDomainReturn(domain, -1);
8433     conn = domain->conn;
8434 
8435     virCheckNonNullArgGoto(xml, error);
8436     virCheckReadOnlyGoto(conn->flags, error);
8437 
8438     if (conn->driver->domainDetachDevice) {
8439         int ret;
8440         ret = conn->driver->domainDetachDevice(domain, xml);
8441          if (ret < 0)
8442              goto error;
8443          return ret;
8444      }
8445 
8446     virReportUnsupportedError();
8447 
8448  error:
8449     virDispatchError(domain->conn);
8450     return -1;
8451 }
8452 
8453 
8454 /**
8455  * virDomainDetachDeviceFlags:
8456  * @domain: pointer to domain object
8457  * @xml: pointer to XML description of one device
8458  * @flags: bitwise-OR of virDomainDeviceModifyFlags
8459  *
8460  * Detach a virtual device from a domain, using the flags parameter
8461  * to control how the device is detached.  VIR_DOMAIN_AFFECT_CURRENT
8462  * specifies that the device allocation is removed based on current domain
8463  * state.  VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be
8464  * deallocated from the active domain instance only and is not from the
8465  * persisted domain configuration.  VIR_DOMAIN_AFFECT_CONFIG
8466  * specifies that the device shall be deallocated from the persisted domain
8467  * configuration only.  Note that the target hypervisor must return an
8468  * error if unable to satisfy flags.  E.g. the hypervisor driver will
8469  * return failure if LIVE is specified but it only supports removing the
8470  * persisted device allocation.
8471  *
8472  * Some hypervisors may prevent this operation if there is a current
8473  * block job running operation on the device being detached; in that case,
8474  * use virDomainBlockJobAbort() to stop the block job first.
8475  *
8476  * Beware that depending on the hypervisor and device type, detaching a device
8477  * from a running domain may be asynchronous. That is, calling
8478  * virDomainDetachDeviceFlags may just request device removal while the device
8479  * is actually removed later (in cooperation with a guest OS). Previously,
8480  * this fact was ignored and the device could have been removed from domain
8481  * configuration before it was actually removed by the hypervisor causing
8482  * various failures on subsequent operations. To check whether the device was
8483  * successfully removed, either recheck domain configuration using
8484  * virDomainGetXMLDesc() or add a handler for the VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED
8485  * event. In case the device is already gone when virDomainDetachDeviceFlags
8486  * returns, the event is delivered before this API call ends. To help existing
8487  * clients work better in most cases, this API will try to transform an
8488  * asynchronous device removal that finishes shortly after the request into
8489  * a synchronous removal. In other words, this API may wait a bit for the
8490  * removal to complete in case it was not synchronous.
8491  *
8492  * Be aware that hotplug changes might not persist across a domain going
8493  * into S4 state (also known as hibernation) unless you also modify the
8494  * persistent domain definition.
8495  *
8496  * The supplied XML description of the device should be as specific
8497  * as its definition in the domain XML. The set of attributes used
8498  * to match the device are internal to the drivers. Using a partial definition,
8499  * or attempting to detach a device that is not present in the domain XML,
8500  * but shares some specific attributes with one that is present,
8501  * may lead to unexpected results.
8502  *
8503  * Returns 0 in case of success, -1 in case of failure.
8504  */
8505 int
virDomainDetachDeviceFlags(virDomainPtr domain,const char * xml,unsigned int flags)8506 virDomainDetachDeviceFlags(virDomainPtr domain,
8507                            const char *xml, unsigned int flags)
8508 {
8509     virConnectPtr conn;
8510 
8511     VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=0x%x", xml, flags);
8512 
8513     virResetLastError();
8514 
8515     virCheckDomainReturn(domain, -1);
8516     conn = domain->conn;
8517 
8518     virCheckNonNullArgGoto(xml, error);
8519     virCheckReadOnlyGoto(conn->flags, error);
8520 
8521     if (conn->driver->domainDetachDeviceFlags) {
8522         int ret;
8523         ret = conn->driver->domainDetachDeviceFlags(domain, xml, flags);
8524         if (ret < 0)
8525             goto error;
8526         return ret;
8527     }
8528 
8529     virReportUnsupportedError();
8530 
8531  error:
8532     virDispatchError(domain->conn);
8533     return -1;
8534 }
8535 
8536 
8537 /**
8538  * virDomainUpdateDeviceFlags:
8539  * @domain: pointer to domain object
8540  * @xml: pointer to XML description of one device
8541  * @flags: bitwise-OR of virDomainDeviceModifyFlags
8542  *
8543  * Change a virtual device on a domain, using the flags parameter
8544  * to control how the device is changed.  VIR_DOMAIN_AFFECT_CURRENT
8545  * specifies that the device change is made based on current domain
8546  * state.  VIR_DOMAIN_AFFECT_LIVE specifies that the device shall be
8547  * changed on the active domain instance only and is not added to the
8548  * persisted domain configuration. VIR_DOMAIN_AFFECT_CONFIG
8549  * specifies that the device shall be changed on the persisted domain
8550  * configuration only.  Note that the target hypervisor must return an
8551  * error if unable to satisfy flags.  E.g. the hypervisor driver will
8552  * return failure if LIVE is specified but it only supports modifying the
8553  * persisted device allocation.
8554  *
8555  * This method is used for actions such changing CDROM/Floppy device
8556  * media, altering the graphics configuration such as password,
8557  * reconfiguring the NIC device backend connectivity, etc.
8558  *
8559  * The supplied XML description of the device should contain all
8560  * the information that is found in the corresponding domain XML.
8561  * Leaving out any piece of information may be treated as a
8562  * request for its removal, which may be denied. For instance,
8563  * when users want to change CDROM media only for live XML, they
8564  * must provide live disk XML as found in the corresponding live
8565  * domain XML with only the disk path changed.
8566  *
8567  * Returns 0 in case of success, -1 in case of failure.
8568  */
8569 int
virDomainUpdateDeviceFlags(virDomainPtr domain,const char * xml,unsigned int flags)8570 virDomainUpdateDeviceFlags(virDomainPtr domain,
8571                            const char *xml, unsigned int flags)
8572 {
8573     virConnectPtr conn;
8574 
8575     VIR_DOMAIN_DEBUG(domain, "xml=%s, flags=0x%x", xml, flags);
8576 
8577     virResetLastError();
8578 
8579     virCheckDomainReturn(domain, -1);
8580     conn = domain->conn;
8581 
8582     virCheckNonNullArgGoto(xml, error);
8583     virCheckReadOnlyGoto(conn->flags, error);
8584 
8585     if (conn->driver->domainUpdateDeviceFlags) {
8586         int ret;
8587         ret = conn->driver->domainUpdateDeviceFlags(domain, xml, flags);
8588         if (ret < 0)
8589             goto error;
8590         return ret;
8591     }
8592 
8593     virReportUnsupportedError();
8594 
8595  error:
8596     virDispatchError(domain->conn);
8597     return -1;
8598 }
8599 
8600 
8601 /**
8602  * virDomainDetachDeviceAlias:
8603  * @domain: pointer to a domain object
8604  * @alias: device alias
8605  * @flags: bitwise-OR of virDomainDeviceModifyFlags
8606  *
8607  * Detach a virtual device from a domain, using the alias to
8608  * specify the device. The value of @flags should be either
8609  * VIR_DOMAIN_AFFECT_CURRENT, or a bitwise-or of values from
8610  * VIR_DOMAIN_AFFECT_LIVE and VIR_DOMAIN_AFFECT_CURRENT, although
8611  * hypervisors vary in which flags are supported.
8612  *
8613  * In contrast to virDomainDetachDeviceFlags() this API is
8614  * asynchronous - it returns immediately after sending the detach
8615  * request to the hypervisor. It's caller's responsibility to
8616  * wait for VIR_DOMAIN_EVENT_ID_DEVICE_REMOVED event to signal
8617  * actual device removal or for
8618  * VIR_DOMAIN_EVENT_ID_DEVICE_REMOVAL_FAILED to signal rejected
8619  * device removal.
8620  *
8621  * Returns 0 in case of success, -1 in case of failure.
8622  */
8623 int
virDomainDetachDeviceAlias(virDomainPtr domain,const char * alias,unsigned int flags)8624 virDomainDetachDeviceAlias(virDomainPtr domain,
8625                            const char *alias,
8626                            unsigned int flags)
8627 {
8628     virConnectPtr conn;
8629 
8630     VIR_DOMAIN_DEBUG(domain, "alias=%s, flags=0x%x", alias, flags);
8631 
8632     virResetLastError();
8633 
8634     virCheckDomainReturn(domain, -1);
8635     conn = domain->conn;
8636 
8637     virCheckNonNullArgGoto(alias, error);
8638     virCheckReadOnlyGoto(conn->flags, error);
8639 
8640     if (conn->driver->domainDetachDeviceAlias) {
8641         int ret;
8642         ret = conn->driver->domainDetachDeviceAlias(domain, alias, flags);
8643         if (ret < 0)
8644             goto error;
8645         return ret;
8646     }
8647 
8648     virReportUnsupportedError();
8649 
8650  error:
8651     virDispatchError(domain->conn);
8652     return -1;
8653 }
8654 
8655 
8656 /**
8657  * virConnectDomainEventRegister:
8658  * @conn: pointer to the connection
8659  * @cb: callback to the function handling domain events
8660  * @opaque: opaque data to pass on to the callback
8661  * @freecb: optional function to deallocate opaque when not used anymore
8662  *
8663  * Adds a callback to receive notifications of domain lifecycle events
8664  * occurring on a connection.  This function requires that an event loop
8665  * has been previously registered with virEventRegisterImpl() or
8666  * virEventRegisterDefaultImpl().
8667  *
8668  * Use of this method is no longer recommended. Instead applications
8669  * should try virConnectDomainEventRegisterAny() which has a more flexible
8670  * API contract.
8671  *
8672  * The virDomainPtr object handle passed into the callback upon delivery
8673  * of an event is only valid for the duration of execution of the callback.
8674  * If the callback wishes to keep the domain object after the callback returns,
8675  * it shall take a reference to it, by calling virDomainRef.
8676  * The reference can be released once the object is no longer required
8677  * by calling virDomainFree.
8678  *
8679  * Returns 0 on success, -1 on failure.  Older versions of some hypervisors
8680  * sometimes returned a positive number on success, but without any reliable
8681  * semantics on what that number represents.
8682  */
8683 int
virConnectDomainEventRegister(virConnectPtr conn,virConnectDomainEventCallback cb,void * opaque,virFreeCallback freecb)8684 virConnectDomainEventRegister(virConnectPtr conn,
8685                               virConnectDomainEventCallback cb,
8686                               void *opaque,
8687                               virFreeCallback freecb)
8688 {
8689     VIR_DEBUG("conn=%p, cb=%p, opaque=%p, freecb=%p", conn, cb, opaque, freecb);
8690     virResetLastError();
8691 
8692     virCheckConnectReturn(conn, -1);
8693     virCheckNonNullArgGoto(cb, error);
8694 
8695     if (conn->driver && conn->driver->connectDomainEventRegister) {
8696         int ret;
8697         ret = conn->driver->connectDomainEventRegister(conn, cb, opaque, freecb);
8698         if (ret < 0)
8699             goto error;
8700         return ret;
8701     }
8702 
8703     virReportUnsupportedError();
8704  error:
8705     virDispatchError(conn);
8706     return -1;
8707 }
8708 
8709 
8710 /**
8711  * virConnectDomainEventDeregister:
8712  * @conn: pointer to the connection
8713  * @cb: callback to the function handling domain events
8714  *
8715  * Removes a callback previously registered with the
8716  * virConnectDomainEventRegister() function.
8717  *
8718  * Use of this method is no longer recommended. Instead applications
8719  * should try virConnectDomainEventDeregisterAny() which has a more flexible
8720  * API contract
8721  *
8722  * Returns 0 on success, -1 on failure.  Older versions of some hypervisors
8723  * sometimes returned a positive number on success, but without any reliable
8724  * semantics on what that number represents.
8725  */
8726 int
virConnectDomainEventDeregister(virConnectPtr conn,virConnectDomainEventCallback cb)8727 virConnectDomainEventDeregister(virConnectPtr conn,
8728                                 virConnectDomainEventCallback cb)
8729 {
8730     VIR_DEBUG("conn=%p, cb=%p", conn, cb);
8731 
8732     virResetLastError();
8733 
8734     virCheckConnectReturn(conn, -1);
8735     virCheckNonNullArgGoto(cb, error);
8736 
8737     if (conn->driver && conn->driver->connectDomainEventDeregister) {
8738         int ret;
8739         ret = conn->driver->connectDomainEventDeregister(conn, cb);
8740         if (ret < 0)
8741             goto error;
8742         return ret;
8743     }
8744 
8745     virReportUnsupportedError();
8746  error:
8747     virDispatchError(conn);
8748     return -1;
8749 }
8750 
8751 
8752 /**
8753  * virDomainIsActive:
8754  * @dom: pointer to the domain object
8755  *
8756  * Determine if the domain is currently running
8757  *
8758  * Returns 1 if running, 0 if inactive, -1 on error
8759  */
8760 int
virDomainIsActive(virDomainPtr dom)8761 virDomainIsActive(virDomainPtr dom)
8762 {
8763     VIR_DEBUG("dom=%p", dom);
8764 
8765     virResetLastError();
8766 
8767     virCheckDomainReturn(dom, -1);
8768 
8769     if (dom->conn->driver->domainIsActive) {
8770         int ret;
8771         ret = dom->conn->driver->domainIsActive(dom);
8772         if (ret < 0)
8773             goto error;
8774         return ret;
8775     }
8776 
8777     virReportUnsupportedError();
8778  error:
8779     virDispatchError(dom->conn);
8780     return -1;
8781 }
8782 
8783 
8784 /**
8785  * virDomainIsPersistent:
8786  * @dom: pointer to the domain object
8787  *
8788  * Determine if the domain has a persistent configuration
8789  * which means it will still exist after shutting down
8790  *
8791  * Returns 1 if persistent, 0 if transient, -1 on error
8792  */
8793 int
virDomainIsPersistent(virDomainPtr dom)8794 virDomainIsPersistent(virDomainPtr dom)
8795 {
8796     VIR_DOMAIN_DEBUG(dom);
8797 
8798     virResetLastError();
8799 
8800     virCheckDomainReturn(dom, -1);
8801 
8802     if (dom->conn->driver->domainIsPersistent) {
8803         int ret;
8804         ret = dom->conn->driver->domainIsPersistent(dom);
8805         if (ret < 0)
8806             goto error;
8807         return ret;
8808     }
8809 
8810     virReportUnsupportedError();
8811  error:
8812     virDispatchError(dom->conn);
8813     return -1;
8814 }
8815 
8816 /**
8817  * virDomainRename:
8818  * @dom: pointer to the domain object
8819  * @new_name: new domain name
8820  * @flags: extra flags; not used yet, so callers should always pass 0
8821  *
8822  * Rename a domain. New domain name is specified in the second
8823  * argument. Depending on each driver implementation it may be
8824  * required that domain is in a specific state.
8825  *
8826  * There might be some attributes and/or elements in domain XML that if no
8827  * value provided at XML defining time, libvirt will derive their value from
8828  * the domain name. These are not updated by this API. Users are strongly
8829  * advised to change these after the rename was successful.
8830  *
8831  * Returns 0 if successfully renamed, -1 on error
8832  */
8833 int
virDomainRename(virDomainPtr dom,const char * new_name,unsigned int flags)8834 virDomainRename(virDomainPtr dom,
8835                 const char *new_name,
8836                 unsigned int flags)
8837 {
8838     VIR_DEBUG("dom=%p, new_name=%s", dom, NULLSTR(new_name));
8839 
8840     virResetLastError();
8841     virCheckDomainReturn(dom, -1);
8842     virCheckNonEmptyStringArgGoto(new_name, error);
8843     virCheckReadOnlyGoto(dom->conn->flags, error);
8844 
8845     if (dom->conn->driver->domainRename) {
8846         int ret = dom->conn->driver->domainRename(dom, new_name, flags);
8847         if (ret < 0)
8848             goto error;
8849         return ret;
8850     }
8851 
8852     virReportUnsupportedError();
8853  error:
8854     virDispatchError(dom->conn);
8855     return -1;
8856 }
8857 
8858 /**
8859  * virDomainIsUpdated:
8860  * @dom: pointer to the domain object
8861  *
8862  * Determine if the domain has been updated.
8863  *
8864  * Returns 1 if updated, 0 if not, -1 on error
8865  */
8866 int
virDomainIsUpdated(virDomainPtr dom)8867 virDomainIsUpdated(virDomainPtr dom)
8868 {
8869     VIR_DOMAIN_DEBUG(dom);
8870 
8871     virResetLastError();
8872 
8873     virCheckDomainReturn(dom, -1);
8874 
8875     if (dom->conn->driver->domainIsUpdated) {
8876         int ret;
8877         ret = dom->conn->driver->domainIsUpdated(dom);
8878         if (ret < 0)
8879             goto error;
8880         return ret;
8881     }
8882 
8883     virReportUnsupportedError();
8884  error:
8885     virDispatchError(dom->conn);
8886     return -1;
8887 }
8888 
8889 
8890 /**
8891  * virDomainGetJobInfo:
8892  * @domain: a domain object
8893  * @info: pointer to a virDomainJobInfo structure allocated by the user
8894  *
8895  * Extract information about progress of a background job on a domain.
8896  * Will return an error if the domain is not active.
8897  *
8898  * This function returns a limited amount of information in comparison
8899  * to virDomainGetJobStats().
8900  *
8901  * Returns 0 in case of success and -1 in case of failure.
8902  */
8903 int
virDomainGetJobInfo(virDomainPtr domain,virDomainJobInfoPtr info)8904 virDomainGetJobInfo(virDomainPtr domain, virDomainJobInfoPtr info)
8905 {
8906     virConnectPtr conn;
8907 
8908     VIR_DOMAIN_DEBUG(domain, "info=%p", info);
8909 
8910     virResetLastError();
8911 
8912     if (info)
8913         memset(info, 0, sizeof(*info));
8914 
8915     virCheckDomainReturn(domain, -1);
8916     virCheckNonNullArgGoto(info, error);
8917 
8918     conn = domain->conn;
8919 
8920     if (conn->driver->domainGetJobInfo) {
8921         int ret;
8922         ret = conn->driver->domainGetJobInfo(domain, info);
8923         if (ret < 0)
8924             goto error;
8925         return ret;
8926     }
8927 
8928     virReportUnsupportedError();
8929 
8930  error:
8931     virDispatchError(domain->conn);
8932     return -1;
8933 }
8934 
8935 
8936 /**
8937  * virDomainGetJobStats:
8938  * @domain: a domain object
8939  * @type: where to store the job type (one of virDomainJobType)
8940  * @params: where to store job statistics
8941  * @nparams: number of items in @params
8942  * @flags: bitwise-OR of virDomainGetJobStatsFlags
8943  *
8944  * Extract information about progress of a background job on a domain.
8945  * Will return an error if the domain is not active. The function returns
8946  * a superset of progress information provided by virDomainGetJobInfo.
8947  * Possible fields returned in @params are defined by VIR_DOMAIN_JOB_*
8948  * macros and new fields will likely be introduced in the future so callers
8949  * may receive fields that they do not understand in case they talk to a
8950  * newer server.
8951  *
8952  * When @flags contains VIR_DOMAIN_JOB_STATS_COMPLETED, the function will
8953  * return statistics about a recently completed job. Specifically, this
8954  * flag may be used to query statistics of a completed incoming pre-copy
8955  * migration (statistics for post-copy migration are only available on the
8956  * source host). Statistics of a completed job are automatically destroyed
8957  * once read (unless the VIR_DOMAIN_JOB_STATS_COMPLETED_KEEP is used as well)
8958  * or when libvirtd is restarted. Note that time information
8959  * returned for completed migrations may be completely irrelevant unless both
8960  * source and destination hosts have synchronized time (i.e., NTP daemon is
8961  * running on both of them). The statistics of a completed job can also be
8962  * obtained by listening to a VIR_DOMAIN_EVENT_ID_JOB_COMPLETED event (on the
8963  * source host in case of a migration job).
8964  *
8965  * Returns 0 in case of success and -1 in case of failure.
8966  */
8967 int
virDomainGetJobStats(virDomainPtr domain,int * type,virTypedParameterPtr * params,int * nparams,unsigned int flags)8968 virDomainGetJobStats(virDomainPtr domain,
8969                      int *type,
8970                      virTypedParameterPtr *params,
8971                      int *nparams,
8972                      unsigned int flags)
8973 {
8974     virConnectPtr conn;
8975 
8976     VIR_DOMAIN_DEBUG(domain, "type=%p, params=%p, nparams=%p, flags=0x%x",
8977                      type, params, nparams, flags);
8978 
8979     virResetLastError();
8980 
8981     virCheckDomainReturn(domain, -1);
8982     virCheckNonNullArgGoto(type, error);
8983     virCheckNonNullArgGoto(params, error);
8984     virCheckNonNullArgGoto(nparams, error);
8985     VIR_REQUIRE_FLAG_GOTO(VIR_DOMAIN_JOB_STATS_KEEP_COMPLETED,
8986                           VIR_DOMAIN_JOB_STATS_COMPLETED,
8987                           error);
8988 
8989     conn = domain->conn;
8990 
8991     if (conn->driver->domainGetJobStats) {
8992         int ret;
8993         ret = conn->driver->domainGetJobStats(domain, type, params,
8994                                               nparams, flags);
8995         if (ret < 0)
8996             goto error;
8997         return ret;
8998     }
8999 
9000     virReportUnsupportedError();
9001 
9002  error:
9003     virDispatchError(domain->conn);
9004     return -1;
9005 }
9006 
9007 
9008 /**
9009  * virDomainAbortJob:
9010  * @domain: a domain object
9011  *
9012  * Requests that the current background job be aborted at the
9013  * soonest opportunity. In case the job is a migration in a post-copy mode,
9014  * virDomainAbortJob will report an error (see virDomainMigrateStartPostCopy
9015  * for more details).
9016  *
9017  * Returns 0 in case of success and -1 in case of failure.
9018  */
9019 int
virDomainAbortJob(virDomainPtr domain)9020 virDomainAbortJob(virDomainPtr domain)
9021 {
9022     virConnectPtr conn;
9023 
9024     VIR_DOMAIN_DEBUG(domain);
9025 
9026     virResetLastError();
9027 
9028     virCheckDomainReturn(domain, -1);
9029     conn = domain->conn;
9030 
9031     virCheckReadOnlyGoto(conn->flags, error);
9032 
9033     if (conn->driver->domainAbortJob) {
9034         int ret;
9035         ret = conn->driver->domainAbortJob(domain);
9036         if (ret < 0)
9037             goto error;
9038         return ret;
9039     }
9040 
9041     virReportUnsupportedError();
9042 
9043  error:
9044     virDispatchError(conn);
9045     return -1;
9046 }
9047 
9048 
9049 /**
9050  * virDomainMigrateSetMaxDowntime:
9051  * @domain: a domain object
9052  * @downtime: maximum tolerable downtime for live migration, in milliseconds
9053  * @flags: extra flags; not used yet, so callers should always pass 0
9054  *
9055  * Sets maximum tolerable time for which the domain is allowed to be paused
9056  * at the end of live migration. It's supposed to be called while the domain is
9057  * being live-migrated as a reaction to migration progress.
9058  *
9059  * Returns 0 in case of success, -1 otherwise.
9060  */
9061 int
virDomainMigrateSetMaxDowntime(virDomainPtr domain,unsigned long long downtime,unsigned int flags)9062 virDomainMigrateSetMaxDowntime(virDomainPtr domain,
9063                                unsigned long long downtime,
9064                                unsigned int flags)
9065 {
9066     virConnectPtr conn;
9067 
9068     VIR_DOMAIN_DEBUG(domain, "downtime=%llu, flags=0x%x", downtime, flags);
9069 
9070     virResetLastError();
9071 
9072     virCheckDomainReturn(domain, -1);
9073     conn = domain->conn;
9074 
9075     virCheckReadOnlyGoto(conn->flags, error);
9076 
9077     if (conn->driver->domainMigrateSetMaxDowntime) {
9078         if (conn->driver->domainMigrateSetMaxDowntime(domain, downtime, flags) < 0)
9079             goto error;
9080         return 0;
9081     }
9082 
9083     virReportUnsupportedError();
9084  error:
9085     virDispatchError(conn);
9086     return -1;
9087 }
9088 
9089 
9090 /**
9091  * virDomainMigrateGetMaxDowntime:
9092  * @domain: a domain object
9093  * @downtime: return value of the maximum tolerable downtime for live
9094  *            migration, in milliseconds
9095  * @flags: extra flags; not used yet, so callers should always pass 0
9096  *
9097  * Gets current maximum tolerable time for which the domain may be paused
9098  * at the end of live migration.
9099  *
9100  * Returns 0 in case of success, -1 otherwise.
9101  */
9102 int
virDomainMigrateGetMaxDowntime(virDomainPtr domain,unsigned long long * downtime,unsigned int flags)9103 virDomainMigrateGetMaxDowntime(virDomainPtr domain,
9104                                unsigned long long *downtime,
9105                                unsigned int flags)
9106 {
9107     virConnectPtr conn;
9108 
9109     VIR_DOMAIN_DEBUG(domain, "downtime = %p, flags=0x%x", downtime, flags);
9110 
9111     virResetLastError();
9112 
9113     virCheckDomainReturn(domain, -1);
9114     conn = domain->conn;
9115 
9116     virCheckNonNullArgGoto(downtime, error);
9117 
9118     if (conn->driver->domainMigrateGetMaxDowntime) {
9119         if (conn->driver->domainMigrateGetMaxDowntime(domain, downtime, flags) < 0)
9120             goto error;
9121         return 0;
9122     }
9123 
9124     virReportUnsupportedError();
9125  error:
9126     virDispatchError(conn);
9127     return -1;
9128 }
9129 
9130 
9131 /**
9132  * virDomainMigrateGetCompressionCache:
9133  * @domain: a domain object
9134  * @cacheSize: return value of current size of the cache (in bytes)
9135  * @flags: extra flags; not used yet, so callers should always pass 0
9136  *
9137  * Gets current size of the cache (in bytes) used for compressing repeatedly
9138  * transferred memory pages during live migration.
9139  *
9140  * Returns 0 in case of success, -1 otherwise.
9141  */
9142 int
virDomainMigrateGetCompressionCache(virDomainPtr domain,unsigned long long * cacheSize,unsigned int flags)9143 virDomainMigrateGetCompressionCache(virDomainPtr domain,
9144                                     unsigned long long *cacheSize,
9145                                     unsigned int flags)
9146 {
9147     virConnectPtr conn;
9148 
9149     VIR_DOMAIN_DEBUG(domain, "cacheSize=%p, flags=0x%x", cacheSize, flags);
9150 
9151     virResetLastError();
9152 
9153     virCheckDomainReturn(domain, -1);
9154     conn = domain->conn;
9155 
9156     virCheckNonNullArgGoto(cacheSize, error);
9157 
9158     if (conn->driver->domainMigrateGetCompressionCache) {
9159         if (conn->driver->domainMigrateGetCompressionCache(domain, cacheSize,
9160                                                            flags) < 0)
9161             goto error;
9162         return 0;
9163     }
9164 
9165     virReportUnsupportedError();
9166  error:
9167     virDispatchError(conn);
9168     return -1;
9169 }
9170 
9171 
9172 /**
9173  * virDomainMigrateSetCompressionCache:
9174  * @domain: a domain object
9175  * @cacheSize: size of the cache (in bytes) used for compression
9176  * @flags: extra flags; not used yet, so callers should always pass 0
9177  *
9178  * Sets size of the cache (in bytes) used for compressing repeatedly
9179  * transferred memory pages during live migration. It's supposed to be called
9180  * while the domain is being live-migrated as a reaction to migration progress
9181  * and increasing number of compression cache misses obtained from
9182  * virDomainGetJobStats.
9183  *
9184  * Returns 0 in case of success, -1 otherwise.
9185  */
9186 int
virDomainMigrateSetCompressionCache(virDomainPtr domain,unsigned long long cacheSize,unsigned int flags)9187 virDomainMigrateSetCompressionCache(virDomainPtr domain,
9188                                     unsigned long long cacheSize,
9189                                     unsigned int flags)
9190 {
9191     virConnectPtr conn;
9192 
9193     VIR_DOMAIN_DEBUG(domain, "cacheSize=%llu, flags=0x%x", cacheSize, flags);
9194 
9195     virResetLastError();
9196 
9197     virCheckDomainReturn(domain, -1);
9198     conn = domain->conn;
9199 
9200     virCheckReadOnlyGoto(conn->flags, error);
9201 
9202     if (conn->driver->domainMigrateSetCompressionCache) {
9203         if (conn->driver->domainMigrateSetCompressionCache(domain, cacheSize,
9204                                                            flags) < 0)
9205             goto error;
9206         return 0;
9207     }
9208 
9209     virReportUnsupportedError();
9210  error:
9211     virDispatchError(conn);
9212     return -1;
9213 }
9214 
9215 
9216 /**
9217  * virDomainMigrateSetMaxSpeed:
9218  * @domain: a domain object
9219  * @bandwidth: migration bandwidth limit in MiB/s
9220  * @flags: bitwise-OR of virDomainMigrateMaxSpeedFlags
9221  *
9222  * The maximum bandwidth (in MiB/s) that will be used to do migration
9223  * can be specified with the bandwidth parameter. Not all hypervisors
9224  * will support a bandwidth cap. When VIR_DOMAIN_MIGRATE_MAX_SPEED_POSTCOPY
9225  * is set in @flags, this API sets the maximum bandwidth for the post-copy
9226  * phase of the migration.
9227  *
9228  * Returns 0 in case of success, -1 otherwise.
9229  */
9230 int
virDomainMigrateSetMaxSpeed(virDomainPtr domain,unsigned long bandwidth,unsigned int flags)9231 virDomainMigrateSetMaxSpeed(virDomainPtr domain,
9232                             unsigned long bandwidth,
9233                             unsigned int flags)
9234 {
9235     virConnectPtr conn;
9236 
9237     VIR_DOMAIN_DEBUG(domain, "bandwidth=%lu, flags=0x%x", bandwidth, flags);
9238 
9239     virResetLastError();
9240 
9241     virCheckDomainReturn(domain, -1);
9242     conn = domain->conn;
9243 
9244     virCheckReadOnlyGoto(conn->flags, error);
9245 
9246     if (conn->driver->domainMigrateSetMaxSpeed) {
9247         if (conn->driver->domainMigrateSetMaxSpeed(domain, bandwidth, flags) < 0)
9248             goto error;
9249         return 0;
9250     }
9251 
9252     virReportUnsupportedError();
9253  error:
9254     virDispatchError(conn);
9255     return -1;
9256 }
9257 
9258 
9259 /**
9260  * virDomainMigrateGetMaxSpeed:
9261  * @domain: a domain object
9262  * @bandwidth: return value of current migration bandwidth limit in MiB/s
9263  * @flags: bitwise-OR of virDomainMigrateMaxSpeedFlags
9264  *
9265  * Get the current maximum bandwidth (in MiB/s) that will be used if the
9266  * domain is migrated.  Not all hypervisors will support a bandwidth limit.
9267  * When VIR_DOMAIN_MIGRATE_MAX_SPEED_POSTCOPY is set in @flags, this API
9268  * gets the current maximum bandwidth for the post-copy phase of the
9269  * migration.
9270  *
9271  * Returns 0 in case of success, -1 otherwise.
9272  */
9273 int
virDomainMigrateGetMaxSpeed(virDomainPtr domain,unsigned long * bandwidth,unsigned int flags)9274 virDomainMigrateGetMaxSpeed(virDomainPtr domain,
9275                             unsigned long *bandwidth,
9276                             unsigned int flags)
9277 {
9278     virConnectPtr conn;
9279 
9280     VIR_DOMAIN_DEBUG(domain, "bandwidth = %p, flags=0x%x", bandwidth, flags);
9281 
9282     virResetLastError();
9283 
9284     virCheckDomainReturn(domain, -1);
9285     conn = domain->conn;
9286 
9287     virCheckNonNullArgGoto(bandwidth, error);
9288     virCheckReadOnlyGoto(conn->flags, error);
9289 
9290     if (conn->driver->domainMigrateGetMaxSpeed) {
9291         if (conn->driver->domainMigrateGetMaxSpeed(domain, bandwidth, flags) < 0)
9292             goto error;
9293         return 0;
9294     }
9295 
9296     virReportUnsupportedError();
9297  error:
9298     virDispatchError(conn);
9299     return -1;
9300 }
9301 
9302 
9303 /**
9304  * virDomainMigrateStartPostCopy:
9305  * @domain: a domain object
9306  * @flags: extra flags; not used yet, so callers should always pass 0
9307  *
9308  * Starts post-copy migration. This function has to be called while
9309  * migration (initiated with VIR_MIGRATE_POSTCOPY flag) is in progress.
9310  *
9311  * Traditional pre-copy migration iteratively walks through guest memory
9312  * pages and migrates those that changed since the previous iteration. The
9313  * iterative phase stops when the number of dirty pages is low enough so that
9314  * the virtual CPUs can be paused, all dirty pages transferred to the
9315  * destination, where the virtual CPUs are unpaused, and all this can happen
9316  * within a predefined downtime period. It's clear that this process may never
9317  * converge if downtime is too short and/or the guest keeps changing a lot of
9318  * memory pages.
9319  *
9320  * When migration is switched to post-copy mode, the virtual CPUs are paused
9321  * immediately, only a minimum set of pages is transferred, and the CPUs are
9322  * unpaused on destination. The source keeps sending all remaining memory pages
9323  * to the destination while the guest is already running there. Whenever the
9324  * guest tries to read a memory page which has not been migrated yet, the
9325  * hypervisor has to tell the source to transfer that page in a priority
9326  * channel. To minimize such page faults, it is a good idea to run at least one
9327  * iteration of pre-copy migration before switching to post-copy.
9328  *
9329  * Post-copy migration is guaranteed to converge since each page is transferred
9330  * at most once no matter how fast it changes. On the other hand once the
9331  * guest is running on the destination host, the migration can no longer be
9332  * rolled back because none of the hosts has complete state. If this happens,
9333  * libvirt will leave the domain paused on both hosts with
9334  * VIR_DOMAIN_PAUSED_POSTCOPY_FAILED reason. It's up to the upper layer to
9335  * decide what to do in such case. Because of this, libvirt will refuse to
9336  * cancel post-copy migration via virDomainAbortJob.
9337  *
9338  * The following domain life cycle events are emitted during post-copy
9339  * migration:
9340  *  VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY (on the source) -- migration entered
9341  *      post-copy mode.
9342  *  VIR_DOMAIN_EVENT_RESUMED_POSTCOPY (on the destination) -- the guest is
9343  *      running on the destination host while some of its memory pages still
9344  *      remain on the source host; neither the source nor the destination host
9345  *      contain a complete guest state from this point until migration
9346  *      finishes.
9347  *  VIR_DOMAIN_EVENT_RESUMED_MIGRATED (on the destination),
9348  *  VIR_DOMAIN_EVENT_STOPPED_MIGRATED (on the source) -- migration finished
9349  *      successfully and the destination host holds a complete guest state.
9350  *  VIR_DOMAIN_EVENT_SUSPENDED_POSTCOPY_FAILED (on the destination) -- emitted
9351  *      when migration fails in post-copy mode and it's unclear whether any
9352  *      of the hosts has a complete guest state.
9353  *
9354  * The progress of a post-copy migration can be monitored normally using
9355  * virDomainGetJobStats on the source host. Fetching statistics of a completed
9356  * post-copy migration can also be done on the source host (by calling
9357  * virDomainGetJobStats or listening to VIR_DOMAIN_EVENT_ID_JOB_COMPLETED
9358  * event, but (in contrast to pre-copy migration) the statistics are not
9359  * available on the destination host. Thus, VIR_DOMAIN_EVENT_ID_JOB_COMPLETED
9360  * event is the only way of getting statistics of a completed post-copy
9361  * migration of a transient domain (because the domain is removed after
9362  * migration and there's no domain to run virDomainGetJobStats on).
9363  *
9364  * Returns 0 in case of success, -1 otherwise.
9365  */
9366 int
virDomainMigrateStartPostCopy(virDomainPtr domain,unsigned int flags)9367 virDomainMigrateStartPostCopy(virDomainPtr domain,
9368                               unsigned int flags)
9369 {
9370     virConnectPtr conn;
9371 
9372     VIR_DOMAIN_DEBUG(domain);
9373 
9374     virResetLastError();
9375 
9376     virCheckDomainReturn(domain, -1);
9377     conn = domain->conn;
9378 
9379     virCheckReadOnlyGoto(conn->flags, error);
9380 
9381     if (conn->driver->domainMigrateStartPostCopy) {
9382         if (conn->driver->domainMigrateStartPostCopy(domain, flags) < 0)
9383             goto error;
9384         return 0;
9385     }
9386 
9387     virReportUnsupportedError();
9388  error:
9389     virDispatchError(conn);
9390     return -1;
9391 }
9392 
9393 
9394 /**
9395  * virConnectDomainEventRegisterAny:
9396  * @conn: pointer to the connection
9397  * @dom: pointer to the domain
9398  * @eventID: the event type to receive
9399  * @cb: callback to the function handling domain events
9400  * @opaque: opaque data to pass on to the callback
9401  * @freecb: optional function to deallocate opaque when not used anymore
9402  *
9403  * Adds a callback to receive notifications of arbitrary domain events
9404  * occurring on a domain.  This function requires that an event loop
9405  * has been previously registered with virEventRegisterImpl() or
9406  * virEventRegisterDefaultImpl().
9407  *
9408  * If @dom is NULL, then events will be monitored for any domain. If @dom
9409  * is non-NULL, then only the specific domain will be monitored.
9410  *
9411  * Most types of event have a callback providing a custom set of parameters
9412  * for the event. When registering an event, it is thus necessary to use
9413  * the VIR_DOMAIN_EVENT_CALLBACK() macro to cast the supplied function pointer
9414  * to match the signature of this method.
9415  *
9416  * The virDomainPtr object handle passed into the callback upon delivery
9417  * of an event is only valid for the duration of execution of the callback.
9418  * If the callback wishes to keep the domain object after the callback returns,
9419  * it shall take a reference to it, by calling virDomainRef().
9420  * The reference can be released once the object is no longer required
9421  * by calling virDomainFree().
9422  *
9423  * The return value from this method is a positive integer identifier
9424  * for the callback. To unregister a callback, this callback ID should
9425  * be passed to the virConnectDomainEventDeregisterAny() method.
9426  *
9427  * Returns a callback identifier on success, -1 on failure.
9428  */
9429 int
virConnectDomainEventRegisterAny(virConnectPtr conn,virDomainPtr dom,int eventID,virConnectDomainEventGenericCallback cb,void * opaque,virFreeCallback freecb)9430 virConnectDomainEventRegisterAny(virConnectPtr conn,
9431                                  virDomainPtr dom,
9432                                  int eventID,
9433                                  virConnectDomainEventGenericCallback cb,
9434                                  void *opaque,
9435                                  virFreeCallback freecb)
9436 {
9437     VIR_DOMAIN_DEBUG(dom, "conn=%p, eventID=%d, cb=%p, opaque=%p, freecb=%p",
9438                      conn, eventID, cb, opaque, freecb);
9439 
9440     virResetLastError();
9441 
9442     virCheckConnectReturn(conn, -1);
9443     if (dom) {
9444         virCheckDomainGoto(dom, error);
9445         if (dom->conn != conn) {
9446             virReportInvalidArg(dom,
9447                                 _("domain '%s' must match connection"),
9448                                 dom->name);
9449             goto error;
9450         }
9451     }
9452     virCheckNonNullArgGoto(cb, error);
9453     virCheckNonNegativeArgGoto(eventID, error);
9454     if (eventID >= VIR_DOMAIN_EVENT_ID_LAST) {
9455         virReportInvalidArg(eventID,
9456                             _("eventID must be less than %d"),
9457                             VIR_DOMAIN_EVENT_ID_LAST);
9458         goto error;
9459     }
9460 
9461     if (conn->driver && conn->driver->connectDomainEventRegisterAny) {
9462         int ret;
9463         ret = conn->driver->connectDomainEventRegisterAny(conn, dom, eventID, cb, opaque, freecb);
9464         if (ret < 0)
9465             goto error;
9466         return ret;
9467     }
9468 
9469     virReportUnsupportedError();
9470  error:
9471     virDispatchError(conn);
9472     return -1;
9473 }
9474 
9475 
9476 /**
9477  * virConnectDomainEventDeregisterAny:
9478  * @conn: pointer to the connection
9479  * @callbackID: the callback identifier
9480  *
9481  * Removes an event callback. The callbackID parameter should be the
9482  * value obtained from a previous virConnectDomainEventRegisterAny() method.
9483  *
9484  * Returns 0 on success, -1 on failure.  Older versions of some hypervisors
9485  * sometimes returned a positive number on success, but without any reliable
9486  * semantics on what that number represents. */
9487 int
virConnectDomainEventDeregisterAny(virConnectPtr conn,int callbackID)9488 virConnectDomainEventDeregisterAny(virConnectPtr conn,
9489                                    int callbackID)
9490 {
9491     VIR_DEBUG("conn=%p, callbackID=%d", conn, callbackID);
9492 
9493     virResetLastError();
9494 
9495     virCheckConnectReturn(conn, -1);
9496     virCheckNonNegativeArgGoto(callbackID, error);
9497 
9498     if (conn->driver && conn->driver->connectDomainEventDeregisterAny) {
9499         int ret;
9500         ret = conn->driver->connectDomainEventDeregisterAny(conn, callbackID);
9501         if (ret < 0)
9502             goto error;
9503         return ret;
9504     }
9505 
9506     virReportUnsupportedError();
9507  error:
9508     virDispatchError(conn);
9509     return -1;
9510 }
9511 
9512 
9513 /**
9514  * virDomainManagedSave:
9515  * @dom: pointer to the domain
9516  * @flags: bitwise-OR of virDomainSaveRestoreFlags
9517  *
9518  * This method will suspend a domain and save its memory contents to
9519  * a file on disk. After the call, if successful, the domain is not
9520  * listed as running anymore.
9521  * The difference from virDomainSave() is that libvirt is keeping track of
9522  * the saved state itself, and will reuse it once the domain is being
9523  * restarted (automatically or via an explicit libvirt call).
9524  * As a result any running domain is sure to not have a managed saved image.
9525  * This also implies that managed save only works on persistent domains,
9526  * since the domain must still exist in order to use virDomainCreate() to
9527  * restart it.
9528  *
9529  * If @flags includes VIR_DOMAIN_SAVE_BYPASS_CACHE, then libvirt will
9530  * attempt to bypass the file system cache while creating the file, or
9531  * fail if it cannot do so for the given system; this can allow less
9532  * pressure on file system cache, but also risks slowing saves to NFS.
9533  *
9534  * Normally, the managed saved state will remember whether the domain
9535  * was running or paused, and start will resume to the same state.
9536  * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in
9537  * @flags will override the default saved into the file.  These two
9538  * flags are mutually exclusive.
9539  *
9540  * Returns 0 in case of success or -1 in case of failure
9541  */
9542 int
virDomainManagedSave(virDomainPtr dom,unsigned int flags)9543 virDomainManagedSave(virDomainPtr dom, unsigned int flags)
9544 {
9545     virConnectPtr conn;
9546 
9547     VIR_DOMAIN_DEBUG(dom, "flags=0x%x", flags);
9548 
9549     virResetLastError();
9550 
9551     virCheckDomainReturn(dom, -1);
9552     conn = dom->conn;
9553 
9554     virCheckReadOnlyGoto(conn->flags, error);
9555 
9556     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING,
9557                              VIR_DOMAIN_SAVE_PAUSED,
9558                              error);
9559 
9560     if (conn->driver->domainManagedSave) {
9561         int ret;
9562 
9563         ret = conn->driver->domainManagedSave(dom, flags);
9564         if (ret < 0)
9565             goto error;
9566         return ret;
9567     }
9568 
9569     virReportUnsupportedError();
9570 
9571  error:
9572     virDispatchError(conn);
9573     return -1;
9574 }
9575 
9576 
9577 /**
9578  * virDomainHasManagedSaveImage:
9579  * @dom: pointer to the domain
9580  * @flags: extra flags; not used yet, so callers should always pass 0
9581  *
9582  * Check if a domain has a managed save image as created by
9583  * virDomainManagedSave(). Note that any running domain should not have
9584  * such an image, as it should have been removed on restart.
9585  *
9586  * Returns 0 if no image is present, 1 if an image is present, and
9587  *         -1 in case of error
9588  */
9589 int
virDomainHasManagedSaveImage(virDomainPtr dom,unsigned int flags)9590 virDomainHasManagedSaveImage(virDomainPtr dom, unsigned int flags)
9591 {
9592     virConnectPtr conn;
9593 
9594     VIR_DOMAIN_DEBUG(dom, "flags=0x%x", flags);
9595 
9596     virResetLastError();
9597 
9598     virCheckDomainReturn(dom, -1);
9599     conn = dom->conn;
9600 
9601     if (conn->driver->domainHasManagedSaveImage) {
9602         int ret;
9603 
9604         ret = conn->driver->domainHasManagedSaveImage(dom, flags);
9605         if (ret < 0)
9606             goto error;
9607         return ret;
9608     }
9609 
9610     virReportUnsupportedError();
9611 
9612  error:
9613     virDispatchError(conn);
9614     return -1;
9615 }
9616 
9617 
9618 /**
9619  * virDomainManagedSaveRemove:
9620  * @dom: pointer to the domain
9621  * @flags: extra flags; not used yet, so callers should always pass 0
9622  *
9623  * Remove any managed save image for this domain.
9624  *
9625  * Returns 0 in case of success, and -1 in case of error
9626  */
9627 int
virDomainManagedSaveRemove(virDomainPtr dom,unsigned int flags)9628 virDomainManagedSaveRemove(virDomainPtr dom, unsigned int flags)
9629 {
9630     virConnectPtr conn;
9631 
9632     VIR_DOMAIN_DEBUG(dom, "flags=0x%x", flags);
9633 
9634     virResetLastError();
9635 
9636     virCheckDomainReturn(dom, -1);
9637     conn = dom->conn;
9638 
9639     virCheckReadOnlyGoto(conn->flags, error);
9640 
9641     if (conn->driver->domainManagedSaveRemove) {
9642         int ret;
9643 
9644         ret = conn->driver->domainManagedSaveRemove(dom, flags);
9645         if (ret < 0)
9646             goto error;
9647         return ret;
9648     }
9649 
9650     virReportUnsupportedError();
9651 
9652  error:
9653     virDispatchError(conn);
9654     return -1;
9655 }
9656 
9657 
9658 /**
9659  * virDomainManagedSaveGetXMLDesc:
9660  * @domain: a domain object
9661  * @flags: bitwise-OR of supported virDomainSaveImageXMLFlags
9662  *
9663  * This method will extract the XML description of the managed save
9664  * state file of a domain.
9665  *
9666  * No security-sensitive data will be included unless @flags contains
9667  * VIR_DOMAIN_SAVE_IMAGE_XML_SECURE; this flag is rejected on read-only
9668  * connections.
9669  *
9670  * Returns a 0 terminated UTF-8 encoded XML instance, or NULL in case of
9671  * error.  The caller must free() the returned value.
9672  */
9673 char *
virDomainManagedSaveGetXMLDesc(virDomainPtr domain,unsigned int flags)9674 virDomainManagedSaveGetXMLDesc(virDomainPtr domain, unsigned int flags)
9675 {
9676     virConnectPtr conn;
9677 
9678     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
9679 
9680     virResetLastError();
9681 
9682     virCheckDomainReturn(domain, NULL);
9683     conn = domain->conn;
9684 
9685     if ((conn->flags & VIR_CONNECT_RO) &&
9686         (flags & VIR_DOMAIN_SAVE_IMAGE_XML_SECURE)) {
9687         virReportError(VIR_ERR_OPERATION_DENIED, "%s",
9688                        _("virDomainManagedSaveGetXMLDesc with secure flag"));
9689         goto error;
9690     }
9691 
9692     if (conn->driver->domainManagedSaveGetXMLDesc) {
9693         char *ret;
9694         ret = conn->driver->domainManagedSaveGetXMLDesc(domain, flags);
9695         if (!ret)
9696             goto error;
9697         return ret;
9698     }
9699 
9700     virReportUnsupportedError();
9701 
9702  error:
9703     virDispatchError(domain->conn);
9704     return NULL;
9705 }
9706 
9707 
9708 /**
9709  * virDomainManagedSaveDefineXML:
9710  * @domain: a domain object
9711  * @dxml: XML config for adjusting guest xml used on restore
9712  * @flags: bitwise-OR of virDomainSaveRestoreFlags
9713  *
9714  * This updates the definition of a domain stored in a saved state
9715  * file.
9716  *
9717  * @dxml can be used to alter host-specific portions of the domain XML
9718  * that will be used on the next start of the domain. For example, it is
9719  * possible to alter the backing filename that is associated with a
9720  * disk device.
9721  *
9722  * Normally, the saved state file will remember whether the domain was
9723  * running or paused, and restore defaults to the same state.
9724  * Specifying VIR_DOMAIN_SAVE_RUNNING or VIR_DOMAIN_SAVE_PAUSED in
9725  * @flags will override the default saved into the file; omitting both
9726  * leaves the file's default unchanged.  These two flags are mutually
9727  * exclusive.
9728  *
9729  * Returns 0 in case of success and -1 in case of failure.
9730  */
9731 int
virDomainManagedSaveDefineXML(virDomainPtr domain,const char * dxml,unsigned int flags)9732 virDomainManagedSaveDefineXML(virDomainPtr domain, const char *dxml,
9733                               unsigned int flags)
9734 {
9735     virConnectPtr conn;
9736 
9737     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
9738 
9739     virResetLastError();
9740 
9741     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_SAVE_RUNNING,
9742                              VIR_DOMAIN_SAVE_PAUSED,
9743                              error);
9744 
9745     virCheckDomainReturn(domain, -1);
9746     conn = domain->conn;
9747     virCheckReadOnlyGoto(conn->flags, error);
9748 
9749     if (conn->driver->domainManagedSaveDefineXML) {
9750         int ret;
9751         ret = conn->driver->domainManagedSaveDefineXML(domain, dxml, flags);
9752 
9753         if (ret < 0)
9754             goto error;
9755         return ret;
9756     }
9757 
9758     virReportUnsupportedError();
9759 
9760  error:
9761     virDispatchError(domain->conn);
9762     return -1;
9763 }
9764 
9765 
9766 /**
9767  * virDomainOpenConsole:
9768  * @dom: a domain object
9769  * @dev_name: the console, serial or parallel port device alias, or NULL
9770  * @st: a stream to associate with the console
9771  * @flags: bitwise-OR of virDomainConsoleFlags
9772  *
9773  * This opens the backend associated with a console, serial or
9774  * parallel port device on a guest, if the backend is supported.
9775  * If the @dev_name is omitted, then the first console or serial
9776  * device is opened. The console is associated with the passed
9777  * in @st stream, which should have been opened in non-blocking
9778  * mode for bi-directional I/O.
9779  *
9780  * By default, when @flags is 0, the open will fail if libvirt
9781  * detects that the console is already in use by another client;
9782  * passing VIR_DOMAIN_CONSOLE_FORCE will cause libvirt to forcefully
9783  * remove the other client prior to opening this console.
9784  *
9785  * If flag VIR_DOMAIN_CONSOLE_SAFE the console is opened only in the
9786  * case where the hypervisor driver supports safe (mutually exclusive)
9787  * console handling.
9788  *
9789  * Older servers did not support either flag, and also did not forbid
9790  * simultaneous clients on a console, with potentially confusing results.
9791  * When passing @flags of 0 in order to support a wider range of server
9792  * versions, it is up to the client to ensure mutual exclusion.
9793  *
9794  * Returns 0 if the console was opened, -1 on error
9795  */
9796 int
virDomainOpenConsole(virDomainPtr dom,const char * dev_name,virStreamPtr st,unsigned int flags)9797 virDomainOpenConsole(virDomainPtr dom,
9798                      const char *dev_name,
9799                      virStreamPtr st,
9800                      unsigned int flags)
9801 {
9802     virConnectPtr conn;
9803 
9804     VIR_DOMAIN_DEBUG(dom, "dev_name=%s, st=%p, flags=0x%x",
9805                      NULLSTR(dev_name), st, flags);
9806 
9807     virResetLastError();
9808 
9809     virCheckDomainReturn(dom, -1);
9810     conn = dom->conn;
9811 
9812     virCheckStreamGoto(st, error);
9813     virCheckReadOnlyGoto(conn->flags, error);
9814 
9815     if (conn != st->conn) {
9816         virReportInvalidArg(st,
9817                             _("stream must match connection of domain '%s'"),
9818                             dom->name);
9819         goto error;
9820     }
9821 
9822     if (conn->driver->domainOpenConsole) {
9823         int ret;
9824         ret = conn->driver->domainOpenConsole(dom, dev_name, st, flags);
9825         if (ret < 0)
9826             goto error;
9827         return ret;
9828     }
9829 
9830     virReportUnsupportedError();
9831 
9832  error:
9833     virDispatchError(conn);
9834     return -1;
9835 }
9836 
9837 
9838 /**
9839  * virDomainOpenChannel:
9840  * @dom: a domain object
9841  * @name: the channel name, or NULL
9842  * @st: a stream to associate with the channel
9843  * @flags: bitwise-OR of virDomainChannelFlags
9844  *
9845  * This opens the host interface associated with a channel device on a
9846  * guest, if the host interface is supported.  If @name is given, it
9847  * can match either the device alias (e.g. "channel0"), or the virtio
9848  * target name (e.g. "org.qemu.guest_agent.0").  If @name is omitted,
9849  * then the first channel is opened. The channel is associated with
9850  * the passed in @st stream, which should have been opened in
9851  * non-blocking mode for bi-directional I/O.
9852  *
9853  * By default, when @flags is 0, the open will fail if libvirt detects
9854  * that the channel is already in use by another client; passing
9855  * VIR_DOMAIN_CHANNEL_FORCE will cause libvirt to forcefully remove the
9856  * other client prior to opening this channel.
9857  *
9858  * Returns 0 if the channel was opened, -1 on error
9859  */
9860 int
virDomainOpenChannel(virDomainPtr dom,const char * name,virStreamPtr st,unsigned int flags)9861 virDomainOpenChannel(virDomainPtr dom,
9862                      const char *name,
9863                      virStreamPtr st,
9864                      unsigned int flags)
9865 {
9866     virConnectPtr conn;
9867 
9868     VIR_DOMAIN_DEBUG(dom, "name=%s, st=%p, flags=0x%x",
9869                      NULLSTR(name), st, flags);
9870 
9871     virResetLastError();
9872 
9873     virCheckDomainReturn(dom, -1);
9874     conn = dom->conn;
9875 
9876     virCheckStreamGoto(st, error);
9877     virCheckReadOnlyGoto(conn->flags, error);
9878 
9879     if (conn != st->conn) {
9880         virReportInvalidArg(st,
9881                             _("stream must match connection of domain '%s'"),
9882                             dom->name);
9883         goto error;
9884     }
9885 
9886     if (conn->driver->domainOpenChannel) {
9887         int ret;
9888         ret = conn->driver->domainOpenChannel(dom, name, st, flags);
9889         if (ret < 0)
9890             goto error;
9891         return ret;
9892     }
9893 
9894     virReportUnsupportedError();
9895 
9896  error:
9897     virDispatchError(conn);
9898     return -1;
9899 }
9900 
9901 
9902 /**
9903  * virDomainGetPerfEvents:
9904  * @domain: a domain object
9905  * @params: where to store perf events setting
9906  * @nparams: number of items in @params
9907  * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
9908  *
9909  * Get all Linux perf events setting. Possible fields returned in
9910  * @params are defined by VIR_PERF_EVENT_* macros and new fields
9911  * will likely be introduced in the future.
9912  *
9913  * Linux perf events are performance analyzing tool in Linux.
9914  *
9915  * Returns -1 in case of failure, 0 in case of success.
9916  */
virDomainGetPerfEvents(virDomainPtr domain,virTypedParameterPtr * params,int * nparams,unsigned int flags)9917 int virDomainGetPerfEvents(virDomainPtr domain,
9918                            virTypedParameterPtr *params,
9919                            int *nparams,
9920                            unsigned int flags)
9921 {
9922     virConnectPtr conn;
9923 
9924     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p flags=0x%x",
9925                      params, nparams, flags);
9926 
9927     virResetLastError();
9928 
9929     virCheckDomainReturn(domain, -1);
9930     virCheckNonNullArgGoto(params, error);
9931     virCheckNonNullArgGoto(nparams, error);
9932 
9933     conn = domain->conn;
9934 
9935     if (conn->driver->domainGetPerfEvents) {
9936         int ret;
9937         ret = conn->driver->domainGetPerfEvents(domain, params,
9938                                                 nparams, flags);
9939         if (ret < 0)
9940             goto error;
9941         return ret;
9942     }
9943     virReportUnsupportedError();
9944 
9945  error:
9946     virDispatchError(domain->conn);
9947     return -1;
9948 }
9949 
9950 
9951 /**
9952  * virDomainSetPerfEvents:
9953  * @domain: a domain object
9954  * @params: pointer to perf events parameter object
9955  * @nparams: number of perf event parameters (this value can be the same
9956  *           less than the number of parameters supported)
9957  * @flags: bitwise-OR of virDomainModificationImpact
9958  *
9959  * Enable or disable the particular list of Linux perf events you
9960  * care about. The @params argument should contain any subset of
9961  * VIR_PERF_EVENT_ macros.
9962  *
9963  * Linux perf events are performance analyzing tool in Linux.
9964  *
9965  * Returns -1 in case of error, 0 in case of success.
9966  */
virDomainSetPerfEvents(virDomainPtr domain,virTypedParameterPtr params,int nparams,unsigned int flags)9967 int virDomainSetPerfEvents(virDomainPtr domain,
9968                            virTypedParameterPtr params,
9969                            int nparams,
9970                            unsigned int flags)
9971 {
9972     virConnectPtr conn;
9973 
9974     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%d flags=0x%x",
9975                      params, nparams, flags);
9976     VIR_TYPED_PARAMS_DEBUG(params, nparams);
9977 
9978     virResetLastError();
9979 
9980     virCheckDomainReturn(domain, -1);
9981     conn = domain->conn;
9982 
9983     virCheckReadOnlyGoto(conn->flags, error);
9984     virCheckNonNullArgGoto(params, error);
9985     virCheckPositiveArgGoto(nparams, error);
9986 
9987     if (virTypedParameterValidateSet(conn, params, nparams) < 0)
9988         goto error;
9989 
9990     if (conn->driver->domainSetPerfEvents) {
9991         int ret;
9992         ret = conn->driver->domainSetPerfEvents(domain, params,
9993                                                 nparams, flags);
9994         if (ret < 0)
9995             goto error;
9996         return ret;
9997     }
9998 
9999     virReportUnsupportedError();
10000 
10001  error:
10002     virDispatchError(domain->conn);
10003     return -1;
10004 }
10005 
10006 
10007 /**
10008  * virDomainBlockJobAbort:
10009  * @dom: pointer to domain object
10010  * @disk: path to the block device, or device shorthand
10011  * @flags: bitwise-OR of virDomainBlockJobAbortFlags
10012  *
10013  * Cancel the active block job on the given disk.
10014  *
10015  * The @disk parameter is either an unambiguous source name of the
10016  * block device (the <source file='...'/> sub-element, such as
10017  * "/path/to/image"), or (since 0.9.5) the device target shorthand
10018  * (the <target dev='...'/> sub-element, such as "vda").  Valid names
10019  * can be found by calling virDomainGetXMLDesc() and inspecting
10020  * elements within //domain/devices/disk.
10021  *
10022  * If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, then
10023  * by default, this function performs a synchronous operation and the caller
10024  * may assume that the operation has completed when 0 is returned.  However,
10025  * BlockJob operations may take a long time to cancel, and during this time
10026  * further domain interactions may be unresponsive.  To avoid this problem,
10027  * pass VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC in the @flags argument to enable
10028  * asynchronous behavior, returning as soon as possible.  When the job has
10029  * been canceled, a BlockJob event will be emitted, with status
10030  * VIR_DOMAIN_BLOCK_JOB_CANCELED (even if the ABORT_ASYNC flag was not
10031  * used); it is also possible to poll virDomainBlockJobInfo() to see if
10032  * the job cancellation is still pending.  This type of job can be restarted
10033  * to pick up from where it left off.
10034  *
10035  * If the current block job for @disk is VIR_DOMAIN_BLOCK_JOB_TYPE_COPY, then
10036  * the default is to abort the mirroring and revert to the source disk;
10037  * likewise, if the current job is VIR_DOMAIN_BLOCK_JOB_TYPE_ACTIVE_COMMIT,
10038  * the default is to abort without changing the active layer of @disk.
10039  * Adding @flags of VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT causes this call to
10040  * fail with VIR_ERR_BLOCK_COPY_ACTIVE if the copy or commit is not yet
10041  * ready; otherwise it will swap the disk over to the new active image
10042  * to end the mirroring or active commit.  An event will be issued when the
10043  * job is ended, and it is possible to use VIR_DOMAIN_BLOCK_JOB_ABORT_ASYNC
10044  * to control whether this command waits for the completion of the job.
10045  * Restarting a copy or active commit job requires starting over from the
10046  * beginning of the first phase.
10047  *
10048  * Returns -1 in case of failure, 0 when successful.
10049  */
10050 int
virDomainBlockJobAbort(virDomainPtr dom,const char * disk,unsigned int flags)10051 virDomainBlockJobAbort(virDomainPtr dom, const char *disk,
10052                        unsigned int flags)
10053 {
10054     virConnectPtr conn;
10055 
10056     VIR_DOMAIN_DEBUG(dom, "disk=%s, flags=0x%x", disk, flags);
10057 
10058     virResetLastError();
10059 
10060     virCheckDomainReturn(dom, -1);
10061     conn = dom->conn;
10062 
10063     virCheckReadOnlyGoto(conn->flags, error);
10064     virCheckNonNullArgGoto(disk, error);
10065 
10066     if (conn->driver->domainBlockJobAbort) {
10067         int ret;
10068         ret = conn->driver->domainBlockJobAbort(dom, disk, flags);
10069         if (ret < 0)
10070             goto error;
10071         return ret;
10072     }
10073 
10074     virReportUnsupportedError();
10075 
10076  error:
10077     virDispatchError(dom->conn);
10078     return -1;
10079 }
10080 
10081 
10082 /**
10083  * virDomainGetBlockJobInfo:
10084  * @dom: pointer to domain object
10085  * @disk: path to the block device, or device shorthand
10086  * @info: pointer to a virDomainBlockJobInfo structure
10087  * @flags: bitwise-OR of virDomainBlockJobInfoFlags
10088  *
10089  * Request block job information for the given disk.  If an operation is active
10090  * @info will be updated with the current progress.  The units used for the
10091  * bandwidth field of @info depends on @flags.  If @flags includes
10092  * VIR_DOMAIN_BLOCK_JOB_INFO_BANDWIDTH_BYTES, bandwidth is in bytes/second
10093  * (although this mode can risk failure due to overflow, depending on both
10094  * client and server word size); otherwise, the value is rounded up to MiB/s.
10095  *
10096  * The @disk parameter is either an unambiguous source name of the
10097  * block device (the <source file='...'/> sub-element, such as
10098  * "/path/to/image"), or (since 0.9.5) the device target shorthand
10099  * (the <target dev='...'/> sub-element, such as "vda").  Valid names
10100  * can be found by calling virDomainGetXMLDesc() and inspecting
10101  * elements within //domain/devices/disk.
10102  *
10103  * In cases when libvirt can't determine actual progress of the block job from
10104  * the underlying hypervisor due to corner cases such as the job wasn't yet
10105  * fully initialized, or finalized and thus the progress can't be queried,
10106  * libvirt reports 'cur = 0, end = 1'.
10107  *
10108  * For jobs requiring finalizing via qemuDomainBlockJobAbort() with
10109  * VIR_DOMAIN_BLOCK_JOB_ABORT_PIVOT flag which reached synchronised phase, but
10110  * were empty, or the progress can't be determined libvirt returns
10111  * 'cur = 1, end = 1'.
10112  *
10113  * Users thus should not consider any data where 'end = 1' as absolute progress
10114  * value.
10115  *
10116  * Applications looking for a reliable and low-overhead way to determine whether
10117  * a block job already finished or reached synchronised phase should register a
10118  * handler for the VIR_DOMAIN_EVENT_ID_BLOCK_JOB_2 event instead of polling this
10119  * API.
10120  *
10121  * Note that the progress reported for blockjobs corresponding to a pull-mode
10122  * backup don't report progress of the backup but rather usage of temporary
10123  * space required for the backup.
10124  *
10125  * Returns -1 in case of failure, 0 when nothing found, 1 when info was found.
10126  */
10127 int
virDomainGetBlockJobInfo(virDomainPtr dom,const char * disk,virDomainBlockJobInfoPtr info,unsigned int flags)10128 virDomainGetBlockJobInfo(virDomainPtr dom, const char *disk,
10129                          virDomainBlockJobInfoPtr info, unsigned int flags)
10130 {
10131     virConnectPtr conn;
10132 
10133     VIR_DOMAIN_DEBUG(dom, "disk=%s, info=%p, flags=0x%x", disk, info, flags);
10134 
10135     virResetLastError();
10136 
10137     if (info)
10138         memset(info, 0, sizeof(*info));
10139 
10140     virCheckDomainReturn(dom, -1);
10141     conn = dom->conn;
10142 
10143     virCheckNonNullArgGoto(disk, error);
10144     virCheckNonNullArgGoto(info, error);
10145 
10146     if (conn->driver->domainGetBlockJobInfo) {
10147         int ret;
10148         ret = conn->driver->domainGetBlockJobInfo(dom, disk, info, flags);
10149         if (ret < 0)
10150             goto error;
10151         return ret;
10152     }
10153 
10154     virReportUnsupportedError();
10155 
10156  error:
10157     virDispatchError(dom->conn);
10158     return -1;
10159 }
10160 
10161 
10162 /**
10163  * virDomainBlockJobSetSpeed:
10164  * @dom: pointer to domain object
10165  * @disk: path to the block device, or device shorthand
10166  * @bandwidth: specify bandwidth limit; flags determine the unit
10167  * @flags: bitwise-OR of virDomainBlockJobSetSpeedFlags
10168  *
10169  * Set the maximum allowable bandwidth that a block job may consume.  If
10170  * bandwidth is 0, the limit will revert to the hypervisor default of
10171  * unlimited.
10172  *
10173  * If @flags contains VIR_DOMAIN_BLOCK_JOB_SPEED_BANDWIDTH_BYTES, @bandwidth
10174  * is in bytes/second; otherwise, it is in MiB/second.  Values larger than
10175  * 2^52 bytes/sec may be rejected due to overflow considerations based on
10176  * the word size of both client and server, and values larger than 2^31
10177  * bytes/sec may cause overflow problems if later queried by
10178  * virDomainGetBlockJobInfo() without scaling.  Hypervisors may further
10179  * restrict the range of valid bandwidth values.
10180  *
10181  * The @disk parameter is either an unambiguous source name of the
10182  * block device (the <source file='...'/> sub-element, such as
10183  * "/path/to/image"), or (since 0.9.5) the device target shorthand
10184  * (the <target dev='...'/> sub-element, such as "vda").  Valid names
10185  * can be found by calling virDomainGetXMLDesc() and inspecting
10186  * elements within //domain/devices/disk.
10187  *
10188  * Returns -1 in case of failure, 0 when successful.
10189  */
10190 int
virDomainBlockJobSetSpeed(virDomainPtr dom,const char * disk,unsigned long bandwidth,unsigned int flags)10191 virDomainBlockJobSetSpeed(virDomainPtr dom, const char *disk,
10192                           unsigned long bandwidth, unsigned int flags)
10193 {
10194     virConnectPtr conn;
10195 
10196     VIR_DOMAIN_DEBUG(dom, "disk=%s, bandwidth=%lu, flags=0x%x",
10197                      disk, bandwidth, flags);
10198 
10199     virResetLastError();
10200 
10201     virCheckDomainReturn(dom, -1);
10202     conn = dom->conn;
10203 
10204     virCheckReadOnlyGoto(conn->flags, error);
10205     virCheckNonNullArgGoto(disk, error);
10206 
10207     if (conn->driver->domainBlockJobSetSpeed) {
10208         int ret;
10209         ret = conn->driver->domainBlockJobSetSpeed(dom, disk, bandwidth, flags);
10210         if (ret < 0)
10211             goto error;
10212         return ret;
10213     }
10214 
10215     virReportUnsupportedError();
10216 
10217  error:
10218     virDispatchError(dom->conn);
10219     return -1;
10220 }
10221 
10222 
10223 /**
10224  * virDomainBlockPull:
10225  * @dom: pointer to domain object
10226  * @disk: path to the block device, or device shorthand
10227  * @bandwidth: (optional) specify bandwidth limit; flags determine the unit
10228  * @flags: bitwise-OR of virDomainBlockPullFlags
10229  *
10230  * Populate a disk image with data from its backing image.  Once all data from
10231  * its backing image has been pulled, the disk no longer depends on a backing
10232  * image.  This function pulls data for the entire device in the background.
10233  * Progress of the operation can be checked with virDomainGetBlockJobInfo() and
10234  * the operation can be aborted with virDomainBlockJobAbort().  When finished,
10235  * an asynchronous event is raised to indicate the final status.  To move
10236  * data in the opposite direction, see virDomainBlockCommit().
10237  *
10238  * The @disk parameter is either an unambiguous source name of the
10239  * block device (the <source file='...'/> sub-element, such as
10240  * "/path/to/image"), or (since 0.9.5) the device target shorthand
10241  * (the <target dev='...'/> sub-element, such as "vda").  Valid names
10242  * can be found by calling virDomainGetXMLDesc() and inspecting
10243  * elements within //domain/devices/disk.
10244  *
10245  * The maximum bandwidth that will be used to do the copy can be
10246  * specified with the @bandwidth parameter.  If set to 0, there is no
10247  * limit.  If @flags includes VIR_DOMAIN_BLOCK_PULL_BANDWIDTH_BYTES,
10248  * @bandwidth is in bytes/second; otherwise, it is in MiB/second.
10249  * Values larger than 2^52 bytes/sec may be rejected due to overflow
10250  * considerations based on the word size of both client and server,
10251  * and values larger than 2^31 bytes/sec may cause overflow problems
10252  * if later queried by virDomainGetBlockJobInfo() without scaling.
10253  * Hypervisors may further restrict the range of valid bandwidth
10254  * values.  Some hypervisors do not support this feature and will
10255  * return an error if bandwidth is not 0; in this case, it might still
10256  * be possible for a later call to virDomainBlockJobSetSpeed() to
10257  * succeed.  The actual speed can be determined with
10258  * virDomainGetBlockJobInfo().
10259  *
10260  * This is shorthand for virDomainBlockRebase() with a NULL base.
10261  *
10262  * Returns 0 if the operation has started, -1 on failure.
10263  */
10264 int
virDomainBlockPull(virDomainPtr dom,const char * disk,unsigned long bandwidth,unsigned int flags)10265 virDomainBlockPull(virDomainPtr dom, const char *disk,
10266                    unsigned long bandwidth, unsigned int flags)
10267 {
10268     virConnectPtr conn;
10269 
10270     VIR_DOMAIN_DEBUG(dom, "disk=%s, bandwidth=%lu, flags=0x%x",
10271                      disk, bandwidth, flags);
10272 
10273     virResetLastError();
10274 
10275     virCheckDomainReturn(dom, -1);
10276     conn = dom->conn;
10277 
10278     virCheckReadOnlyGoto(conn->flags, error);
10279     virCheckNonNullArgGoto(disk, error);
10280 
10281     if (conn->driver->domainBlockPull) {
10282         int ret;
10283         ret = conn->driver->domainBlockPull(dom, disk, bandwidth, flags);
10284         if (ret < 0)
10285             goto error;
10286         return ret;
10287     }
10288 
10289     virReportUnsupportedError();
10290 
10291  error:
10292     virDispatchError(dom->conn);
10293     return -1;
10294 }
10295 
10296 
10297 /**
10298  * virDomainBlockRebase:
10299  * @dom: pointer to domain object
10300  * @disk: path to the block device, or device shorthand
10301  * @base: path to backing file to keep, or device shorthand,
10302  *        or NULL for no backing file
10303  * @bandwidth: (optional) specify bandwidth limit; flags determine the unit
10304  * @flags: bitwise-OR of virDomainBlockRebaseFlags
10305  *
10306  * Populate a disk image with data from its backing image chain, and
10307  * setting the backing image to @base, or alternatively copy an entire
10308  * backing chain to a new file @base.
10309  *
10310  * When @flags is 0, this starts a pull, where @base must be the absolute
10311  * path of one of the backing images further up the chain, or NULL to
10312  * convert the disk image so that it has no backing image.  Once all
10313  * data from its backing image chain has been pulled, the disk no
10314  * longer depends on those intermediate backing images.  This function
10315  * pulls data for the entire device in the background.  Progress of
10316  * the operation can be checked with virDomainGetBlockJobInfo() with a
10317  * job type of VIR_DOMAIN_BLOCK_JOB_TYPE_PULL, and the operation can be
10318  * aborted with virDomainBlockJobAbort().  When finished, an asynchronous
10319  * event is raised to indicate the final status, and the job no longer
10320  * exists.  If the job is aborted, a new one can be started later to
10321  * resume from the same point.
10322  *
10323  * If @flags contains VIR_DOMAIN_BLOCK_REBASE_RELATIVE, the name recorded
10324  * into the active disk as the location for @base will be kept relative.
10325  * The operation will fail if libvirt can't infer the name.
10326  *
10327  * When @flags includes VIR_DOMAIN_BLOCK_REBASE_COPY, this starts a copy,
10328  * where @base must be the name of a new file to copy the chain to.  By
10329  * default, the copy will pull the entire source chain into the destination
10330  * file, but if @flags also contains VIR_DOMAIN_BLOCK_REBASE_SHALLOW, then
10331  * only the top of the source chain will be copied (the source and
10332  * destination have a common backing file).  By default, @base will be
10333  * created with the same file format as the source, but this can be altered
10334  * by adding VIR_DOMAIN_BLOCK_REBASE_COPY_RAW to force the copy to be raw
10335  * (does not make sense with the shallow flag unless the source is also raw),
10336  * or by using VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT to reuse an existing file
10337  * which was pre-created with the correct format and metadata and sufficient
10338  * size to hold the copy. In case the VIR_DOMAIN_BLOCK_REBASE_SHALLOW flag
10339  * is used the pre-created file has to exhibit the same guest visible contents
10340  * as the backing file of the original image. This allows a management app to
10341  * pre-create files with relative backing file names, rather than the default
10342  * of absolute backing file names; as a security precaution, you should
10343  * generally only use reuse_ext with the shallow flag and a non-raw
10344  * destination file.  By default, the copy destination will be treated as
10345  * type='file', but using VIR_DOMAIN_BLOCK_REBASE_COPY_DEV treats the
10346  * destination as type='block' (affecting how virDomainGetBlockInfo() will
10347  * report allocation after pivoting).
10348  *
10349  * A copy job has two parts; in the first phase, the @bandwidth parameter
10350  * affects how fast the source is pulled into the destination, and the job
10351  * can only be canceled by reverting to the source file; progress in this
10352  * phase can be tracked via the virDomainBlockJobInfo() command, with a
10353  * job type of VIR_DOMAIN_BLOCK_JOB_TYPE_COPY.  The job transitions to the
10354  * second phase when the job info states cur == end, and remains alive to
10355  * mirror all further changes to both source and destination.  The user
10356  * must call virDomainBlockJobAbort() to end the mirroring while choosing
10357  * whether to revert to source or pivot to the destination.  An event is
10358  * issued when the job ends, and depending on the hypervisor, an event may
10359  * also be issued when the job transitions from pulling to mirroring.  If
10360  * the job is aborted, a new job will have to start over from the beginning
10361  * of the first phase.
10362  *
10363  * Some hypervisors will restrict certain actions, such as virDomainSave()
10364  * or virDomainDetachDevice(), while a copy job is active; they may
10365  * also restrict a copy job to transient domains.
10366  *
10367  * The @disk parameter is either an unambiguous source name of the
10368  * block device (the <source file='...'/> sub-element, such as
10369  * "/path/to/image"), or the device target shorthand (the
10370  * <target dev='...'/> sub-element, such as "vda").  Valid names
10371  * can be found by calling virDomainGetXMLDesc() and inspecting
10372  * elements within //domain/devices/disk.
10373  *
10374  * The @base parameter can be either a path to a file within the backing
10375  * chain, or the device target shorthand (the <target dev='...'/>
10376  * sub-element, such as "vda") followed by an index to the backing chain
10377  * enclosed in square brackets. Backing chain indexes can be found by
10378  * inspecting //disk//backingStore/@index in the domain XML. Thus, for
10379  * example, "vda[3]" refers to the backing store with index equal to "3"
10380  * in the chain of disk "vda".
10381  *
10382  * The maximum bandwidth that will be used to do the copy can be
10383  * specified with the @bandwidth parameter.  If set to 0, there is no
10384  * limit.  If @flags includes VIR_DOMAIN_BLOCK_REBASE_BANDWIDTH_BYTES,
10385  * @bandwidth is in bytes/second; otherwise, it is in MiB/second.
10386  * Values larger than 2^52 bytes/sec may be rejected due to overflow
10387  * considerations based on the word size of both client and server,
10388  * and values larger than 2^31 bytes/sec may cause overflow problems
10389  * if later queried by virDomainGetBlockJobInfo() without scaling.
10390  * Hypervisors may further restrict the range of valid bandwidth
10391  * values.  Some hypervisors do not support this feature and will
10392  * return an error if bandwidth is not 0; in this case, it might still
10393  * be possible for a later call to virDomainBlockJobSetSpeed() to
10394  * succeed.  The actual speed can be determined with
10395  * virDomainGetBlockJobInfo().
10396  *
10397  * When @base is NULL and @flags is 0, this is identical to
10398  * virDomainBlockPull().  When @flags contains VIR_DOMAIN_BLOCK_REBASE_COPY,
10399  * this command is shorthand for virDomainBlockCopy() where the destination
10400  * XML encodes @base as a <disk type='file'>, @bandwidth is properly scaled
10401  * and passed as a typed parameter, the shallow and reuse external flags
10402  * are preserved, and remaining flags control whether the XML encodes a
10403  * destination format of raw instead of leaving the destination identical
10404  * to the source format or probed from the reused file.
10405  *
10406  * Returns 0 if the operation has started, -1 on failure.
10407  */
10408 int
virDomainBlockRebase(virDomainPtr dom,const char * disk,const char * base,unsigned long bandwidth,unsigned int flags)10409 virDomainBlockRebase(virDomainPtr dom, const char *disk,
10410                      const char *base, unsigned long bandwidth,
10411                      unsigned int flags)
10412 {
10413     virConnectPtr conn;
10414 
10415     VIR_DOMAIN_DEBUG(dom, "disk=%s, base=%s, bandwidth=%lu, flags=0x%x",
10416                      disk, NULLSTR(base), bandwidth, flags);
10417 
10418     virResetLastError();
10419 
10420     virCheckDomainReturn(dom, -1);
10421     conn = dom->conn;
10422 
10423     virCheckReadOnlyGoto(conn->flags, error);
10424     virCheckNonNullArgGoto(disk, error);
10425 
10426     if (flags & VIR_DOMAIN_BLOCK_REBASE_COPY) {
10427         virCheckNonNullArgGoto(base, error);
10428     } else if (flags & (VIR_DOMAIN_BLOCK_REBASE_SHALLOW |
10429                         VIR_DOMAIN_BLOCK_REBASE_REUSE_EXT |
10430                         VIR_DOMAIN_BLOCK_REBASE_COPY_RAW |
10431                         VIR_DOMAIN_BLOCK_REBASE_COPY_DEV)) {
10432         virReportInvalidArg(flags, "%s",
10433                             _("use of flags requires a copy job"));
10434         goto error;
10435     }
10436 
10437     if (conn->driver->domainBlockRebase) {
10438         int ret;
10439         ret = conn->driver->domainBlockRebase(dom, disk, base, bandwidth,
10440                                               flags);
10441         if (ret < 0)
10442             goto error;
10443         return ret;
10444     }
10445 
10446     virReportUnsupportedError();
10447 
10448  error:
10449     virDispatchError(dom->conn);
10450     return -1;
10451 }
10452 
10453 
10454 /**
10455  * virDomainBlockCopy:
10456  * @dom: pointer to domain object
10457  * @disk: path to the block device, or device shorthand
10458  * @destxml: XML description of the copy destination
10459  * @params: Pointer to block copy parameter objects, or NULL
10460  * @nparams: Number of block copy parameters (this value can be the same or
10461  *           less than the number of parameters supported)
10462  * @flags: bitwise-OR of virDomainBlockCopyFlags
10463  *
10464  * Copy the guest-visible contents of a disk image to a new file described
10465  * by @destxml.  The destination XML has a top-level element of <disk>, and
10466  * resembles what is used when hot-plugging a disk via virDomainAttachDevice(),
10467  * except that only sub-elements related to describing the new host resource
10468  * are necessary (sub-elements related to the guest view, such as <target>,
10469  * are ignored).  It is strongly recommended to include a <driver type='...'/>
10470  * format designation for the destination, to avoid the potential of any
10471  * security problem that might be caused by probing a file for its format.
10472  *
10473  * This command starts a long-running copy.  By default, the copy will pull
10474  * the entire source chain into the destination file, but if @flags also
10475  * contains VIR_DOMAIN_BLOCK_COPY_SHALLOW, then only the top of the source
10476  * chain will be copied (the source and destination have a common backing
10477  * file).  The format of the destination file is controlled by the <driver>
10478  * sub-element of the XML.  The destination will be created unless the
10479  * VIR_DOMAIN_BLOCK_COPY_REUSE_EXT flag is present stating that the file
10480  * was pre-created with the correct format and metadata and sufficient
10481  * size to hold the copy. In case the VIR_DOMAIN_BLOCK_COPY_SHALLOW flag
10482  * is used the pre-created file has to exhibit the same guest visible contents
10483  * as the backing file of the original image. This allows a management app to
10484  * pre-create files with relative backing file names, rather than the default
10485  * of absolute backing file names.
10486  *
10487  * A copy job has two parts; in the first phase, the source is copied into
10488  * the destination, and the job can only be canceled by reverting to the
10489  * source file; progress in this phase can be tracked via the
10490  * virDomainBlockJobInfo() command, with a job type of
10491  * VIR_DOMAIN_BLOCK_JOB_TYPE_COPY.  The job transitions to the second
10492  * phase when the block job event with state VIR_DOMAIN_BLOCK_JOB_READY is
10493  * emitted for the given device. This information is also visible in the
10494  * live XML as 'ready="yes"' attribute of the corresponding <mirror> element.
10495  * All further changes are saved to both source and destination.  The user must
10496  * call virDomainBlockJobAbort() to end the mirroring while choosing
10497  * whether to revert to source or pivot to the destination.  An event is
10498  * issued when the job ends, and depending on the hypervisor, an event may
10499  * also be issued when the job transitions from pulling to mirroring.  If
10500  * the job is aborted, a new job will have to start over from the beginning
10501  * of the first phase.
10502  *
10503  * Some hypervisors will restrict certain actions, such as virDomainSave()
10504  * or virDomainDetachDevice(), while a copy job is active; they may
10505  * also restrict a copy job to transient domains.
10506  *
10507  * If @flags contains VIR_DOMAIN_BLOCK_COPY_TRANSIENT_JOB the job will not be
10508  * recoverable if the VM is turned off while job is active. This flag will
10509  * remove the restriction of copy jobs to transient domains. Note that this flag
10510  * is automatically implied if the VM is transient at the time it's started.
10511  *
10512  * The @disk parameter is either an unambiguous source name of the
10513  * block device (the <source file='...'/> sub-element, such as
10514  * "/path/to/image"), or the device target shorthand (the
10515  * <target dev='...'/> sub-element, such as "vda").  Valid names
10516  * can be found by calling virDomainGetXMLDesc() and inspecting
10517  * elements within //domain/devices/disk.
10518  *
10519  * The @params and @nparams arguments can be used to set hypervisor-specific
10520  * tuning parameters, such as maximum bandwidth or granularity.  For a
10521  * parameter that the hypervisor understands, explicitly specifying 0
10522  * behaves the same as omitting the parameter, to use the hypervisor
10523  * default; however, omitting a parameter is less likely to fail.
10524  *
10525  * This command is a superset of the older virDomainBlockRebase() when used
10526  * with the VIR_DOMAIN_BLOCK_REBASE_COPY flag, and offers better control
10527  * over the destination format, the ability to copy to a destination that
10528  * is not a local file, and the possibility of additional tuning parameters.
10529  *
10530  * Returns 0 if the operation has started, -1 on failure.
10531  */
10532 int
virDomainBlockCopy(virDomainPtr dom,const char * disk,const char * destxml,virTypedParameterPtr params,int nparams,unsigned int flags)10533 virDomainBlockCopy(virDomainPtr dom, const char *disk,
10534                    const char *destxml,
10535                    virTypedParameterPtr params,
10536                    int nparams,
10537                    unsigned int flags)
10538 {
10539     virConnectPtr conn;
10540 
10541     VIR_DOMAIN_DEBUG(dom,
10542                      "disk=%s, destxml=%s, params=%p, nparams=%d, flags=0x%x",
10543                      disk, destxml, params, nparams, flags);
10544     VIR_TYPED_PARAMS_DEBUG(params, nparams);
10545 
10546     virResetLastError();
10547 
10548     virCheckDomainReturn(dom, -1);
10549     conn = dom->conn;
10550 
10551     virCheckReadOnlyGoto(conn->flags, error);
10552     virCheckNonNullArgGoto(disk, error);
10553     virCheckNonNullArgGoto(destxml, error);
10554     virCheckNonNegativeArgGoto(nparams, error);
10555     if (nparams)
10556         virCheckNonNullArgGoto(params, error);
10557 
10558     if (conn->driver->domainBlockCopy) {
10559         int ret;
10560         ret = conn->driver->domainBlockCopy(dom, disk, destxml,
10561                                             params, nparams, flags);
10562         if (ret < 0)
10563             goto error;
10564         return ret;
10565     }
10566 
10567     virReportUnsupportedError();
10568 
10569  error:
10570     virDispatchError(dom->conn);
10571     return -1;
10572 }
10573 
10574 
10575 /**
10576  * virDomainBlockCommit:
10577  * @dom: pointer to domain object
10578  * @disk: path to the block device, or device shorthand
10579  * @base: path to backing file to merge into, or device shorthand,
10580  *        or NULL for default
10581  * @top: path to file within backing chain that contains data to be merged,
10582  *       or device shorthand, or NULL to merge all possible data
10583  * @bandwidth: (optional) specify bandwidth limit; flags determine the unit
10584  * @flags: bitwise-OR of virDomainBlockCommitFlags
10585  *
10586  * Commit changes that were made to temporary top-level files within a disk
10587  * image backing file chain into a lower-level base file.  In other words,
10588  * take all the difference between @base and @top, and update @base to contain
10589  * that difference; after the commit, any portion of the chain that previously
10590  * depended on @top will now depend on @base, and all files after @base up
10591  * to and including @top will now be invalidated.  A typical use of this
10592  * command is to reduce the length of a backing file chain after taking an
10593  * external disk snapshot.  To move data in the opposite direction, see
10594  * virDomainBlockPull().
10595  *
10596  * This command starts a long-running commit block job, whose status may
10597  * be tracked by virDomainBlockJobInfo() with a job type of
10598  * VIR_DOMAIN_BLOCK_JOB_TYPE_COMMIT, and the operation can be aborted with
10599  * virDomainBlockJobAbort().  When finished, an asynchronous event is
10600  * raised to indicate the final status, and the job no longer exists.  If
10601  * the job is aborted, it is up to the hypervisor whether starting a new
10602  * job will resume from the same point, or start over.
10603  *
10604  * As a special case, if @top is the active image (or NULL), and @flags
10605  * includes VIR_DOMAIN_BLOCK_COMMIT_ACTIVE, the block job will have a type
10606  * of VIR_DOMAIN_BLOCK_JOB_TYPE_ACTIVE_COMMIT, and operates in two phases.
10607  * In the first phase, the contents are being committed into @base, and the
10608  * job can only be canceled.  The job transitions to the second phase when
10609  * the block job event with state VIR_DOMAIN_BLOCK_JOB_READY is
10610  * emitted for the given device. This information is also visible in the
10611  * live XML as 'ready="yes"' attribute of the corresponding <mirror> element.
10612  * Once in the second phase, the user must choose whether to cancel the job
10613  * (keeping @top as the active image, but now containing only the changes
10614  * since the time the job ended) or to pivot the job (adjusting to @base as
10615  * the active image, and invalidating @top).
10616  *
10617  * Be aware that this command may invalidate files even if it is aborted;
10618  * the user is cautioned against relying on the contents of invalidated
10619  * intermediate files such as @top (when @top is not the active image)
10620  * without manually rebasing those files to use a backing file of a
10621  * read-only copy of @base prior to the point where the commit operation
10622  * was started (and such a rebase cannot be safely done until the commit
10623  * has successfully completed).  However, the domain itself will not have
10624  * any issues; the active layer remains valid throughout the entire commit
10625  * operation.
10626  *
10627  * Some hypervisors may support a shortcut where if @flags contains
10628  * VIR_DOMAIN_BLOCK_COMMIT_DELETE, then this command will unlink all files
10629  * that were invalidated, after the commit successfully completes.
10630  *
10631  * If @flags contains VIR_DOMAIN_BLOCK_COMMIT_RELATIVE, the name recorded
10632  * into the overlay of the @top image (if there is such image) as the
10633  * path to the new backing file will be kept relative to other images.
10634  * The operation will fail if libvirt can't infer the name.
10635  *
10636  * By default, if @base is NULL, the commit target will be the bottom of
10637  * the backing chain; if @flags contains VIR_DOMAIN_BLOCK_COMMIT_SHALLOW,
10638  * then the immediate backing file of @top will be used instead.  If @top
10639  * is NULL, the active image at the top of the chain will be used.  Some
10640  * hypervisors place restrictions on how much can be committed, and might
10641  * fail if @base is not the immediate backing file of @top, or if @top is
10642  * the active layer in use by a running domain but @flags did not include
10643  * VIR_DOMAIN_BLOCK_COMMIT_ACTIVE, or if @top is not the top-most file;
10644  * restrictions may differ for online vs. offline domains.
10645  *
10646  * The @disk parameter is either an unambiguous source name of the
10647  * block device (the <source file='...'/> sub-element, such as
10648  * "/path/to/image"), or the device target shorthand (the
10649  * <target dev='...'/> sub-element, such as "vda").  Valid names
10650  * can be found by calling virDomainGetXMLDesc() and inspecting
10651  * elements within //domain/devices/disk.
10652  *
10653  * The @base and @top parameters can be either paths to files within the
10654  * backing chain, or the device target shorthand (the <target dev='...'/>
10655  * sub-element, such as "vda") followed by an index to the backing chain
10656  * enclosed in square brackets. Backing chain indexes can be found by
10657  * inspecting //disk//backingStore/@index in the domain XML. Thus, for
10658  * example, "vda[3]" refers to the backing store with index equal to "3"
10659  * in the chain of disk "vda".
10660  *
10661  * The maximum bandwidth that will be used to do the commit can be
10662  * specified with the @bandwidth parameter.  If set to 0, there is no
10663  * limit.  If @flags includes VIR_DOMAIN_BLOCK_COMMIT_BANDWIDTH_BYTES,
10664  * @bandwidth is in bytes/second; otherwise, it is in MiB/second.
10665  * Values larger than 2^52 bytes/sec may be rejected due to overflow
10666  * considerations based on the word size of both client and server,
10667  * and values larger than 2^31 bytes/sec may cause overflow problems
10668  * if later queried by virDomainGetBlockJobInfo() without scaling.
10669  * Hypervisors may further restrict the range of valid bandwidth
10670  * values.  Some hypervisors do not support this feature and will
10671  * return an error if bandwidth is not 0; in this case, it might still
10672  * be possible for a later call to virDomainBlockJobSetSpeed() to
10673  * succeed.  The actual speed can be determined with
10674  * virDomainGetBlockJobInfo().
10675  *
10676  * Returns 0 if the operation has started, -1 on failure.
10677  */
10678 int
virDomainBlockCommit(virDomainPtr dom,const char * disk,const char * base,const char * top,unsigned long bandwidth,unsigned int flags)10679 virDomainBlockCommit(virDomainPtr dom, const char *disk,
10680                      const char *base, const char *top,
10681                      unsigned long bandwidth, unsigned int flags)
10682 {
10683     virConnectPtr conn;
10684 
10685     VIR_DOMAIN_DEBUG(dom, "disk=%s, base=%s, top=%s, bandwidth=%lu, flags=0x%x",
10686                      disk, NULLSTR(base), NULLSTR(top), bandwidth, flags);
10687 
10688     virResetLastError();
10689 
10690     virCheckDomainReturn(dom, -1);
10691     conn = dom->conn;
10692 
10693     virCheckReadOnlyGoto(conn->flags, error);
10694     virCheckNonNullArgGoto(disk, error);
10695 
10696     if (conn->driver->domainBlockCommit) {
10697         int ret;
10698         ret = conn->driver->domainBlockCommit(dom, disk, base, top, bandwidth,
10699                                               flags);
10700         if (ret < 0)
10701             goto error;
10702         return ret;
10703     }
10704 
10705     virReportUnsupportedError();
10706 
10707  error:
10708     virDispatchError(dom->conn);
10709     return -1;
10710 }
10711 
10712 
10713 /**
10714  * virDomainOpenGraphics:
10715  * @dom: pointer to domain object
10716  * @idx: index of graphics config to open
10717  * @fd: file descriptor to attach graphics to
10718  * @flags: bitwise-OR of virDomainOpenGraphicsFlags
10719  *
10720  * This will attempt to connect the file descriptor @fd, to
10721  * the graphics backend of @dom. If @dom has multiple graphics
10722  * backends configured, then @idx will determine which one is
10723  * opened, starting from @idx 0.
10724  *
10725  * To disable any authentication, pass the VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH
10726  * constant for @flags.
10727  *
10728  * The caller should use an anonymous socketpair to open
10729  * @fd before invocation.
10730  *
10731  * This method can only be used when connected to a local
10732  * libvirt hypervisor, over a UNIX domain socket. Attempts
10733  * to use this method over a TCP connection will always fail
10734  *
10735  * Returns 0 on success, -1 on failure
10736  */
10737 int
virDomainOpenGraphics(virDomainPtr dom,unsigned int idx,int fd,unsigned int flags)10738 virDomainOpenGraphics(virDomainPtr dom,
10739                       unsigned int idx,
10740                       int fd,
10741                       unsigned int flags)
10742 {
10743     struct stat sb;
10744     int rc;
10745 
10746     VIR_DOMAIN_DEBUG(dom, "idx=%u, fd=%d, flags=0x%x",
10747                      idx, fd, flags);
10748 
10749     virResetLastError();
10750 
10751     virCheckDomainReturn(dom, -1);
10752     virCheckNonNegativeArgGoto(fd, error);
10753 
10754     if (fstat(fd, &sb) < 0) {
10755         virReportSystemError(errno,
10756                              _("Unable to access file descriptor %d"), fd);
10757         goto error;
10758     }
10759 
10760 #ifndef WIN32
10761     if (!S_ISSOCK(sb.st_mode)) {
10762         virReportInvalidArg(fd,
10763                             _("fd %d must be a socket"),
10764                             fd);
10765         goto error;
10766     }
10767 #endif /* !WIN32 */
10768 
10769     virCheckReadOnlyGoto(dom->conn->flags, error);
10770 
10771     rc = VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn,
10772                                   VIR_DRV_FEATURE_FD_PASSING);
10773     if (rc <= 0) {
10774         if (rc == 0)
10775             virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
10776                            _("fd passing is not supported by this connection"));
10777         goto error;
10778     }
10779 
10780     if (dom->conn->driver->domainOpenGraphics) {
10781         int ret;
10782         ret = dom->conn->driver->domainOpenGraphics(dom, idx, fd, flags);
10783         if (ret < 0)
10784             goto error;
10785         return ret;
10786     }
10787 
10788     virReportUnsupportedError();
10789 
10790  error:
10791     virDispatchError(dom->conn);
10792     return -1;
10793 }
10794 
10795 
10796 /**
10797  * virDomainOpenGraphicsFD:
10798  * @dom: pointer to domain object
10799  * @idx: index of graphics config to open
10800  * @flags: bitwise-OR of virDomainOpenGraphicsFlags
10801  *
10802  * This will create a socket pair connected to the graphics backend of @dom.
10803  * One end of the socket will be returned on success, and the other end is
10804  * handed to the hypervisor.
10805  * If @dom has multiple graphics backends configured, then @idx will determine
10806  * which one is opened, starting from @idx 0.
10807  *
10808  * To disable any authentication, pass the VIR_DOMAIN_OPEN_GRAPHICS_SKIPAUTH
10809  * constant for @flags.
10810  *
10811  * This method can only be used when connected to a local
10812  * libvirt hypervisor, over a UNIX domain socket. Attempts
10813  * to use this method over a TCP connection will always fail.
10814  *
10815  * Returns an fd on success, -1 on failure
10816  */
10817 int
virDomainOpenGraphicsFD(virDomainPtr dom,unsigned int idx,unsigned int flags)10818 virDomainOpenGraphicsFD(virDomainPtr dom,
10819                         unsigned int idx,
10820                         unsigned int flags)
10821 {
10822     int rc;
10823 
10824     VIR_DOMAIN_DEBUG(dom, "idx=%u, flags=0x%x", idx, flags);
10825 
10826     virResetLastError();
10827 
10828     virCheckDomainReturn(dom, -1);
10829 
10830     virCheckReadOnlyGoto(dom->conn->flags, error);
10831 
10832     rc = VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn,
10833                                   VIR_DRV_FEATURE_FD_PASSING);
10834 
10835     if (rc <= 0) {
10836         if (rc == 0)
10837             virReportError(VIR_ERR_ARGUMENT_UNSUPPORTED, "%s",
10838                            _("fd passing is not supported by this connection"));
10839         goto error;
10840     }
10841 
10842     if (dom->conn->driver->domainOpenGraphicsFD) {
10843         int ret;
10844         ret = dom->conn->driver->domainOpenGraphicsFD(dom, idx, flags);
10845         if (ret < 0)
10846             goto error;
10847         return ret;
10848     }
10849 
10850     virReportUnsupportedError();
10851 
10852  error:
10853     virDispatchError(dom->conn);
10854     return -1;
10855 }
10856 
10857 
10858 /**
10859  * virDomainSetBlockIoTune:
10860  * @dom: pointer to domain object
10861  * @disk: path to the block device, or device shorthand
10862  * @params: Pointer to blkio parameter objects
10863  * @nparams: Number of blkio parameters (this value can be the same or
10864  *           less than the number of parameters supported)
10865  * @flags: bitwise-OR of virDomainModificationImpact
10866  *
10867  * Change all or a subset of the per-device block IO tunables.
10868  *
10869  * The @disk parameter is either an unambiguous source name of the
10870  * block device (the <source file='...'/> sub-element, such as
10871  * "/path/to/image"), or the device target shorthand (the <target
10872  * dev='...'/> sub-element, such as "xvda").  Valid names can be found
10873  * by calling virDomainGetXMLDesc() and inspecting elements
10874  * within //domain/devices/disk.
10875  *
10876  * Returns -1 in case of error, 0 in case of success.
10877  */
10878 int
virDomainSetBlockIoTune(virDomainPtr dom,const char * disk,virTypedParameterPtr params,int nparams,unsigned int flags)10879 virDomainSetBlockIoTune(virDomainPtr dom,
10880                         const char *disk,
10881                         virTypedParameterPtr params,
10882                         int nparams,
10883                         unsigned int flags)
10884 {
10885     virConnectPtr conn;
10886 
10887     VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=0x%x",
10888                      disk, params, nparams, flags);
10889     VIR_TYPED_PARAMS_DEBUG(params, nparams);
10890 
10891     virResetLastError();
10892 
10893     virCheckDomainReturn(dom, -1);
10894     conn = dom->conn;
10895 
10896     virCheckReadOnlyGoto(conn->flags, error);
10897     virCheckNonNullArgGoto(disk, error);
10898     virCheckPositiveArgGoto(nparams, error);
10899     virCheckNonNullArgGoto(params, error);
10900 
10901     if (virTypedParameterValidateSet(dom->conn, params, nparams) < 0)
10902         goto error;
10903 
10904     if (conn->driver->domainSetBlockIoTune) {
10905         int ret;
10906         ret = conn->driver->domainSetBlockIoTune(dom, disk, params, nparams, flags);
10907         if (ret < 0)
10908             goto error;
10909         return ret;
10910     }
10911 
10912     virReportUnsupportedError();
10913 
10914  error:
10915     virDispatchError(dom->conn);
10916     return -1;
10917 }
10918 
10919 
10920 /**
10921  * virDomainGetBlockIoTune:
10922  * @dom: pointer to domain object
10923  * @disk: path to the block device, or device shorthand
10924  * @params: Pointer to blkio parameter object
10925  *          (return value, allocated by the caller)
10926  * @nparams: Pointer to number of blkio parameters
10927  * @flags: bitwise-OR of virDomainModificationImpact and virTypedParameterFlags
10928  *
10929  * Get all block IO tunable parameters for a given device.  On input,
10930  * @nparams gives the size of the @params array; on output, @nparams
10931  * gives how many slots were filled with parameter information, which
10932  * might be less but will not exceed the input value.
10933  *
10934  * As a special case, calling with @params as NULL and @nparams as 0
10935  * on input will cause @nparams on output to contain the number of
10936  * parameters supported by the hypervisor, either for the given @disk
10937  * (note that block devices of different types might support different
10938  * parameters), or if @disk is NULL, for all possible disks. The
10939  * caller should then allocate @params array,
10940  * i.e. (sizeof(@virTypedParameter) * @nparams) bytes and call the API
10941  * again.  See virDomainGetMemoryParameters() for more details.
10942  *
10943  * The @disk parameter is either an unambiguous source name of the
10944  * block device (the <source file='...'/> sub-element, such as
10945  * "/path/to/image"), or the device target shorthand (the <target
10946  * dev='...'/> sub-element, such as "xvda").  Valid names can be found
10947  * by calling virDomainGetXMLDesc() and inspecting elements
10948  * within //domain/devices/disk.  This parameter cannot be NULL
10949  * unless @nparams is 0 on input.
10950  *
10951  * Returns -1 in case of error, 0 in case of success.
10952  */
10953 int
virDomainGetBlockIoTune(virDomainPtr dom,const char * disk,virTypedParameterPtr params,int * nparams,unsigned int flags)10954 virDomainGetBlockIoTune(virDomainPtr dom,
10955                         const char *disk,
10956                         virTypedParameterPtr params,
10957                         int *nparams,
10958                         unsigned int flags)
10959 {
10960     virConnectPtr conn;
10961     int rc;
10962 
10963     VIR_DOMAIN_DEBUG(dom, "disk=%s, params=%p, nparams=%d, flags=0x%x",
10964                      NULLSTR(disk), params, (nparams) ? *nparams : -1, flags);
10965 
10966     virResetLastError();
10967 
10968     virCheckDomainReturn(dom, -1);
10969 
10970     virCheckNonNullArgGoto(nparams, error);
10971     virCheckNonNegativeArgGoto(*nparams, error);
10972     if (*nparams != 0) {
10973         virCheckNonNullArgGoto(params, error);
10974         virCheckNonNullArgGoto(disk, error);
10975     }
10976 
10977     rc = VIR_DRV_SUPPORTS_FEATURE(dom->conn->driver, dom->conn,
10978                                   VIR_DRV_FEATURE_TYPED_PARAM_STRING);
10979     if (rc < 0)
10980         goto error;
10981     if (rc)
10982         flags |= VIR_TYPED_PARAM_STRING_OKAY;
10983 
10984     VIR_EXCLUSIVE_FLAGS_GOTO(VIR_DOMAIN_AFFECT_LIVE,
10985                              VIR_DOMAIN_AFFECT_CONFIG,
10986                              error);
10987 
10988     conn = dom->conn;
10989 
10990     if (conn->driver->domainGetBlockIoTune) {
10991         int ret;
10992         ret = conn->driver->domainGetBlockIoTune(dom, disk, params, nparams, flags);
10993         if (ret < 0)
10994             goto error;
10995         return ret;
10996     }
10997 
10998     virReportUnsupportedError();
10999 
11000  error:
11001     virDispatchError(dom->conn);
11002     return -1;
11003 }
11004 
11005 
11006 /**
11007  * virDomainGetCPUStats:
11008  * @domain: domain to query
11009  * @params: array to populate on output
11010  * @nparams: number of parameters per cpu
11011  * @start_cpu: which cpu to start with, or -1 for summary
11012  * @ncpus: how many cpus to query
11013  * @flags: bitwise-OR of virTypedParameterFlags
11014  *
11015  * Get statistics relating to CPU usage attributable to a single
11016  * domain (in contrast to the statistics returned by
11017  * virNodeGetCPUStats() for all processes on the host).  @dom
11018  * must be running (an inactive domain has no attributable cpu
11019  * usage).  On input, @params must contain at least @nparams * @ncpus
11020  * entries, allocated by the caller.
11021  *
11022  * If @start_cpu is -1, then @ncpus must be 1, and the returned
11023  * results reflect the statistics attributable to the entire
11024  * domain (such as user and system time for the process as a
11025  * whole).  Otherwise, @start_cpu represents which cpu to start
11026  * with, and @ncpus represents how many consecutive processors to
11027  * query, with statistics attributable per processor (such as
11028  * per-cpu usage).  If @ncpus is larger than the number of cpus
11029  * available to query, then the trailing part of the array will
11030  * be unpopulated.
11031  *
11032  * The remote driver imposes a limit of 128 @ncpus and 16 @nparams;
11033  * the number of parameters per cpu should not exceed 16, but if you
11034  * have a host with more than 128 CPUs, your program should split
11035  * the request into multiple calls.
11036  *
11037  * As special cases, if @params is NULL and @nparams is 0 and
11038  * @ncpus is 1, and the return value will be how many
11039  * statistics are available for the given @start_cpu.  This number
11040  * may be different for @start_cpu of -1 than for any non-negative
11041  * value, but will be the same for all non-negative @start_cpu.
11042  * Likewise, if @params is NULL and @nparams is 0 and @ncpus is 0,
11043  * the number of cpus available to query is returned.  From the
11044  * host perspective, this would typically match the cpus member
11045  * of virNodeGetInfo(), but might be less due to host cpu hotplug.
11046  *
11047  * For now, @flags is unused, and the statistics all relate to the
11048  * usage from the host perspective.  It is possible that a future
11049  * version will support a flag that queries the cpu usage from the
11050  * guest's perspective, where the maximum cpu to query would be
11051  * related to virDomainGetVcpusFlags() rather than virNodeGetInfo().
11052  * An individual guest vcpu cannot be reliably mapped back to a
11053  * specific host cpu unless a single-processor vcpu pinning was used,
11054  * but when @start_cpu is -1, any difference in usage between a host
11055  * and guest perspective would serve as a measure of hypervisor overhead.
11056  *
11057  * Typical use sequence is below.
11058  *
11059  * getting total stats: set start_cpu as -1, ncpus 1
11060  *
11061  *   virDomainGetCPUStats(dom, NULL, 0, -1, 1, 0); // nparams
11062  *   params = calloc(nparams, sizeof(virTypedParameter))
11063  *   virDomainGetCPUStats(dom, params, nparams, -1, 1, 0); // total stats.
11064  *
11065  * getting per-cpu stats:
11066  *
11067  *   virDomainGetCPUStats(dom, NULL, 0, 0, 0, 0); // ncpus
11068  *   virDomainGetCPUStats(dom, NULL, 0, 0, 1, 0); // nparams
11069  *   params = calloc(ncpus * nparams, sizeof(virTypedParameter));
11070  *   virDomainGetCPUStats(dom, params, nparams, 0, ncpus, 0); // per-cpu stats
11071  *
11072  * Returns -1 on failure, or the number of statistics that were
11073  * populated per cpu on success (this will be less than the total
11074  * number of populated @params, unless @ncpus was 1; and may be
11075  * less than @nparams).  The populated parameters start at each
11076  * stride of @nparams, which means the results may be discontiguous;
11077  * any unpopulated parameters will be zeroed on success (this includes
11078  * skipped elements if @nparams is too large, and tail elements if
11079  * @ncpus is too large).  The caller is responsible for freeing any
11080  * returned string parameters.
11081  */
11082 int
virDomainGetCPUStats(virDomainPtr domain,virTypedParameterPtr params,unsigned int nparams,int start_cpu,unsigned int ncpus,unsigned int flags)11083 virDomainGetCPUStats(virDomainPtr domain,
11084                      virTypedParameterPtr params,
11085                      unsigned int nparams,
11086                      int start_cpu,
11087                      unsigned int ncpus,
11088                      unsigned int flags)
11089 {
11090     virConnectPtr conn;
11091     int rc;
11092 
11093     VIR_DOMAIN_DEBUG(domain,
11094                      "params=%p, nparams=%d, start_cpu=%d, ncpus=%u, flags=0x%x",
11095                      params, nparams, start_cpu, ncpus, flags);
11096     virResetLastError();
11097 
11098     virCheckDomainReturn(domain, -1);
11099     conn = domain->conn;
11100 
11101     /* Special cases:
11102      * start_cpu must be non-negative, or else -1
11103      * if start_cpu is -1, ncpus must be 1
11104      * params == NULL must match nparams == 0
11105      * ncpus must be non-zero unless params == NULL
11106      * nparams * ncpus must not overflow (RPC may restrict it even more)
11107      */
11108     if (start_cpu == -1) {
11109         if (ncpus != 1) {
11110             virReportInvalidArg(start_cpu, "%s",
11111                                 _("ncpus must be 1 when start_cpu is -1"));
11112             goto error;
11113         }
11114     } else {
11115         virCheckNonNegativeArgGoto(start_cpu, error);
11116     }
11117     if (nparams)
11118         virCheckNonNullArgGoto(params, error);
11119     else
11120         virCheckNullArgGoto(params, error);
11121     if (ncpus == 0)
11122         virCheckNullArgGoto(params, error);
11123 
11124     if (nparams && ncpus > UINT_MAX / nparams) {
11125         virReportError(VIR_ERR_OVERFLOW, _("input too large: %u * %u"),
11126                        nparams, ncpus);
11127         goto error;
11128     }
11129     rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
11130                                   VIR_DRV_FEATURE_TYPED_PARAM_STRING);
11131     if (rc < 0)
11132         goto error;
11133     if (rc)
11134         flags |= VIR_TYPED_PARAM_STRING_OKAY;
11135 
11136     if (conn->driver->domainGetCPUStats) {
11137         int ret;
11138 
11139         ret = conn->driver->domainGetCPUStats(domain, params, nparams,
11140                                               start_cpu, ncpus, flags);
11141         if (ret < 0)
11142             goto error;
11143         return ret;
11144     }
11145 
11146     virReportUnsupportedError();
11147 
11148  error:
11149     virDispatchError(domain->conn);
11150     return -1;
11151 }
11152 
11153 
11154 /**
11155  * virDomainGetDiskErrors:
11156  * @dom: a domain object
11157  * @errors: array to populate on output
11158  * @maxerrors: size of @errors array
11159  * @flags: extra flags; not used yet, so callers should always pass 0
11160  *
11161  * The function populates @errors array with all disks that encountered an
11162  * I/O error.  Disks with no error will not be returned in the @errors array.
11163  * Each disk is identified by its target (the dev attribute of target
11164  * subelement in domain XML), such as "vda", and accompanied with the error
11165  * that was seen on it.  The caller is also responsible for calling free()
11166  * on each disk name returned.
11167  *
11168  * In a special case when @errors is NULL and @maxerrors is 0, the function
11169  * returns preferred size of @errors that the caller should use to get all
11170  * disk errors.
11171  *
11172  * Since calling virDomainGetDiskErrors(dom, NULL, 0, 0) to get preferred size
11173  * of @errors array and getting the errors are two separate operations, new
11174  * disks may be hotplugged to the domain and new errors may be encountered
11175  * between the two calls.  Thus, this function may not return all disk errors
11176  * because the supplied array is not large enough.  Such errors may, however,
11177  * be detected by listening to domain events.
11178  *
11179  * Returns number of disks with errors filled in the @errors array or -1 on
11180  * error.
11181  */
11182 int
virDomainGetDiskErrors(virDomainPtr dom,virDomainDiskErrorPtr errors,unsigned int maxerrors,unsigned int flags)11183 virDomainGetDiskErrors(virDomainPtr dom,
11184                        virDomainDiskErrorPtr errors,
11185                        unsigned int maxerrors,
11186                        unsigned int flags)
11187 {
11188     VIR_DOMAIN_DEBUG(dom, "errors=%p, maxerrors=%u, flags=0x%x",
11189                      errors, maxerrors, flags);
11190 
11191     virResetLastError();
11192 
11193     virCheckDomainReturn(dom, -1);
11194 
11195     virCheckNonNullArrayArgGoto(errors, maxerrors, error);
11196 
11197     if (dom->conn->driver->domainGetDiskErrors) {
11198         int ret = dom->conn->driver->domainGetDiskErrors(dom, errors,
11199                                                          maxerrors, flags);
11200         if (ret < 0)
11201             goto error;
11202         return ret;
11203     }
11204 
11205     virReportUnsupportedError();
11206 
11207  error:
11208     virDispatchError(dom->conn);
11209     return -1;
11210 }
11211 
11212 
11213 /**
11214  * virDomainGetHostname:
11215  * @domain: a domain object
11216  * @flags: bitwise-OR of virDomainGetHostnameFlags
11217  *
11218  * Get the hostname for that domain. If no hostname is found,
11219  * then an error is raised with VIR_ERR_NO_HOSTNAME code.
11220  *
11221  * Dependent on hypervisor and @flags used, this may require a
11222  * guest agent to be available.
11223  *
11224  * Returns the hostname which must be freed by the caller, or
11225  * NULL if there was an error.
11226  */
11227 char *
virDomainGetHostname(virDomainPtr domain,unsigned int flags)11228 virDomainGetHostname(virDomainPtr domain, unsigned int flags)
11229 {
11230     virConnectPtr conn;
11231 
11232     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
11233 
11234     virResetLastError();
11235 
11236     virCheckDomainReturn(domain, NULL);
11237     conn = domain->conn;
11238 
11239     virCheckReadOnlyGoto(domain->conn->flags, error);
11240 
11241     if (conn->driver->domainGetHostname) {
11242         char *ret;
11243         ret = conn->driver->domainGetHostname(domain, flags);
11244         if (!ret)
11245             goto error;
11246         return ret;
11247     }
11248 
11249     virReportUnsupportedError();
11250 
11251  error:
11252     virDispatchError(domain->conn);
11253     return NULL;
11254 }
11255 
11256 
11257 /**
11258  * virDomainFSTrim:
11259  * @dom: a domain object
11260  * @mountPoint: which mount point to trim
11261  * @minimum: Minimum contiguous free range to discard in bytes
11262  * @flags: extra flags, not used yet, so callers should always pass 0
11263  *
11264  * Calls FITRIM within the guest (hence guest agent may be
11265  * required depending on hypervisor used). Either call it on each
11266  * mounted filesystem (@mountPoint is NULL) or just on specified
11267  * @mountPoint. @minimum hints that free ranges smaller than this
11268  * may be ignored (this is a hint and the guest may not respect
11269  * it).  By increasing this value, the fstrim operation will
11270  * complete more quickly for filesystems with badly fragmented
11271  * free space, although not all blocks will be discarded.
11272  * If @minimum is not zero, the command may fail.
11273  *
11274  * Returns 0 on success, -1 otherwise.
11275  */
11276 int
virDomainFSTrim(virDomainPtr dom,const char * mountPoint,unsigned long long minimum,unsigned int flags)11277 virDomainFSTrim(virDomainPtr dom,
11278                 const char *mountPoint,
11279                 unsigned long long minimum,
11280                 unsigned int flags)
11281 {
11282     VIR_DOMAIN_DEBUG(dom, "mountPoint=%s, minimum=%llu, flags=0x%x",
11283                      mountPoint, minimum, flags);
11284 
11285     virResetLastError();
11286 
11287     virCheckDomainReturn(dom, -1);
11288     virCheckReadOnlyGoto(dom->conn->flags, error);
11289 
11290     if (dom->conn->driver->domainFSTrim) {
11291         int ret = dom->conn->driver->domainFSTrim(dom, mountPoint,
11292                                                   minimum, flags);
11293         if (ret < 0)
11294             goto error;
11295         return ret;
11296     }
11297 
11298     virReportUnsupportedError();
11299 
11300  error:
11301     virDispatchError(dom->conn);
11302     return -1;
11303 }
11304 
11305 /**
11306  * virDomainFSFreeze:
11307  * @dom: a domain object
11308  * @mountpoints: list of mount points to be frozen
11309  * @nmountpoints: the number of mount points specified in @mountpoints
11310  * @flags: extra flags; not used yet, so callers should always pass 0
11311  *
11312  * Freeze specified filesystems within the guest (hence guest agent
11313  * may be required depending on hypervisor used). If @mountpoints is NULL and
11314  * @nmountpoints is 0, every mounted filesystem on the guest is frozen.
11315  * In some environments (e.g. QEMU guest with guest agent which doesn't
11316  * support mountpoints argument), @mountpoints may need to be NULL.
11317  *
11318  * Returns the number of frozen filesystems on success, -1 otherwise.
11319  */
11320 int
virDomainFSFreeze(virDomainPtr dom,const char ** mountpoints,unsigned int nmountpoints,unsigned int flags)11321 virDomainFSFreeze(virDomainPtr dom,
11322                   const char **mountpoints,
11323                   unsigned int nmountpoints,
11324                   unsigned int flags)
11325 {
11326     VIR_DOMAIN_DEBUG(dom, "mountpoints=%p, nmountpoints=%d, flags=0x%x",
11327                      mountpoints, nmountpoints, flags);
11328 
11329     virResetLastError();
11330 
11331     virCheckDomainReturn(dom, -1);
11332     virCheckReadOnlyGoto(dom->conn->flags, error);
11333     virCheckNonNullArrayArgGoto(mountpoints, nmountpoints, error);
11334 
11335     if (dom->conn->driver->domainFSFreeze) {
11336         int ret = dom->conn->driver->domainFSFreeze(
11337             dom, mountpoints, nmountpoints, flags);
11338         if (ret < 0)
11339             goto error;
11340         return ret;
11341     }
11342 
11343     virReportUnsupportedError();
11344 
11345  error:
11346     virDispatchError(dom->conn);
11347     return -1;
11348 }
11349 
11350 /**
11351  * virDomainFSThaw:
11352  * @dom: a domain object
11353  * @mountpoints: list of mount points to be thawed
11354  * @nmountpoints: the number of mount points specified in @mountpoints
11355  * @flags: extra flags; not used yet, so callers should always pass 0
11356  *
11357  * Thaw specified filesystems within the guest. If @mountpoints is NULL and
11358  * @nmountpoints is 0, every mounted filesystem on the guest is thawed.
11359  * In some drivers (e.g. QEMU driver), @mountpoints may need to be NULL.
11360  *
11361  * Returns the number of thawed filesystems on success, -1 otherwise.
11362  */
11363 int
virDomainFSThaw(virDomainPtr dom,const char ** mountpoints,unsigned int nmountpoints,unsigned int flags)11364 virDomainFSThaw(virDomainPtr dom,
11365                 const char **mountpoints,
11366                 unsigned int nmountpoints,
11367                 unsigned int flags)
11368 {
11369     VIR_DOMAIN_DEBUG(dom, "flags=0x%x", flags);
11370 
11371     virResetLastError();
11372 
11373     virCheckDomainReturn(dom, -1);
11374     virCheckReadOnlyGoto(dom->conn->flags, error);
11375     virCheckNonNullArrayArgGoto(mountpoints, nmountpoints, error);
11376 
11377     if (dom->conn->driver->domainFSThaw) {
11378         int ret = dom->conn->driver->domainFSThaw(
11379             dom, mountpoints, nmountpoints, flags);
11380         if (ret < 0)
11381             goto error;
11382         return ret;
11383     }
11384 
11385     virReportUnsupportedError();
11386 
11387  error:
11388     virDispatchError(dom->conn);
11389     return -1;
11390 }
11391 
11392 /**
11393  * virDomainGetTime:
11394  * @dom: a domain object
11395  * @seconds: domain's time in seconds
11396  * @nseconds: the nanosecond part of @seconds
11397  * @flags: extra flags; not used yet, so callers should always pass 0
11398  *
11399  * Extract information about guest time and store it into
11400  * @seconds and @nseconds. The @seconds represents the number of
11401  * seconds since the UNIX Epoch of 1970-01-01 00:00:00 in UTC.
11402  *
11403  * Please note that some hypervisors may require guest agent to
11404  * be configured and running in order to run this API.
11405  *
11406  * Returns 0 on success, -1 otherwise.
11407  */
11408 int
virDomainGetTime(virDomainPtr dom,long long * seconds,unsigned int * nseconds,unsigned int flags)11409 virDomainGetTime(virDomainPtr dom,
11410                  long long *seconds,
11411                  unsigned int *nseconds,
11412                  unsigned int flags)
11413 {
11414     VIR_DOMAIN_DEBUG(dom, "seconds=%p, nseconds=%p, flags=0x%x",
11415                      seconds, nseconds, flags);
11416 
11417     virResetLastError();
11418 
11419     virCheckDomainReturn(dom, -1);
11420     virCheckReadOnlyGoto(dom->conn->flags, error);
11421 
11422     if (dom->conn->driver->domainGetTime) {
11423         int ret = dom->conn->driver->domainGetTime(dom, seconds,
11424                                                    nseconds, flags);
11425         if (ret < 0)
11426             goto error;
11427         return ret;
11428     }
11429 
11430     virReportUnsupportedError();
11431 
11432  error:
11433     virDispatchError(dom->conn);
11434     return -1;
11435 }
11436 
11437 /**
11438  * virDomainSetTime:
11439  * @dom: a domain object
11440  * @seconds: time to set
11441  * @nseconds: the nanosecond part of @seconds
11442  * @flags: bitwise-OR of virDomainSetTimeFlags
11443  *
11444  * When a domain is suspended or restored from a file the
11445  * domain's OS has no idea that there was a big gap in the time.
11446  * Depending on how long the gap was, NTP might not be able to
11447  * resynchronize the guest.
11448  *
11449  * This API tries to set guest time to the given value. The time
11450  * to set (@seconds and @nseconds) should be in seconds relative
11451  * to the Epoch of 1970-01-01 00:00:00 in UTC.
11452  *
11453  * Please note that some hypervisors may require guest agent to
11454  * be configured and running in order to be able to run this API.
11455  *
11456  * Returns 0 on success, -1 otherwise.
11457  */
11458 int
virDomainSetTime(virDomainPtr dom,long long seconds,unsigned int nseconds,unsigned int flags)11459 virDomainSetTime(virDomainPtr dom,
11460                  long long seconds,
11461                  unsigned int nseconds,
11462                  unsigned int flags)
11463 {
11464     VIR_DOMAIN_DEBUG(dom, "seconds=%lld, nseconds=%u, flags=0x%x",
11465                      seconds, nseconds, flags);
11466 
11467     virResetLastError();
11468 
11469     virCheckDomainReturn(dom, -1);
11470     virCheckReadOnlyGoto(dom->conn->flags, error);
11471 
11472     if (dom->conn->driver->domainSetTime) {
11473         int ret = dom->conn->driver->domainSetTime(dom, seconds,
11474                                                    nseconds, flags);
11475         if (ret < 0)
11476             goto error;
11477         return ret;
11478     }
11479 
11480     virReportUnsupportedError();
11481 
11482  error:
11483     virDispatchError(dom->conn);
11484     return -1;
11485 }
11486 
11487 
11488 /**
11489  * virDomainSetUserPassword:
11490  * @dom: a domain object
11491  * @user: the username that will get a new password
11492  * @password: the password to set
11493  * @flags: bitwise-OR of virDomainSetUserPasswordFlags
11494  *
11495  * Sets the @user password to the value specified by @password.
11496  * If @flags contain VIR_DOMAIN_PASSWORD_ENCRYPTED, the password
11497  * is assumed to be encrypted by the method required by the guest OS.
11498  *
11499  * Please note that some hypervisors may require guest agent to
11500  * be configured and running in order to be able to run this API.
11501  *
11502  * Returns 0 on success, -1 otherwise.
11503  */
11504 int
virDomainSetUserPassword(virDomainPtr dom,const char * user,const char * password,unsigned int flags)11505 virDomainSetUserPassword(virDomainPtr dom,
11506                          const char *user,
11507                          const char *password,
11508                          unsigned int flags)
11509 {
11510     VIR_DOMAIN_DEBUG(dom, "user=%s, password=%s, flags=0x%x",
11511                      NULLSTR(user), NULLSTR(password), flags);
11512 
11513     virResetLastError();
11514 
11515     virCheckDomainReturn(dom, -1);
11516     virCheckReadOnlyGoto(dom->conn->flags, error);
11517     virCheckNonNullArgGoto(user, error);
11518     virCheckNonNullArgGoto(password, error);
11519 
11520     if (dom->conn->driver->domainSetUserPassword) {
11521         int ret = dom->conn->driver->domainSetUserPassword(dom, user, password,
11522                                                            flags);
11523         if (ret < 0)
11524             goto error;
11525         return ret;
11526     }
11527 
11528     virReportUnsupportedError();
11529 
11530  error:
11531     virDispatchError(dom->conn);
11532     return -1;
11533 }
11534 
11535 
11536 /**
11537  * virConnectGetDomainCapabilities:
11538  * @conn: pointer to the hypervisor connection
11539  * @emulatorbin: path to emulator
11540  * @arch: domain architecture
11541  * @machine: machine type
11542  * @virttype: virtualization type
11543  * @flags: extra flags; not used yet, so callers should always pass 0
11544  *
11545  * Prior creating a domain (for instance via virDomainCreateXML
11546  * or virDomainDefineXML) it may be suitable to know what the
11547  * underlying emulator and/or libvirt is capable of. For
11548  * instance, if host, libvirt and qemu is capable of VFIO
11549  * passthrough and so on.
11550  *
11551  * Returns NULL in case of error or an XML string
11552  * defining the capabilities.
11553  */
11554 char *
virConnectGetDomainCapabilities(virConnectPtr conn,const char * emulatorbin,const char * arch,const char * machine,const char * virttype,unsigned int flags)11555 virConnectGetDomainCapabilities(virConnectPtr conn,
11556                                 const char *emulatorbin,
11557                                 const char *arch,
11558                                 const char *machine,
11559                                 const char *virttype,
11560                                 unsigned int flags)
11561 {
11562     VIR_DEBUG("conn=%p, emulatorbin=%s, arch=%s, "
11563               "machine=%s, virttype=%s, flags=0x%x",
11564               conn, NULLSTR(emulatorbin), NULLSTR(arch),
11565               NULLSTR(machine), NULLSTR(virttype), flags);
11566 
11567     virResetLastError();
11568 
11569     virCheckConnectReturn(conn, NULL);
11570     virCheckReadOnlyGoto(conn->flags, error);
11571 
11572     if (conn->driver->connectGetDomainCapabilities) {
11573         char *ret;
11574         ret = conn->driver->connectGetDomainCapabilities(conn, emulatorbin,
11575                                                          arch, machine,
11576                                                          virttype, flags);
11577         if (!ret)
11578             goto error;
11579         VIR_DEBUG("conn=%p, ret=%s", conn, ret);
11580         return ret;
11581     }
11582 
11583     virReportUnsupportedError();
11584 
11585  error:
11586     virDispatchError(conn);
11587     return NULL;
11588 }
11589 
11590 
11591 /**
11592  * virConnectGetAllDomainStats:
11593  * @conn: pointer to the hypervisor connection
11594  * @stats: stats to return, binary-OR of virDomainStatsTypes
11595  * @retStats: Pointer that will be filled with the array of returned stats
11596  * @flags: extra flags; binary-OR of virConnectGetAllDomainStatsFlags
11597  *
11598  * Query statistics for all domains on a given connection.
11599  *
11600  * Report statistics of various parameters for a running VM according to @stats
11601  * field. The statistics are returned as an array of structures for each queried
11602  * domain. The structure contains an array of typed parameters containing the
11603  * individual statistics. The typed parameter name for each statistic field
11604  * consists of a dot-separated string containing name of the requested group
11605  * followed by a group specific description of the statistic value.
11606  *
11607  * The statistic groups are enabled using the @stats parameter which is a
11608  * binary-OR of enum virDomainStatsTypes. The following groups are available
11609  * (although not necessarily implemented for each hypervisor):
11610  *
11611  * VIR_DOMAIN_STATS_STATE:
11612  *     Return domain state and reason for entering that state. The typed
11613  *     parameter keys are in this format:
11614  *
11615  *     "state.state" - state of the VM, returned as int from virDomainState enum
11616  *     "state.reason" - reason for entering given state, returned as int from
11617  *                      virDomain*Reason enum corresponding to given state.
11618  *
11619  * VIR_DOMAIN_STATS_CPU_TOTAL:
11620  *     Return CPU statistics and usage information. The typed parameter keys
11621  *     are in this format:
11622  *
11623  *     "cpu.time" - total cpu time spent for this domain in nanoseconds
11624  *                  as unsigned long long.
11625  *     "cpu.user" - user cpu time spent in nanoseconds as unsigned long long.
11626  *     "cpu.system" - system cpu time spent in nanoseconds as unsigned long
11627  *                    long.
11628  *     "cpu.haltpoll.success.time" - halt-polling cpu usage about the VCPU polled
11629  *                                   until a virtual interrupt was delivered in
11630  *                                   nanoseconds as unsigned long long.
11631  *     "cpu.haltpoll.fail.time" - halt-polling cpu usage about the VCPU had to schedule
11632  *                                out (either because the maximum poll time was reached
11633  *                                or it needed to yield the CPU) in nanoseconds as
11634  *                                unsigned long long.
11635  *     "cpu.cache.monitor.count" - the number of cache monitors for this domain
11636  *     "cpu.cache.monitor.<num>.name" - the name of cache monitor <num>
11637  *     "cpu.cache.monitor.<num>.vcpus" - vcpu list of cache monitor <num>
11638  *     "cpu.cache.monitor.<num>.bank.count" - the number of cache banks in
11639  *                                            cache monitor <num>
11640  *     "cpu.cache.monitor.<num>.bank.<index>.id" - host allocated cache id for
11641  *                                                 bank <index> in cache
11642  *                                                 monitor <num>
11643  *     "cpu.cache.monitor.<num>.bank.<index>.bytes" - the number of bytes of
11644  *                                                    last level cache that the
11645  *                                                    domain is using on cache
11646  *                                                    bank <index>
11647  *
11648  * VIR_DOMAIN_STATS_BALLOON:
11649  *     Return memory balloon device information.
11650  *     The typed parameter keys are in this format:
11651  *
11652  *     "balloon.current" - the memory in kiB currently used
11653  *                         as unsigned long long.
11654  *     "balloon.maximum" - the maximum memory in kiB allowed
11655  *                         as unsigned long long.
11656  *     "balloon.swap_in" - the amount of data read from swap space (in KiB)
11657  *                         as unsigned long long
11658  *     "balloon.swap_out" - the amount of memory written out to swap space
11659  *                          (in KiB) as unsigned long long
11660  *     "balloon.major_fault" - the number of page faults when disk IO was
11661  *                             required as unsigned long long
11662  *     "balloon.minor_fault" - the number of other page faults
11663  *                             as unsigned long long
11664  *     "balloon.unused" - the amount of memory left unused by the system
11665  *                        (in KiB) as unsigned long long
11666  *     "balloon.available" - the amount of usable memory as seen by the domain
11667  *                           (in KiB) as unsigned long long
11668  *     "balloon.rss" - Resident Set Size of running domain's process
11669  *                     (in KiB) as unsigned long long
11670  *     "balloon.usable" - the amount of memory which can be reclaimed by balloon
11671  *                        without causing host swapping (in KiB)
11672  *                        as unsigned long long
11673  *     "balloon.last-update" - timestamp of the last update of statistics
11674  *                             (in seconds) as unsigned long long
11675  *     "balloon.disk_caches" - the amount of memory that can be reclaimed
11676  *                             without additional I/O, typically disk (in KiB)
11677  *                             as unsigned long long
11678  *     "balloon.hugetlb_pgalloc" - the number of successful huge page allocations
11679  *                                 from inside the domain via virtio balloon
11680  *                                 as unsigned long long
11681  *     "balloon.hugetlb_pgfail" - the number of failed huge page allocations
11682  *                                from inside the domain via virtio balloon
11683  *                                as unsigned long long
11684  *
11685  * VIR_DOMAIN_STATS_VCPU:
11686  *     Return virtual CPU statistics.
11687  *     Due to VCPU hotplug, the vcpu.<num>.* array could be sparse.
11688  *     The actual size of the array corresponds to "vcpu.current".
11689  *     The array size will never exceed "vcpu.maximum".
11690  *     The typed parameter keys are in this format:
11691  *
11692  *     "vcpu.current" - current number of online virtual CPUs as unsigned int.
11693  *     "vcpu.maximum" - maximum number of online virtual CPUs as unsigned int.
11694  *     "vcpu.<num>.state" - state of the virtual CPU <num>, as int
11695  *                          from virVcpuState enum.
11696  *     "vcpu.<num>.time" - virtual cpu time spent by virtual CPU <num>
11697  *                         as unsigned long long.
11698  *     "vcpu.<num>.wait" - time the vCPU <num> wants to run, but the host
11699  *                         scheduler has something else running ahead of it.
11700  *     "vcpu.<num>.halted" - virtual CPU <num> is halted, may indicate the
11701  *                           processor is idle or even disabled, depending
11702  *                           on the architecture)
11703  *     "vcpu.<num>.delay" - time the vCPU <num> thread was enqueued by the
11704  *                          host scheduler, but was waiting in the queue
11705  *                          instead of running. Exposed to the VM as a steal
11706  *                          time.
11707  *
11708  * VIR_DOMAIN_STATS_INTERFACE:
11709  *     Return network interface statistics (from domain point of view).
11710  *     The typed parameter keys are in this format:
11711  *
11712  *     "net.count" - number of network interfaces on this domain
11713  *                   as unsigned int.
11714  *     "net.<num>.name" - name of the interface <num> as string.
11715  *     "net.<num>.rx.bytes" - bytes received as unsigned long long.
11716  *     "net.<num>.rx.pkts" - packets received as unsigned long long.
11717  *     "net.<num>.rx.errs" - receive errors as unsigned long long.
11718  *     "net.<num>.rx.drop" - receive packets dropped as unsigned long long.
11719  *     "net.<num>.tx.bytes" - bytes transmitted as unsigned long long.
11720  *     "net.<num>.tx.pkts" - packets transmitted as unsigned long long.
11721  *     "net.<num>.tx.errs" - transmission errors as unsigned long long.
11722  *     "net.<num>.tx.drop" - transmit packets dropped as unsigned long long.
11723  *
11724  * VIR_DOMAIN_STATS_BLOCK:
11725  *     Return block devices statistics.  By default,
11726  *     this information is limited to the active layer of each <disk> of the
11727  *     domain (where block.count is equal to the number of disks), but adding
11728  *     VIR_CONNECT_GET_ALL_DOMAINS_STATS_BACKING to @flags will expand the
11729  *     array to cover backing chains (block.count corresponds to the number
11730  *     of host resources used together to provide the guest disks).
11731  *     The typed parameter keys are in this format:
11732  *
11733  *     "block.count" - number of block devices in the subsequent list,
11734  *                     as unsigned int.
11735  *     "block.<num>.name" - name of the block device <num> as string.
11736  *                          matches the target name (vda/sda/hda) of the
11737  *                          block device.  If the backing chain is listed,
11738  *                          this name is the same for all host resources tied
11739  *                          to the same guest device.
11740  *     "block.<num>.backingIndex" - unsigned int giving the <backingStore>
11741  *                                   index, only used when backing images
11742  *                                   are listed.
11743  *     "block.<num>.path" - string describing the source of block device <num>,
11744  *                          if it is a file or block device (omitted for network
11745  *                          sources and drives with no media inserted).
11746  *     "block.<num>.rd.reqs" - number of read requests as unsigned long long.
11747  *     "block.<num>.rd.bytes" - number of read bytes as unsigned long long.
11748  *     "block.<num>.rd.times" - total time (ns) spent on reads as
11749  *                              unsigned long long.
11750  *     "block.<num>.wr.reqs" - number of write requests as unsigned long long.
11751  *     "block.<num>.wr.bytes" - number of written bytes as unsigned long long.
11752  *     "block.<num>.wr.times" - total time (ns) spent on writes as
11753  *                              unsigned long long.
11754  *     "block.<num>.fl.reqs" - total flush requests as unsigned long long.
11755  *     "block.<num>.fl.times" - total time (ns) spent on cache flushing as
11756  *                              unsigned long long.
11757  *     "block.<num>.errors" - Xen only: the 'oo_req' value as
11758  *                            unsigned long long.
11759  *     "block.<num>.allocation" - offset of the highest written sector
11760  *                                as unsigned long long.
11761  *     "block.<num>.capacity" - logical size in bytes of the block device
11762  *                              backing image as unsigned long long.
11763  *     "block.<num>.physical" - physical size in bytes of the container of the
11764  *                              backing image as unsigned long long.
11765  *     "block.<num>.threshold" - current threshold for delivering the
11766  *                               VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD
11767  *                               event in bytes. See virDomainSetBlockThreshold.
11768  *
11769  * VIR_DOMAIN_STATS_PERF:
11770  *     Return perf event statistics.
11771  *     The typed parameter keys are in this format:
11772  *
11773  *     "perf.cmt" - the usage of l3 cache (bytes) by applications running on
11774  *                  the platform as unsigned long long. It is produced by cmt
11775  *                  perf event.
11776  *     "perf.mbmt" - the total system bandwidth (bytes/s) from one level of
11777  *                   cache to another as unsigned long long. It is produced
11778  *                   by mbmt perf event.
11779  *     "perf.mbml" - the amount of data (bytes/s) sent through the memory
11780  *                   controller on the socket as unsigned long long. It is
11781  *                   produced by mbml perf event.
11782  *     "perf.cache_misses" - the count of cache misses as unsigned long long.
11783  *                           It is produced by cache_misses perf event.
11784  *     "perf.cache_references" - the count of cache hits as unsigned long long.
11785  *                               It is produced by cache_references perf event.
11786  *     "perf.instructions" - The count of instructions as unsigned long long.
11787  *                           It is produced by instructions perf event.
11788  *     "perf.cpu_cycles" - The count of cpu cycles (total/elapsed) as an
11789  *                         unsigned long long. It is produced by cpu_cycles
11790  *                         perf event.
11791  *     "perf.branch_instructions" - The count of branch instructions as
11792  *                                  unsigned long long. It is produced by
11793  *                                  branch_instructions perf event.
11794  *     "perf.branch_misses" - The count of branch misses as unsigned long
11795  *                            long. It is produced by branch_misses perf event.
11796  *     "perf.bus_cycles" - The count of bus cycles as unsigned long
11797  *                         long. It is produced by bus_cycles perf event.
11798  *     "perf.stalled_cycles_frontend" - The count of stalled cpu cycles in the
11799  *                                      frontend of the instruction processor
11800  *                                      pipeline as unsigned long long. It is
11801  *                                      produced by stalled_cycles_frontend
11802  *                                      perf event.
11803  *     "perf.stalled_cycles_backend"  - The count of stalled cpu cycles in the
11804  *                                      backend of the instruction processor
11805  *                                      pipeline as unsigned long long. It is
11806  *                                      produced by stalled_cycles_backend
11807  *                                      perf event.
11808  *     "perf.ref_cpu_cycles" - The count of total cpu cycles not affected by
11809  *                             CPU frequency scaling by applications running
11810  *                             as unsigned long long. It is produced by the
11811  *                             ref_cpu_cycles perf event.
11812  *     "perf.cpu_clock" - The count of cpu clock time as unsigned long long.
11813  *                        It is produced by the cpu_clock perf event.
11814  *     "perf.task_clock" - The count of task clock time as unsigned long long.
11815  *                         It is produced by the task_clock perf event.
11816  *     "perf.page_faults" - The count of page faults as unsigned long long.
11817  *                          It is produced by the page_faults perf event
11818  *     "perf.context_switches" - The count of context switches as unsigned long
11819  *                               long. It is produced by the context_switches
11820  *                               perf event.
11821  *     "perf.cpu_migrations" - The count of cpu migrations, from one logical
11822  *                             processor to another, as unsigned long
11823  *                             long. It is produced by the cpu_migrations
11824  *                             perf event.
11825  *     "perf.page_faults_min" - The count of minor page faults as unsigned
11826  *                              long long. It is produced by the
11827  *                              page_faults_min perf event.
11828  *     "perf.page_faults_maj" - The count of major page faults as unsigned
11829  *                              long long. It is produced by the
11830  *                              page_faults_maj perf event.
11831  *     "perf.alignment_faults" - The count of alignment faults as unsigned
11832  *                               long long. It is produced by the
11833  *                               alignment_faults perf event
11834  *     "perf.emulation_faults" - The count of emulation faults as unsigned
11835  *                               long long. It is produced by the
11836  *                               emulation_faults perf event
11837  *
11838  * VIR_DOMAIN_STATS_IOTHREAD:
11839  *     Return IOThread statistics if available. IOThread polling is a
11840  *     timing mechanism that allows the hypervisor to generate a longer
11841  *     period of time in which the guest will perform operations on the
11842  *     CPU being used by the IOThread. The higher the value for poll-max-ns
11843  *     the longer the guest will keep the CPU. This may affect other host
11844  *     threads using the CPU. The poll-grow and poll-shrink values allow
11845  *     the hypervisor to generate a mechanism to add or remove polling time
11846  *     within the confines of 0 and poll-max-ns. For QEMU, the poll-grow is
11847  *     multiplied by the polling interval, while poll-shrink is used as a
11848  *     divisor. When not provided, QEMU may double the polling time until
11849  *     poll-max-ns is reached. When poll-shrink is 0 (zero) QEMU may reset
11850  *     the polling interval to 0 until it finds its "sweet spot". Setting
11851  *     poll-grow too large may cause frequent fluctuation of the time; however,
11852  *     this can be tempered by a high poll-shrink to reduce the polling
11853  *     interval. For example, a poll-grow of 3 will triple the polling time
11854  *     which could quickly exceed poll-max-ns; however, a poll-shrink of
11855  *     10 would cut that polling time more gradually.
11856  *
11857  *     The typed parameter keys are in this format:
11858  *
11859  *     "iothread.count" - maximum number of IOThreads in the subsequent list
11860  *                        as unsigned int. Each IOThread in the list will
11861  *                        will use it's iothread_id value as the <id>. There
11862  *                        may be fewer <id> entries than the iothread.count
11863  *                        value if the polling values are not supported.
11864  *     "iothread.<id>.poll-max-ns" - maximum polling time in ns as an unsigned
11865  *                                   long long. A 0 (zero) means polling is
11866  *                                   disabled.
11867  *     "iothread.<id>.poll-grow" - polling time factor as an unsigned int.
11868  *                                 A 0 (zero) indicates to allow the underlying
11869  *                                 hypervisor to choose how to grow the
11870  *                                 polling time.
11871  *     "iothread.<id>.poll-shrink" - polling time divisor as an unsigned int.
11872  *                                 A 0 (zero) indicates to allow the underlying
11873  *                                 hypervisor to choose how to shrink the
11874  *                                 polling time.
11875  *
11876  * VIR_DOMAIN_STATS_MEMORY:
11877  *     Return memory bandwidth statistics and the usage information. The typed
11878  *     parameter keys are in this format:
11879  *
11880  *     "memory.bandwidth.monitor.count" - the number of memory bandwidth
11881  *                                        monitors for this domain
11882  *     "memory.bandwidth.monitor.<num>.name" - the name of monitor <num>
11883  *     "memory.bandwidth.monitor.<num>.vcpus" - the vcpu list of monitor <num>
11884  *     "memory.bandwidth.monitor.<num>.node.count" - the number of memory
11885  *                                            controller in monitor <num>
11886  *     "memory.bandwidth.monitor.<num>.node.<index>.id" - host allocated memory
11887  *                                                 controller id for controller
11888  *                                                 <index> of monitor <num>
11889  *     "memory.bandwidth.monitor.<num>.node.<index>.bytes.local" - the
11890  *                       accumulative bytes consumed by @vcpus that passing
11891  *                       through the memory controller in the same processor
11892  *                       that the scheduled host CPU belongs to.
11893  *     "memory.bandwidth.monitor.<num>.node.<index>.bytes.total" - the total
11894  *                       bytes consumed by @vcpus that passing through all
11895  *                       memory controllers, either local or remote controller.
11896  *
11897  * VIR_DOMAIN_STATS_DIRTYRATE:
11898  *     Return memory dirty rate information. The typed parameter keys are in
11899  *     this format:
11900  *
11901  *     "dirtyrate.calc_status" - the status of last memory dirty rate calculation,
11902  *                               returned as int from virDomainDirtyRateStatus
11903  *                               enum.
11904  *     "dirtyrate.calc_start_time" - the start time of last memory dirty rate
11905  *                                   calculation as long long.
11906  *     "dirtyrate.calc_period" - the period of last memory dirty rate calculation
11907  *                               as int.
11908  *     "dirtyrate.megabytes_per_second" - the calculated memory dirty rate in
11909  *                                        MiB/s as long long. It is produced
11910  *                                        only if the calc_status is measured.
11911  *
11912  * Note that entire stats groups or individual stat fields may be missing from
11913  * the output in case they are not supported by the given hypervisor, are not
11914  * applicable for the current state of the guest domain, or their retrieval
11915  * was not successful.
11916  *
11917  * Using 0 for @stats returns all stats groups supported by the given
11918  * hypervisor.
11919  *
11920  * Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes
11921  * the function return error in case some of the stat types in @stats were
11922  * not recognized by the daemon.  However, even with this flag, a hypervisor
11923  * may omit individual fields within a known group if the information is not
11924  * available; as an extreme example, a supported group may produce zero
11925  * fields for offline domains if the statistics are meaningful only for a
11926  * running domain.
11927  *
11928  * Passing VIR_CONNECT_GET_ALL_DOMAINS_STATS_NOWAIT in
11929  * @flags means when libvirt is unable to fetch stats for any of
11930  * the domains (for whatever reason) only a subset of statistics
11931  * is returned for the domain.  That subset being statistics that
11932  * don't involve querying the underlying hypervisor.
11933  *
11934  * Similarly to virConnectListAllDomains, @flags can contain various flags to
11935  * filter the list of domains to provide stats for.
11936  *
11937  * VIR_CONNECT_GET_ALL_DOMAINS_STATS_ACTIVE selects online domains while
11938  * VIR_CONNECT_GET_ALL_DOMAINS_STATS_INACTIVE selects offline ones.
11939  *
11940  * VIR_CONNECT_GET_ALL_DOMAINS_STATS_PERSISTENT and
11941  * VIR_CONNECT_GET_ALL_DOMAINS_STATS_TRANSIENT allow to filter the list
11942  * according to their persistence.
11943  *
11944  * To filter the list of VMs by domain state @flags can contain
11945  * VIR_CONNECT_GET_ALL_DOMAINS_STATS_RUNNING,
11946  * VIR_CONNECT_GET_ALL_DOMAINS_STATS_PAUSED,
11947  * VIR_CONNECT_GET_ALL_DOMAINS_STATS_SHUTOFF and/or
11948  * VIR_CONNECT_GET_ALL_DOMAINS_STATS_OTHER for all other states.
11949  *
11950  * Returns the count of returned statistics structures on success, -1 on error.
11951  * The requested data are returned in the @retStats parameter. The returned
11952  * array should be freed by the caller. See virDomainStatsRecordListFree.
11953  */
11954 int
virConnectGetAllDomainStats(virConnectPtr conn,unsigned int stats,virDomainStatsRecordPtr ** retStats,unsigned int flags)11955 virConnectGetAllDomainStats(virConnectPtr conn,
11956                             unsigned int stats,
11957                             virDomainStatsRecordPtr **retStats,
11958                             unsigned int flags)
11959 {
11960     int ret = -1;
11961 
11962     VIR_DEBUG("conn=%p, stats=0x%x, retStats=%p, flags=0x%x",
11963               conn, stats, retStats, flags);
11964 
11965     virResetLastError();
11966 
11967     virCheckConnectReturn(conn, -1);
11968     virCheckNonNullArgGoto(retStats, cleanup);
11969 
11970     if (!conn->driver->connectGetAllDomainStats) {
11971         virReportUnsupportedError();
11972         goto cleanup;
11973     }
11974 
11975     ret = conn->driver->connectGetAllDomainStats(conn, NULL, 0, stats,
11976                                                  retStats, flags);
11977 
11978  cleanup:
11979     if (ret < 0)
11980         virDispatchError(conn);
11981 
11982     return ret;
11983 }
11984 
11985 
11986 /**
11987  * virDomainListGetStats:
11988  * @doms: NULL terminated array of domains
11989  * @stats: stats to return, binary-OR of virDomainStatsTypes
11990  * @retStats: Pointer that will be filled with the array of returned stats
11991  * @flags: extra flags; binary-OR of virConnectGetAllDomainStatsFlags
11992  *
11993  * Query statistics for domains provided by @doms. Note that all domains in
11994  * @doms must share the same connection.
11995  *
11996  * Report statistics of various parameters for a running VM according to @stats
11997  * field. The statistics are returned as an array of structures for each queried
11998  * domain. The structure contains an array of typed parameters containing the
11999  * individual statistics. The typed parameter name for each statistic field
12000  * consists of a dot-separated string containing name of the requested group
12001  * followed by a group specific description of the statistic value.
12002  *
12003  * The statistic groups are enabled using the @stats parameter which is a
12004  * binary-OR of enum virDomainStatsTypes. The stats groups are documented
12005  * in virConnectGetAllDomainStats.
12006  *
12007  * Using 0 for @stats returns all stats groups supported by the given
12008  * hypervisor.
12009  *
12010  * Specifying VIR_CONNECT_GET_ALL_DOMAINS_STATS_ENFORCE_STATS as @flags makes
12011  * the function return error in case some of the stat types in @stats were
12012  * not recognized by the daemon.  However, even with this flag, a hypervisor
12013  * may omit individual fields within a known group if the information is not
12014  * available; as an extreme example, a supported group may produce zero
12015  * fields for offline domains if the statistics are meaningful only for a
12016  * running domain.
12017  *
12018  * Passing VIR_CONNECT_GET_ALL_DOMAINS_STATS_NOWAIT in
12019  * @flags means when libvirt is unable to fetch stats for any of
12020  * the domains (for whatever reason) only a subset of statistics
12021  * is returned for the domain.  That subset being statistics that
12022  * don't involve querying the underlying hypervisor.
12023  *
12024  * Note that any of the domain list filtering flags in @flags may be rejected
12025  * by this function.
12026  *
12027  * Returns the count of returned statistics structures on success, -1 on error.
12028  * The requested data are returned in the @retStats parameter. The returned
12029  * array should be freed by the caller. See virDomainStatsRecordListFree.
12030  * Note that the count of returned stats may be less than the domain count
12031  * provided via @doms.
12032  */
12033 int
virDomainListGetStats(virDomainPtr * doms,unsigned int stats,virDomainStatsRecordPtr ** retStats,unsigned int flags)12034 virDomainListGetStats(virDomainPtr *doms,
12035                       unsigned int stats,
12036                       virDomainStatsRecordPtr **retStats,
12037                       unsigned int flags)
12038 {
12039     virConnectPtr conn = NULL;
12040     virDomainPtr *nextdom = doms;
12041     unsigned int ndoms = 0;
12042     int ret = -1;
12043 
12044     VIR_DEBUG("doms=%p, stats=0x%x, retStats=%p, flags=0x%x",
12045               doms, stats, retStats, flags);
12046 
12047     virResetLastError();
12048 
12049     virCheckNonNullArgGoto(doms, cleanup);
12050     virCheckNonNullArgGoto(retStats, cleanup);
12051 
12052     if (!*doms) {
12053         virReportError(VIR_ERR_INVALID_ARG,
12054                        _("doms array in %s must contain at least one domain"),
12055                        __FUNCTION__);
12056         goto cleanup;
12057     }
12058 
12059     conn = doms[0]->conn;
12060     virCheckConnectReturn(conn, -1);
12061 
12062     if (!conn->driver->connectGetAllDomainStats) {
12063         virReportUnsupportedError();
12064         goto cleanup;
12065     }
12066 
12067     while (*nextdom) {
12068         virDomainPtr dom = *nextdom;
12069 
12070         virCheckDomainGoto(dom, cleanup);
12071 
12072         if (dom->conn != conn) {
12073             virReportError(VIR_ERR_INVALID_ARG, "%s",
12074                            _("domains in 'doms' array must belong to a "
12075                              "single connection"));
12076             goto cleanup;
12077         }
12078 
12079         ndoms++;
12080         nextdom++;
12081     }
12082 
12083     ret = conn->driver->connectGetAllDomainStats(conn, doms, ndoms,
12084                                                  stats, retStats, flags);
12085 
12086  cleanup:
12087     if (ret < 0)
12088         virDispatchError(conn);
12089     return ret;
12090 }
12091 
12092 
12093 /**
12094  * virDomainStatsRecordListFree:
12095  * @stats: NULL terminated array of virDomainStatsRecords to free
12096  *
12097  * Convenience function to free a list of domain stats returned by
12098  * virDomainListGetStats and virConnectGetAllDomainStats.
12099  */
12100 void
virDomainStatsRecordListFree(virDomainStatsRecordPtr * stats)12101 virDomainStatsRecordListFree(virDomainStatsRecordPtr *stats)
12102 {
12103     virDomainStatsRecordPtr *next;
12104 
12105     if (!stats)
12106         return;
12107 
12108     for (next = stats; *next; next++) {
12109         virTypedParamsFree((*next)->params, (*next)->nparams);
12110         virDomainFree((*next)->dom);
12111         g_free(*next);
12112     }
12113 
12114     g_free(stats);
12115 }
12116 
12117 
12118 /**
12119  * virDomainGetFSInfo:
12120  * @dom: a domain object
12121  * @info: a pointer to a variable to store an array of mount points information
12122  * @flags: extra flags; not used yet, so callers should always pass 0
12123  *
12124  * Get a list of mapping information for each mounted file systems within the
12125  * specified guest and the disks.
12126  *
12127  * Returns the number of returned mount points, or -1 in case of error.
12128  * On success, the array of the information is stored into @info. The caller is
12129  * responsible for calling virDomainFSInfoFree() on each array element, then
12130  * calling free() on @info. On error, @info is set to NULL.
12131  */
12132 int
virDomainGetFSInfo(virDomainPtr dom,virDomainFSInfoPtr ** info,unsigned int flags)12133 virDomainGetFSInfo(virDomainPtr dom,
12134                    virDomainFSInfoPtr **info,
12135                    unsigned int flags)
12136 {
12137     VIR_DOMAIN_DEBUG(dom, "info=%p, flags=0x%x", info, flags);
12138 
12139     virResetLastError();
12140 
12141     virCheckDomainReturn(dom, -1);
12142     virCheckReadOnlyGoto(dom->conn->flags, error);
12143     virCheckNonNullArgGoto(info, error);
12144     *info = NULL;
12145 
12146     if (dom->conn->driver->domainGetFSInfo) {
12147         int ret = dom->conn->driver->domainGetFSInfo(dom, info, flags);
12148         if (ret < 0)
12149             goto error;
12150         return ret;
12151     }
12152 
12153     virReportUnsupportedError();
12154 
12155  error:
12156     virDispatchError(dom->conn);
12157     return -1;
12158 }
12159 
12160 
12161 /**
12162  * virDomainFSInfoFree:
12163  * @info: pointer to a FSInfo object
12164  *
12165  * Frees all the memory occupied by @info.
12166  */
12167 void
virDomainFSInfoFree(virDomainFSInfoPtr info)12168 virDomainFSInfoFree(virDomainFSInfoPtr info)
12169 {
12170     size_t i;
12171 
12172     if (!info)
12173         return;
12174 
12175     g_free(info->mountpoint);
12176     g_free(info->name);
12177     g_free(info->fstype);
12178 
12179     for (i = 0; i < info->ndevAlias; i++)
12180         g_free(info->devAlias[i]);
12181     g_free(info->devAlias);
12182 
12183     g_free(info);
12184 }
12185 
12186 /**
12187  * virDomainInterfaceAddresses:
12188  * @dom: domain object
12189  * @ifaces: pointer to an array of pointers pointing to interface objects
12190  * @source: one of the virDomainInterfaceAddressesSource constants
12191  * @flags: currently unused, pass zero
12192  *
12193  * Return a pointer to the allocated array of pointers to interfaces
12194  * present in given domain along with their IP and MAC addresses. Note that
12195  * single interface can have multiple or even 0 IP addresses.
12196  *
12197  * This API dynamically allocates the virDomainInterfacePtr struct based on
12198  * how many interfaces domain @dom has, usually there's 1:1 correlation. The
12199  * count of the interfaces is returned as the return value.
12200  *
12201  * If @source is VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE, the DHCP lease
12202  * file associated with any virtual networks will be examined to obtain
12203  * the interface addresses. This only returns data for interfaces which
12204  * are connected to virtual networks managed by libvirt.
12205  *
12206  * If @source is VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT, a configured
12207  * guest agent is needed for successful return from this API. Moreover, if
12208  * guest agent is used then the interface name is the one seen by guest OS.
12209  * To match such interface with the one from @dom XML use MAC address or IP
12210  * range.
12211  *
12212  * If @source is VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_ARP, the host
12213  * ARP table will be check to obtain the interface addresses. As
12214  * the arp cache refreshes in time, the returned ip address may
12215  * be unreachable. Depending on the route table config of the
12216  * guest, the returned mac address may be duplicated.
12217  *
12218  * Note that for some @source values some pieces of returned @ifaces
12219  * might be unset (e.g. VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_ARP does not
12220  * set IP address prefix as ARP table does not have any notion of that).
12221  *
12222  * @ifaces->name and @ifaces->hwaddr are never NULL.
12223  *
12224  * The caller *must* free @ifaces when no longer needed. Usual use case
12225  * looks like this:
12226  *
12227  *   virDomainInterfacePtr *ifaces = NULL;
12228  *   int ifaces_count = 0;
12229  *   size_t i, j;
12230  *   virDomainPtr dom = ... obtain a domain here ...;
12231  *
12232  *   if ((ifaces_count = virDomainInterfaceAddresses(dom, &ifaces,
12233  *            VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_LEASE)) < 0)
12234  *       goto cleanup;
12235  *
12236  *  ... do something with returned values, for example:
12237  *
12238  *   for (i = 0; i < ifaces_count; i++) {
12239  *       printf("name: %s", ifaces[i]->name);
12240  *       if (ifaces[i]->hwaddr)
12241  *           printf(" hwaddr: %s", ifaces[i]->hwaddr);
12242  *
12243  *       for (j = 0; j < ifaces[i]->naddrs; j++) {
12244  *           virDomainIPAddressPtr ip_addr = ifaces[i]->addrs + j;
12245  *           printf("[addr: %s prefix: %d type: %d]",
12246  *                  ip_addr->addr, ip_addr->prefix, ip_addr->type);
12247  *       }
12248  *       printf("\n");
12249  *   }
12250  *
12251  *   cleanup:
12252  *       if (ifaces && ifaces_count > 0)
12253  *           for (i = 0; i < ifaces_count; i++)
12254  *               virDomainInterfaceFree(ifaces[i]);
12255  *       free(ifaces);
12256  *
12257  * Returns the number of interfaces on success, -1 in case of error.
12258  */
12259 int
virDomainInterfaceAddresses(virDomainPtr dom,virDomainInterfacePtr ** ifaces,unsigned int source,unsigned int flags)12260 virDomainInterfaceAddresses(virDomainPtr dom,
12261                             virDomainInterfacePtr **ifaces,
12262                             unsigned int source,
12263                             unsigned int flags)
12264 {
12265     VIR_DOMAIN_DEBUG(dom, "ifaces=%p, source=%d, flags=0x%x", ifaces, source, flags);
12266 
12267     virResetLastError();
12268 
12269     if (ifaces)
12270         *ifaces = NULL;
12271     virCheckDomainReturn(dom, -1);
12272     virCheckNonNullArgGoto(ifaces, error);
12273     if (source == VIR_DOMAIN_INTERFACE_ADDRESSES_SRC_AGENT)
12274         virCheckReadOnlyGoto(dom->conn->flags, error);
12275 
12276     if (dom->conn->driver->domainInterfaceAddresses) {
12277         int ret;
12278         ret = dom->conn->driver->domainInterfaceAddresses(dom, ifaces, source, flags);
12279         if (ret < 0)
12280             goto error;
12281         return ret;
12282     }
12283 
12284     virReportError(VIR_ERR_NO_SUPPORT, __FUNCTION__);
12285 
12286  error:
12287     virDispatchError(dom->conn);
12288     return -1;
12289 }
12290 
12291 
12292 /**
12293  * virDomainInterfaceFree:
12294  * @iface: an interface object
12295  *
12296  * Free the interface object. The data structure is
12297  * freed and should not be used thereafter. If @iface
12298  * is NULL, then this method has no effect.
12299  */
12300 void
virDomainInterfaceFree(virDomainInterfacePtr iface)12301 virDomainInterfaceFree(virDomainInterfacePtr iface)
12302 {
12303     size_t i;
12304 
12305     if (!iface)
12306         return;
12307 
12308     g_free(iface->name);
12309     g_free(iface->hwaddr);
12310 
12311     for (i = 0; i < iface->naddrs; i++)
12312         g_free(iface->addrs[i].addr);
12313     g_free(iface->addrs);
12314 
12315     g_free(iface);
12316 }
12317 
12318 
12319 /**
12320  * virDomainGetGuestVcpus:
12321  * @domain: pointer to domain object
12322  * @params: pointer that will be filled with an array of typed parameters
12323  * @nparams: pointer filled with number of elements in @params
12324  * @flags: currently unused, callers shall pass 0
12325  *
12326  * Queries the guest agent for state and information regarding vCPUs from
12327  * guest's perspective. The reported data depends on the guest agent
12328  * implementation.
12329  *
12330  * Reported fields stored in @params:
12331  * 'vcpus': string containing bitmap representing vCPU ids as reported by the
12332  *          guest
12333  * 'online': string containing bitmap representing online vCPUs as reported
12334  *           by the guest agent.
12335  * 'offlinable': string containing bitmap representing ids of vCPUs that can be
12336  *               offlined
12337  *
12338  * This API requires the VM to run. The caller is responsible for calling
12339  * virTypedParamsFree to free memory returned in @params.
12340  *
12341  * Returns 0 on success, -1 on error.
12342  */
12343 int
virDomainGetGuestVcpus(virDomainPtr domain,virTypedParameterPtr * params,unsigned int * nparams,unsigned int flags)12344 virDomainGetGuestVcpus(virDomainPtr domain,
12345                        virTypedParameterPtr *params,
12346                        unsigned int *nparams,
12347                        unsigned int flags)
12348 {
12349     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p, flags=0x%x",
12350                      params, nparams, flags);
12351 
12352     virResetLastError();
12353 
12354     virCheckDomainReturn(domain, -1);
12355     virCheckReadOnlyGoto(domain->conn->flags, error);
12356 
12357     virCheckNonNullArgGoto(params, error);
12358     virCheckNonNullArgGoto(nparams, error);
12359 
12360     if (domain->conn->driver->domainGetGuestVcpus) {
12361         int ret;
12362         ret = domain->conn->driver->domainGetGuestVcpus(domain, params, nparams,
12363                                                         flags);
12364         if (ret < 0)
12365             goto error;
12366         return ret;
12367     }
12368 
12369     virReportUnsupportedError();
12370 
12371  error:
12372     virDispatchError(domain->conn);
12373     return -1;
12374 }
12375 
12376 
12377 /**
12378  * virDomainSetGuestVcpus:
12379  * @domain: pointer to domain object
12380  * @cpumap: text representation of a bitmap of vcpus to set
12381  * @state: 0 to disable/1 to enable cpus described by @cpumap
12382  * @flags: currently unused, callers shall pass 0
12383  *
12384  * Sets state of individual vcpus described by @cpumap via guest agent. Other
12385  * vcpus are not modified.
12386  *
12387  * This API requires the VM to run. Various hypervisors or guest agent
12388  * implementation may limit to operate on just 1 vCPU per call.
12389  *
12390  * @cpumap is a list of vCPU numbers. Its syntax is a comma separated list and
12391  * a special markup using '-' and '^' (ex. '0-4', '0-3,^2'). The '-' denotes
12392  * the range and the '^' denotes exclusive. The expression is sequentially
12393  * evaluated, so "0-15,^8" is identical to "9-14,0-7,15" but not identical to
12394  * "^8,0-15".
12395  *
12396  * Note that OSes (notably Linux) may require vCPU 0 to stay online to support
12397  * low-level features a S3 sleep.
12398  *
12399  * Returns 0 on success, -1 on error.
12400  */
12401 int
virDomainSetGuestVcpus(virDomainPtr domain,const char * cpumap,int state,unsigned int flags)12402 virDomainSetGuestVcpus(virDomainPtr domain,
12403                        const char *cpumap,
12404                        int state,
12405                        unsigned int flags)
12406 {
12407     VIR_DOMAIN_DEBUG(domain, "cpumap='%s' state=%d flags=0x%x",
12408                      NULLSTR(cpumap), state, flags);
12409 
12410     virResetLastError();
12411 
12412     virCheckDomainReturn(domain, -1);
12413     virCheckReadOnlyGoto(domain->conn->flags, error);
12414 
12415     virCheckNonNullArgGoto(cpumap, error);
12416 
12417     if (domain->conn->driver->domainSetGuestVcpus) {
12418         int ret;
12419         ret = domain->conn->driver->domainSetGuestVcpus(domain, cpumap, state,
12420                                                         flags);
12421         if (ret < 0)
12422             goto error;
12423         return ret;
12424     }
12425 
12426     virReportUnsupportedError();
12427 
12428  error:
12429     virDispatchError(domain->conn);
12430     return -1;
12431 }
12432 
12433 
12434 /**
12435  * virDomainSetVcpu:
12436  * @domain: pointer to domain object
12437  * @vcpumap: text representation of a bitmap of vcpus to set
12438  * @state: 0 to disable/1 to enable cpus described by @vcpumap
12439  * @flags: bitwise-OR of virDomainModificationImpact
12440  *
12441  * Enables/disables individual vcpus described by @vcpumap in the hypervisor.
12442  *
12443  * Various hypervisor implementations may limit to operate on just 1
12444  * hotpluggable entity (which may contain multiple vCPUs on certain platforms).
12445  *
12446  * Note that OSes and hypervisors may require vCPU 0 to stay online.
12447  *
12448  * Returns 0 on success, -1 on error.
12449  */
12450 int
virDomainSetVcpu(virDomainPtr domain,const char * vcpumap,int state,unsigned int flags)12451 virDomainSetVcpu(virDomainPtr domain,
12452                  const char *vcpumap,
12453                  int state,
12454                  unsigned int flags)
12455 {
12456     VIR_DOMAIN_DEBUG(domain, "vcpumap='%s' state=%i flags=0x%x",
12457                      NULLSTR(vcpumap), state, flags);
12458 
12459     virResetLastError();
12460 
12461     virCheckDomainReturn(domain, -1);
12462     virCheckReadOnlyGoto(domain->conn->flags, error);
12463 
12464     virCheckNonNullArgGoto(vcpumap, error);
12465 
12466     if (domain->conn->driver->domainSetVcpu) {
12467         int ret;
12468         ret = domain->conn->driver->domainSetVcpu(domain, vcpumap, state, flags);
12469         if (ret < 0)
12470             goto error;
12471         return ret;
12472     }
12473 
12474     virReportUnsupportedError();
12475 
12476  error:
12477     virDispatchError(domain->conn);
12478     return -1;
12479 }
12480 
12481 /**
12482  * virDomainGetGuestInfo:
12483  * @domain: pointer to domain object
12484  * @types: types of information to return, binary-OR of virDomainGuestInfoTypes
12485  * @params: location to store the guest info parameters
12486  * @nparams: number of items in @params
12487  * @flags: currently unused, set to 0
12488  *
12489  * Queries the guest agent for the various information about the guest system.
12490  * The reported data depends on the guest agent implementation. The information
12491  * is returned as an array of typed parameters containing the individual
12492  * parameters. The parameter name for each information field consists of a
12493  * dot-separated string containing the name of the requested group followed by
12494  * a group-specific description of the statistic value.
12495  *
12496  * The information groups are enabled using the @types parameter which is a
12497  * binary-OR of enum virDomainGuestInfoTypes. The following groups are available
12498  * (although not necessarily implemented for each hypervisor):
12499  *
12500  * VIR_DOMAIN_GUEST_INFO_USERS:
12501  *  returns information about users that are currently logged in within the
12502  *  guest domain. The typed parameter keys are in this format:
12503  *
12504  *      "user.count" - the number of active users on this domain as an
12505  *                     unsigned int
12506  *      "user.<num>.name" - username of the user as a string
12507  *      "user.<num>.domain" - domain of the user as a string (may only be
12508  *                            present on certain guest types)
12509  *      "user.<num>.login-time" - the login time of a user in milliseconds
12510  *                                since the epoch as unsigned long long
12511  *
12512  * VIR_DOMAIN_GUEST_INFO_OS:
12513  *  Return information about the operating system running within the guest. The
12514  *  typed parameter keys are in this format:
12515  *
12516  *      "os.id" - a string identifying the operating system
12517  *      "os.name" - the name of the operating system, suitable for presentation
12518  *                  to a user, as a string
12519  *      "os.pretty-name" - a pretty name for the operating system, suitable for
12520  *                         presentation to a user, as a string
12521  *      "os.version" - the version of the operating system suitable for
12522  *                     presentation to a user, as a string
12523  *      "os.version-id" - the version id of the operating system suitable for
12524  *                        processing by scripts, as a string
12525  *      "os.kernel-release" - the release of the operating system kernel, as a
12526  *                            string
12527  *      "os.kernel-version" - the version of the operating system kernel, as a
12528  *                            string
12529  *      "os.machine" - the machine hardware name as a string
12530  *      "os.variant" - a specific variant or edition of the operating system
12531  *                     suitable for presentation to a user, as a string
12532  *      "os.variant-id" - the id for a specific variant or edition of the
12533  *                        operating system, as a string
12534  *
12535  * VIR_DOMAIN_GUEST_INFO_TIMEZONE:
12536  *  Returns information about the timezone within the domain. The typed
12537  *  parameter keys are in this format:
12538  *
12539  *      "timezone.name" - the name of the timezone as a string
12540  *      "timezone.offset" - the offset to UTC in seconds as an int
12541  *
12542  * VIR_DOMAIN_GUEST_INFO_FILESYSTEM:
12543  *  Returns information about the filesystems within the domain.  The typed
12544  *  parameter keys are in this format:
12545  *
12546  *      "fs.count" - the number of filesystems defined on this domain
12547  *                   as an unsigned int
12548  *      "fs.<num>.mountpoint" - the path to the mount point for the filesystem
12549  *      "fs.<num>.name" - device name in the guest (e.g. "sda1")
12550  *      "fs.<num>.fstype" - the type of filesystem
12551  *      "fs.<num>.total-bytes" - the total size of the filesystem
12552  *      "fs.<num>.used-bytes" - the number of bytes used in the filesystem
12553  *      "fs.<num>.disk.count" - the number of disks targeted by this filesystem
12554  *      "fs.<num>.disk.<num>.alias" - the device alias of the disk (e.g. sda)
12555  *      "fs.<num>.disk.<num>.serial" - the serial number of the disk
12556  *      "fs.<num>.disk.<num>.device" - the device node of the disk
12557  *
12558  * VIR_DOMAIN_GUEST_INFO_DISKS:
12559  *  Returns information about the disks within the domain.  The typed
12560  *  parameter keys are in this format:
12561  *
12562  *      "disk.count" - the number of disks defined on this domain
12563  *                      as an unsigned int
12564  *      "disk.<num>.name" - device node (Linux) or device UNC (Windows)
12565  *      "disk.<num>.partition" - whether this is a partition or disk
12566  *      "disk.<num>.dependency.count" - the number of device dependencies
12567  *                      e.g. for LVs of the LVM this will
12568  *                      hold the list of PVs, for LUKS encrypted volume this will
12569  *                      contain the disk where the volume is placed. (Linux)
12570  *      "disk.<num>.dependency.<num>.name" - a dependency
12571  *      "disk.<num>.serial" - optional disk serial number (as string)
12572  *      "disk.<num>.alias" - the device alias of the disk (e.g. sda)
12573  *      "disk.<num>.guest_alias" - optional alias assigned to the disk, on Linux
12574  *                      this is a name assigned by device mapper
12575  *
12576  * VIR_DOMAIN_GUEST_INFO_HOSTNAME:
12577  *  Returns information about the hostname of the domain. The typed
12578  *  parameter keys are in this format:
12579  *
12580  *      "hostname" - the hostname of the domain
12581  *
12582  * VIR_DOMAIN_GUEST_INFO_INTERFACES:
12583  *  Returns information about the interfaces within the domain. The typed
12584  *  parameter keys are in this format:
12585  *
12586  *      "if.count" - the number of interfaces defined on this domain
12587  *      "if.<num>.name" - name in the guest (e.g. ``eth0``) for interface <num>
12588  *      "if.<num>.hwaddr" - hardware address in the guest for interface <num>
12589  *      "if.<num>.addr.count - the number of IP addresses of interface <num>
12590  *      "if.<num>.addr.<num1>.type" - the IP address type of addr <num1> (e.g. ipv4)
12591  *      "if.<num>.addr.<num1>.addr" - the IP address of addr <num1>
12592  *      "if.<num>.addr.<num1>.prefix" - the prefix of IP address of addr <num1>
12593  *
12594  * Using 0 for @types returns all information groups supported by the given
12595  * hypervisor.
12596  *
12597  * This API requires the VM to run. The caller is responsible for calling
12598  * virTypedParamsFree to free memory returned in @params.
12599  *
12600  * Returns 0 on success, -1 on error.
12601  */
virDomainGetGuestInfo(virDomainPtr domain,unsigned int types,virTypedParameterPtr * params,int * nparams,unsigned int flags)12602 int virDomainGetGuestInfo(virDomainPtr domain,
12603                           unsigned int types,
12604                           virTypedParameterPtr *params,
12605                           int *nparams,
12606                           unsigned int flags)
12607 {
12608     VIR_DOMAIN_DEBUG(domain, "types=0x%x, params=%p, nparams=%p, flags=0x%x",
12609                      types, params, nparams, flags);
12610 
12611     virResetLastError();
12612 
12613     virCheckDomainReturn(domain, -1);
12614     virCheckReadOnlyGoto(domain->conn->flags, error);
12615 
12616     virCheckNonNullArgGoto(params, error);
12617     virCheckNonNullArgGoto(nparams, error);
12618 
12619     if (domain->conn->driver->domainGetGuestInfo) {
12620         int ret;
12621         ret = domain->conn->driver->domainGetGuestInfo(domain, types,
12622                                                        params, nparams, flags);
12623 
12624         if (ret < 0)
12625             goto error;
12626         return ret;
12627     }
12628 
12629     virReportUnsupportedError();
12630 
12631  error:
12632     virDispatchError(domain->conn);
12633     return -1;
12634 }
12635 
12636 /**
12637  * virDomainSetBlockThreshold:
12638  * @domain: pointer to domain object
12639  * @dev: string specifying the block device or backing chain element
12640  * @threshold: threshold in bytes when to fire the event
12641  * @flags: currently unused, callers should pass 0
12642  *
12643  * Set the threshold level for delivering the
12644  * VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD if the device or backing chain element
12645  * described by @dev is written beyond the set threshold level. The threshold
12646  * level is unset once the event fires. The event might not be delivered at all
12647  * if libvirtd was not running at the moment when the threshold was reached.
12648  * Note that if the threshold level is reached for a top level image, the event
12649  * is emitted for @dev corresponding to the disk target, and may also be reported
12650  * with @dev corresponding to the disk target with an index corresponding to the
12651  * 'index' attribute of 'source' in the live VM XML if the attribute is present.
12652  *
12653  * @dev can either be a disk target name (vda, sda) or disk target with index (
12654  * vda[4]). Without the index the top image in the backing chain will have the
12655  * threshold set. The index corresponds to the 'index' attribute reported in the
12656  * live VM XML for 'backingStore' or 'source' elements of a disk. If index is
12657  * given the threshold is set for the corresponding image.
12658  *
12659  * In case when @dev does not contain index the
12660  * VIR_DOMAIN_EVENT_ID_BLOCK_THRESHOLD event may be emitted twice, once for the
12661  * disk device target without index and once containing the index.
12662  *
12663  * Note that the threshold event can be registered also for destinations of a
12664  * 'virDomainBlockCopy' destination by using the 'index' of the 'mirror' source.
12665  *
12666  * Hypervisors report the last written sector of an image in the bulk stats API
12667  * (virConnectGetAllDomainStats/virDomainListGetStats) as
12668  * "block.<num>.allocation" in the VIR_DOMAIN_STATS_BLOCK group. The current
12669  * threshold value is reported as "block.<num>.threshold".
12670  *
12671  * This event allows to use thin-provisioned storage which needs management
12672  * tools to grow it without the need for polling of the data.
12673  *
12674  * Returns 0 if the operation has started, -1 on failure.
12675  */
12676 int
virDomainSetBlockThreshold(virDomainPtr domain,const char * dev,unsigned long long threshold,unsigned int flags)12677 virDomainSetBlockThreshold(virDomainPtr domain,
12678                            const char *dev,
12679                            unsigned long long threshold,
12680                            unsigned int flags)
12681 {
12682     VIR_DOMAIN_DEBUG(domain, "dev='%s' threshold=%llu flags=0x%x",
12683                      NULLSTR(dev), threshold, flags);
12684 
12685     virResetLastError();
12686 
12687     virCheckDomainReturn(domain, -1);
12688     virCheckReadOnlyGoto(domain->conn->flags, error);
12689 
12690     virCheckNonNullArgGoto(dev, error);
12691 
12692     if (domain->conn->driver->domainSetBlockThreshold) {
12693         int ret;
12694         ret = domain->conn->driver->domainSetBlockThreshold(domain, dev,
12695                                                             threshold, flags);
12696         if (ret < 0)
12697             goto error;
12698         return ret;
12699     }
12700 
12701     virReportUnsupportedError();
12702 
12703  error:
12704     virDispatchError(domain->conn);
12705     return -1;
12706 }
12707 
12708 
12709 /**
12710  * virDomainSetLifecycleAction:
12711  * @domain: pointer to domain object
12712  * @type: the lifecycle type from virDomainLifecycle
12713  * @action: the action type from virDomainLifecycleAction
12714  * @flags: bitwise-OR of virDomainModificationImpact
12715  *
12716  * Changes the actions of lifecycle events for domain represented as
12717  * <on_$type>$action</on_$type> in the domain XML.
12718  *
12719  * QEMU driver has a limitation that if all lifecycle events are set
12720  * to destroy when the domain is started, it's not possible to change
12721  * any action for running domain.
12722  *
12723  * Returns 0 on success, -1 on failure.
12724  */
virDomainSetLifecycleAction(virDomainPtr domain,unsigned int type,unsigned int action,unsigned int flags)12725 int virDomainSetLifecycleAction(virDomainPtr domain,
12726                                 unsigned int type,
12727                                 unsigned int action,
12728                                 unsigned int flags)
12729 {
12730     VIR_DOMAIN_DEBUG(domain, "type='%u' action='%u' flags='0x%x'",
12731                      type, action, flags);
12732 
12733     virResetLastError();
12734 
12735     virCheckDomainReturn(domain, -1);
12736     virCheckReadOnlyGoto(domain->conn->flags, error);
12737 
12738     if (type >= VIR_DOMAIN_LIFECYCLE_LAST) {
12739         virReportError(VIR_ERR_INVALID_ARG,
12740                        _("invalid lifecycle type '%u'"), type);
12741         goto error;
12742     }
12743 
12744     if (action >= VIR_DOMAIN_LIFECYCLE_ACTION_LAST) {
12745         virReportError(VIR_ERR_INVALID_ARG,
12746                        _("invalid lifecycle action '%u'"), action);
12747         goto error;
12748     }
12749 
12750     if (domain->conn->driver->domainSetLifecycleAction) {
12751         int ret;
12752         ret = domain->conn->driver->domainSetLifecycleAction(domain,
12753                                                              type,
12754                                                              action,
12755                                                              flags);
12756         if (ret < 0)
12757             goto error;
12758         return ret;
12759     }
12760 
12761     virReportUnsupportedError();
12762 
12763  error:
12764     virDispatchError(domain->conn);
12765     return -1;
12766 }
12767 
12768 /**
12769  * virDomainGetLaunchSecurityInfo:
12770  * @domain: a domain object
12771  * @params: where to store security info
12772  * @nparams: number of items in @params
12773  * @flags: currently used, set to 0.
12774  *
12775  * Get the launch security info. In case of the SEV guest, this will
12776  * return the launch measurement.
12777  *
12778  * Returns -1 in case of failure, 0 in case of success.
12779  */
virDomainGetLaunchSecurityInfo(virDomainPtr domain,virTypedParameterPtr * params,int * nparams,unsigned int flags)12780 int virDomainGetLaunchSecurityInfo(virDomainPtr domain,
12781                                    virTypedParameterPtr *params,
12782                                    int *nparams,
12783                                    unsigned int flags)
12784 {
12785     virConnectPtr conn = domain->conn;
12786     int rc;
12787 
12788     VIR_DOMAIN_DEBUG(domain, "params=%p, nparams=%p flags=0x%x",
12789                      params, nparams, flags);
12790 
12791     virResetLastError();
12792 
12793     virCheckDomainReturn(domain, -1);
12794     virCheckNonNullArgGoto(params, error);
12795     virCheckNonNullArgGoto(nparams, error);
12796     virCheckReadOnlyGoto(conn->flags, error);
12797 
12798     rc = VIR_DRV_SUPPORTS_FEATURE(domain->conn->driver, domain->conn,
12799                                   VIR_DRV_FEATURE_TYPED_PARAM_STRING);
12800     if (rc < 0)
12801         goto error;
12802     if (rc)
12803         flags |= VIR_TYPED_PARAM_STRING_OKAY;
12804 
12805     if (conn->driver->domainGetLaunchSecurityInfo) {
12806         int ret;
12807         ret = conn->driver->domainGetLaunchSecurityInfo(domain, params,
12808                                                         nparams, flags);
12809         if (ret < 0)
12810             goto error;
12811         return ret;
12812     }
12813     virReportUnsupportedError();
12814 
12815  error:
12816     virDispatchError(domain->conn);
12817     return -1;
12818 }
12819 
12820 
12821 /**
12822  * virDomainAgentSetResponseTimeout:
12823  * @domain: a domain object
12824  * @timeout: timeout in seconds
12825  * @flags: extra flags; not used yet, so callers should always pass 0
12826  *
12827  * Set how long to wait for a response from guest agent commands. By default,
12828  * agent commands block forever waiting for a response.
12829  *
12830  * @timeout must be a value from virDomainAgentResponseTimeoutValues or
12831  * positive:
12832  *
12833  *   VIR_DOMAIN_AGENT_RESPONSE_TIMEOUT_BLOCK(-2): meaning to block forever
12834  *      waiting for a result.
12835  *   VIR_DOMAIN_AGENT_RESPONSE_TIMEOUT_DEFAULT(-1): use default timeout value.
12836  *   VIR_DOMAIN_AGENT_RESPONSE_TIMEOUT_NOWAIT(0): does not wait.
12837  *   positive value: wait for @timeout seconds
12838  *
12839  * Returns 0 on success, -1 on failure
12840  */
12841 int
virDomainAgentSetResponseTimeout(virDomainPtr domain,int timeout,unsigned int flags)12842 virDomainAgentSetResponseTimeout(virDomainPtr domain,
12843                                  int timeout,
12844                                  unsigned int flags)
12845 {
12846     virConnectPtr conn;
12847 
12848     VIR_DOMAIN_DEBUG(domain, "timeout=%i, flags=0x%x",
12849                      timeout, flags);
12850 
12851     virResetLastError();
12852 
12853     virCheckDomainReturn(domain, -1);
12854     conn = domain->conn;
12855 
12856     virCheckReadOnlyGoto(conn->flags, error);
12857 
12858     if (conn->driver->domainAgentSetResponseTimeout) {
12859         if (conn->driver->domainAgentSetResponseTimeout(domain, timeout, flags) < 0)
12860             goto error;
12861         return 0;
12862     }
12863 
12864     virReportUnsupportedError();
12865 
12866  error:
12867     virDispatchError(conn);
12868     return -1;
12869 }
12870 
12871 
12872 /**
12873  * virDomainBackupBegin:
12874  * @domain: a domain object
12875  * @backupXML: description of the requested backup
12876  * @checkpointXML: description of a checkpoint to create or NULL
12877  * @flags: bitwise or of virDomainBackupBeginFlags
12878  *
12879  * Start a point-in-time backup job for the specified disks of a
12880  * running domain.
12881  *
12882  * A backup job is a domain job and thus mutually exclusive with any other
12883  * domain job such as migration.
12884  *
12885  * For now, backup jobs are also mutually exclusive with any
12886  * other block job on the same device, although this restriction may
12887  * be lifted in a future release. Progress of the backup job can be
12888  * tracked via virDomainGetJobStats(). Completion of the job is also announced
12889  * asynchronously via VIR_DOMAIN_EVENT_ID_JOB_COMPLETED event.
12890  *
12891  * There are two fundamental backup approaches. The first, called a
12892  * push model, instructs the hypervisor to copy the state of the guest
12893  * disk to the designated storage destination (which may be on the
12894  * local file system or a network device). In this mode, the
12895  * hypervisor writes the content of the guest disk to the destination,
12896  * then emits VIR_DOMAIN_EVENT_ID_JOB_COMPLETED when the backup is
12897  * either complete or failed (the backup image is invalid if the job
12898  * fails or virDomainAbortJob() is used prior to the event being
12899  * emitted). This kind of the job finishes automatically. Users can
12900  * determine success by using virDomainGetJobStats() with
12901  * VIR_DOMAIN_JOB_STATS_COMPLETED flag.
12902  *
12903  * The second, called a pull model, instructs the hypervisor to expose
12904  * the state of the guest disk over an NBD export. A third-party
12905  * client can then connect to this export and read whichever portions
12906  * of the disk it desires.  In this mode libvirt has to be informed via
12907  * virDomainAbortJob() when the third-party NBD client is done and the backup
12908  * resources can be released.
12909  *
12910  * The @backupXML parameter contains details about the backup in the top-level
12911  * element <domainbackup>, including which backup mode to use, whether the
12912  * backup is incremental from a previous checkpoint, which disks
12913  * participate in the backup, the destination for a push model backup,
12914  * and the temporary storage and NBD server details for a pull model
12915  * backup.
12916  *
12917  * virDomainBackupGetXMLDesc() can be called to learn actual
12918  * values selected.  For more information, see
12919  * formatcheckpoint.html#BackupAttributes.
12920  *
12921  * The @checkpointXML parameter is optional; if non-NULL, then libvirt
12922  * behaves as if virDomainCheckpointCreateXML() were called to create
12923  * a checkpoint atomically covering the same point in time as the
12924  * backup.
12925  *
12926  * The VIR_DOMAIN_BACKUP_BEGIN_REUSE_EXTERNAL specifies that the output or
12927  * temporary files described by the @backupXML document were created by the
12928  * caller with correct format and size to hold the backup or temporary data.
12929  *
12930  * The creation of a new checkpoint allows for future incremental backups.
12931  * Note that some hypervisors may require a particular disk format, such as
12932  * qcow2, in order to take advantage of checkpoints, while allowing arbitrary
12933  * formats if checkpoints are not involved.
12934  *
12935  * Returns 0 on success or -1 on failure.
12936  */
12937 int
virDomainBackupBegin(virDomainPtr domain,const char * backupXML,const char * checkpointXML,unsigned int flags)12938 virDomainBackupBegin(virDomainPtr domain,
12939                      const char *backupXML,
12940                      const char *checkpointXML,
12941                      unsigned int flags)
12942 {
12943     virConnectPtr conn;
12944 
12945     VIR_DOMAIN_DEBUG(domain, "backupXML=%s, checkpointXML=%s, flags=0x%x",
12946                      NULLSTR(backupXML), NULLSTR(checkpointXML), flags);
12947 
12948     virResetLastError();
12949 
12950     virCheckDomainReturn(domain, -1);
12951     conn = domain->conn;
12952 
12953     virCheckNonNullArgGoto(backupXML, error);
12954     virCheckReadOnlyGoto(conn->flags, error);
12955 
12956     if (conn->driver->domainBackupBegin) {
12957         int ret;
12958         ret = conn->driver->domainBackupBegin(domain, backupXML, checkpointXML,
12959                                               flags);
12960         if (ret < 0)
12961             goto error;
12962         return ret;
12963     }
12964 
12965     virReportUnsupportedError();
12966  error:
12967     virDispatchError(conn);
12968     return -1;
12969 }
12970 
12971 
12972 /**
12973  * virDomainBackupGetXMLDesc:
12974  * @domain: a domain object
12975  * @flags: extra flags; not used yet, so callers should always pass 0
12976  *
12977  * Queries the configuration of the active backup job.
12978  *
12979  * In some cases, a user can start a backup job without supplying all
12980  * details and rely on libvirt to fill in the rest (for example,
12981  * selecting the port used for an NBD export). This API can then be
12982  * used to learn what default values were chosen.
12983  *
12984  * Returns a NUL-terminated UTF-8 encoded XML instance or NULL in
12985  * case of error.  The caller must free() the returned value.
12986  */
12987 char *
virDomainBackupGetXMLDesc(virDomainPtr domain,unsigned int flags)12988 virDomainBackupGetXMLDesc(virDomainPtr domain,
12989                           unsigned int flags)
12990 {
12991     virConnectPtr conn;
12992 
12993     VIR_DOMAIN_DEBUG(domain, "flags=0x%x", flags);
12994 
12995     virResetLastError();
12996 
12997     virCheckDomainReturn(domain, NULL);
12998     conn = domain->conn;
12999 
13000     if (conn->driver->domainBackupGetXMLDesc) {
13001         char *ret;
13002         ret = conn->driver->domainBackupGetXMLDesc(domain, flags);
13003         if (!ret)
13004             goto error;
13005         return ret;
13006     }
13007 
13008     virReportUnsupportedError();
13009  error:
13010     virDispatchError(conn);
13011     return NULL;
13012 }
13013 
13014 
13015 /**
13016  * virDomainAuthorizedSSHKeysGet:
13017  * @domain: a domain object
13018  * @user: user to list keys for
13019  * @keys: pointer to a variable to store authorized keys
13020  * @flags: extra flags; not used yet, so callers should always pass 0
13021  *
13022  * For given @user in @domain fetch list of public SSH authorized
13023  * keys and store them into @keys array which is allocated upon
13024  * successful return and is NULL terminated. The caller is
13025  * responsible for freeing @keys when no longer needed.
13026  *
13027  * Keys are in OpenSSH format (see sshd(8)) but from libvirt's
13028  * point of view are opaque strings, i.e. not interpreted.
13029  *
13030  * Please note that some hypervisors may require guest agent to
13031  * be configured and running in order to be able to run this API.
13032  *
13033  * Returns: number of keys stored in @keys,
13034  *          -1 otherwise.
13035  */
13036 int
virDomainAuthorizedSSHKeysGet(virDomainPtr domain,const char * user,char *** keys,unsigned int flags)13037 virDomainAuthorizedSSHKeysGet(virDomainPtr domain,
13038                               const char *user,
13039                               char ***keys,
13040                               unsigned int flags)
13041 {
13042     virConnectPtr conn;
13043 
13044     VIR_DOMAIN_DEBUG(domain, "user=%s, keys=%p, flags=0x%x",
13045                      user, keys, flags);
13046 
13047     virResetLastError();
13048 
13049     virCheckDomainReturn(domain, -1);
13050     conn = domain->conn;
13051     virCheckNonNullArgGoto(user, error);
13052     virCheckNonNullArgGoto(keys, error);
13053 
13054     virCheckReadOnlyGoto(conn->flags, error);
13055 
13056     if (conn->driver->domainAuthorizedSSHKeysGet) {
13057         int ret;
13058         ret = conn->driver->domainAuthorizedSSHKeysGet(domain, user,
13059                                                        keys, flags);
13060         if (ret < 0)
13061             goto error;
13062         return ret;
13063     }
13064 
13065     virReportUnsupportedError();
13066  error:
13067     virDispatchError(conn);
13068     return -1;
13069 }
13070 
13071 
13072 /**
13073  * virDomainAuthorizedSSHKeysSet:
13074  * @domain: a domain object
13075  * @user: user to add keys for
13076  * @keys: authorized keys to set
13077  * @nkeys: number of keys in @keys array
13078  * @flags: bitwise or of virDomainAuthorizedSSHKeysSetFlags
13079  *
13080  * For given @user in @domain set @keys in authorized keys file.
13081  * Any previous content of the file is overwritten with new keys.
13082  * That is, if this API is called with @nkeys = 0, @keys = NULL
13083  * and @flags = 0 then the authorized keys file for @user is
13084  * cleared out.
13085  *
13086  * Keys are in OpenSSH format (see sshd(8)) but from libvirt's
13087  * point of view are opaque strings, i.e. not interpreted.
13088  *
13089  * If VIR_DOMAIN_AUTHORIZED_SSH_KEYS_SET_APPEND flag is set
13090  * then the file is not overwritten and new @keys are appended
13091  * instead.
13092  *
13093  * If VIR_DOMAIN_AUTHORIZED_SSH_KEYS_SET_REMOVE flag is set then
13094  * instead of adding any new keys, provided @keys are removed
13095  * from the file. It's not considered error if the key doesn't
13096  * exist.
13097  *
13098  * Please note that some hypervisors may require guest agent to
13099  * be configured and running in order to be able to run this API.
13100  *
13101  * Returns: 0 on success,
13102  *         -1 otherwise.
13103  */
13104 int
virDomainAuthorizedSSHKeysSet(virDomainPtr domain,const char * user,const char ** keys,unsigned int nkeys,unsigned int flags)13105 virDomainAuthorizedSSHKeysSet(virDomainPtr domain,
13106                               const char *user,
13107                               const char **keys,
13108                               unsigned int nkeys,
13109                               unsigned int flags)
13110 {
13111     virConnectPtr conn;
13112 
13113     VIR_DOMAIN_DEBUG(domain, "user=%s, keys=%p, nkeys=%u, flags=0x%x",
13114                      user, keys, nkeys, flags);
13115 
13116     virResetLastError();
13117 
13118     virCheckDomainReturn(domain, -1);
13119     conn = domain->conn;
13120     virCheckNonNullArgGoto(user, error);
13121 
13122     if (flags & VIR_DOMAIN_AUTHORIZED_SSH_KEYS_SET_APPEND ||
13123         flags & VIR_DOMAIN_AUTHORIZED_SSH_KEYS_SET_REMOVE)
13124         virCheckNonNullArgGoto(keys, error);
13125 
13126     VIR_EXCLUSIVE_FLAGS_RET(VIR_DOMAIN_AUTHORIZED_SSH_KEYS_SET_APPEND,
13127                             VIR_DOMAIN_AUTHORIZED_SSH_KEYS_SET_REMOVE,
13128                             -1);
13129 
13130     virCheckReadOnlyGoto(conn->flags, error);
13131 
13132     if (conn->driver->domainAuthorizedSSHKeysSet) {
13133         int ret;
13134         ret = conn->driver->domainAuthorizedSSHKeysSet(domain, user,
13135                                                        keys, nkeys, flags);
13136         if (ret < 0)
13137             goto error;
13138         return ret;
13139     }
13140 
13141     virReportUnsupportedError();
13142  error:
13143     virDispatchError(conn);
13144     return -1;
13145 }
13146 
13147 
13148 /**
13149  * virDomainGetMessages:
13150  * @domain: a domain object
13151  * @msgs: pointer to a variable to store messages
13152  * @flags: zero or more virDomainMessageType flags
13153  *
13154  * Fetch a list of all messages recorded against the VM and
13155  * store them into @msgs array which is allocated upon
13156  * successful return and is NULL terminated. The caller is
13157  * responsible for freeing @msgs when no longer needed.
13158  *
13159  * If @flags is zero then all messages are reported. The
13160  * virDomainMessageType constants can be used to restrict
13161  * results to certain types of message.
13162  *
13163  * Note it is hypervisor dependent whether messages are
13164  * available for shutoff guests, or running guests, or
13165  * both. Thus a client should be prepared to re-fetch
13166  * messages when a guest transitions between running
13167  * and shutoff states.
13168  *
13169  * Returns: number of messages stored in @msgs,
13170  *          -1 otherwise.
13171  */
13172 int
virDomainGetMessages(virDomainPtr domain,char *** msgs,unsigned int flags)13173 virDomainGetMessages(virDomainPtr domain,
13174                      char ***msgs,
13175                      unsigned int flags)
13176 {
13177     virConnectPtr conn;
13178 
13179     VIR_DOMAIN_DEBUG(domain, "msgs=%p, flags=0x%x", msgs, flags);
13180 
13181     virResetLastError();
13182 
13183     virCheckDomainReturn(domain, -1);
13184     conn = domain->conn;
13185     virCheckNonNullArgGoto(msgs, error);
13186 
13187     if (conn->driver->domainGetMessages) {
13188         int ret;
13189         ret = conn->driver->domainGetMessages(domain, msgs, flags);
13190         if (ret < 0)
13191             goto error;
13192         return ret;
13193     }
13194 
13195     virReportUnsupportedError();
13196  error:
13197     virDispatchError(conn);
13198     return -1;
13199 }
13200 
13201 
13202 /**
13203  * virDomainStartDirtyRateCalc:
13204  * @domain: a domain object
13205  * @seconds: specified calculating time in seconds
13206  * @flags: extra flags; not used yet, so callers should always pass 0
13207  *
13208  * Calculate the current domain's memory dirty rate in next @seconds.
13209  * The calculated dirty rate information is available by calling
13210  * virConnectGetAllDomainStats.
13211  *
13212  * Returns 0 in case of success, -1 otherwise.
13213  */
13214 int
virDomainStartDirtyRateCalc(virDomainPtr domain,int seconds,unsigned int flags)13215 virDomainStartDirtyRateCalc(virDomainPtr domain,
13216                             int seconds,
13217                             unsigned int flags)
13218 {
13219     virConnectPtr conn;
13220 
13221     VIR_DOMAIN_DEBUG(domain, "seconds=%d, flags=0x%x", seconds, flags);
13222 
13223     virResetLastError();
13224 
13225     virCheckDomainReturn(domain, -1);
13226     conn = domain->conn;
13227 
13228     virCheckReadOnlyGoto(conn->flags, error);
13229 
13230     if (conn->driver->domainStartDirtyRateCalc) {
13231         int ret;
13232         ret = conn->driver->domainStartDirtyRateCalc(domain, seconds, flags);
13233         if (ret < 0)
13234             goto error;
13235         return ret;
13236     }
13237 
13238     virReportUnsupportedError();
13239 
13240  error:
13241     virDispatchError(conn);
13242     return -1;
13243 }
13244