orcs 0.0.8

Microservices monorepo orchestration tool
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
use crate::git::get_user_info;
use crate::{CommandExt, Error, Project, Recipe, Stage, Template};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::fs::{create_dir_all, read_dir, File};
use std::hash::{Hash, Hasher};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use tracing::{debug, info, instrument};

pub const SERVICE_FOLDER: &str = "srv";
pub const SERVICE_CFG_FILE: &str = "orcs.toml";
pub const SERVICE_CFG_TEMPLATE: &str = "maintainers = [
  \"{{{ user_info }}}\"
]

recipes = []

##################
#     Stages     #
##################

# BUILD STAGE
[stages.build]
depends_on = []

# Actions
actions = [
  \"echo Hello from $ORCS_SERVICE\"
]

# Check
check = \"false\"

# DEPLOY STAGE
[stages.deploy]
depends_on = []

# Actions
actions = []

# Check
check = \"false\"
";

#[derive(Clone, Serialize, Deserialize)]
pub struct Service {
    #[serde(skip)]
    project: Arc<Project>,

    #[serde(skip)]
    pub name: String,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    description: Option<String>,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    maintainers: Vec<String>,

    #[serde(default, skip_serializing_if = "Option::is_none")]
    homepage: Option<String>,

    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    recipes: Vec<String>,

    #[serde(default, skip_serializing_if = "HashMap::is_empty")]
    stages: HashMap<String, Stage>,
}

impl Service {
    #[instrument(skip(project))]
    pub fn create(project: Arc<Project>, name: &str, template: Option<&str>) -> Result<(), Error> {
        info!("Create service {}", name);
        if name.contains("..") {
            return Err(Error::CreateServiceError(
                "illegal sequence in service name",
                name.to_string(),
            ));
        }

        let path = get_service_path(&project.canonical_path(), name);

        // Create the service folder
        debug!("Create service folder {:?}", path);
        create_dir_all(&path)?;

        // Retrieve current user information
        let user_info = get_user_info()?;

        // Create template
        let template = match template {
            Some(template) => Template::from_string(template),
            // Default template
            None => {
                let mut template_map = HashMap::new();
                template_map.insert("orcs.toml".to_string(), SERVICE_CFG_TEMPLATE.to_string());
                Template::from_map(template_map)
            }
        };

        // Render template
        let mut template_data = HashMap::new();
        template_data.insert("service_name", name);
        template_data.insert("user_info", &user_info);

        template.render(path.as_path(), &template_data)?;

        // Done
        Ok(())
    }

    #[instrument(skip(project))]
    pub fn from_name(project: Arc<Project>, name: &str) -> Result<Arc<Self>, Error> {
        // Check if the service exists in the global store
        {
            if let Some(service) = project.services.read().unwrap().get(name) {
                return Ok(service.clone());
            }
        }

        // Load the service from disk
        info!("Load service {}", name);
        let path = get_service_path(&project.canonical_path(), name);

        // Load service from configuration file
        debug!("Load service configuration file");
        let file_path = path.join(SERVICE_CFG_FILE);
        let mut file = File::open(file_path)?;
        let mut data = String::new();
        file.read_to_string(&mut data)?;

        // Store service in project cache
        let service = Arc::new(Self::from_toml(project.clone(), name, &data)?);
        project
            .services
            .write()
            .unwrap()
            .insert(name.to_string(), service.clone());
        Ok(service)
    }

    fn from_toml(project: Arc<Project>, name: &str, data: &str) -> Result<Self, Error> {
        // Load service from TOML
        let mut service = toml::from_str::<Self>(data)?;

        // Inject data
        service.project = project;
        service.name = name.to_string();

        // Load recipes
        service.with_recipes()
    }

