1 (** OCaml bindings for libvirt. *)
2 (* (C) Copyright 2007 Richard W.M. Jones, Red Hat Inc.
5 This library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2 of the License, or (at your option) any later version.
10 This library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public
16 License along with this library; if not, write to the Free Software
17 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 {2 Introduction and examples}
23 This is a set of bindings for writing OCaml programs to
24 manage virtual machines through {{:http://libvirt.org/}libvirt}.
26 {3 Using libvirt interactively}
28 Using the interactive toplevel:
32 Objective Caml version 3.10.0
35 # #load "mllibvirt.cma";;
36 # let name = "test:///default";;
37 val name : string = "test:///default"
38 # let conn = Libvirt.Connect.connect_readonly ~name () ;;
39 val conn : Libvirt.ro Libvirt.Connect.t = <abstr>
40 # Libvirt.Connect.get_node_info conn;;
41 : Libvirt.Connect.node_info =
42 {Libvirt.Connect.model = "i686"; Libvirt.Connect.memory = 3145728L;
43 Libvirt.Connect.cpus = 16; Libvirt.Connect.mhz = 1400;
44 Libvirt.Connect.nodes = 2; Libvirt.Connect.sockets = 2;
45 Libvirt.Connect.cores = 2; Libvirt.Connect.threads = 2}
48 {3 Compiling libvirt programs}
50 This command compiles a program to native code:
53 ocamlopt -I +libvirt mllibvirt.cmxa list_domains.ml -o list_domains
56 {3 Example: Connect to the hypervisor}
58 The main modules are {!Libvirt.Connect}, {!Libvirt.Domain} and
59 {!Libvirt.Network} corresponding respectively to the
60 {{:http://libvirt.org/html/libvirt-libvirt.html}virConnect*, virDomain* and virNetwork* functions from libvirt}.
61 For brevity I usually rename these modules like this:
64 module C = Libvirt.Connect
65 module D = Libvirt.Domain
66 module N = Libvirt.Network
69 To get a connection handle, assuming a Xen hypervisor:
73 let conn = C.connect_readonly ~name ()
76 {3 Example: List running domains}
81 let n = C.num_of_domains conn in
82 let ids = C.list_domains conn n in
83 let domains = Array.map (D.lookup_by_id conn) ids in
86 printf "%8d %s\n%!" (D.get_id dom) (D.get_name dom)
90 {3 Example: List inactive domains}
93 let n = C.num_of_defined_domains conn in
94 let names = C.list_defined_domains conn n in
97 printf "inactive %s\n%!" name
101 {3 Example: Print node info}
104 let node_info = C.get_node_info conn in
105 printf "model = %s\n" node_info.C.model;
106 printf "memory = %Ld K\n" node_info.C.memory;
107 printf "cpus = %d\n" node_info.C.cpus;
108 printf "mhz = %d\n" node_info.C.mhz;
109 printf "nodes = %d\n" node_info.C.nodes;
110 printf "sockets = %d\n" node_info.C.sockets;
111 printf "cores = %d\n" node_info.C.cores;
112 printf "threads = %d\n%!" node_info.C.threads;
114 let hostname = C.get_hostname conn in
115 printf "hostname = %s\n%!" hostname;
117 let uri = C.get_uri conn in
118 printf "uri = %s\n%!" uri
124 (** {2 Programming issues}
126 {3 General safety issues}
128 Memory allocation / automatic garbage collection of all libvirt
129 objects should be completely safe (except in the specific
130 virterror case noted below). If you find any safety issues or if your
131 pure OCaml program ever segfaults, please contact the author.
133 You can force a libvirt object to be freed early by calling
134 the [close] function on the object. This shouldn't affect
135 the safety of garbage collection and should only be used when
136 you want to explicitly free memory. Note that explicitly
137 closing a connection object does nothing if there are still
138 unclosed domain or network objects referencing it.
140 Note that even though you hold open (eg) a domain object, that
141 doesn't mean that the domain (virtual machine) actually exists.
142 The domain could have been shut down or deleted by another user.
143 Thus domain objects can through odd exceptions at any time.
144 This is just the nature of virtualisation.
146 Virterror has a specific design error which means that the
147 objects embedded in a virterror exception message are only
148 valid as long as the connection handle is still open. This
149 is a design flaw in the C code of libvirt and we cannot fix
150 or work around it in the OCaml bindings.
152 {3 Backwards and forwards compatibility}
154 OCaml-libvirt is backwards and forwards compatible with
155 any libvirt >= 0.2.1. One consequence of this is that
156 your program can dynamically link to a {i newer} version of
157 libvirt than it was compiled with, and it should still
160 When we link to an older version of libvirt.so, there may
161 be missing functions. If ocaml-libvirt was compiled with
162 gcc, then these are turned into OCaml {!Libvirt.Not_supported}
165 We don't support libvirt < 0.2.1, and never will so don't ask us.
169 You can issue multiple concurrent libvirt requests in
170 different threads. However you must follow this rule:
171 Each thread must have its own separate libvirt connection, {i or}
172 you must implement your own mutex scheme to ensure that no
173 two threads can ever make concurrent calls using the same
176 (Note that multithreaded code is not well tested. If you find
177 bugs please report them.)
181 Libvirt requires all callers to call virInitialize before
182 using the library. This is done automatically for you by
183 these bindings when the program starts up, and we believe
184 that the way this is done is safe.
190 (** This is a "raw" UUID, ie. a packed string of bytes. *)
193 (** Type of XML (an uninterpreted string of bytes). Use PXP, expat,
194 xml-light, etc. if you want to do anything useful with the XML.
197 type filename = string
200 val get_version : ?driver:string -> unit -> int * int
201 (** [get_version ()] returns the library version in the first part
202 of the tuple, and [0] in the second part.
204 [get_version ~driver ()] returns the library version in the first
205 part of the tuple, and the version of the driver called [driver]
208 The version numbers are encoded as
209 1,000,000 * major + 1,000 * minor + release.
212 val uuid_length : int
213 (** Length of packed UUIDs. *)
215 val uuid_string_length : int
216 (** Length of UUID strings. *)
221 {{:http://caml.inria.fr/pub/ml-archives/caml-list/2004/07/80683af867cce6bf8fff273973f70c95.en.html}phantom types}
222 are used to ensure the type-safety of read-only
223 versus read-write connections.
225 All connection/domain/etc. objects are marked with
226 a phantom read-write or read-only type, and trying to
227 pass a read-only object into a function which could
228 mutate the object will cause a compile time error.
230 Each module provides a function like {!Libvirt.Connect.const}
231 to demote a read-write object into a read-only object. The
232 opposite operation is, of course, not allowed.
234 If you want to handle both read-write and read-only
235 connections at runtime, use a variant similar to this:
239 | Read_only of Libvirt.ro Libvirt.Connect.t
240 | Read_write of Libvirt.rw Libvirt.Connect.t
242 See also the source of [mlvirsh].
245 (** {3 Connections} *)
250 (** Connection. Read-only connections have type [ro Connect.t] and
251 read-write connections have type [rw Connect.t].
255 model : string; (** CPU model *)
256 memory : int64; (** memory size in kilobytes *)
257 cpus : int; (** number of active CPUs *)
258 mhz : int; (** expected CPU frequency *)
259 nodes : int; (** number of NUMA nodes (1 = UMA) *)
260 sockets : int; (** number of CPU sockets per node *)
261 cores : int; (** number of cores per socket *)
262 threads : int; (** number of threads per core *)
265 val connect : ?name:string -> unit -> rw t
266 val connect_readonly : ?name:string -> unit -> ro t
267 (** [connect ~name ()] connects to the hypervisor with URI [name].
269 [connect ()] connects to the default hypervisor.
271 [connect_readonly] is the same but connects in read-only mode.
274 val close : [>`R] t -> unit
275 (** [close conn] closes and frees the connection object in memory.
277 The connection is automatically closed if it is garbage
278 collected. This function just forces it to be closed
279 and freed right away.
282 val get_type : [>`R] t -> string
283 (** Returns the name of the driver (hypervisor). *)
285 val get_version : [>`R] t -> int
286 (** Returns the driver version
287 [major * 1_000_000 + minor * 1000 + release]
289 val get_hostname : [>`R] t -> string
290 (** Returns the hostname of the physical server. *)
291 val get_uri : [>`R] t -> string
292 (** Returns the canonical connection URI. *)
293 val get_max_vcpus : [>`R] t -> ?type_:string -> unit -> int
294 (** Returns the maximum number of virtual CPUs
295 supported by a guest VM of a particular type. *)
296 val list_domains : [>`R] t -> int -> int array
297 (** [list_domains conn max] returns the running domain IDs,
298 up to a maximum of [max] entries.
299 Call {!num_of_domains} first to get a value for [max].
301 val num_of_domains : [>`R] t -> int
302 (** Returns the number of running domains. *)
303 val get_capabilities : [>`R] t -> xml
304 (** Returns the hypervisor capabilities (as XML). *)
305 val num_of_defined_domains : [>`R] t -> int
306 (** Returns the number of inactive (shutdown) domains. *)
307 val list_defined_domains : [>`R] t -> int -> string array
308 (** [list_defined_domains conn max]
309 returns the names of the inactive domains, up to
310 a maximum of [max] entries.
311 Call {!num_of_defined_domains} first to get a value for [max].
313 val num_of_networks : [>`R] t -> int
314 (** Returns the number of networks. *)
315 val list_networks : [>`R] t -> int -> string array
316 (** [list_networks conn max]
317 returns the names of the networks, up to a maximum
319 Call {!num_of_networks} first to get a value for [max].
321 val num_of_defined_networks : [>`R] t -> int
322 (** Returns the number of inactive networks. *)
323 val list_defined_networks : [>`R] t -> int -> string array
324 (** [list_defined_networks conn max]
325 returns the names of the inactive networks, up to a maximum
327 Call {!num_of_defined_networks} first to get a value for [max].
330 (* The name of this function is inconsistent, but the inconsistency
331 * is really in libvirt itself.
333 val get_node_info : [>`R] t -> node_info
334 (** Return information about the physical server. *)
336 val node_get_free_memory : [> `R] t -> int64
338 [node_get_free_memory conn]
339 returns the amount of free memory (not allocated to any guest)
343 val node_get_cells_free_memory : [> `R] t -> int -> int -> int64 array
345 [node_get_cells_free_memory conn start max]
346 returns the amount of free memory on each NUMA cell in kilobytes.
347 [start] is the first cell for which we return free memory.
348 [max] is the maximum number of cells for which we return free memory.
349 Returns an array of up to [max] entries in length.
352 val maxcpus_of_node_info : node_info -> int
353 (** Calculate the total number of CPUs supported (but not necessarily
357 val cpumaplen : int -> int
358 (** Calculate the length (in bytes) required to store the complete
359 CPU map between a single virtual and all physical CPUs of a domain.
362 val use_cpu : string -> int -> unit
363 (** [use_cpu cpumap cpu] marks [cpu] as usable in [cpumap]. *)
364 val unuse_cpu : string -> int -> unit
365 (** [unuse_cpu cpumap cpu] marks [cpu] as not usable in [cpumap]. *)
366 val cpu_usable : string -> int -> int -> int -> bool
367 (** [cpu_usable cpumaps maplen vcpu cpu] checks returns true iff the
368 [cpu] is usable by [vcpu]. *)
370 external const : [>`R] t -> ro t = "%identity"
371 (** [const conn] turns a read/write connection into a read-only
372 connection. Note that the opposite operation is impossible.
375 (** Module dealing with connections. [Connect.t] is the
384 (** Domain handle. Read-only handles have type [ro Domain.t] and
385 read-write handles have type [rw Domain.t].
389 | InfoNoState | InfoRunning | InfoBlocked | InfoPaused
390 | InfoShutdown | InfoShutoff | InfoCrashed
393 state : state; (** running state *)
394 max_mem : int64; (** maximum memory in kilobytes *)
395 memory : int64; (** memory used in kilobytes *)
396 nr_virt_cpu : int; (** number of virtual CPUs *)
397 cpu_time : int64; (** CPU time used in nanoseconds *)
400 type vcpu_state = VcpuOffline | VcpuRunning | VcpuBlocked
403 number : int; (** virtual CPU number *)
404 vcpu_state : vcpu_state; (** state *)
405 vcpu_time : int64; (** CPU time used in nanoseconds *)
406 cpu : int; (** real CPU number, -1 if offline *)
409 type sched_param = string * sched_param_value
410 and sched_param_value =
411 | SchedFieldInt32 of int32 | SchedFieldUInt32 of int32
412 | SchedFieldInt64 of int64 | SchedFieldUInt64 of int64
413 | SchedFieldFloat of float | SchedFieldBool of bool
415 type migrate_flag = Live
425 type interface_stats = {
436 val create_linux : [>`W] Connect.t -> xml -> rw t
437 (** Create a new guest domain (not necessarily a Linux one)
440 val lookup_by_id : 'a Connect.t -> int -> 'a t
441 (** Lookup a domain by ID. *)
442 val lookup_by_uuid : 'a Connect.t -> uuid -> 'a t
443 (** Lookup a domain by UUID. This uses the packed byte array UUID. *)
444 val lookup_by_uuid_string : 'a Connect.t -> string -> 'a t
445 (** Lookup a domain by (string) UUID. *)
446 val lookup_by_name : 'a Connect.t -> string -> 'a t
447 (** Lookup a domain by name. *)
448 val destroy : [>`W] t -> unit
449 (** Abruptly destroy a domain. *)
450 val free : [>`R] t -> unit
451 (** [free domain] frees the domain object in memory.
453 The domain object is automatically freed if it is garbage
454 collected. This function just forces it to be freed right
458 val suspend : [>`W] t -> unit
459 (** Suspend a domain. *)
460 val resume : [>`W] t -> unit
461 (** Resume a domain. *)
462 val save : [>`W] t -> filename -> unit
463 (** Suspend a domain, then save it to the file. *)
464 val restore : [>`W] Connect.t -> filename -> unit
465 (** Restore a domain from a file. *)
466 val core_dump : [>`W] t -> filename -> unit
467 (** Force a domain to core dump to the named file. *)
468 val shutdown : [>`W] t -> unit
469 (** Shutdown a domain. *)
470 val reboot : [>`W] t -> unit
471 (** Reboot a domain. *)
472 val get_name : [>`R] t -> string
473 (** Get the domain name. *)
474 val get_uuid : [>`R] t -> uuid
475 (** Get the domain UUID (as a packed byte array). *)
476 val get_uuid_string : [>`R] t -> string
477 (** Get the domain UUID (as a printable string). *)
478 val get_id : [>`R] t -> int
479 (** [getid dom] returns the ID of the domain.
481 Do not call this on a defined but not running domain. Those
482 domains don't have IDs, and you'll get an error here.
485 val get_os_type : [>`R] t -> string
486 (** Get the operating system type. *)
487 val get_max_memory : [>`R] t -> int64
488 (** Get the maximum memory allocation. *)
489 val set_max_memory : [>`W] t -> int64 -> unit
490 (** Set the maximum memory allocation. *)
491 val set_memory : [>`W] t -> int64 -> unit
492 (** Set the normal memory allocation. *)
493 val get_info : [>`R] t -> info
494 (** Get information about a domain. *)
495 val get_xml_desc : [>`R] t -> xml
496 (** Get the XML description of a domain. *)
497 val get_scheduler_type : [>`R] t -> string * int
498 (** Get the scheduler type. *)
499 val get_scheduler_parameters : [>`R] t -> int -> sched_param array
500 (** Get the array of scheduler parameters. *)
501 val set_scheduler_parameters : [>`W] t -> sched_param array -> unit
502 (** Set the array of scheduler parameters. *)
503 val define_xml : [>`W] Connect.t -> xml -> rw t
504 (** Define a new domain (but don't start it up) from the XML. *)
505 val undefine : [>`W] t -> unit
506 (** Undefine a domain - removes its configuration. *)
507 val create : [>`W] t -> unit
508 (** Launch a defined (inactive) domain. *)
509 val get_autostart : [>`R] t -> bool
510 (** Get the autostart flag for a domain. *)
511 val set_autostart : [>`W] t -> bool -> unit
512 (** Set the autostart flag for a domain. *)
513 val set_vcpus : [>`W] t -> int -> unit
514 (** Change the number of vCPUs available to a domain. *)
515 val pin_vcpu : [>`W] t -> int -> string -> unit
516 (** [pin_vcpu dom vcpu bitmap] pins a domain vCPU to a bitmap of physical
517 CPUs. See the libvirt documentation for details of the
518 layout of the bitmap. *)
519 val get_vcpus : [>`R] t -> int -> int -> int * vcpu_info array * string
520 (** [get_vcpus dom maxinfo maplen] returns the pinning information
521 for a domain. See the libvirt documentation for details
522 of the array and bitmap returned from this function.
524 val get_max_vcpus : [>`R] t -> int
525 (** Returns the maximum number of vCPUs supported for this domain. *)
526 val attach_device : [>`W] t -> xml -> unit
527 (** Attach a device (described by the device XML) to a domain. *)
528 val detach_device : [>`W] t -> xml -> unit
529 (** Detach a device (described by the device XML) from a domain. *)
531 val migrate : [>`W] t -> [>`W] Connect.t -> migrate_flag list ->
532 ?dname:string -> ?uri:string -> ?bandwidth:int -> unit -> rw t
533 (** [migrate dom dconn flags ()] migrates a domain to a
534 destination host described by [dconn].
536 The optional flag [?dname] is used to rename the domain.
538 The optional flag [?uri] is used to route the migration.
540 The optional flag [?bandwidth] is used to limit the bandwidth
541 used for migration (in Mbps). *)
543 val block_stats : [>`R] t -> string -> block_stats
544 (** Returns block device stats. *)
545 val interface_stats : [>`R] t -> string -> interface_stats
546 (** Returns network interface stats. *)
548 external const : [>`R] t -> ro t = "%identity"
549 (** [const dom] turns a read/write domain handle into a read-only
550 domain handle. Note that the opposite operation is impossible.
553 (** Module dealing with domains. [Domain.t] is the
562 (** Network handle. Read-only handles have type [ro Network.t] and
563 read-write handles have type [rw Network.t].
566 val lookup_by_name : 'a Connect.t -> string -> 'a t
567 (** Lookup a network by name. *)
568 val lookup_by_uuid : 'a Connect.t -> uuid -> 'a t
569 (** Lookup a network by (packed) UUID. *)
570 val lookup_by_uuid_string : 'a Connect.t -> string -> 'a t
571 (** Lookup a network by UUID string. *)
572 val create_xml : [>`W] Connect.t -> xml -> rw t
573 (** Create a network. *)
574 val define_xml : [>`W] Connect.t -> xml -> rw t
575 (** Define but don't activate a network. *)
576 val undefine : [>`W] t -> unit
577 (** Undefine configuration of a network. *)
578 val create : [>`W] t -> unit
579 (** Start up a defined (inactive) network. *)
580 val destroy : [>`W] t -> unit
581 (** Destroy a network. *)
582 val free : [>`R] t -> unit
583 (** [free network] frees the network object in memory.
585 The network object is automatically freed if it is garbage
586 collected. This function just forces it to be freed right
590 val get_name : [>`R] t -> string
591 (** Get network name. *)
592 val get_uuid : [>`R] t -> uuid
593 (** Get network packed UUID. *)
594 val get_uuid_string : [>`R] t -> string
595 (** Get network UUID as a printable string. *)
596 val get_xml_desc : [>`R] t -> xml
597 (** Get XML description of a network. *)
598 val get_bridge_name : [>`R] t -> string
599 (** Get bridge device name of a network. *)
600 val get_autostart : [>`R] t -> bool
601 (** Get the autostart flag for a network. *)
602 val set_autostart : [>`W] t -> bool -> unit
603 (** Set the autostart flag for a network. *)
605 external const : [>`R] t -> ro t = "%identity"
606 (** [const network] turns a read/write network handle into a read-only
607 network handle. Note that the opposite operation is impossible.
610 (** Module dealing with networks. [Network.t] is the
614 (** {3 Error handling and exceptions} *)
620 | VIR_ERR_INTERNAL_ERROR
623 | VIR_ERR_UNKNOWN_HOST
625 | VIR_ERR_INVALID_CONN
626 | VIR_ERR_INVALID_DOMAIN
627 | VIR_ERR_INVALID_ARG
628 | VIR_ERR_OPERATION_FAILED
630 | VIR_ERR_POST_FAILED
632 | VIR_ERR_SEXPR_SERIAL
643 | VIR_ERR_NO_XENSTORE
644 | VIR_ERR_DRIVER_FULL
645 | VIR_ERR_CALL_FAILED
648 | VIR_ERR_OPERATION_DENIED
649 | VIR_ERR_OPEN_FAILED
650 | VIR_ERR_READ_FAILED
651 | VIR_ERR_PARSE_FAILED
652 | VIR_ERR_CONF_SYNTAX
653 | VIR_ERR_WRITE_FAILED
655 | VIR_ERR_INVALID_NETWORK
656 | VIR_ERR_NETWORK_EXIST
657 | VIR_ERR_SYSTEM_ERROR
659 | VIR_ERR_GNUTLS_ERROR
663 | VIR_ERR_INVALID_MAC
664 (* ^^ NB: If you add a variant you MUST edit libvirt_c.c:MAX_VIR_* *)
665 | VIR_ERR_UNKNOWN of int
666 (** See [<libvirt/virterror.h>] for meaning of these codes. *)
668 val string_of_code : code -> string
687 | VIR_FROM_STATS_LINUX
688 (* ^^ NB: If you add a variant you MUST edit libvirt_c.c: MAX_VIR_* *)
689 | VIR_FROM_UNKNOWN of int
690 (** Subsystem / driver which produced the error. *)
692 val string_of_domain : domain -> string
698 (* ^^ NB: If you add a variant you MUST edit libvirt_c.c: MAX_VIR_* *)
699 | VIR_ERR_UNKNOWN_LEVEL of int
700 (** No error, a warning or an error. *)
702 val string_of_level : level -> string
705 code : code; (** Error code. *)
706 domain : domain; (** Origin of the error. *)
707 message : string option; (** Human-readable message. *)
708 level : level; (** Error or warning. *)
709 conn : ro Connect.t option; (** Associated connection. *)
710 dom : ro Domain.t option; (** Associated domain. *)
711 str1 : string option; (** Informational string. *)
712 str2 : string option; (** Informational string. *)
713 str3 : string option; (** Informational string. *)
714 int1 : int32; (** Informational integer. *)
715 int2 : int32; (** Informational integer. *)
716 net : ro Network.t option; (** Associated network. *)
718 (** An error object. *)
720 val to_string : t -> string
721 (** Turn the exception into a printable string. *)
723 val get_last_error : unit -> t option
724 val get_last_conn_error : [>`R] Connect.t -> t option
725 (** Get the last error at a global or connection level.
727 Normally you do not need to use these functions because
728 the library automatically turns errors into exceptions.
731 val reset_last_error : unit -> unit
732 val reset_last_conn_error : [>`R] Connect.t -> unit
733 (** Reset the error at a global or connection level.
735 Normally you do not need to use these functions.
738 val no_error : unit -> t
739 (** Creates an empty error message.
741 Normally you do not need to use this function.
744 (** Module dealing with errors. *)
746 exception Virterror of Virterror.t
747 (** This exception can be raised by any library function that detects
748 an error. To get a printable error message, call
749 {!Virterror.to_string} on the content of this exception.
752 exception Not_supported of string
755 [Not_supported "virFoo"]
756 (where [virFoo] is the libvirt function name) if a function is
757 not supported at either compile or run time. This applies to
758 any libvirt function added after version 0.2.1.
760 See also {{:http://libvirt.org/hvsupport.html}http://libvirt.org/hvsupport.html}