~science-computing/butido

ref: 9cbbff2be1f5938c83c097c6cb1094c8b2bfc49e butido/src/endpoint/configured.rs -rw-r--r-- 24.3 KiB
9cbbff2b — Matthias Beyer Implement scheduling with max jobs per endpoint 8 months ago
                                                                                
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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//
// Copyright (c) 2020-2021 science+computing ag and other contributors
//
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//

use std::fmt::{Debug, Formatter};
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Arc;

use anyhow::anyhow;
use anyhow::Context;
use anyhow::Error;
use anyhow::Result;
use futures::FutureExt;
use getset::{CopyGetters, Getters};
use log::trace;
use shiplift::Container;
use shiplift::Docker;
use shiplift::ExecContainerOptions;
use tokio::sync::mpsc::UnboundedSender;
use tokio::sync::RwLock;
use tokio_stream::StreamExt;
use typed_builder::TypedBuilder;

use crate::endpoint::EndpointConfiguration;
use crate::filestore::ReleaseStore;
use crate::filestore::StagingStore;
use crate::filestore::path::ArtifactPath;
use crate::job::JobResource;
use crate::job::RunnableJob;
use crate::log::LogItem;
use crate::log::buffer_stream_to_line_stream;
use crate::package::Script;
use crate::util::docker::ContainerHash;
use crate::util::docker::ImageName;

#[derive(Getters, CopyGetters, TypedBuilder)]
pub struct Endpoint {
    #[getset(get = "pub")]
    name: String,

    #[getset(get = "pub")]
    docker: Docker,

    #[getset(get_copy = "pub")]
    num_max_jobs: usize,

    #[getset(get = "pub")]
    network_mode: Option<String>,

    #[getset(get = "pub")]
    uri: String,

    #[builder(default)]
    running_jobs: std::sync::atomic::AtomicUsize,
}

impl Debug for Endpoint {
    fn fmt(&self, f: &mut Formatter) -> std::result::Result<(), std::fmt::Error> {
        write!(f, "Endpoint({}, max: {})", self.name, self.num_max_jobs)
    }
}

impl Endpoint {
    pub(super) async fn setup(epc: EndpointConfiguration) -> Result<Self> {
        let ep = Endpoint::setup_endpoint(epc.endpoint()).with_context(|| {
            anyhow!(
                "Setting up endpoint: {} -> {}",
                epc.endpoint().name(),
                epc.endpoint().uri()
            )
        })?;

        let versions_compat =
            Endpoint::check_version_compat(epc.required_docker_versions().as_ref(), &ep);
        let api_versions_compat =
            Endpoint::check_api_version_compat(epc.required_docker_api_versions().as_ref(), &ep);
        let imgs_avail = Endpoint::check_images_available(epc.required_images().as_ref(), &ep);

        let (versions_compat, api_versions_compat, imgs_avail) =
            tokio::join!(versions_compat, api_versions_compat, imgs_avail);

        let _ = versions_compat.with_context(|| {
            anyhow!(
                "Checking version compatibility for {} -> {}",
                epc.endpoint().name(),
                epc.endpoint().uri()
            )
        })?;
        let _ = api_versions_compat.with_context(|| {
            anyhow!(
                "Checking API version compatibility for {} -> {}",
                epc.endpoint().name(),
                epc.endpoint().uri()
            )
        })?;
        let _ = imgs_avail.with_context(|| {
            anyhow!(
                "Checking for available images on {} -> {}",
                epc.endpoint().name(),
                epc.endpoint().uri()
            )
        })?;

        Ok(ep)
    }

    fn setup_endpoint(ep: &crate::config::Endpoint) -> Result<Endpoint> {
        match ep.endpoint_type() {
            crate::config::EndpointType::Http => shiplift::Uri::from_str(ep.uri())
                .map(shiplift::Docker::host)
                .with_context(|| anyhow!("Connecting to {}", ep.uri()))
                .map_err(Error::from)
                .map(|docker| {
                    Endpoint::builder()
                        .name(ep.name().clone())
                        .uri(ep.uri().clone())
                        .docker(docker)
                        .num_max_jobs(ep.maxjobs())
                        .network_mode(ep.network_mode().clone())
                        .build()
                }),

            crate::config::EndpointType::Socket => Ok({
                Endpoint::builder()
                    .name(ep.name().clone())
                    .uri(ep.uri().clone())
                    .num_max_jobs(ep.maxjobs())
                    .network_mode(ep.network_mode().clone())
                    .docker(shiplift::Docker::unix(ep.uri()))
                    .build()
            }),
        }
    }

