libvirt-rpc 0.1.0

libvirt protocol implementation and client
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
use ::xdr_codec;
use xdr_codec::{Pack,Unpack};
use std::convert::From;
use std::default::Default;

pub mod generated {
    //! This module is generated from protocol files.
    //!
    //! It follows original naming convention
    #![allow(non_camel_case_types)]
    #![allow(dead_code)]
    #![allow(non_snake_case)]
    #![allow(unused_assignments)]
    use ::xdr_codec;
    use xdr_codec::{Pack,Unpack};

    include!(concat!(env!("OUT_DIR"), "/virnetprotocol_xdr.rs"));
    include!(concat!(env!("OUT_DIR"), "/remote_protocol_xdr.rs"));
}

pub trait LibvirtRpc<R: ::std::io::Read> where {
    type Response: Send + ::xdr_codec::Unpack<R>;
}

pub use self::generated::remote_procedure;
pub use self::generated::{virNetMessageStatus,virNetMessageHeader,virNetMessageError};

/// VM instance
#[derive(Debug)]
pub struct Domain(generated::remote_nonnull_domain);

impl Domain {
    /// positive integer, unique amongst running guest domains on a single host. An inactive domain does not have an ID.
    pub fn id(&self) -> i32 {
        self.0.id
    }

    /// short string, unique amongst all guest domains on a single host, both running and inactive.
    pub fn name(&self) -> String {
        self.0.name.0.clone()
    }

    /// guaranteed to be unique amongst all guest domains on any host.
    pub fn uuid(&self) -> ::uuid::Uuid {
        let bytes = self.0.uuid.0;
        ::uuid::Uuid::from_bytes(&bytes).unwrap()
    }
}

impl ::std::default::Default for generated::virNetMessageHeader {
    fn default() -> Self {
        generated::virNetMessageHeader {
            prog: 0x20008086,
            vers: 1,
            proc_: 0,
            type_: generated::virNetMessageType::VIR_NET_CALL,
            serial: 0,
            status: generated::virNetMessageStatus::VIR_NET_OK,
        }
    }
}

#[derive(Debug)]
pub struct LibvirtMessage<P> {
    pub header: generated::virNetMessageHeader,
    pub payload: P,
}

impl<P: xdr_codec::Pack<Out>, Out: xdr_codec::Write> Pack<Out> for LibvirtMessage<P> {
    fn pack(&self, out: &mut Out) -> xdr_codec::Result<usize> {
        let mut sz: usize = 0;
        sz += try!(self.header.pack(out));
        sz += try!(self.payload.pack(out));
        Ok(sz)
    }
}

macro_rules! delegate_pack_impl {
    ($t:ty) => {
        impl<Out: xdr_codec::Write> Pack<Out> for $t {
            fn pack(&self, out: &mut Out) -> xdr_codec::Result<usize> {
                self.0.pack(out)
            }
        }
    }
}

#[derive(Debug)]
pub struct LibvirtResponse<P>(P);

impl<P> From<P> for LibvirtResponse<P> {
    fn from(inner: P) -> Self {
        LibvirtResponse(inner)
    }
}

impl<P: xdr_codec::Unpack<In>, In: xdr_codec::Read> Unpack<In> for LibvirtResponse<P> {
    fn unpack(mut input: &mut In) -> xdr_codec::Result<(Self, usize)> {
        let (payload, len) = try!(P::unpack(&mut input));
        Ok((LibvirtResponse(payload), len))
    }
}

macro_rules! delegate_unpack_impl {
    ($t:ty) => {
        impl<In: xdr_codec::Read> Unpack<In> for $t {
            fn unpack(mut input: &mut In) -> xdr_codec::Result<(Self, usize)> {
                let (inner, len) = try!(xdr_codec::Unpack::unpack(input));
                let mut pkt: $t = unsafe { ::std::mem::zeroed() };
                pkt.0 = inner;
                Ok((pkt, len))
            }
        }

    }
}

/// Auth list request must be the first request
#[derive(Debug)]
pub struct AuthListRequest(());

impl AuthListRequest {
    pub fn new() -> Self {
        AuthListRequest(())
    }
}

delegate_pack_impl!(AuthListRequest);

