planetary-server 0.2.0

The shared Planetary server implementation
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
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
//! Provides an implementation of rendering a task resource template.
//!
//! This is used by both the orchestrator when creating task resources and by
//! the monitor when tasks are garbage collected.

use std::borrow::Cow;
use std::collections::HashMap;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;

use anyhow::Context as _;
use anyhow::Result;
use anyhow::bail;
use kube::Discovery;
use kube::api::ApiResource;
use kube::api::DynamicObject;
use kube::api::GroupVersionKind;
use kube::discovery::ApiCapabilities;
use kube::discovery::Scope;
use kube::runtime::reflector::Lookup;
use planetary_db::TaskTemplateData;
use reqwest::Url;
use serde::Deserialize as _;
use serde_yaml_ng::Deserializer;
use tera::Context;
use tera::Map;
use tera::Tera;
use tera::Value;
use tes::v1::types::task::Executor;

/// The orchestrator id label.
pub const ORCHESTRATOR_LABEL: &str = "planetary/orchestrator";

/// The task id label.
pub const TASK_LABEL: &str = "planetary/task";

/// The cancellation label used to mark canceled task for garbage collection.
pub const CANCELED_LABEL: &str = "planetary/canceled";

/// The expected name of the task resource template.
const TEMPLATE_NAME: &str = "task.yaml";

/// The default task storage size, in gigabytes.
///
/// Uses a 1 GiB default.
const DEFAULT_STORAGE_SIZE: f64 = 1.07374182;

/// The default CPU request (in cores) for tasks.
const DEFAULT_CPU: i32 = 1;

/// The default memory request (in GB) for tasks.
///
/// Uses a 256 MiB default.
const DEFAULT_MEMORY: f64 = 0.268435455;

/// Determines if the given username is valid.
pub fn is_username_valid(username: &str) -> bool {
    // Ensure the username does not contain any control characters
    // YAML 1.1 treats `\u2028` and `\u2029` as line breaks, so exclude them
    !username
        .chars()
        .any(|c| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}'))
}

/// Helper for converting a URL to a file path.
///
/// Returns `None` if the URL is invalid or if the URL does not represent a file
/// path.
fn url_to_file_path(url: &str) -> Option<PathBuf> {
    let url = Url::parse(url).ok()?;
    if url.scheme() != "file" {
        return None;
    }

    url.to_file_path().ok()
}

/// Represents a Planetary task template.
///
/// A task template defines the Kubernetes resources that will be created for
/// each TES task.
pub struct Template(Tera);

impl Template {
    /// Constructs a new Planetary task template.
    ///
    /// The specified directory must contain a `task.yaml` template.
    pub fn new(templates_dir: impl AsRef<Path>) -> Result<Self> {
        let templates_dir = templates_dir.as_ref();

        let mut templates = Tera::new();

        // Set the default escape function so that, by default, unsafe strings
        // are JSON serialized
        templates.set_escape_fn(|value: &str, writer: &mut dyn Write| {
            serde_json::to_writer(writer, value).map_err(std::io::Error::other)
        });

        templates.load_from_glob(templates_dir.join("**/*.yaml").to_str().with_context(
            || {
                format!(
                    "templates directory `{path}` is not valid UTF-8",
                    path = templates_dir.display()
                )
            },
        )?)?;

        // Automatically escape any YAML or JSON templates
        templates.autoescape_on([".yaml"]);

        if !templates.get_template_names().any(|n| n == TEMPLATE_NAME) {
            bail!(
                "templates directory `{path}` does not contain a template named `{TEMPLATE_NAME}`",
                path = templates_dir.display()
            );
        }

        Ok(Self(templates))
    }