    fn with_recipes(&self) -> Result<Self, Error> {
        debug!("Parse recipes for service {}", self.name);
        let mut service = self.clone();

        for recipe_name in &service.recipes {
            // TODO: Decouple loading recipes here
            let recipe = Recipe::from_name(service.project.clone(), &recipe_name)?;
            for (stage_name, recipe_stage) in recipe.stages.clone() {
                match service.stages.get_mut(&stage_name) {
                    Some(service_stage) => {
                        // The stage already exists, let the stage handle replacements.
                        service_stage.use_recipe(recipe_stage)
                    }
                    None => {
                        // The stage doesn't exist, therefore insert the whole stage from the
                        // recipe.
                        service
                            .stages
                            .insert(stage_name.clone(), recipe_stage.clone());
                    }
                }
            }
        }

        Ok(service)
    }

    /// Return the service path
    pub fn path(&self) -> PathBuf {
        get_service_path(&self.project.canonical_path(), &self.name)
    }

    /// Return dependencies for a given stage name
    pub fn depends_on(&self, stage_name: &str) -> Vec<String> {
        let stage = match self.stages.get(stage_name) {
            Some(stage) => stage,
            None => return Default::default(),
        };

        stage.depends_on.clone()
    }

    /// Check if all dependencies are in the latest state for a given stage
    #[instrument(skip(self))]
    pub fn check_deps(&self, stage_name: &str) -> Result<bool, Error> {
        debug!(
            "Check dependencies for service {} in stage {}",
            self.name, stage_name
        );
        let stage = match self.stages.get(stage_name) {
            Some(stage) => stage,
            // The stage doesn't exist for this service, therefore there is
            // nothing to do.
            None => return Ok(true),
        };

        // Run check for all services that this service depends on for the
        // given stage.
        for dep_name in &stage.depends_on {
            debug!("Check {}", dep_name);
            let dep = Service::from_name(self.project.clone(), dep_name)?;
            if !dep.run_check(stage_name)? {
                return Ok(false);
            }
        }

        Ok(true)
    }

    /// Check if all dependent stages are in the latest state for a given stage
    #[instrument(skip(self))]
    pub fn check_dep_stages(&self, stage_name: &str) -> Result<bool, Error> {
        debug!(
            "Check stage dependencies for service {} in stage {}",
            self.name, stage_name
        );

        let stage = match self.project.stages.get(stage_name) {
            Some(stage) => stage,
            // The state does not exist, therefore we set it to up-to-date.
            None => return Ok(true),
        };

        // Run check for all stages that this stage depends on.
        for dep_stage in &stage.depends_on {
            println!("dep_stage: {}", dep_stage);
            if !self.run_check(dep_stage)? {
                return Err(Error::RunStageError(
                    "needs to run another stage before this one",
                    stage_name.to_string(),
                ));
            }
        }

        Ok(true)
    }

    /// Check the service for a given stage
    ///
    /// Returns false if the actions for the given service/stage combo needs
    /// to be run.
    #[instrument(skip(self))]
    pub fn run_check(&self, stage_name: &str) -> Result<bool, Error> {
        info!(
            "Running check for service {} in stage {}",
            self.name, stage_name
        );

        // If the stage does not exist for the service, we can safely skip.
        let stage = match self.stages.get(stage_name) {
            Some(stage) => stage,
            None => return Ok(true),
        };

        // Run the stage in its own bash environment
        let result = Command::new("bash")
            .current_dir(self.path())
            .with_context(&self.project, &self, stage_name)
            .arg("-e")
            .arg("-c")
            // Move to the service folder before running the check
            .arg(format!("{}", stage.check))
            .status()?
            .success();

        if result {
            debug!(
                "Service {} in stage {} is up-to-date",
                self.name, stage_name
            );
        } else {
            debug!(
                "Service {} in stage {} is not up-to-date",
                self.name, stage_name
            );
        }

        Ok(result)
    }

