ambient-ci 0.14.0

A continuous integration engine
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
use std::path::{Path, PathBuf};

use clap::Parser;
use tempfile::tempdir;

use ambient_ci::{
    action::UnsafeAction,
    cloud_init::{CloudInitError, LocalDataStoreBuilder},
    image_store::{ImageStore, ImageStoreError, MetadataBuilder},
    plan::RunnablePlan,
    qemu::{self, QemuError, QemuRunner},
    qemu_utils::{convert_image, QemuUtilError},
    run::{create_cloud_init_iso, create_executor_vdrive, create_source_vdrive},
    runlog::{RunLog, RunLogSource},
    util::{cat_text_file, mkdir, UtilError},
    vdrive::VirtualDriveError,
};

use super::{AmbientError, Config, Leaf};

const SECRET: &str = "xyzzy";

/// Prepare image.
#[derive(Debug, Parser)]
pub struct PrepareImage {
    /// The name of the image in the image store to use as the base image.
    #[clap(long)]
    base: String,

    /// The name of the image in the new prepared image in the image store.
    #[clap(long)]
    new: String,

    /// Location of the ambient-execute-plan binary.
    #[clap(long)]
    executor: PathBuf,

    /// Enable network?
    #[clap(long)]
    network: bool,

    /// Run log goes to this file.
    #[clap(long)]
    run_log: Option<PathBuf>,

    /// Console log goes to this file.
    #[clap(long)]
    console_log: Option<PathBuf>,

    /// Run shell command to modify image.
    #[clap(long)]
    shell: Option<String>,
}

impl Leaf for PrepareImage {
    fn run(&self, config: &Config, _runlog: &mut RunLog) -> Result<(), AmbientError> {
        let mut image_store =
            ImageStore::new(config.image_store()).map_err(ImageError::ImageStore)?;
        if image_store.contains(&self.new) {
            return Err(ImageError::ExistsAlready(self.new.clone()).into());
        }
        if let Some(metadata) = image_store.get_metadata(&self.base) {
            let filename = image_store.image_filename(metadata);
            if !filename.exists() {
                return Err(ImageError::NoSuchFile(filename.clone()).into());
            }

            let filename = std::fs::canonicalize(&filename)
                .map_err(|err| ImageError::Canonicalize(filename.clone(), err))?;

            let tmp = tempdir().map_err(ImageError::TempDir)?;
            let cow_image = tmp.path().join("new.qcow2");
            let src = tmp.path().join("src");
            mkdir(&src).map_err(ImageError::Util)?;

            let mut plan = RunnablePlan::default();

            let shell = self.shell.clone().unwrap_or("echo hello, world".into());

            plan.push_unsafe_actions(
                [
                    UnsafeAction::mkdir(Path::new(qemu::WORKSPACE_DIR)),
                    UnsafeAction::mkdir(Path::new(qemu::SOURCE_DIR)),
                    UnsafeAction::shell(&shell),
                ]
                .iter(),
            );
            plan.set_executor_drive(qemu::EXECUTOR_DRIVE);
            plan.set_source_drive(qemu::SOURCE_DRIVE);
            plan.set_source_dir(qemu::SOURCE_DIR);
            let executor_drive = create_executor_vdrive(&tmp, &plan, &self.executor)
                .map_err(ImageError::CreateDrive)?;
            let source_drive = create_source_vdrive(&tmp, &src).map_err(ImageError::CreateDrive)?;

            let run_log = self
                .run_log
                .clone()
                .unwrap_or_else(|| tmp.path().join("run.log"));
            let console_log = self
                .console_log
                .clone()
                .unwrap_or_else(|| tmp.path().join("console.log"));

            let ds = create_cloud_init_iso(self.network).map_err(ImageError::CreateDrive)?;

            let mut runlog = RunLog::default();
            let res = QemuRunner::default()
                .config(config)
                .base_image(&filename)
                .cow_image(&cow_image)
                .executor(&executor_drive)
                .source(&source_drive)
                .cloud_init(&ds)
                .console_log(&console_log)
                .raw_log(&run_log)
                .network(self.network)
                .run(RunLogSource::Plan, &mut runlog)
                .map_err(ImageError::Qemu);

            res?;

            let full_image = tmp.path().join("full.qcow2");
            convert_image(&cow_image, &full_image).map_err(|err| {
                ImageError::ConvertImage(cow_image.clone(), full_image.clone(), err)
            })?;

            let mut new_metadata =
                MetadataBuilder::new(&self.new, &full_image).map_err(ImageError::ImageStore)?;
            new_metadata.uefi(metadata.uefi());
            let new_metadata = new_metadata.build();

            image_store
                .import(new_metadata)
                .map_err(ImageError::ImageStore)?;
            image_store.save().map_err(ImageError::ImageStore)?;

            Ok(())
        } else {
            Err(ImageError::NoSuchImage(self.base.clone()).into())
        }
    }
}

