Skip to main content

capsid_task/
task.rs

1use std::{
2    collections::BTreeMap,
3    ffi::{OsStr, OsString},
4    fs, io,
5    path::PathBuf,
6    process::Command,
7    str::FromStr,
8};
9
10use capsid_model::{
11    AttemptId, DiskStagingId, InstanceId, PreparationId, ProcessIdentity, VolumeId, WorkloadId,
12};
13
14use crate::{Error, Result};
15
16pub const SUBCOMMAND: &str = "internal";
17
18// A helper re-executes through this link, which keeps the exact executable
19// inode even while a developer rebuild replaces the file.
20const SELF_EXECUTABLE: &str = "/proc/self/exe";
21
22const STATE_DIR: &str = "state-dir";
23
24const ID: &str = "id";
25
26const ATTEMPT: &str = "attempt";
27
28const INSTANCE: &str = "instance";
29
30const STAGING: &str = "staging";
31
32const WORKLOAD: &str = "workload";
33
34const OWNER_PID: &str = "owner-pid";
35
36const OWNER_START_TICKS: &str = "owner-start-ticks";
37
38const PREPARE_IMAGE: &str = "prepare-image";
39
40const PREPARE_IMAGE_WORKER: &str = "prepare-image-worker";
41
42const FORMAT_PRIVATE_DISK: &str = "format-private-disk";
43
44const PREPARE_VOLUME: &str = "prepare-volume";
45
46const PUBLISH_SERVICE: &str = "publish-service";
47
48const SUPERVISE: &str = "supervise";
49
50const NETWORK_GATEWAY: &str = "network-gateway";
51
52const NETWORK_PROXY: &str = "network-proxy";
53
54const NETWORK_DNS: &str = "network-dns";
55
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct Invocation {
58    pub state_dir: PathBuf,
59
60    pub task: Task,
61}
62
63#[derive(Debug, Clone, PartialEq, Eq)]
64pub enum Task {
65    PrepareImage {
66        id: PreparationId,
67    },
68
69    PrepareImageWorker {
70        id: PreparationId,
71        owner: ProcessIdentity,
72    },
73
74    FormatPrivateDisk {
75        instance: InstanceId,
76        attempt: AttemptId,
77        staging: DiskStagingId,
78        owner: ProcessIdentity,
79    },
80
81    PrepareVolume {
82        id: VolumeId,
83    },
84
85    PublishService {
86        workload: WorkloadId,
87    },
88
89    Supervise {
90        attempt: AttemptId,
91    },
92
93    NetworkGateway {
94        attempt: AttemptId,
95    },
96
97    NetworkProxy {
98        attempt: AttemptId,
99    },
100
101    NetworkDns {
102        attempt: AttemptId,
103    },
104}
105
106impl Task {
107    fn name(&self) -> &'static str {
108        match self {
109            Self::PrepareImage { .. } => PREPARE_IMAGE,
110            Self::PrepareImageWorker { .. } => PREPARE_IMAGE_WORKER,
111            Self::FormatPrivateDisk { .. } => FORMAT_PRIVATE_DISK,
112            Self::PrepareVolume { .. } => PREPARE_VOLUME,
113            Self::PublishService { .. } => PUBLISH_SERVICE,
114            Self::Supervise { .. } => SUPERVISE,
115            Self::NetworkGateway { .. } => NETWORK_GATEWAY,
116            Self::NetworkProxy { .. } => NETWORK_PROXY,
117            Self::NetworkDns { .. } => NETWORK_DNS,
118        }
119    }
120
121    fn flags(&self) -> Vec<(&'static str, String)> {
122        let owner = |owner: &ProcessIdentity| {
123            [
124                (OWNER_PID, owner.pid.to_string()),
125                (OWNER_START_TICKS, owner.start_ticks.to_string()),
126            ]
127        };
128        match self {
129            Self::PrepareImage { id } => vec![(ID, id.to_string())],
130            Self::PrepareImageWorker { id, owner: process } => {
131                let mut flags = vec![(ID, id.to_string())];
132                flags.extend(owner(process));
133                flags
134            }
135            Self::FormatPrivateDisk {
136                instance,
137                attempt,
138                staging,
139                owner: process,
140            } => {
141                let mut flags = vec![
142                    (ATTEMPT, attempt.to_string()),
143                    (INSTANCE, instance.to_string()),
144                    (STAGING, staging.to_string()),
145                ];
146                flags.extend(owner(process));
147                flags
148            }
149            Self::PrepareVolume { id } => vec![(ID, id.to_string())],
150            Self::PublishService { workload } => vec![(WORKLOAD, workload.to_string())],
151            Self::Supervise { attempt }
152            | Self::NetworkGateway { attempt }
153            | Self::NetworkProxy { attempt }
154            | Self::NetworkDns { attempt } => vec![(ATTEMPT, attempt.to_string())],
155        }
156    }
157
158    fn parse(name: &OsStr, flags: &mut Flags) -> Result<Self> {
159        Ok(match name.to_str() {
160            Some(PREPARE_IMAGE) => Self::PrepareImage {
161                id: flags.take(ID)?,
162            },
163            Some(PREPARE_IMAGE_WORKER) => Self::PrepareImageWorker {
164                id: flags.take(ID)?,
165                owner: flags.owner()?,
166            },
167            Some(FORMAT_PRIVATE_DISK) => Self::FormatPrivateDisk {
168                instance: flags.take(INSTANCE)?,
169                attempt: flags.take(ATTEMPT)?,
170                staging: flags.take(STAGING)?,
171                owner: flags.owner()?,
172            },
173            Some(PREPARE_VOLUME) => Self::PrepareVolume {
174                id: flags.take(ID)?,
175            },
176            Some(PUBLISH_SERVICE) => Self::PublishService {
177                workload: flags.take(WORKLOAD)?,
178            },
179            Some(SUPERVISE) => Self::Supervise {
180                attempt: flags.take(ATTEMPT)?,
181            },
182            Some(NETWORK_GATEWAY) => Self::NetworkGateway {
183                attempt: flags.take(ATTEMPT)?,
184            },
185            Some(NETWORK_PROXY) => Self::NetworkProxy {
186                attempt: flags.take(ATTEMPT)?,
187            },
188            Some(NETWORK_DNS) => Self::NetworkDns {
189                attempt: flags.take(ATTEMPT)?,
190            },
191            _ => return Err(Error::UnknownName(name.to_owned())),
192        })
193    }
194}
195
196impl Invocation {
197    pub fn new(state_dir: impl Into<PathBuf>, task: Task) -> Self {
198        Self {
199            state_dir: state_dir.into(),
200            task,
201        }
202    }
203
204    pub fn args(&self) -> Vec<OsString> {
205        let mut args = vec![
206            OsString::from(SUBCOMMAND),
207            OsString::from(self.task.name()),
208            OsString::from(format!("--{STATE_DIR}")),
209            self.state_dir.clone().into_os_string(),
210        ];
211        for (flag, value) in self.task.flags() {
212            args.push(OsString::from(format!("--{flag}")));
213            args.push(OsString::from(value));
214        }
215        args
216    }
217
218    pub fn command(&self, program: impl AsRef<OsStr>) -> Command {
219        let mut command = Command::new(program);
220        command.args(self.args());
221        command
222    }
223
224    pub fn reexec(&self) -> Command {
225        self.command(SELF_EXECUTABLE)
226    }
227
228    pub fn parse(args: impl IntoIterator<Item = OsString>) -> Result<Self> {
229        let mut args = args.into_iter();
230        let name = args.next().ok_or(Error::MissingName)?;
231        let mut flags = Flags::parse(args)?;
232        let state_dir = PathBuf::from(flags.take_raw(STATE_DIR)?);
233        let task = Task::parse(&name, &mut flags)?;
234        if let Some(flag) = flags.values.into_keys().next() {
235            return Err(Error::Unexpected(OsString::from(format!("--{flag}"))));
236        }
237        Ok(Self { state_dir, task })
238    }
239}
240
241pub fn executable() -> io::Result<PathBuf> {
242    fs::read_link(SELF_EXECUTABLE)
243}
244
245struct Flags {
246    values: BTreeMap<String, OsString>,
247}
248
249impl Flags {
250    fn parse(args: impl Iterator<Item = OsString>) -> Result<Self> {
251        let mut values = BTreeMap::new();
252        let mut args = args.peekable();
253        while let Some(arg) = args.next() {
254            let Some(flag) = arg.to_str().and_then(|arg| arg.strip_prefix("--")) else {
255                return Err(Error::Unexpected(arg));
256            };
257            let value = args.next().ok_or_else(|| Error::Unexpected(arg.clone()))?;
258            if values.insert(flag.to_owned(), value).is_some() {
259                return Err(Error::Unexpected(arg));
260            }
261        }
262        Ok(Self { values })
263    }
264
265    fn take_raw(&mut self, flag: &'static str) -> Result<OsString> {
266        self.values.remove(flag).ok_or(Error::Missing(flag))
267    }
268
269    fn take<T: FromStr>(&mut self, flag: &'static str) -> Result<T> {
270        self.take_raw(flag)?
271            .to_str()
272            .and_then(|value| value.parse().ok())
273            .ok_or(Error::Invalid(flag))
274    }
275
276    fn owner(&mut self) -> Result<ProcessIdentity> {
277        Ok(ProcessIdentity {
278            pid: self.take(OWNER_PID)?,
279            start_ticks: self.take(OWNER_START_TICKS)?,
280        })
281    }
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287    use crate::testing::Result;
288
289    #[test]
290    fn test_every_task_round_trips_through_its_arguments() -> Result {
291        let owner = ProcessIdentity {
292            pid: 42,
293            start_ticks: 7,
294        };
295        let attempt = AttemptId::new();
296        for task in [
297            Task::PrepareImage {
298                id: PreparationId::new(),
299            },
300            Task::PrepareImageWorker {
301                id: PreparationId::new(),
302                owner: owner.clone(),
303            },
304            Task::FormatPrivateDisk {
305                instance: InstanceId::new(),
306                attempt,
307                staging: DiskStagingId::new(),
308                owner,
309            },
310            Task::PrepareVolume {
311                id: VolumeId::new(),
312            },
313            Task::PublishService {
314                workload: WorkloadId::new(),
315            },
316            Task::Supervise { attempt },
317            Task::NetworkGateway { attempt },
318            Task::NetworkProxy { attempt },
319            Task::NetworkDns { attempt },
320        ] {
321            let invocation = Invocation::new("/var/lib/capsid", task);
322            let args = invocation.args();
323            assert_eq!(args[0], SUBCOMMAND);
324            assert_eq!(Invocation::parse(args.into_iter().skip(1))?, invocation);
325        }
326        Ok(())
327    }
328
329    #[test]
330    fn test_unknown_and_missing_flags_are_rejected() {
331        let parse = |args: &[&str]| Invocation::parse(args.iter().map(OsString::from));
332        assert!(matches!(
333            parse(&["supervise", "--state-dir", "/state"]),
334            Err(Error::Missing(ATTEMPT))
335        ));
336        assert!(matches!(
337            parse(&["supervise", "--state-dir", "/state", "--attempt", "x"]),
338            Err(Error::Invalid(ATTEMPT))
339        ));
340        assert!(matches!(
341            parse(&["mystery", "--state-dir", "/state"]),
342            Err(Error::UnknownName(_))
343        ));
344        assert!(matches!(
345            parse(&[
346                "supervise",
347                "--state-dir",
348                "/state",
349                "--attempt",
350                &AttemptId::new().to_string(),
351                "--extra",
352                "1",
353            ]),
354            Err(Error::Unexpected(_))
355        ));
356    }
357}