    async fn check_version_compat(req: Option<&Vec<String>>, ep: &Endpoint) -> Result<()> {
        match req {
            None => Ok(()),
            Some(v) => {
                let avail = ep
                    .docker()
                    .version()
                    .await
                    .with_context(|| anyhow!("Getting version of endpoint: {}", ep.name))?;

                if !v.contains(&avail.version) {
                    Err(anyhow!(
                        "Incompatible docker version on endpoint {}: Expected: {}, Available: [{}]",
                        ep.name(),
                        avail.version,
                        v.join(", ")
                    ))
                } else {
                    Ok(())
                }
            }
        }
    }

    async fn check_api_version_compat(req: Option<&Vec<String>>, ep: &Endpoint) -> Result<()> {
        match req {
            None => Ok(()),
            Some(v) => {
                let avail = ep
                    .docker()
                    .version()
                    .await
                    .with_context(|| anyhow!("Getting API version of endpoint: {}", ep.name))?;

                if !v.contains(&avail.api_version) {
                    Err(anyhow!("Incompatible docker API version on endpoint {}: Exepected: {}, Available: [{}]",
                            ep.name(), avail.api_version, v.join(", ")))
                } else {
                    Ok(())
                }
            }
        }
    }

    async fn check_images_available(imgs: &[ImageName], ep: &Endpoint) -> Result<()> {
        use shiplift::ImageListOptions;

        trace!("Checking availability of images: {:?}", imgs);
        let available_names = ep
            .docker()
            .images()
            .list(&ImageListOptions::builder().all().build())
            .await
            .with_context(|| anyhow!("Listing images on endpoint: {}", ep.name))?
            .into_iter()
            .map(|image_rep| {
                image_rep
                    .repo_tags
                    .unwrap_or_default()
                    .into_iter()
                    .map(ImageName::from)
            })
            .flatten()
            .collect::<Vec<ImageName>>();

        trace!("Available images = {:?}", available_names);

        imgs.iter()
            .map(|img| {
                if !available_names.contains(img) {
                    Err(anyhow!(
                        "Image '{}' missing from endpoint '{}'",
                        img.as_ref(),
                        ep.name
                    ))
                } else {
                    Ok(())
                }
            })
            .collect::<Result<Vec<_>>>()
            .map(|_| ())
    }

    pub async fn prepare_container(
        &self,
        job: RunnableJob,
        staging_store: Arc<RwLock<StagingStore>>,
        release_stores: Vec<Arc<ReleaseStore>>,
    ) -> Result<PreparedContainer<'_>> {
        PreparedContainer::new(self, job, staging_store, release_stores).await
    }

    pub fn running_jobs(&self) -> usize {
        self.running_jobs.load(std::sync::atomic::Ordering::Relaxed)
    }
}

pub struct EndpointHandle(Arc<Endpoint>);

impl EndpointHandle {
    pub fn new(ep: Arc<Endpoint>) -> Self {
        let _ = ep.running_jobs.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        EndpointHandle(ep)
    }
}

impl Drop for EndpointHandle {
    fn drop(&mut self) {
        let _ = self.0.running_jobs.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
    }
}

impl std::ops::Deref for EndpointHandle {
    type Target = Endpoint;

    fn deref(&self) -> &Self::Target {
        self.0.deref()
    }
}


#[derive(Getters)]
pub struct PreparedContainer<'a> {
    endpoint: &'a Endpoint,
    script: Script,

    #[getset(get = "pub")]
    create_info: shiplift::rep::ContainerCreateInfo,
}

impl<'a> PreparedContainer<'a> {
    async fn new(
        endpoint: &'a Endpoint,
        job: RunnableJob,
        staging_store: Arc<RwLock<StagingStore>>,
        release_stores: Vec<Arc<ReleaseStore>>,
    ) -> Result<PreparedContainer<'a>> {
        let script = job.script().clone();
        let create_info = Self::build_container(endpoint, &job).await?;
        let container = endpoint.docker.containers().get(&create_info.id);