/// Verify that a virtual machine image is acceptable for use with
/// ambient. This is done by booting a VM using the image, and
/// making sure the VM run the provided executable and then shuts down.
///
/// If the verification doesn't finish within a reasonable time, the
/// image is not acceptable.
#[derive(Debug, Parser)]
pub struct VerifyImage {
    /// The name of the image in the image store to test.
    #[clap(long)]
    name: String,

    /// Location of the ambient-execute-plan binary.
    #[clap(long)]
    executor: PathBuf,

    /// Enable network?
    #[clap(long)]
    network: bool,

    /// Run log goes to this file.
    #[clap(long)]
    run_log: Option<PathBuf>,

    /// Console log goes to this file.
    #[clap(long)]
    console_log: Option<PathBuf>,
}

impl Leaf for VerifyImage {
    fn run(&self, config: &Config, _runlog: &mut RunLog) -> Result<(), AmbientError> {
        let image_store = ImageStore::new(config.image_store()).map_err(ImageError::ImageStore)?;
        if let Some(metadata) = image_store.get_metadata(&self.name) {
            let filename = image_store.image_filename(metadata);
            if !filename.exists() {
                return Err(ImageError::NoSuchFile(filename.clone()).into());
            }

            let filename = std::fs::canonicalize(&filename)
                .map_err(|err| ImageError::Canonicalize(filename.clone(), err))?;

            let tmp = tempdir().map_err(ImageError::TempDir)?;
            let src = tmp.path().join("src");
            mkdir(&src).map_err(ImageError::Util)?;

            let mut plan = RunnablePlan::default();
            plan.push_unsafe_actions(
                [
                    UnsafeAction::mkdir(Path::new(qemu::WORKSPACE_DIR)),
                    UnsafeAction::mkdir(Path::new(qemu::SOURCE_DIR)),
                    UnsafeAction::shell(&format!("echo {SECRET}")),
                ]
                .iter(),
            );
            plan.set_executor_drive(qemu::EXECUTOR_DRIVE);
            plan.set_source_drive(qemu::SOURCE_DRIVE);
            plan.set_source_dir(qemu::SOURCE_DIR);
            let executor_drive = create_executor_vdrive(&tmp, &plan, &self.executor)
                .map_err(ImageError::CreateDrive)?;
            let source_drive = create_source_vdrive(&tmp, &src).map_err(ImageError::CreateDrive)?;

            let run_log = self
                .run_log
                .clone()
                .unwrap_or_else(|| tmp.path().join("run.log"));
            let console_log = self
                .console_log
                .clone()
                .unwrap_or_else(|| tmp.path().join("console.log"));

            let ds = create_cloud_init_iso(self.network).map_err(ImageError::CreateDrive)?;

            let mut runlog = RunLog::default();
            let res = QemuRunner::default()
                .config(config)
                .base_image(&filename)
                .executor(&executor_drive)
                .source(&source_drive)
                .cloud_init(&ds)
                .console_log(&console_log)
                .raw_log(&run_log)
                .network(self.network)
                .run(RunLogSource::Plan, &mut runlog)
                .map_err(ImageError::Qemu);

            let log = cat_text_file(&run_log).map_err(ImageError::Util)?;
            if !log.contains(SECRET) {
                return Err(ImageError::NotAcceptable(filename.clone()).into());
            }
            println!("image {} is acceptable to Ambient", filename.display());

            res?;
            Ok(())
        } else {
            Err(ImageError::NoSuchImage(self.name.clone()).into())
        }
    }
}

/// Create a cloud-init local data store ISO file.
#[derive(Debug, Parser)]
pub struct CloudInit {
    /// The name of the ISO file.
    #[clap(long)]
    filename: PathBuf,

    /// Commands to run via cloud-init.
    #[clap(long)]
    runcmd: Vec<String>,

    /// Enable networking?
    #[clap(long)]
    network: bool,
}