    /// Run the service for a given stage
    #[instrument(skip(self))]
    pub fn run(&self, stage_name: &str) -> Result<(), Error> {
        info!(
            "Start running service {} in stage {}",
            self.name, stage_name
        );

        // If the stage does not exist for the service, we can safely skip.
        let stage = match self.stages.get(stage_name) {
            Some(stage) => stage,
            None => return Ok(()),
        };

        debug!("Running commands:\n{}", stage.actions);

        // Run the stage in its own bash environment
        match Command::new("bash")
            .current_dir(self.path())
            .with_context(&self.project, &self, stage_name)
            .arg("-e")
            .arg("-c")
            // Move to the service folder before running the actions
            .arg(format!("{}", stage.actions))
            .status()?
            .success()
        {
            true => info!("Done running service {} in stage {}", self.name, stage_name),
            false => {
                return Err(Error::RunStageError(
                    "Failed to run stage",
                    stage_name.to_string(),
                ))
            }
        }

        Ok(())
    }
}

impl Eq for Service {}

impl Hash for Service {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.project.path.hash(state);
        self.name.hash(state);
    }
}

impl PartialEq for Service {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name && self.project == other.project
    }
}

impl fmt::Debug for Service {
    /// Custom formatter to prevent recursion with the project
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Service")
            .field("name", &self.name)
            .field("description", &self.description)
            .field("maintainers", &self.maintainers)
            .field("homepage", &self.homepage)
            .field("recipes", &self.recipes)
            .field("stages", &self.stages)
            .finish()
    }
}

/// Return all services in a given project
///
/// As services may be at various depth within the project folder structure,
/// this will iteratively look through all folders until it finds a service
/// configuration file.
#[instrument(skip(project))]
pub fn get_all_services(project: Arc<Project>) -> Result<HashMap<String, Arc<Service>>, Error> {
    debug!("Load all services for project {}", (*project).path);
    let path = Path::new(&project.path).join(SERVICE_FOLDER);

    // It's possible that the 'srv/' folder does not exist yet.
    if !path.is_dir() {
        return Ok(HashMap::new());
    }

    visit_dir(project, &path)
}

/// Gather all services in a folder
fn visit_dir(project: Arc<Project>, dir: &Path) -> Result<HashMap<String, Arc<Service>>, Error> {
    let mut services = HashMap::<String, Arc<Service>>::new();
    for entry in read_dir(dir)? {
        let path = entry?.path();

        // We only need to look at dirs.
        if !path.is_dir() {
            continue;
        }

        // This is a dir, but it doesn't contain a service config file.
        // Scan recursively for service dirs.
        if !path.join(SERVICE_CFG_FILE).is_file() {
            services.extend(visit_dir(project.clone(), &path)?);
        } else {
            let name = get_name_from_path(project.clone(), &path);
            services.insert(name.clone(), Service::from_name(project.clone(), &name)?);
        }
    }

    Ok(services)
}

fn get_name_from_path(project: Arc<Project>, path: &Path) -> String {
    let root = Path::new(&project.path).join(SERVICE_FOLDER);
    path.strip_prefix(root)
        .unwrap()
        .to_str()
        .unwrap()
        .to_string()
}

/// Return the canonical path for a service
fn get_service_path<'a>(project_path: &'a Path, name: &str) -> PathBuf {
    project_path.join(SERVICE_FOLDER).join(name)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_get_name_from_path() {
        let mut project = Project::default();
        project.path = "project".to_string();

        let path = Path::new(&project.path)
            .join(SERVICE_FOLDER)
            .join("a")
            .join("b")
            .join("c");
        let name = get_name_from_path(Arc::new(project), path.as_path());

        assert_eq!(&name, if cfg!(windows) { "a\\b\\c" } else { "a/b/c" });
    }

    #[test]
    fn test_get_service_path() {
        let project_path = Path::new("project");
        let name = if cfg!(windows) { "a\\b\\c" } else { "a/b/c" };

        let path = get_service_path(&project_path, name);

        assert_eq!(
            path,
            Path::new(project_path).join(SERVICE_FOLDER).join(name)
        )
    }
}