#[derive(Debug)]
pub struct AuthListResponse(LibvirtResponse<generated::remote_auth_list_ret>);
delegate_unpack_impl!(AuthListResponse);

impl<R: ::std::io::Read> LibvirtRpc<R> for AuthListRequest {
    type Response = AuthListResponse;
}

/// Connect open request
#[derive(Debug)]
pub struct ConnectOpenRequest(generated::remote_connect_open_args);

impl ConnectOpenRequest {
    pub fn new() -> Self {
        let payload = generated::remote_connect_open_args {
            name: Some(generated::remote_nonnull_string("qemu:///system".to_string())),
            flags: 0,
        };

        ConnectOpenRequest(payload)
    }
}

delegate_pack_impl!(ConnectOpenRequest);

#[derive(Debug)]
pub struct ConnectOpenResponse(LibvirtResponse<()>);
delegate_unpack_impl!(ConnectOpenResponse);

impl<R: ::std::io::Read> LibvirtRpc<R> for ConnectOpenRequest {
    type Response = ConnectOpenResponse;
}

#[derive(Debug)]
pub struct GetLibVersionRequest(());

impl GetLibVersionRequest {
    pub fn new() -> Self {
        GetLibVersionRequest(())
    }
}

delegate_pack_impl!(GetLibVersionRequest);

#[derive(Debug)]
pub struct GetLibVersionResponse(LibvirtResponse<generated::remote_connect_get_lib_version_ret>);

impl GetLibVersionResponse {
    pub fn version(&self) -> (u32, u32, u32) {
        let mut version = (self.0).0.lib_ver;

        let major = version / 1000000;
        version %= 1000000;
        let minor = version / 1000;
        version %= 1000;
        let micro = version;

        (major as u32, minor as u32, micro as u32)
    }
}

delegate_unpack_impl!(GetLibVersionResponse);

impl<R: ::std::io::Read> LibvirtRpc<R> for GetLibVersionRequest {
    type Response = GetLibVersionResponse;
}

#[derive(Debug)]
pub struct ListDefinedDomainsRequest(generated::remote_connect_list_defined_domains_args);

impl ListDefinedDomainsRequest {
    pub fn new() -> Self {
        let payload = generated::remote_connect_list_defined_domains_args {
            maxnames: generated::REMOTE_DOMAIN_LIST_MAX as i32,
        };
        ListDefinedDomainsRequest(payload)
    }
}

delegate_pack_impl!(ListDefinedDomainsRequest);

#[derive(Debug)]
pub struct ListDefinedDomainsResponse(LibvirtResponse<generated::remote_connect_list_defined_domains_ret>);

impl ListDefinedDomainsResponse {
    pub fn get_domain_names(&self) -> Vec<String> {
        let mut names = Vec::new();
        for name in &(self.0).0.names {
            names.push(name.0.to_string());
        }
        names
    }
}

delegate_unpack_impl!(ListDefinedDomainsResponse);

impl<R: ::std::io::Read> LibvirtRpc<R> for ListDefinedDomainsRequest {
    type Response = ListDefinedDomainsResponse;
}

#[derive(Debug)]
pub struct DomainDefineXMLRequest(generated::remote_domain_define_xml_flags_args);

impl DomainDefineXMLRequest {
    pub fn new(xml: &str, flags: u32) -> Self {
        let payload = generated::remote_domain_define_xml_flags_args {
            xml: generated::remote_nonnull_string(xml.to_string()),
            flags: flags,
        };
        DomainDefineXMLRequest(payload)
    }
}

delegate_pack_impl!(DomainDefineXMLRequest);

#[derive(Debug)]
pub struct DomainDefineXMLResponse(LibvirtResponse<generated::remote_domain_define_xml_flags_ret>);

impl DomainDefineXMLResponse {
    pub fn get_domain(&self) -> Domain {
        Domain ((self.0).0.dom.clone())
    }
}

delegate_unpack_impl!(DomainDefineXMLResponse);

impl<R: ::std::io::Read> LibvirtRpc<R> for DomainDefineXMLRequest {
    type Response = DomainDefineXMLResponse;
}

#[derive(Debug)]
pub struct DomainUndefineRequest(generated::remote_domain_undefine_flags_args);

