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
use serde_json;
use chrono::UTC;
use std::path::{Path, PathBuf};
use std::fs;
use std::vec::Vec;
use std::io::prelude::*;
use std::collections::BTreeMap;
use std::env;

use super::{Container, LalResult, CliError};
use storage::BackendConfiguration;

fn find_home_dir() -> PathBuf {
    // Either we have LAL_CONFIG_HOME evar, or HOME
    if let Ok(lh) = env::var("LAL_CONFIG_HOME") {
        Path::new(&lh).to_owned()
    } else {
        env::home_dir().unwrap()
    }
}

/// Master override for where the .lal config lives
pub fn config_dir() -> PathBuf {
    let home = find_home_dir();
    Path::new(&home).join(".lal")
}

/// Docker volume mount representation
#[derive(Serialize, Deserialize, Clone)]
pub struct Mount {
    /// File or folder to mount
    pub src: String,
    /// Location inside the container to mount it at
    pub dest: String,
    /// Whether or not to write protect the mount inside the container
    pub readonly: bool,
}

/// Representation of `~/.lal/config`
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Clone)]
pub struct Config {
    /// Configuration settings for the `Backend`
    pub backend: BackendConfiguration,
    /// Cache directory for global and stashed builds
    pub cache: String,
    /// Environments shorthands that are allowed and their full meaning
    pub environments: BTreeMap<String, Container>,
    /// Time of last upgrade
    pub lastUpgrade: String,
    /// Whether to perform automatic upgrade
    pub autoupgrade: bool,
    /// Extra volume mounts to be set for the container
    pub mounts: Vec<Mount>,
    /// Force inteactive shells
    pub interactive: bool,
    /// Minimum version restriction of lal enforced by this config
    pub minimum_lal: Option<String>,
}

/// Representation of a configuration defaults file
///
/// This file is being used to generate the config when using `lal configure`
#[derive(Serialize, Deserialize, Clone, Default)]
pub struct ConfigDefaults {
    /// Configuration settings for the `Backend`
    pub backend: BackendConfiguration,
    /// Environments shorthands that are allowed and their full meaning
    pub environments: BTreeMap<String, Container>,
    /// Extra volume mounts to be set for the container
    pub mounts: Vec<Mount>,
    /// Optional minimum version restriction of lal
    pub minimum_lal: Option<String>,
}

impl ConfigDefaults {
    /// Open and deserialize a defaults file
    pub fn read(file: &str) -> LalResult<ConfigDefaults> {
        let pth = Path::new(file);
        if !pth.exists() {
            error!("No such defaults file '{}'", file); // file open will fail below
        }
        let mut f = fs::File::open(&pth)?;
        let mut data = String::new();
        f.read_to_string(&mut data)?;
        let defaults: ConfigDefaults = serde_json::from_str(&data)?;
        Ok(defaults)
    }
}

fn check_mount(name: &str) -> LalResult<String> {
    // See if it's a path first:
    let home = find_home_dir();
    let src = name.to_string().replace("~", &home.to_string_lossy());
    let mount_path = Path::new(&src);
    if mount_path.exists() {
        debug!("Configuring existing mount {}", &src);
        return Ok(src.clone()); // pass along the real source
    }

    // Otherwise, if it does not contain a slash
    if !name.contains("/") {
        use std::process::Command;
        let volume_output = Command::new("docker").args(vec!["volume", "ls", "-q"]).output()?;
        let volstr = String::from_utf8_lossy(&volume_output.stdout);
        // If it exists, do nothing:
        if volstr.contains(name) {
            debug!("Configuring existing volume {}", name);
            return Ok(name.into());
        }
        // Otherwise warn
        warn!("Discarding missing docker volume {}", name);
        Err(CliError::MissingMount(name.into()))
    } else {
        warn!("Discarding missing mount {}", src);
        Err(CliError::MissingMount(src.clone()))
    }
}


impl Config {
    /// Initialize a Config with ConfigDefaults
    ///
    /// This will locate you homedir, and set last update check 2 days in the past.
    /// Thus, with a blank default config, you will always trigger an upgrade check.
    pub fn new(defaults: ConfigDefaults) -> Config {
        let cachepath = config_dir().join("cache");
        let cachedir = cachepath.as_path().to_str().unwrap();

        // reset last update time
        let time = UTC::now();

        // scan default mounts
        let mut mounts = vec![];
        for mount in defaults.mounts {
            // Check src for pathiness or prepare a docker volume
            match check_mount(&mount.src) {
                Ok(src) => {
                    let mut mountnew = mount.clone();
                    mountnew.src = src; // update potentially mapped source
                    mounts.push(mountnew);
                }
                Err(e) => debug!("Ignoring mount check error {}", e),
            }
        }

        Config {
            cache: cachedir.into(),
            mounts: mounts, // the filtered defaults
            lastUpgrade: time.to_rfc3339(),
            autoupgrade: cfg!(feature = "upgrade"),
            environments: defaults.environments,
            backend: defaults.backend,
            minimum_lal: defaults.minimum_lal,
            interactive: true,
        }
    }

    /// Read and deserialize a Config from ~/.lal/config
    pub fn read() -> LalResult<Config> {
        let cfg_path = config_dir().join("config");
        if !cfg_path.exists() {
            return Err(CliError::MissingConfig);
        }
        let mut f = fs::File::open(&cfg_path)?;
        let mut cfg_str = String::new();
        f.read_to_string(&mut cfg_str)?;
        let res: Config = serde_json::from_str(&cfg_str)?;
        if res.environments.contains_key("default") {
            return Err(CliError::InvalidEnvironment);
        }
        Ok(res)
    }

    /// Checks if it is time to perform an upgrade check
    #[cfg(feature = "upgrade")]
    pub fn upgrade_check_time(&self) -> bool {
        use chrono::{Duration, DateTime};
        let last = self.lastUpgrade.parse::<DateTime<UTC>>().unwrap();
        let cutoff = UTC::now() - Duration::days(1);
        last < cutoff
    }
    /// Update the lastUpgrade time to avoid triggering it for another day
    #[cfg(feature = "upgrade")]
    pub fn performed_upgrade(&mut self) -> LalResult<()> {
        self.lastUpgrade = UTC::now().to_rfc3339();
        Ok(self.write(true)?)
    }

    /// Overwrite `~/.lal/config` with serialized data from this struct
    pub fn write(&self, silent: bool) -> LalResult<()> {
        let cfg_path = config_dir().join("config");
        let encoded = serde_json::to_string_pretty(self)?;

        let mut f = fs::File::create(&cfg_path)?;
        write!(f, "{}\n", encoded)?;
        if !silent {
            info!("Wrote config to {}", cfg_path.display());
        }
        debug!("Wrote config \n{}", encoded);
        Ok(())
    }

    /// Resolve an arbitrary container shorthand
    pub fn get_container(&self, env: String) -> LalResult<Container> {
        if let Some(container) = self.environments.get(&env) {
            return Ok(container.clone());
        }
        Err(CliError::MissingEnvironment(env))
    }
}