        let (cpysrc, cpyart, cpyscr) = tokio::join!(
            Self::copy_source_to_container(&container, &job),
            Self::copy_artifacts_to_container(&container, &job, staging_store, &release_stores),
            Self::copy_script_to_container(&container, &script)
        );

        let _ = cpysrc.with_context(|| {
            anyhow!(
                "Copying the sources to container {} on '{}'",
                create_info.id,
                endpoint.name
            )
        })?;

        let _ = cpyart.with_context(|| {
            anyhow!(
                "Copying the artifacts to container {} on '{}'",
                create_info.id,
                endpoint.name
            )
        })?;

        let _ = cpyscr.with_context(|| {
            anyhow!(
                "Copying the script to container {} on '{}'",
                create_info.id,
                endpoint.name
            )
        })?;

        Ok({
            PreparedContainer {
                endpoint,
                script,
                create_info,
            }
        })
    }

    async fn build_container(
        endpoint: &Endpoint,
        job: &RunnableJob,
    ) -> Result<shiplift::rep::ContainerCreateInfo> {
        let envs = job
            .environment()
            .map(|(k, v)| format!("{}={}", k.as_ref(), v))
            .collect::<Vec<_>>();
        trace!("Job resources: Environment variables = {:?}", envs);

        let builder_opts = {
            let mut builder_opts = shiplift::ContainerOptions::builder(job.image().as_ref());
            builder_opts.env(envs.iter().map(AsRef::as_ref).collect::<Vec<&str>>());
            builder_opts.cmd(vec!["/bin/bash"]); // we start the container with /bin/bash, but exec() the script in it later
            builder_opts.attach_stdin(true); // we have to attach, otherwise bash exits

            if let Some(network_mode) = endpoint.network_mode().as_ref() {
                builder_opts.network_mode(network_mode);
            }

            builder_opts.build()
        };
        trace!("Builder options = {:?}", builder_opts);

        let create_info = endpoint
            .docker
            .containers()
            .create(&builder_opts)
            .await
            .with_context(|| anyhow!("Creating container on '{}'", endpoint.name))?;
        trace!("Create info = {:?}", create_info);
        Ok(create_info)
    }

    async fn copy_source_to_container<'ca>(
        container: &Container<'ca>,
        job: &RunnableJob,
    ) -> Result<()> {
        use tokio::io::AsyncReadExt;

        job.package_sources()
            .into_iter()
            .map(|entry| async {
                let source_path = entry.path();
                let destination = PathBuf::from(crate::consts::INPUTS_DIR_PATH).join({
                    source_path
                        .file_name()
                        .ok_or_else(|| anyhow!("Not a file: {}", source_path.display()))
                        .with_context(|| {
                            anyhow!(
                                "Copying package source from {} to container {}",
                                source_path.display(),
                                container.id()
                            )
                        })?
                });
                trace!("Source path    = {:?}", source_path);
                trace!("Source dest    = {:?}", destination);
                let mut buf = vec![];
                tokio::fs::OpenOptions::new()
                    .create(false)
                    .create_new(false)
                    .append(false)
                    .write(false)
                    .read(true)
                    .open(&source_path)
                    .await
                    .with_context(|| anyhow!("Getting source file: {}", source_path.display()))?
                    .read_to_end(&mut buf)
                    .await
                    .with_context(|| anyhow!("Reading file {}", source_path.display()))?;

                drop(entry);
                let _ = container.copy_file_into(destination, &buf).await?;
                Ok(())
            })
            .collect::<futures::stream::FuturesUnordered<_>>()
            .collect::<Result<()>>()
            .await
            .with_context(|| anyhow!("Copying sources to container {}", container.id()))
            .map_err(Error::from)
    }

    async fn copy_artifacts_to_container<'ca>(
        container: &Container<'ca>,
        job: &RunnableJob,
        staging_store: Arc<RwLock<StagingStore>>,
        release_stores: &[Arc<ReleaseStore>],
    ) -> Result<()> {
        job.resources()
            .iter()
            .filter_map(JobResource::artifact)
            .cloned()
            .map(|art| async {
                let artifact_file_name = art
                    .file_name()
                    .ok_or_else(|| anyhow!("BUG: artifact {} is not a file", art.display()))
                    .with_context(|| {
                        anyhow!(
                            "Collecting artifacts for copying to container {}",
                            container.id()
                        )
                    })?;
                let destination = PathBuf::from(crate::consts::INPUTS_DIR_PATH).join(artifact_file_name);
                trace!(
                    "Copying {} to container: {}:{}",
                    art.display(),
                    container.id(),
                    destination.display()
                );
                let staging_read = staging_store.read().await;
                let buf = match staging_read.root_path().join(&art)?  {
                    Some(fp) => fp,
                    None     => {
                        // TODO: Optimize.
                        // I know this is not nice, but it works for now.
                        let mut found = None;
                        for release_store in release_stores.iter() {
                            let p = release_store.root_path().join(&art);
                            match p {
                                Ok(Some(path)) => {
                                    found = Some(path);
                                    break;
                                },
                                Err(e) => return Err(e),
                                Ok(None) =>  continue,
                            }
                        }
                        found.ok_or_else(|| anyhow!("Not found in staging or release store: {:?}", art))?
                    },
                }
                .read()
                .await
                .with_context(|| {
                    anyhow!(
                        "Reading artifact {}, so it can be copied to container",
                        art.display()
                    )
                })?;

                let r = container
                    .copy_file_into(&destination, &buf)
                    .await
                    .with_context(|| {
                        anyhow!(
                            "Copying artifact {} to container {} at {}",
                            art.display(),
                            container.id(),
                            destination.display()
                        )
                    })
                    .map_err(Error::from);
                drop(art); // ensure `art` is moved into closure
                r
            })
            .collect::<futures::stream::FuturesUnordered<_>>()
            .collect::<Result<Vec<_>>>()
            .await
            .with_context(|| anyhow!("Copying artifacts to container {}", container.id()))
            .map_err(Error::from)
            .map(|_| ())
    }

    async fn copy_script_to_container<'ca>(
        container: &Container<'ca>,
        script: &Script,
    ) -> Result<()> {
        let script_path = PathBuf::from(crate::consts::SCRIPT_PATH);
        container
            .copy_file_into(script_path, script.as_ref().as_bytes())
            .await
            .with_context(|| anyhow!("Copying the script into container {}", container.id()))
            .map_err(Error::from)
    }

    pub async fn start(self) -> Result<StartedContainer<'a>> {
        let container = self.endpoint.docker.containers().get(&self.create_info.id);
        let _ = container
            .start()
            .inspect(|r| {
                trace!("Starting container {} -> {:?}", self.create_info.id, r);
            })
            .map(|r| {
                r.with_context(|| {
                    anyhow!(
                        "Starting the container {} on '{}'",
                        self.create_info.id,
                        self.endpoint.name
                    )
                })
            })
            .await?;

        Ok({
            StartedContainer {
                endpoint: self.endpoint,
                script: self.script,
                create_info: self.create_info,
            }
        })
    }
}