impl DomainUndefineRequest {
    pub fn new(domain: Domain, flags: u32) -> Self {
        // XXX: use bitflags for flags
        let payload = generated::remote_domain_undefine_flags_args {
            dom: domain.0,
            flags: flags,
        };
        DomainUndefineRequest(payload)
    }
}

delegate_pack_impl!(DomainUndefineRequest);

#[derive(Debug)]
pub struct DomainUndefineResponse(LibvirtResponse<()>);
delegate_unpack_impl!(DomainUndefineResponse);

impl<R: ::std::io::Read> LibvirtRpc<R> for DomainUndefineRequest {
    type Response = DomainUndefineResponse;
}

bitflags! {
    pub flags DomainCreateFlags: u32 {
        const VIR_DOMAIN_START_PAUSED = 1,
        const VIR_DOMAIN_START_AUTODESTROY = 2,
        const VIR_DOMAIN_START_BYPASS_CACHE = 4,
        const VIR_DOMAIN_START_FORCE_BOOT = 8,
        const VIR_DOMAIN_START_VALIDATE = 16,
    }
}

#[derive(Debug)]
pub struct DomainCreateRequest(generated::remote_domain_create_with_flags_args);

impl DomainCreateRequest {
    pub fn new(domain: Domain, flags: DomainCreateFlags) -> Self {
        let payload = generated::remote_domain_create_with_flags_args {
            dom: domain.0,
            flags: flags.bits(),
        };
        DomainCreateRequest(payload)
    }
}

delegate_pack_impl!(DomainCreateRequest);

#[derive(Debug)]
pub struct DomainCreateResponse(LibvirtResponse<generated::remote_domain_create_with_flags_ret>);

delegate_unpack_impl!(DomainCreateResponse);

impl DomainCreateResponse {
    pub fn get_domain(&self) -> Domain {
        Domain ((self.0).0.dom.clone())
    }
}

impl<R: ::std::io::Read> LibvirtRpc<R> for DomainCreateRequest {
    type Response = DomainCreateResponse;
}

pub mod flags {
    bitflags! {
        pub flags ListAllDomainsFlags: u32 {
            const DOMAINS_ACTIVE	=	1,
            const DOMAINS_INACTIVE	=	2,
            const DOMAINS_PERSISTENT	=	4,
            const DOMAINS_TRANSIENT	=	8,
            const DOMAINS_RUNNING	=	16,
            const DOMAINS_PAUSED	=	32,
            const DOMAINS_SHUTOFF	=	64,
            const DOMAINS_OTHER	=	128,
            const DOMAINS_MANAGEDSAVE	=	256,
            const DOMAINS_NO_MANAGEDSAVE	=	512,
            const DOMAINS_AUTOSTART	=	1024,
            const DOMAINS_NO_AUTOSTART	=	2048,
            const DOMAINS_HAS_SNAPSHOT	=	4096,
            const DOMAINS_NO_SNAPSHOT	=	8192,
        }
    }
}

#[derive(Debug)]
pub struct ListAllDomainsRequest(generated::remote_connect_list_all_domains_args);

impl ListAllDomainsRequest {
    pub fn new(flags: flags::ListAllDomainsFlags) -> Self {
        let payload = generated::remote_connect_list_all_domains_args {
            need_results: 1,
            flags: flags.bits(),
        };
        ListAllDomainsRequest(payload)
    }
}

delegate_pack_impl!(ListAllDomainsRequest);

#[derive(Debug)]
pub struct ListAllDomainsResponse(generated::remote_connect_list_all_domains_ret);

impl ::std::convert::Into<Vec<Domain>> for ListAllDomainsResponse {
    fn into(self) -> Vec<Domain> {
        let mut domains = Vec::new();
        for dom in &(self.0).domains {
            domains.push(Domain(dom.clone()))
        }
        domains
    }
}

delegate_unpack_impl!(ListAllDomainsResponse);

impl<R: ::std::io::Read> LibvirtRpc<R> for ListAllDomainsRequest {
    type Response = ListAllDomainsResponse;
}

#[derive(Debug)]
pub struct DomainEventRegisterAnyRequest(generated::remote_connect_domain_event_register_any_args);

impl DomainEventRegisterAnyRequest {
    pub fn new(event: i32) -> Self {
        let payload = generated::remote_connect_domain_event_register_any_args {
            eventID: event,
        };
        DomainEventRegisterAnyRequest(payload)
    }
}