    /// Renders a template for the given TES task.
    ///
    /// The TES task must have at least the task id present.
    ///
    /// The provided discovery is used to validate the requested Kubernetes
    /// resources.
    ///
    /// The provided Kubernetes namespace is used to apply to the task
    /// resources.
    ///
    /// The provided script callback is called once per executor defined on the
    /// task to retrieve the executor's script.
    ///
    /// Returns the set of resources defined by the task template.
    ///
    /// An error is returned if the template does not define exactly one pod
    /// with a restart policy of `Never`.
    pub fn render(
        &self,
        data: &TaskTemplateData,
        discovery: &Discovery,
        namespace: &str,
        script: impl Fn(&Executor) -> Result<String>,
    ) -> Result<Vec<TaskResource>> {
        let rendered = self.render_to_string(data, script)?;

        let resources = serde_yaml_ng::Deserializer::from_str(&rendered)
            .map(|de| self.deserialize_object(&data.id, discovery, namespace, de))
            .collect::<Result<Vec<_>>>()?;

        // Ensure there is exactly one pod that has a restart policy of `Never`
        let mut has_pod = false;

        for r in &resources {
            if r.api().api_version == "v1" && r.api().kind == "Pod" {
                if has_pod {
                    bail!("task template defines more than one pod for the task")
                }

                if r.object()
                    .data
                    .get("spec")
                    .and_then(|o| o.get("restartPolicy"))
                    .map(|v| v.as_str() != Some("Never"))
                    .unwrap_or(true)
                {
                    bail!("task pod must have a `Never` restart policy");
                }

                has_pod = true;
            }
        }

        if !has_pod {
            bail!("task template does not define a pod for the task");
        }

        Ok(resources)
    }

    /// Renders the template with only the given TES task identifier.
    pub fn render_id_only(
        &self,
        id: impl Into<String>,
        discovery: &Discovery,
        namespace: &str,
    ) -> Result<Vec<TaskResource>> {
        // Render the template using only the identifier of the task
        self.render(
            &TaskTemplateData {
                id: id.into(),
                username: String::new(),
                preemptible: false,
                cpu: None,
                memory: None,
                disk: None,
                inputs: Default::default(),
                outputs: Default::default(),
                volumes: Default::default(),
                executors: Default::default(),
            },
            discovery,
            namespace,
            |_| Ok(String::new()),
        )
    }

    /// Renders the template to a string.
    fn render_to_string(
        &self,
        data: &TaskTemplateData,
        script: impl Fn(&Executor) -> Result<String>,
    ) -> Result<String> {
        self.0
            .render(TEMPLATE_NAME, &Self::create_context(data, script)?)
            .context("failed to render task resource template")
    }

    /// Creates a template context for a TES task.
    ///
    /// The provided callback is used to format an executor script for the
    /// template.
    ///
    /// Returns an error if the task was invalid.
    fn create_context(
        data: &TaskTemplateData,
        script: impl Fn(&Executor) -> Result<String>,
    ) -> Result<Context> {
        // Validate the username as often it is treated as "safe"
        if !is_username_valid(&data.username) {
            bail!(
                "username `{username}` is invalid for template rendering",
                username = data.username
            );
        }

        let mut context = Context::new();
        context.insert("id", data.id.as_str());
        context.insert("username", data.username.as_str());
        context.insert("preemptible", &data.preemptible);

        // Set the requested resources
        context.insert("cpu", &data.cpu.unwrap_or(DEFAULT_CPU));
        context.insert(
            "memory",
            &format!(
                "{memory}G",
                memory = data.memory.unwrap_or(DEFAULT_MEMORY).ceil()
            ),
        );
        context.insert(
            "disk",
            &format!(
                "{disk}G",
                disk = data.disk.unwrap_or(0.0).max(DEFAULT_STORAGE_SIZE)
            ),
        );

        // Set the inputs
        let inputs: Vec<_> = data
            .inputs
            .iter()
            .map(|input| {
                let mut value: HashMap<_, Cow<'_, str>> = HashMap::new();
                value.insert("path", input.path.as_str().into());

                if let Some(local_path) = input.url.as_ref().and_then(|url| {
                    Some(
                        // SAFETY: URLs are validated when tasks are created
                        url_to_file_path(url)?
                            .strip_prefix("/")
                            .expect("path should be absolute")
                            .to_str()
                            .expect("path should be UTF-8")
                            .to_string(),
                    )
                }) {
                    value.insert("local_path", local_path.into());
                }

                value
            })
            .collect();
        context.insert("inputs", &inputs);

        // Set the outputs
        let outputs: Vec<_> = data
            .outputs
            .iter()
            .map(|output| {
                let mut value: HashMap<_, Cow<'_, str>> = HashMap::new();
                value.insert(
                    "path",
                    output.path_prefix.as_deref().unwrap_or(&output.path).into(),
                );

                if let Some(path) = url_to_file_path(&output.url) {
                    // SAFETY: URLs are validated when tasks are created
                    let local_path = path
                        .strip_prefix("/")
                        .expect("path should be absolute")
                        .to_str()
                        .expect("path should be UTF-8");
                    value.insert("local_path", local_path.to_string().into());
                }

                value
            })
            .collect();
        context.insert("outputs", &outputs);

        // Set the volumes
        context.insert("volumes", &data.volumes);

        // Set the executors
        let executors: Vec<_> = data
            .executors
            .iter()
            .map(|e| {
                let mut value: HashMap<_, Value> = HashMap::new();
                value.insert("image", e.image.as_str().into());
                value.insert("script", script(e)?.into());
                value.insert("workdir", e.workdir.as_deref().unwrap_or_default().into());

                if let Some(env) = e.env.as_ref() {
                    value.insert("env", Value::from_serializable(env));
                } else {
                    value.insert("env", Map::new().into());
                }

                Ok(value)
            })
            .collect::<Result<_>>()?;
        context.insert("executors", &executors);

        Ok(context)
    }