pub struct StartedContainer<'a> {
    endpoint: &'a Endpoint,
    script: Script,
    create_info: shiplift::rep::ContainerCreateInfo,
}

impl<'a> StartedContainer<'a> {
    pub async fn execute_script(
        self,
        logsink: UnboundedSender<LogItem>,
    ) -> Result<ExecutedContainer<'a>> {
        let exec_opts = ExecContainerOptions::builder()
            .cmd(vec!["/bin/bash", "/script"])
            .attach_stderr(true)
            .attach_stdout(true)
            .build();
        trace!("Exec options = {:?}", exec_opts);

        let container = self.endpoint.docker.containers().get(&self.create_info.id);

        trace!(
            "Moving logs to log sink for container {}",
            self.create_info.id
        );
        let stream = container.exec(&exec_opts);

        let exited_successfully: Option<(bool, Option<String>)> =
            buffer_stream_to_line_stream(stream)
                .map(|line| {
                    trace!(
                        "['{}':{}] Found log line: {:?}",
                        self.endpoint.name,
                        self.create_info.id,
                        line
                    );
                    line.with_context(|| {
                        anyhow!(
                            "Getting log from {}:{}",
                            self.endpoint.name,
                            self.create_info.id
                        )
                    })
                    .map_err(Error::from)
                    .and_then(|l| {
                        crate::log::parser()
                            .parse(l.as_bytes())
                            .with_context(|| {
                                anyhow!(
                                    "Parsing log from {}:{}: {:?}",
                                    self.endpoint.name,
                                    self.create_info.id,
                                    l
                                )
                            })
                            .map_err(Error::from)
                            .and_then(|item| {
                                let mut exited_successfully = None;
                                {
                                    match item {
                                        LogItem::State(Ok(_)) => {
                                            exited_successfully = Some((true, None))
                                        }
                                        LogItem::State(Err(ref msg)) => {
                                            exited_successfully = Some((false, Some(msg.clone())))
                                        }
                                        _ => {
                                            // Nothing
                                        }
                                    }
                                }

                                trace!("Log item: {}", item.display()?);
                                logsink
                                    .send(item)
                                    .with_context(|| anyhow!("Sending log to log sink"))
                                    .map_err(Error::from)
                                    .map(|_| exited_successfully)
                            })
                    })
                })
                .collect::<Result<Vec<_>>>()
                .map(|r| {
                    r.with_context(|| {
                        anyhow!(
                            "Fetching log from container {} on {}",
                            self.create_info.id,
                            self.endpoint.name
                        )
                    })
                })
                .await
                .with_context(|| {
                    anyhow!(
                        "Copying script to container, running container and getting logs: {}",
                        self.create_info.id
                    )
                })?
                .into_iter()
                .fold(None, |accu, elem| match (accu, elem) {
                    (None, b) => b,
                    (Some((false, msg)), _) => Some((false, msg)),
                    (_, Some((false, msg))) => Some((false, msg)),
                    (a, None) => a,
                    (Some((true, _)), Some((true, _))) => Some((true, None)),
                });

