quickcfg 0.6.3

Do basic configuration of a system, declaratively and quickly.
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
use anyhow::{anyhow, bail, Context as _, Error};
use directories::BaseDirs;

use quickcfg::{
    environment as e,
    facts::Facts,
    git, hierarchy,
    opts::{self, Opts},
    packages, stage,
    system::{self, SystemInput},
    unit::{self, Unit, UnitAllocator, UnitInput},
    Config, DiskState, FileSystem, Load, Save, State, Timestamp,
};
use std::collections::HashMap;
use std::fs;
use std::path::Path;

fn report_error(e: Error) {
    let mut it = e.chain();

    if let Some(e) = it.next() {
        eprintln!("Error: {}", e);

        #[cfg(feature = "nightly")]
        {
            if let Some(bt) = e.backtrace() {
                eprintln!("{}", bt);
            }
        }
    }

    for e in it {
        eprintln!("Caused by: {}", e);

        #[cfg(feature = "nightly")]
        {
            if let Some(bt) = e.backtrace() {
                eprintln!("{}", bt);
            }
        }
    }
}

fn main() {
    use std::process;

    if let Err(e) = try_main() {
        report_error(e);
        process::exit(1);
    }
}

fn try_main() -> Result<(), Error> {
    pretty_env_logger::formatted_builder()
        .parse_filters("trace")
        .init();

    let base_dirs = BaseDirs::new();

    let mut opts = opts::opts()?;
    let root = opts.root(base_dirs.as_ref())?;

    let config_path = root.join("quickcfg.yml");
    let state_path = root.join(".state.yml");
    let state_dir = root.join(".state");

    if opts.paths {
        println!("OS: {}", std::env::consts::OS);
        println!("Root: {}", root.display());
        println!("Configuration File: {}", config_path.display());
        println!("State File: {}", state_path.display());
        println!("State Dir: {}", state_dir.display());
        return Ok(());
    }

    if opts.debug {
        log::set_max_level(log::LevelFilter::Trace);
    } else {
        log::set_max_level(log::LevelFilter::Info);
    }

    if !root.is_dir()
        && opts.init.is_none()
        && opts.prompt(
            "No configuration directory, would you like to set it up?",
            true,
        )?
    {
        opts.init = opts.input("[Git Repository]")?;
    }

    let git_system = git::setup().with_context(|| "failed to set up git system")?;

    if let Some(init) = opts.init.as_ref() {
        log::info!("Initializing {} from {}", root.display(), init);
        try_init(&*git_system, init, &root)?;
    } else {
        log::trace!("Using config from {}", root.display());
    }

    if !root.is_dir() {
        bail!("Missing configuration directory: {}", root.display());
    }

    if !state_dir.is_dir() {
        fs::create_dir(&state_dir).with_context(|| {
            anyhow!("Failed to create state directory: {}", state_dir.display())
        })?;
    }

    let config = Config::load(&config_path)
        .with_context(|| anyhow!("Failed to load configuration: {}", config_path.display()))?
        .unwrap_or_default();
    let now = Timestamp::now();

    let state = match DiskState::load(&state_path) {
        Ok(state) => state.unwrap_or_default(),
        Err(err) => {
            log::error!("Invalid disk state `{}`: {}", state_path.display(), err);

            if !opts.prompt("Remove it?", true)? {
                return Ok(());
            }

            DiskState::default()
        }
    };

    let mut state = state.into_state(&config, now);

    let result = try_apply_config(
        &*git_system,
        &opts,
        &config,
        now,
        base_dirs.as_ref(),
        &root,
        &state_dir,
        &mut state,
    );

    if let Some(serialized) = state.serialize() {
        log::trace!("Writing state: {}", state_path.display());
        serialized.save(&state_path)?;
    }

    result
}

/// Try to initialize the repository from the given path.
fn try_init(git_system: &dyn git::GitSystem, url: &str, root: &Path) -> Result<(), Error> {
    let _ = git::GitSystem::clone(git_system, url, root)?;
    Ok(())
}