delegate_pack_impl!(DomainEventRegisterAnyRequest);

#[derive(Debug)]
pub struct DomainEventRegisterAnyResponse(());
delegate_unpack_impl!(DomainEventRegisterAnyResponse);

impl<R: ::std::io::Read> LibvirtRpc<R> for DomainEventRegisterAnyRequest {
    type Response = DomainEventRegisterAnyResponse;
}

#[derive(Debug)]
pub struct DomainEventCallbackRegisterAnyRequest(generated::remote_connect_domain_event_callback_register_any_args);

impl DomainEventCallbackRegisterAnyRequest {
    pub fn new(event: i32, domain: &Domain) -> Self {
        let payload = generated::remote_connect_domain_event_callback_register_any_args {
            eventID: event,
            dom: Some(Box::new(domain.0.clone())),
        };
        DomainEventCallbackRegisterAnyRequest(payload)
    }
}

delegate_pack_impl!(DomainEventCallbackRegisterAnyRequest);

#[derive(Debug)]
pub struct DomainEventCallbackRegisterAnyResponse(generated::remote_connect_domain_event_callback_register_any_ret);

delegate_unpack_impl!(DomainEventCallbackRegisterAnyResponse);

impl DomainEventCallbackRegisterAnyResponse {
    pub fn callback_id(&self) -> i32 {
        self.0.callbackID
    }
}

impl<R: ::std::io::Read> LibvirtRpc<R> for DomainEventCallbackRegisterAnyRequest {
    type Response = DomainEventCallbackRegisterAnyResponse;
}

#[derive(Debug)]
pub struct DomainLookupByUuidRequest(generated::remote_domain_lookup_by_uuid_args);

impl DomainLookupByUuidRequest {
    pub fn new(uuid: &::uuid::Uuid) -> Self {
        let payload = generated::remote_domain_lookup_by_uuid_args {
            uuid: generated::remote_uuid(uuid.as_bytes().clone()),
        };
        DomainLookupByUuidRequest(payload)
    }
}

delegate_pack_impl!(DomainLookupByUuidRequest);

#[derive(Debug)]
pub struct DomainLookupByUuidResponse(generated::remote_domain_lookup_by_uuid_ret);

impl DomainLookupByUuidResponse {
    pub fn domain(&self) -> Domain {
        Domain ((self.0).dom.clone())
    }
}

delegate_unpack_impl!(DomainLookupByUuidResponse);

impl<R: ::std::io::Read> LibvirtRpc<R> for DomainLookupByUuidRequest {
    type Response = DomainLookupByUuidResponse;
}

/* http://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventStartedDetailType */
#[derive(Debug)]
pub enum EventStartedDetailType {
    /// Normal startup from boot
    Booted = 0,
    /// Incoming migration from another host
    Migrated = 1,
    /// Restored from a state file
    Restored = 2,
    /// Restored from snapshot
    FromSnapshot = 3,
    /// Started due to wakeup event
    Wakeup = 4,
}

/* http://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventStoppedDetailType */
#[derive(Debug)]
pub enum EventStoppedDetailType {
    /// Normal shutdown
    Shutdown = 0,
    /// Forced poweroff from host
    Destroyed = 1,
    /// Guest crashed
    Crashed = 2,
    /// Migrated off to another host
    Migrated = 3,
    /// Saved to a state file
    Saved = 4,
    /// Host emulator/mgmt failed
    Failed = 5,
    /// Offline snapshot loaded
    FromSnapshot = 6,
}

/* http://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventSuspendedDetailType */
#[derive(Debug)]
pub enum EventSuspendedDetailType {
    /// Normal suspend due to admin pause
    Paused = 0,
    /// Suspended for offline migration
    Migrated = 1,
    /// Suspended due to a disk I/O error
    IoError = 2,
    /// Suspended due to a watchdog firing
    Watchdog = 3,
    /// Restored from paused state file
    Restored = 4,
    /// Restored from paused snapshot
    FromSnapshot = 5,
    /// Suspended after failure during libvirt API call
    ApiError = 6,
    /// Suspended for post-copy migration
    PostCopy = 7,
    /// Suspended after failed post-copy
    PostCopyFailed = 8,
}