        Ok({
            ExecutedContainer {
                endpoint: self.endpoint,
                create_info: self.create_info,
                script: self.script,
                exit_info: exited_successfully,
            }
        })
    }
}

pub struct ExecutedContainer<'a> {
    endpoint: &'a Endpoint,
    create_info: shiplift::rep::ContainerCreateInfo,
    script: Script,
    exit_info: Option<(bool, Option<String>)>,
}

impl<'a> ExecutedContainer<'a> {
    pub fn container_hash(&self) -> ContainerHash {
        ContainerHash::from(self.create_info.id.clone())
    }

    pub fn script(&self) -> &Script {
        &self.script
    }

    pub async fn finalize(self, staging_store: Arc<RwLock<StagingStore>>) -> Result<FinalizedContainer> {
        let (exit_info, artifacts) = match self.exit_info {
            Some((false, msg)) => {
                let err = anyhow!("Error during container run: '{msg}'", msg = msg.as_deref().unwrap_or(""));

                // error because the container errored
                (Err(err), vec![])
            }

            Some((true, _)) | None => {
                let container = self.endpoint.docker.containers().get(&self.create_info.id);

                trace!("Fetching {} from container {}", crate::consts::OUTPUTS_DIR_PATH, self.create_info.id);
                let tar_stream = container
                    .copy_from(&PathBuf::from(crate::consts::OUTPUTS_DIR_PATH))
                    .map(|item| {
                        item.with_context(|| {
                            anyhow!(
                                "Copying item from container {} to host",
                                self.create_info.id
                            )
                        })
                        .map_err(Error::from)
                    });

                let mut writelock = staging_store.write().await;
                let artifacts = writelock
                    .write_files_from_tar_stream(tar_stream)
                    .await
                    .with_context(|| anyhow!("Copying the TAR stream to the staging store"))?;
                container
                    .stop(Some(std::time::Duration::new(1, 0)))
                    .await
                    .with_context(|| anyhow!("Stopping container {}", self.create_info.id))?;
                (Ok(()), artifacts)
            }
        };

        Ok({
            FinalizedContainer {
                artifacts,
                exit_info,
            }
        })
    }
}

#[derive(Debug)]
pub struct FinalizedContainer {
    artifacts: Vec<ArtifactPath>,
    exit_info: Result<()>,
}

impl FinalizedContainer {
    pub fn unpack(self) -> (Vec<ArtifactPath>, Result<()>) {
        (self.artifacts, self.exit_info)
    }
}