#[allow(clippy::too_many_arguments)]
/// Internal method to try to apply the given configuration.
fn try_apply_config(
    git_system: &dyn git::GitSystem,
    opts: &Opts,
    config: &Config,
    now: Timestamp,
    base_dirs: Option<&BaseDirs>,
    root: &Path,
    state_dir: &Path,
    state: &mut State<'_>,
) -> Result<(), Error> {
    use rayon::prelude::*;

    let pool = rayon::ThreadPoolBuilder::new()
        .build()
        .with_context(|| anyhow!("Failed to construct thread pool"))?;

    if !try_update_config(git_system, opts, config, now, root, state)? {
        // if we only want to run on updates, exit now.
        if opts.updates_only {
            return Ok(());
        }
    }

    if opts.updates_only {
        log::info!("Updated found, running...");
    }

    let facts = Facts::load().with_context(|| "Failed to load facts")?;
    let environment = e::Real;
    let data = hierarchy::load(&config.hierarchy, root, &facts, environment)
        .with_context(|| "Failed to load hierarchy")?;

    let packages = packages::detect(&facts)?;

    let allocator = UnitAllocator::default();

    let file_system = FileSystem::new(opts, state_dir, &allocator, &data);

    // post-hook for all systems, mapped by id.
    let mut post_systems = HashMap::new();
    let mut all_units = Vec::new();
    let mut pre_systems = Vec::new();
    let mut errors = Vec::new();

    // translate systems that needs translation.
    let systems = {
        use std::collections::VecDeque;

        let mut out = Vec::with_capacity(config.systems.len());
        let mut queue = VecDeque::new();
        queue.extend(&config.systems);

        while let Some(system) = queue.pop_back() {
            match system.translate() {
                system::Translation::Discard => {}
                system::Translation::Keep => out.push(system),
                system::Translation::Expand(systems) => queue.extend(systems),
            }
        }

        out
    };

    pool.install(|| {
        let res = systems.par_iter().map(|system| {
            let res = system.apply(SystemInput {
                root,
                base_dirs,
                facts: &facts,
                data: &data,
                packages: &packages,
                environment,
                allocator: &allocator,
                file_system: &file_system,
                state,
                now,
                opts,
                git_system,
            });

            match res {
                Ok(units) => Ok((system, units)),
                Err(e) => Err((system, e)),
            }
        });

        // Collect all units and map out a unit id to each system that can be used as a dependency.
        for res in res.collect::<Vec<_>>() {
            let (system, mut units) = match res {
                Ok(result) => result,
                Err((system, e)) => {
                    errors.push((system, e));
                    continue;
                }
            };

            if !system.requires().is_empty() {
                // Unit that all contained units depend on.
                // This unit finishes _before_ any unit in the system.
                let pre = allocator.unit(Unit::System);

                for unit in &mut units {
                    unit.dependencies.push(unit::Dependency::Unit(pre.id));
                }

                pre_systems.push((pre, system::Dependency::Transitive(system.requires())));
            }

            if let Some(system_id) = system.id() {
                if units.is_empty() {
                    // If system is empty, there is nothing to depend on.
                    post_systems
                        .insert(system_id, system::Dependency::Transitive(system.requires()));
                    continue;
                }

                // Unit that other systems depend on.
                // This unit finishes _after_ all units in the system have finished.
                // System units depend on all units it contains.
                let mut post = allocator.unit(Unit::System);
                post.dependencies
                    .extend(units.iter().map(|u| unit::Dependency::Unit(u.id)));
                post_systems.insert(system_id, system::Dependency::Direct(post.id));
                all_units.push(post);
            }

            all_units.extend(units);
        }
    });

    file_system.validate()?;

    if !errors.is_empty() {
        for (system, e) in errors.into_iter() {
            log::error!("System failed: {}", system);
            report_error(e);
        }

        bail!("Failed to run all systems");
    }

    // Wire up systems that have requires.
    for (mut pre, depend) in pre_systems {
        pre.dependencies.extend(depend.resolve(&post_systems));
        all_units.push(pre);
    }

    // Schedule all units into stages that can be run independently in parallel.
    let mut scheduler = stage::Stager::new(all_units);

    let mut errors = Vec::new();
    let mut i = 0;

    // Note: convert into a scoped pool that feeds units to be scheduled.
    pool.install(|| {
        while let Some(stage) = scheduler.stage() {
            i += 1;

            if log::log_enabled!(log::Level::Trace) {
                log::trace!(
                    "Running stage #{} ({} unit(s)) (thread_local: {})",
                    i,
                    stage.units.len(),
                    stage.thread_local
                );

                for (i, unit) in stage.units.iter().enumerate() {
                    log::trace!("{:2}: {}", i, unit);
                }
            }

            if stage.thread_local {
                for unit in stage.units {
                    let mut s = State::new(config, now);

                    match unit.apply(UnitInput {
                        data: &data,
                        packages: &packages,
                        read_state: state,
                        state: &mut s,
                        now,
                        git_system,
                    }) {
                        Ok(()) => {
                            scheduler.mark(unit);
                        }
                        Err(e) => {
                            errors.push((unit, e));
                        }
                    }

                    state.extend(s);
                }

                continue;
            }

            let results = stage
                .units
                .into_par_iter()
                .map(|unit| {
                    let mut s = State::new(config, now);

                    let res = unit.apply(UnitInput {
                        data: &data,
                        packages: &packages,
                        read_state: state,
                        state: &mut s,
                        now,
                        git_system,
                    });

                    (res, unit, s)
                })
                .collect::<Vec<_>>();

            for (res, unit, s) in results {
                match res {
                    Ok(()) => {
                        scheduler.mark(unit);
                    }
                    Err(e) => {
                        errors.push((unit, e));
                    }
                }

                state.extend(s);
            }
        }
    });

    if !errors.is_empty() {
        for (i, (unit, e)) in errors.into_iter().enumerate() {
            log::error!("{:2}: {}", i, unit);
            report_error(e);
        }

        bail!("Failed to run all units");
    }

    let unscheduled = scheduler.into_unstaged();

    if !unscheduled.is_empty() {
        if log::log_enabled!(log::Level::Trace) {
            log::trace!("Unable to schedule the following units:");

            for (i, unit) in unscheduled.into_iter().enumerate() {
                log::trace!("{:2}: {}", i, unit);
            }
        }

        bail!("Could not schedule all units");
    }

    Ok(())
}

/// Try to update config from git.
///
/// Returns `true` if we have successfully downloaded a new update. `false` otherwise.
fn try_update_config(
    git_system: &dyn git::GitSystem,
    opts: &Opts,
    config: &Config,
    now: Timestamp,
    root: &Path,
    state: &mut State,
) -> Result<bool, Error> {
    if let Some(last_update) = state.last_update("git") {
        let duration = now.duration_since(*last_update)?;

        if duration < config.git_refresh {
            return Ok(false);
        }

        log::info!("{}s since last git update...", duration.as_secs());
    };

    if !opts.prompt("Do you want to check for updates?", true)? {
        return Ok(false);
    }

    if !git_system.test()? {
        log::warn!("no working git command found");
        state.touch("git");
        return Ok(false);
    }

    let git = git_system.open(root)?;

    if !git.needs_update()? {
        state.touch("git");
        return Ok(false);
    }

    if opts.force {
        git.force_update()?;
    } else {
        git.update()?;
    }

    state.touch("git");
    Ok(true)
}