    /// Deserializes a Kubernetes object and returns its resolved API resources
    /// and capabilities.
    fn deserialize_object(
        &self,
        tes_id: &str,
        discovery: &Discovery,
        namespace: &str,
        de: Deserializer<'_>,
    ) -> Result<TaskResource> {
        let mut object = DynamicObject::deserialize(de)
            .context("failed to deserialize task resource template")?;

        let name = object
            .name()
            .context("task template contains a resource that has no name")?;

        let meta = object.types.as_ref().with_context(|| {
            format!("task resource `{name}` does not specify an object API version and kind")
        })?;

        let gvk = GroupVersionKind::try_from(meta).with_context(|| {
            format!(
                "task resource `{name}` has invalid kind: `{kind}` ({api})",
                kind = meta.kind,
                api = meta.api_version
            )
        })?;

        // Set the task label for the object
        let labels = object.metadata.labels.get_or_insert_default();
        labels.insert(TASK_LABEL.to_string(), tes_id.to_string());

        let (resource, capabilities) = discovery.resolve_gvk(&gvk).with_context(|| {
            format!(
                "task resource `{name}` has unknown resource kind `{kind}` ({api})",
                name = object.name().expect("object should have a name"),
                kind = meta.kind,
                api = meta.api_version
            )
        })?;

        if capabilities.scope == Scope::Cluster {
            object.metadata.namespace = None;
        } else {
            object.metadata.namespace = Some(namespace.to_string());
        }

        Ok(TaskResource {
            resource,
            capabilities,
            object,
        })
    }
}

/// Represents a requested task resource from a task template.
pub struct TaskResource {
    /// The Kubernetes API for the resource.
    resource: ApiResource,
    /// The capabilities of the resource's API.
    capabilities: ApiCapabilities,
    /// The object defining the resource.
    object: DynamicObject,
}

impl TaskResource {
    /// Gets the Kubernetes API resource.
    pub fn api(&self) -> &ApiResource {
        &self.resource
    }

    /// Gets the Kubernetes API capabilities.
    pub fn capabilities(&self) -> &ApiCapabilities {
        &self.capabilities
    }

    /// Gets the object defining the resource.
    pub fn object(&self) -> &DynamicObject {
        &self.object
    }

    /// Gets a mutable reference to the object defining the resource.
    pub fn object_mut(&mut self) -> &mut DynamicObject {
        &mut self.object
    }
}

#[cfg(test)]
mod tests {
    use std::fs;

    use pretty_assertions::assert_eq;
    use tempfile::tempdir;

    use super::*;

    #[test]
    fn it_json_encodes_strings() {
        let dir = tempdir().unwrap();
        let template_path = dir.path().join(TEMPLATE_NAME);

        // Test some of the string context variables
        // Not every variable needs to be tested here as this is just testing
        // that, by default, string values are rendered as JSON strings
        fs::write(
            &template_path,
            r#"
{{ id }}
{{ id | safe }}
{{ username }}
{{ memory }}
{{ disk }}
"#,
        )
        .unwrap();

        let template = Template::new(dir.path()).unwrap();

        // Render with some dummy strings containing a newline
        let rendered = template
            .render_to_string(
                &TaskTemplateData {
                    id: "task\nid".into(),
                    username: "username".into(),
                    preemptible: false,
                    cpu: Some(1),
                    memory: Some(1.0),
                    disk: Some(10.0),
                    inputs: Default::default(),
                    outputs: Default::default(),
                    volumes: Default::default(),
                    executors: Default::default(),
                },
                |_| Ok(String::new()),
            )
            .unwrap();

        assert_eq!(
            rendered,
            r#"
"task\nid"
task
id
"username"
"1G"
"10G"
"#
        );
    }
}