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
//! QCOW2 Disk Image Management
//!
//! This module provides functionality for creating, managing, and configuring QCOW2 disk images.
//! QCOW2 (QEMU Copy-On-Write version 2) is a disk image format that supports snapshots, compression,
//! and sparse allocation, making it ideal for virtual machines.
//!
//! # Features
//!
//! - **Create QCOW2 Images**: Create new disk images with specified virtual sizes
//! - **Snapshot Management**: Create, delete, and list snapshots for offline images
//! - **Image Information**: Query detailed information about QCOW2 images in JSON format
//! - **Base Image Builder**: Download and configure Ubuntu 24.04 cloud images as base images
//! - **Cross-Platform**: Works on Linux, macOS, and Windows (where QEMU is installed)
//!
//! # Requirements
//!
//! This module requires `qemu-img` to be installed and available on your system PATH.
//! - **Debian/Ubuntu**: `sudo apt-get install qemu-utils`
//! - **macOS**: `brew install qemu`
//! - **RedHat/CentOS**: `sudo yum install qemu-img`
//!
//! # Example
//!
//! ```rust,no_run
//! use herolib_virt::qcow2;
//!
//! // Create a simple disk image
//! let path = qcow2::create("/tmp/disk.qcow2", 20)?;
//! println!("Created image at: {}", path);
//!
//! // Get image information
//! let info = qcow2::info(&path)?;
//! println!("Image info: {:?}", info);
//!
//! // Create snapshots for backup points
//! qcow2::snapshot_create(&path, "before-install")?;
//! qcow2::snapshot_create(&path, "after-install")?;
//!
//! // List all snapshots
//! let snapshots = qcow2::snapshot_list(&path)?;
//! for snap in snapshots {
//! println!("Snapshot: {:?}", snap.name);
//! }
//!
//! // Delete a snapshot
//! qcow2::snapshot_delete(&path, "before-install")?;
//!
//! # Ok::<(), qcow2::Qcow2Error>(())
//! ```
//!
//! # Rhai Scripting
//!
//! QCOW2 operations are also accessible from Rhai scripts:
//!
//! ```rhai
//! // Create a disk image
//! let disk_path = qcow2_create("/tmp/vm-disk.qcow2", 50);
//! print("Created disk: " + disk_path);
//!
//! // Create snapshots
//! qcow2_snapshot_create(disk_path, "initial");
//! qcow2_snapshot_create(disk_path, "with-packages");
//!
//! // List snapshots
//! let snaps = qcow2_snapshot_list(disk_path);
//! for snap in snaps {
//! print("Snapshot: " + snap.name);
//! }
//! ```
//!
//! # Common Patterns
//!
//! ## Creating a VM Disk
//!
//! ```rust,no_run
//! # use herolib_virt::qcow2;
//! // Create a disk for a virtual machine
//! let vm_disk = qcow2::create("/var/vms/my-vm.qcow2", 50)?; // 50 GiB
//! # Ok::<(), qcow2::Qcow2Error>(())
//! ```
//!
//! ## Using Ubuntu Cloud Images as Base
//!
//! ```rust,no_run
//! # use herolib_virt::qcow2;
//! // Download and prepare an Ubuntu 24.04 cloud image
//! let base = qcow2::build_ubuntu_24_04_base("/var/vms/images", Some(100))?;
//! println!("Base image: {}", base.base_image_path);
//! println!("Snapshot: {}", base.snapshot);
//! println!("Downloaded from: {}", base.url);
//! # Ok::<(), qcow2::Qcow2Error>(())
//! ```
//!
//! ## Snapshot Workflow
//!
//! ```rust,no_run
//! # use herolib_virt::qcow2;
//! let disk = "/tmp/system.qcow2";
//! qcow2::create(disk, 30)?;
//!
//! // Create snapshot before changes
//! qcow2::snapshot_create(disk, "before-changes")?;
//!
//! // ... make changes to disk ...
//!
//! // If changes are good, create another snapshot
//! qcow2::snapshot_create(disk, "after-changes")?;
//!
//! // Query all snapshots
//! let snapshots = qcow2::snapshot_list(disk)?;
//! for snap in snapshots {
//! if let Some(name) = snap.name {
//! if let Some(date) = snap.date_sec {
//! println!("Snapshot '{}' created at Unix time {}", name, date);
//! }
//! }
//! }
//!
//! // Clean up old snapshot
//! qcow2::snapshot_delete(disk, "before-changes")?;
//! # Ok::<(), qcow2::Qcow2Error>(())
//! ```
use Value;
use Error;
use fmt;
use fs;
use Path;
use RunError;
/// Error type for qcow2 operations
///
/// Represents various errors that can occur during QCOW2 operations,
/// including command execution failures, IO errors, and validation errors.
/// Create a new QCOW2 disk image at the specified path.
///
/// Creates a new QCOW2 disk image file with the specified virtual size.
/// The actual file size will be smaller due to QCOW2's sparse allocation.
/// The parent directory will be created if it doesn't exist.
///
/// # Arguments
///
/// * `path` - Full path where the QCOW2 image should be created
/// * `size_gb` - Virtual size of the disk in GiB (must be > 0)
///
/// # Returns
///
/// Returns the path to the created image on success
///
/// # Errors
///
/// Returns `Qcow2Error` if:
/// - `qemu-img` is not found on PATH
/// - `size_gb` is <= 0
/// - Parent directory cannot be created
/// - `qemu-img create` command fails
///
/// # Example
///
/// ```rust,no_run
/// use herolib_virt::qcow2;
///
/// let path = qcow2::create("/tmp/my-disk.qcow2", 20)?;
/// println!("Created disk at: {}", path);
/// # Ok::<(), qcow2::Qcow2Error>(())
/// ```
/// Retrieve detailed information about a QCOW2 image.
///
/// Queries the QCOW2 image using `qemu-img info` and returns the result as JSON.
/// The returned object contains properties like virtual size, actual size, snapshots, etc.
///
/// # Arguments
///
/// * `path` - Path to the QCOW2 image file
///
/// # Returns
///
/// A JSON value containing image information including:
/// - `virtual-size`: Virtual size in bytes
/// - `disk-size`: Actual disk usage in bytes
/// - `format`: Image format (should be "qcow2")
/// - `snapshots`: Array of snapshots (if any)
///
/// # Errors
///
/// Returns `Qcow2Error` if:
/// - `qemu-img` is not found
/// - Image file doesn't exist
/// - Image is corrupted or not a valid QCOW2 file
/// - JSON parsing fails
///
/// # Example
///
/// ```rust,no_run
/// use herolib_virt::qcow2;
///
/// let info = qcow2::info("/tmp/disk.qcow2")?;
/// if let Some(virtual_size) = info.get("virtual-size") {
/// println!("Virtual size: {} bytes", virtual_size);
/// }
/// # Ok::<(), qcow2::Qcow2Error>(())
/// ```
/// Create a snapshot of a QCOW2 image (offline).
///
/// Creates a named snapshot of the QCOW2 image. Snapshots are useful for:
/// - Creating restore points before making changes
/// - Testing different configurations
/// - Backing up the system state
///
/// **Note**: The image must not be in use by a running VM when creating snapshots.
///
/// # Arguments
///
/// * `path` - Path to the QCOW2 image file
/// * `name` - Name for the snapshot (cannot be empty)
///
/// # Errors
///
/// Returns `Qcow2Error` if:
/// - `qemu-img` is not found
/// - Snapshot name is empty
/// - Image file doesn't exist or is corrupted
/// - `qemu-img snapshot` command fails
///
/// # Example
///
/// ```rust,no_run
/// use herolib_virt::qcow2;
///
/// let disk = "/tmp/system.qcow2";
/// qcow2::create(disk, 30)?;
///
/// // Create a snapshot before system changes
/// qcow2::snapshot_create(disk, "clean-install")?;
/// # Ok::<(), qcow2::Qcow2Error>(())
/// ```
/// Delete a snapshot from a QCOW2 image (offline).
///
/// Removes a named snapshot from the QCOW2 image. This operation only works
/// when the image is not in use by a running VM.
///
/// # Arguments
///
/// * `path` - Path to the QCOW2 image file
/// * `name` - Name of the snapshot to delete
///
/// # Errors
///
/// Returns `Qcow2Error` if:
/// - `qemu-img` is not found
/// - Snapshot name is empty
/// - Image file doesn't exist
/// - Snapshot doesn't exist
/// - `qemu-img snapshot` command fails
///
/// # Example
///
/// ```rust,no_run
/// use herolib_virt::qcow2;
///
/// let disk = "/tmp/system.qcow2";
/// qcow2::create(disk, 30)?;
/// qcow2::snapshot_create(disk, "checkpoint")?;
///
/// // ... do some work ...
///
/// // Delete the snapshot when no longer needed
/// qcow2::snapshot_delete(disk, "checkpoint")?;
/// # Ok::<(), qcow2::Qcow2Error>(())
/// ```
/// Represents a snapshot of a QCOW2 image.
///
/// This structure contains metadata about a snapshot created on a QCOW2 disk image,
/// including its name, creation date, and size information.
///
/// # Fields
///
/// * `id` - Snapshot ID (internal QEMU identifier)
/// * `name` - Human-readable snapshot name
/// * `vm_state_size` - Size of VM state data in bytes (if VM was running)
/// * `date_sec` - Unix timestamp (seconds) when snapshot was created
/// * `date_nsec` - Nanoseconds component of the timestamp
/// * `vm_clock_nsec` - VM clock value when snapshot was created
///
/// # Example
///
/// ```rust,no_run
/// use herolib_virt::qcow2;
///
/// let snapshots = qcow2::snapshot_list("/tmp/disk.qcow2")?;
/// for snap in snapshots {
/// println!("Snapshot: {:?}", snap.name);
/// if let Some(date) = snap.date_sec {
/// println!(" Created at Unix time: {}", date);
/// }
/// if let Some(size) = snap.vm_state_size {
/// println!(" VM state size: {} bytes", size);
/// }
/// }
/// # Ok::<(), qcow2::Qcow2Error>(())
/// ```
/// List all snapshots in a QCOW2 image (offline).
///
/// Retrieves all snapshots associated with the QCOW2 image.
/// Returns an empty vector if the image has no snapshots.
///
/// # Arguments
///
/// * `path` - Path to the QCOW2 image file
///
/// # Returns
///
/// A vector of `Qcow2Snapshot` structures, one for each snapshot in the image
///
/// # Errors
///
/// Returns `Qcow2Error` if:
/// - `qemu-img` is not found
/// - Image file doesn't exist
/// - Image is corrupted or not a valid QCOW2 file
/// - JSON parsing fails
///
/// # Example
///
/// ```rust,no_run
/// use herolib_virt::qcow2;
///
/// let disk = "/tmp/system.qcow2";
/// qcow2::create(disk, 30)?;
/// qcow2::snapshot_create(disk, "snapshot1")?;
/// qcow2::snapshot_create(disk, "snapshot2")?;
///
/// let snapshots = qcow2::snapshot_list(disk)?;
/// println!("Found {} snapshots", snapshots.len());
/// for snap in snapshots {
/// if let Some(name) = snap.name {
/// println!(" - {}", name);
/// }
/// }
/// # Ok::<(), qcow2::Qcow2Error>(())
/// ```
/// Result of building a base QCOW2 image from a cloud image.
///
/// Returned by `build_ubuntu_24_04_base()` to provide information about
/// the downloaded and configured base image.
///
/// # Fields
///
/// * `base_image_path` - Full path to the downloaded/resized image
/// * `snapshot` - Name of the base snapshot created (usually "base")
/// * `url` - Source URL of the cloud image
/// * `resized_to_gb` - Virtual size if resized, None if not resized
///
/// # Example
///
/// ```rust,no_run
/// use herolib_virt::qcow2;
///
/// let result = qcow2::build_ubuntu_24_04_base("/var/vms/images", Some(100))?;
/// println!("Base image path: {}", result.base_image_path);
/// println!("Snapshot: {}", result.snapshot);
/// println!("Source URL: {}", result.url);
/// if let Some(size) = result.resized_to_gb {
/// println!("Resized to: {} GiB", size);
/// }
/// # Ok::<(), qcow2::Qcow2Error>(())
/// ```
/// Download and prepare an Ubuntu 24.04 cloud image as a QCOW2 base image.
///
/// This convenience function downloads the Canonical Ubuntu 24.04 (Noble) cloud image,
/// optionally resizes it to the specified size, and creates a "base" snapshot.
/// Cloud images are smaller than full VM images and come pre-configured.
///
/// If the image already exists at the destination, it will be reused (not re-downloaded).
///
/// # Arguments
///
/// * `dest_dir` - Directory where the image should be stored
/// * `size_gb` - Optional new virtual size in GiB. If None, uses the cloud image's default size.
/// If Some, resizes the image to the specified size (must be >= cloud image size).
///
/// # Returns
///
/// A `BuildBaseResult` containing:
/// - Path to the downloaded/resized image
/// - Name of the "base" snapshot that was created
/// - Original download URL
/// - Resized size if applicable
///
/// # Errors
///
/// Returns `Qcow2Error` if:
/// - `qemu-img` is not found
/// - Network download fails or image is corrupted
/// - Directory cannot be created
/// - Resize fails (e.g., size is too small)
/// - Snapshot creation fails
///
/// # Example: Create a base image and clone it for VMs
///
/// ```rust,no_run
/// use herolib_virt::qcow2;
///
/// // Download and resize Ubuntu 24.04 image to 100 GiB
/// let base = qcow2::build_ubuntu_24_04_base("/var/vms/images", Some(100))?;
/// println!("Base image ready at: {}", base.base_image_path);
///
/// // Now you can use this as a base image for cloning or snapshot-based VMs
/// # Ok::<(), qcow2::Qcow2Error>(())
/// ```