impl Leaf for CloudInit {
    fn run(&self, _config: &Config, _runlog: &mut RunLog) -> Result<(), AmbientError> {
        let mut ds = LocalDataStoreBuilder::default()
            .with_network(self.network)
            .with_hostname("ambient")
            .with_bootcmd("echo xyzzy2")
            .with_bootcmd("echo more bootcmd");
        for runcmd in self.runcmd.iter() {
            ds = ds.with_runcmd(runcmd);
        }
        let ds = ds.build().map_err(ImageError::CloudInit)?;
        ds.iso(&self.filename).map_err(ImageError::CloudInit)?;
        Ok(())
    }
}

/// List names of images in the image store.
#[derive(Debug, Parser)]
pub struct ListImages {}

impl Leaf for ListImages {
    fn run(&self, config: &Config, _runlog: &mut RunLog) -> Result<(), AmbientError> {
        let image_store = ImageStore::new(config.image_store()).map_err(ImageError::ImageStore)?;
        for name in image_store.image_names().map_err(ImageError::ImageStore)? {
            println!("{name}");
        }
        Ok(())
    }
}

/// Import images in the image store.
#[derive(Debug, Parser)]
pub struct ImportImage {
    /// Name of image in the store.
    name: String,

    /// File name of the image to import and copy into the store.
    image: PathBuf,

    /// Description of image.
    #[clap(short, long)]
    description: Option<String>,

    /// URL for origin of image.
    #[clap(short, long)]
    url: Option<String>,

    /// Should the image be booted with UEFI?
    #[clap(long)]
    uefi: bool,
}

impl Leaf for ImportImage {
    fn run(&self, config: &Config, _runlog: &mut RunLog) -> Result<(), AmbientError> {
        let mut metadata =
            MetadataBuilder::new(&self.name, &self.image).map_err(ImageError::ImageStore)?;
        if let Some(d) = &self.description {
            metadata.description(d);
        }
        if let Some(u) = &self.url {
            metadata.url(u);
        }
        metadata.uefi(self.uefi || config.uefi());
        let metadata = metadata.build();

        let mut image_store =
            ImageStore::new(config.image_store()).map_err(ImageError::ImageStore)?;
        image_store
            .import(metadata)
            .map_err(ImageError::ImageStore)?;
        image_store.save().map_err(ImageError::ImageStore)?;
        Ok(())
    }
}

/// Remove images from the image store.
#[derive(Debug, Parser)]
pub struct RemoveImages {
    /// Names of image to remove.
    images: Vec<String>,
}

impl Leaf for RemoveImages {
    fn run(&self, config: &Config, _runlog: &mut RunLog) -> Result<(), AmbientError> {
        let mut image_store =
            ImageStore::new(config.image_store()).map_err(ImageError::ImageStore)?;
        for image in self.images.iter() {
            image_store.remove(image).map_err(ImageError::ImageStore)?;
        }
        image_store.save().map_err(ImageError::ImageStore)?;
        Ok(())
    }
}

/// Show information about an image in the image store.
#[derive(Debug, Parser)]
pub struct ShowImage {
    /// Name of image.
    image: String,
}

impl Leaf for ShowImage {
    fn run(&self, config: &Config, _runlog: &mut RunLog) -> Result<(), AmbientError> {
        let image_store = ImageStore::new(config.image_store()).map_err(ImageError::ImageStore)?;
        if let Some(image) = image_store.get_metadata(&self.image) {
            println!("{}", image.to_json().map_err(ImageError::ImageStore)?);
            Ok(())
        } else {
            Err(ImageError::NoSuchImage(self.image.clone()))?
        }
    }
}

#[derive(Debug, thiserror::Error)]
pub enum ImageError {
    #[error(transparent)]
    Qemu(#[from] QemuError),

    #[error("failed to create a temporary directory")]
    TempDir(#[source] std::io::Error),

    #[error(transparent)]
    Util(#[from] UtilError),

    #[error(transparent)]
    VDrive(#[from] VirtualDriveError),

    #[error(transparent)]
    CloudInit(#[from] CloudInitError),

    #[error("image {0} does not exist")]
    NoSuchFile(PathBuf),

    #[error("image {0} does not exist in the image store")]
    NoSuchImage(String),

    #[error("image {0} is NOT an acceptable image for Ambient")]
    NotAcceptable(PathBuf),

    #[error("image store already contains {0}")]
    ExistsAlready(String),

    #[error(transparent)]
    CreateDrive(#[from] ambient_ci::run::RunError),

    #[error(transparent)]
    ImageStore(#[from] ImageStoreError),

    #[error("failed to make filename canonical: {0}")]
    Canonicalize(PathBuf, #[source] std::io::Error),

    #[error("failed to convert image {0} to {1}")]
    ConvertImage(PathBuf, PathBuf, #[source] QemuUtilError),
}