/* http://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventResumedDetailType */
#[derive(Debug)]
pub enum EventResumedDetailType {
    /// Normal resume due to admin unpause
    Unpaused = 0,
    /// Resumed for completion of migration
    Migrated = 1,
    /// Resumed from snapshot
    FromSnapshot = 2,
    /// Resumed, but migration is still running in post-copy mode
    PostCopy = 3,
}

/* http://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventDefinedDetailType */
#[derive(Debug)]
pub enum EventDefinedDetailType {
    /// Newly created config file
    Added =	0,
    /// Changed config file	
    Updated = 1,
    /// Domain was renamed
    Renamed = 2,
    /// Config was restored from a snapshot
    FromSnapshot = 3,
}

/* http://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventUndefinedDetailType */
#[derive(Debug)]
pub enum EventUndefinedDetailType {
    /// Deleted the config file
    Removed = 0,
    /// Domain was renamed
    Renamed = 1,
}

/* http://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventShutdownDetailType */
#[derive(Debug)]
pub enum EventShutdownDetailType {
    /// Guest finished shutdown sequence
    Finished = 0, 
}

#[derive(Debug)]
pub enum DomainEventInfo {
    Defined(EventDefinedDetailType),
    Undefined(EventUndefinedDetailType),
    Started(EventStartedDetailType),
    Suspended(EventSuspendedDetailType),
    Stopped(EventStoppedDetailType),
    Shutdown(EventShutdownDetailType),
    Resumed(EventResumedDetailType),
    Other(i32, i32)
}

#[derive(Debug)]
pub struct DomainEvent {
    domain: Domain,
    info: DomainEventInfo,
}

/* virDomainEventType: http://libvirt.org/html/libvirt-libvirt-domain.html#virDomainEventType */
const VIR_DOMAIN_EVENT_DEFINED: i32	=	0;
const VIR_DOMAIN_EVENT_UNDEFINED: i32	=	1;
const VIR_DOMAIN_EVENT_STARTED: i32	=	2;
const VIR_DOMAIN_EVENT_SUSPENDED: i32	=	3;
const VIR_DOMAIN_EVENT_RESUMED: i32	=	4;
const VIR_DOMAIN_EVENT_STOPPED: i32	=	5;
const VIR_DOMAIN_EVENT_SHUTDOWN: i32	=	6;
const VIR_DOMAIN_EVENT_PMSUSPENDED: i32	=	7;
const VIR_DOMAIN_EVENT_CRASHED: i32	=	8;

impl From<generated::remote_domain_event_callback_lifecycle_msg> for DomainEvent {
    fn from(ev: generated::remote_domain_event_callback_lifecycle_msg) -> Self {
        use ::std::mem;
        let info = match ev.msg.event {
            VIR_DOMAIN_EVENT_DEFINED => {
                let detail = unsafe { mem::transmute(ev.msg.detail as u8) };
                DomainEventInfo::Defined(detail)
            }
            VIR_DOMAIN_EVENT_UNDEFINED => {
                let detail = unsafe { mem::transmute(ev.msg.detail as u8) };
                DomainEventInfo::Undefined(detail)
            }
            VIR_DOMAIN_EVENT_STARTED => {
                let detail = unsafe { mem::transmute(ev.msg.detail as u8) };
                DomainEventInfo::Started(detail)
            }
            VIR_DOMAIN_EVENT_SUSPENDED => {
                let detail = unsafe { mem::transmute(ev.msg.detail as u8) };
                DomainEventInfo::Suspended(detail)
            }
            VIR_DOMAIN_EVENT_STOPPED => {
                let detail = unsafe { mem::transmute(ev.msg.detail as u8) };
                DomainEventInfo::Stopped(detail)
            }
            VIR_DOMAIN_EVENT_RESUMED => {
                let detail = unsafe { mem::transmute(ev.msg.detail as u8) };
                DomainEventInfo::Resumed(detail)
            }
            VIR_DOMAIN_EVENT_SHUTDOWN => {
                let detail = unsafe { mem::transmute(ev.msg.detail as u8) };
                DomainEventInfo::Shutdown(detail)
            }
            i => {
                DomainEventInfo::Other(i, ev.msg.detail)
            }
        };
        let domain = Domain(ev.msg.dom);
        DomainEvent { domain, info }
    }
}