summaryrefslogtreecommitdiffstats
path: root/src/orchestrator/orchestrator.rs
blob: eb03c0abd3ee2acfe65e58218aa1079f12fb7559 (plain)
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
use std::io::Write;
use std::path::PathBuf;
use std::result::Result as RResult;
use std::sync::Arc;

use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use anyhow::anyhow;
use diesel::PgConnection;
use log::trace;
use tokio::sync::RwLock;
use typed_builder::TypedBuilder;

use crate::config::Configuration;
use crate::db::models::Artifact;
use crate::db::models::Submit;
use crate::endpoint::ContainerError;
use crate::endpoint::EndpointConfiguration;
use crate::endpoint::EndpointScheduler;
use crate::filestore::MergedStores;
use crate::filestore::ReleaseStore;
use crate::filestore::StagingStore;
use crate::job::JobSet;
use crate::job::RunnableJob;
use crate::source::SourceCache;
use crate::util::progress::ProgressBars;

pub struct Orchestrator<'a> {
    scheduler: EndpointScheduler,
    progress_generator: ProgressBars,
    merged_stores: MergedStores,
    source_cache: SourceCache,
    jobsets: Vec<JobSet>,
    config: &'a Configuration,
}

#[derive(TypedBuilder)]
pub struct OrchestratorSetup<'a> {
    progress_generator: ProgressBars,
    endpoint_config: Vec<EndpointConfiguration>,
    staging_store: Arc<RwLock<StagingStore>>,
    release_store: Arc<RwLock<ReleaseStore>>,
    source_cache: SourceCache,
    jobsets: Vec<JobSet>,
    database: PgConnection,
    submit: Submit,
    log_dir: Option<PathBuf>,
    config: &'a Configuration,
}

impl<'a> OrchestratorSetup<'a> {
    pub async fn setup(self) -> Result<Orchestrator<'a>> {
        let db = Arc::new(self.database);
        let scheduler = EndpointScheduler::setup(self.endpoint_config, self.staging_store.clone(), db, self.submit.clone(), self.log_dir).await?;

        Ok(Orchestrator {
            scheduler:     scheduler,
            progress_generator: self.progress_generator,
            merged_stores: MergedStores::new(self.release_store, self.staging_store),
            source_cache:  self.source_cache,
            jobsets:       self.jobsets,
            config:        self.config,
        })
    }
}

impl<'a> Orchestrator<'a> {

    pub async fn run(self) -> Result<Vec<Artifact>> {
        let mut report_result = vec![];
        for jobset in self.jobsets.into_iter() {
            let mut results = Self::run_jobset(&self.scheduler,
                &self.merged_stores,
                &self.source_cache,
                &self.config,
                &self.progress_generator,
                jobset)
                .await?;

            report_result.append(&mut results);
        }

        Ok(report_result)
    }

    async fn run_jobset(
        scheduler: &EndpointScheduler,
        merged_store: &MergedStores,
        source_cache: &SourceCache,
        config: &Configuration,
        progress_generator: &ProgressBars,
        jobset: JobSet)
        -> Result<Vec<Artifact>>
    {
        use tokio::stream::StreamExt;

        let multibar = Arc::new(indicatif::MultiProgress::new());
        let results = jobset // run the jobs in the set
            .into_runables(&merged_store, source_cache, config)
            .await?
            .into_iter()
            .map(|runnable| {
                let bar = multibar.add(progress_generator.job_bar(runnable.uuid()));
                Self::run_runnable(runnable, scheduler, bar)
            })
            .collect::<futures::stream::FuturesUnordered<_>>()
            .collect::<Vec<RResult<Vec<Artifact>, ContainerError>>>();

        let multibar_block = tokio::task::spawn_blocking(move || multibar.join());

        let (results, barres) = tokio::join!(results, multibar_block);
        let _ = barres?;
        let (okays, errors): (Vec<_>, Vec<_>) = results
            .into_iter()
            .inspect(|e| trace!("Processing result from jobset run: {:?}", e))
            .partition(|e| e.is_ok());

        let results = okays.into_iter().filter_map(Result::ok).flatten().collect::<Vec<Artifact>>();

        {
            let mut out = std::io::stderr();
            for error in errors {
                if let Err(e) = error {
                    if let Some(expl) = e.explain_container_error() {
                        writeln!(out, "{}", expl)?;
                    }
                }
            }
        }

        { // check if all paths that were written are actually there in the staging store
            let staging_store_lock = merged_store.staging().read().await;

            trace!("Checking {} results...", results.len());
            for artifact in results.iter() {
                let a_path = artifact.path_buf();
                trace!("Checking path: {}", a_path.display());
                if !staging_store_lock.path_exists_in_store_root(&a_path) {
                    return Err(anyhow!("Result path {} is missing from staging store", a_path.display()))
                        .with_context(|| anyhow!("Should be: {}/{}", staging_store_lock.root_path().display(), a_path.display()))
                        .map_err(Error::from)
                }
            }

        }

        Ok(results)
    }

    async fn run_runnable(runnable: RunnableJob, scheduler: &EndpointScheduler, bar: indicatif::ProgressBar)
        -> RResult<Vec<Artifact>, ContainerError>
    {
        let job_id = runnable.uuid().clone();
        trace!("Runnable {} for package {}", job_id, runnable.package().name());

        let jobhandle = scheduler.schedule_job(runnable, bar).await?;
        trace!("Jobhandle -> {:?}", jobhandle);

        let r = jobhandle.run().await;
        trace!("Found result in job {}: {:?}", job_id, r);
        r
    }

}