Skip to main content

mortise_core/runtime/
actuator.rs

1//! The runtime status of a running app, read through `nwidart/laravel-actuator`.
2//!
3//! The client asks for the actuator base path, `health`, `info`, `mappings`, `scheduledtasks` and
4//! `prometheus` only. It never asks for `env` and follows no redirect. It asks for `prometheus`
5//! only while the Metrics tab is open and the window is visible, and reads that answer as text.
6//! What the app answers is called Runtime; it is not mixed with Findings, which Mortise works out
7//! from files.
8
9use std::io::Read;
10use std::time::Duration;
11
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15use crate::runtime::environment::{Credentials, Environment};
16
17/// The status the actuator reports, for the app or for one component.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
19pub enum Status {
20    Up,
21    Down,
22    OutOfService,
23    Unknown,
24}
25
26impl Status {
27    fn parse(text: &str) -> Self {
28        match text {
29            "UP" => Status::Up,
30            "DOWN" => Status::Down,
31            "OUT_OF_SERVICE" => Status::OutOfService,
32            _ => Status::Unknown,
33        }
34    }
35}
36
37/// One health indicator of the app.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Component {
40    pub name: String,
41    pub status: Status,
42    /// The details the app gives, as it wrote them, in its order.
43    pub details: Vec<(String, String)>,
44}
45
46/// What `info` says. Every part is absent when the app does not give it.
47#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
48pub struct Info {
49    pub environment: Option<String>,
50    pub laravel: Option<String>,
51    pub git_branch: Option<String>,
52    pub git_commit: Option<String>,
53    pub php_version: Option<String>,
54    pub php_sapi: Option<String>,
55    /// Bytes. A limit of -1 means there is none.
56    pub memory_usage: Option<i64>,
57    pub memory_peak: Option<i64>,
58    pub memory_limit: Option<i64>,
59}
60
61/// One route of the app, from `mappings`.
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63pub struct Route {
64    pub methods: Vec<String>,
65    /// Without a leading slash, as Laravel has it.
66    pub uri: String,
67    pub name: Option<String>,
68    /// `Modules\Blog\Http\Controllers\BlogController@index`, or `Closure`.
69    pub action: String,
70    pub middleware: Vec<String>,
71}
72
73/// One scheduled task of the app, from `scheduledtasks`.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75pub struct Task {
76    /// The description, else the command, else the class of the job.
77    pub target: String,
78    /// The cron expression. `None` for a task that runs more than once a minute.
79    pub expression: Option<String>,
80    /// For a task that runs more than once a minute: how often, in milliseconds.
81    pub interval_ms: Option<u64>,
82    pub timezone: Option<String>,
83    /// The next run, as the app wrote it: ISO 8601 in the task's timezone.
84    pub next: Option<String>,
85    /// The module that scheduled the task, from its `tags.module`. Newer versions of
86    /// laravel-actuator and laravel-modules add the tag (PKG-2); older versions give `None`.
87    #[serde(default)]
88    pub module: Option<String>,
89}
90
91/// What a running app answered.
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
93pub struct Runtime {
94    pub status: Status,
95    /// The components of `health`. `None` when the app hides them.
96    pub components: Option<Vec<Component>>,
97    /// The endpoints the app exposes, from the links at the actuator's base path.
98    pub exposed: Vec<String>,
99    /// `None` when `info` is not exposed.
100    pub info: Option<Info>,
101    /// `None` when `mappings` is not exposed.
102    pub routes: Option<Vec<Route>>,
103    /// `None` when `scheduledtasks` is not exposed.
104    pub tasks: Option<Vec<Task>>,
105}
106
107impl Runtime {
108    /// True when the app exposes this endpoint.
109    pub fn exposes(&self, endpoint: &str) -> bool {
110        self.exposed.iter().any(|exposed| exposed == endpoint)
111    }
112
113    /// The endpoints Mortise reads beside `health` that the app does not expose.
114    pub fn not_exposed(&self) -> Vec<&'static str> {
115        ["info", "mappings", "scheduledtasks"]
116            .into_iter()
117            .filter(|endpoint| !self.exposes(endpoint))
118            .collect()
119    }
120}
121
122/// What asking an environment gave. "No answer" and "Not authorized" are Mortise's
123/// words for the connection, not statuses of the app.
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125pub enum Answer {
126    /// Nothing came back: a refused connection, a timeout, a name that does not resolve.
127    NoAnswer {
128        url: String,
129        message: String,
130    },
131    /// The app answered 401 or 403.
132    NotAuthorized {
133        url: String,
134        status: u16,
135    },
136    /// The app answered with a status the actuator does not use, such as 500 or 404.
137    Unexpected {
138        url: String,
139        status: u16,
140        /// Where a redirect sends to, as a full address. Mortise does not follow it.
141        location: Option<String>,
142    },
143    Answered(Box<Runtime>),
144}
145
146/// The secret that goes with [`Credentials`]: a token, a password or a header value.
147pub type Secret = Option<String>;
148
149/// The most text Mortise reads from one `prometheus` answer, after decompression.
150pub const METRICS_BODY_LIMIT: u64 = 16 * 1024 * 1024;
151
152/// Why a read of `prometheus` gave no metrics.
153#[derive(Debug, Clone, PartialEq, Eq)]
154pub enum NoMetrics {
155    /// 200 with an empty body: metrics are off in the app.
156    Off,
157    /// 503: the first line of the body as the app wrote it, at most 200 characters.
158    Unavailable {
159        url: String,
160        line: String,
161    },
162    /// The body is longer than the limit.
163    TooLarge {
164        url: String,
165        limit: u64,
166    },
167    NoAnswer {
168        url: String,
169        message: String,
170    },
171    NotAuthorized {
172        url: String,
173        status: u16,
174    },
175    Unexpected {
176        url: String,
177        status: u16,
178        location: Option<String>,
179    },
180}
181
182/// A response of the app: its status, its body and the `Location` header.
183struct Reply {
184    status: u16,
185    body: String,
186    /// The body was longer than the limit of the request. `body` is then empty.
187    too_large: bool,
188    location: Option<String>,
189}
190
191/// One connection to an environment: an agent, and the credentials every request carries.
192struct Client<'a> {
193    agent: ureq::Agent,
194    environment: &'a Environment,
195    secret: &'a Secret,
196}
197
198impl<'a> Client<'a> {
199    fn new(environment: &'a Environment, secret: &'a Secret) -> Self {
200        let config = ureq::Agent::config_builder()
201            .timeout_global(Some(TIMEOUT))
202            // A 503 from health is an answer, not a failed request.
203            .http_status_as_error(false)
204            // A redirect is not followed. It could take a custom header with the secret to
205            // another host, or ask for a path Mortise does not read. It comes back as an
206            // unexpected answer that names where it sends to.
207            .max_redirects(0)
208            // The certificates this computer trusts, so that a local site with its own
209            // certificate authority works as it does in the browser.
210            .tls_config(
211                ureq::tls::TlsConfig::builder()
212                    .root_certs(ureq::tls::RootCerts::PlatformVerifier)
213                    .build(),
214            )
215            .build();
216        Self {
217            agent: ureq::Agent::new_with_config(config),
218            environment,
219            secret,
220        }
221    }
222
223    /// Asks for `url`. With a limit, only the body of a 200 or a 503 is read, up to that many
224    /// decoded bytes, and a read of it that fails, such as a timeout, is a failed request. Any
225    /// other status comes back with an empty body, so a body that breaks off cannot hide it.
226    fn get(&self, url: &str, limit: Option<u64>) -> Result<Reply, ureq::Error> {
227        // Laravel answers errors as JSON only when it is asked for JSON.
228        let mut request = self.agent.get(url).header("Accept", "application/json");
229        let secret = self.secret.as_deref().unwrap_or_default();
230        match &self.environment.credentials {
231            Credentials::None => {}
232            Credentials::Bearer => {
233                request = request.header("Authorization", format!("Bearer {secret}"));
234            }
235            Credentials::Basic { user } => {
236                let pair = base64(format!("{user}:{secret}").as_bytes());
237                request = request.header("Authorization", format!("Basic {pair}"));
238            }
239            Credentials::Header { name } => request = request.header(name.as_str(), secret),
240        }
241        let mut response = request.call()?;
242        let status = response.status().as_u16();
243        let location = response
244            .headers()
245            .get("location")
246            .and_then(|value| value.to_str().ok())
247            .map(|location| resolve(url, location));
248        let (body, too_large) = match limit {
249            None => (
250                response.body_mut().read_to_string().unwrap_or_default(),
251                false,
252            ),
253            Some(_) if !matches!(status, 200 | 503) => (String::new(), false),
254            Some(limit) => {
255                // The reader of `with_config()` has no limit of its own and decodes gzip, so
256                // this one counts decoded bytes. One byte past the limit says the body is longer.
257                let mut bytes = Vec::new();
258                response
259                    .body_mut()
260                    .with_config()
261                    .reader()
262                    .take(limit.saturating_add(1))
263                    .read_to_end(&mut bytes)
264                    .map_err(ureq::Error::from)?;
265                if bytes.len() as u64 > limit {
266                    (String::new(), true)
267                } else {
268                    (String::from_utf8_lossy(&bytes).into_owned(), false)
269                }
270            }
271        };
272        Ok(Reply {
273            status,
274            body,
275            too_large,
276            location,
277        })
278    }
279
280    /// The JSON an endpoint answers, or the answer that says why there is none.
281    fn fetch(&self, endpoint: &str) -> Result<Value, Answer> {
282        let url = self.environment.url(endpoint);
283        let reply = match self.get(&url, None) {
284            Ok(reply) => reply,
285            Err(error) => {
286                return Err(Answer::NoAnswer {
287                    url,
288                    message: reason(&error),
289                });
290            }
291        };
292        match reply.status {
293            // 503: the app is down or out of service, and says so in the body.
294            200 | 503 => Ok(serde_json::from_str(&reply.body).unwrap_or(Value::Null)),
295            status @ (401 | 403) => Err(Answer::NotAuthorized { url, status }),
296            status => Err(Answer::Unexpected {
297                url,
298                status,
299                location: reply.location.filter(|_| (300..400).contains(&status)),
300            }),
301        }
302    }
303
304    /// The text of `prometheus`, or why there is none.
305    fn metrics(&self) -> Result<String, NoMetrics> {
306        let url = self.environment.url("prometheus");
307        let reply = match self.get(&url, Some(METRICS_BODY_LIMIT)) {
308            Ok(reply) => reply,
309            Err(error) => {
310                return Err(NoMetrics::NoAnswer {
311                    url,
312                    message: reason(&error),
313                });
314            }
315        };
316        match reply.status {
317            200 | 503 if reply.too_large => Err(NoMetrics::TooLarge {
318                url,
319                limit: METRICS_BODY_LIMIT,
320            }),
321            200 if reply.body.trim().is_empty() => Err(NoMetrics::Off),
322            200 => Ok(reply.body),
323            // A 503 of maintenance mode can be a whole page: only its first line is kept.
324            503 => Err(NoMetrics::Unavailable {
325                url,
326                line: reply
327                    .body
328                    .lines()
329                    .next()
330                    .unwrap_or_default()
331                    .chars()
332                    .take(200)
333                    .collect(),
334            }),
335            status @ (401 | 403) => Err(NoMetrics::NotAuthorized { url, status }),
336            status => Err(NoMetrics::Unexpected {
337                url,
338                status,
339                location: reply.location.filter(|_| (300..400).contains(&status)),
340            }),
341        }
342    }
343
344    /// The status of the app and of its components, from `health`.
345    fn health(&self) -> Result<(Status, Option<Vec<Component>>), Answer> {
346        let health = self.fetch("health")?;
347        let status = |value: &Value| {
348            value
349                .get("status")
350                .and_then(Value::as_str)
351                .map_or(Status::Unknown, Status::parse)
352        };
353        let components = health
354            .get("components")
355            .and_then(Value::as_object)
356            .map(|components| {
357                components
358                    .iter()
359                    .map(|(name, component)| Component {
360                        name: name.clone(),
361                        status: status(component),
362                        details: component
363                            .get("details")
364                            .and_then(Value::as_object)
365                            .map(|details| {
366                                details
367                                    .iter()
368                                    .map(|(key, value)| (key.clone(), plain(value)))
369                                    .collect()
370                            })
371                            .unwrap_or_default(),
372                    })
373                    .collect()
374            });
375        Ok((status(&health), components))
376    }
377
378    fn everything(&self) -> Result<Runtime, Answer> {
379        // What is exposed: the links at the base path. An endpoint that is not listed
380        // has no route in the app.
381        let exposed: Vec<String> = self
382            .fetch("")?
383            .get("_links")
384            .and_then(Value::as_object)
385            .map(|links| {
386                links
387                    .keys()
388                    .filter(|key| *key != "self" && !key.contains('-'))
389                    .cloned()
390                    .collect()
391            })
392            .unwrap_or_default();
393        let (status, components) = self.health()?;
394        let mut runtime = Runtime {
395            status,
396            components,
397            exposed,
398            info: None,
399            routes: None,
400            tasks: None,
401        };
402        if runtime.exposes("info") {
403            runtime.info = Some(read_info(&self.fetch("info")?));
404        }
405        if runtime.exposes("mappings") {
406            runtime.routes = Some(read_routes(&self.fetch("mappings")?));
407        }
408        if runtime.exposes("scheduledtasks") {
409            runtime.tasks = Some(read_tasks(&self.fetch("scheduledtasks")?));
410        }
411        Ok(runtime)
412    }
413}
414
415/// A `Location` header read against the address that was asked for.
416fn resolve(url: &str, location: &str) -> String {
417    let Some((scheme, rest)) = url.split_once("://") else {
418        return location.to_owned();
419    };
420    let host = rest.split('/').next().unwrap_or_default();
421    if location.starts_with("//") {
422        format!("{scheme}:{location}")
423    } else if location.starts_with('/') {
424        format!("{scheme}://{host}{location}")
425    } else {
426        // A full address, or a relative path, which is shown as given.
427        location.to_owned()
428    }
429}
430
431/// How long Mortise waits for one endpoint.
432const TIMEOUT: Duration = Duration::from_secs(10);
433
434/// Why nothing came back, in a few words.
435fn reason(error: &ureq::Error) -> String {
436    use std::io::ErrorKind;
437    let timeout = || format!("no answer in {} s", TIMEOUT.as_secs());
438    let text = match error {
439        ureq::Error::Timeout(_) => return timeout(),
440        ureq::Error::HostNotFound => return "the host was not found".to_owned(),
441        ureq::Error::ConnectionFailed => return "connection failed".to_owned(),
442        ureq::Error::BadUri(_) => return "the URL is not valid".to_owned(),
443        ureq::Error::Io(error) => match error.kind() {
444            ErrorKind::ConnectionRefused => return "connection refused".to_owned(),
445            ErrorKind::ConnectionReset | ErrorKind::ConnectionAborted => {
446                return "the connection was closed".to_owned();
447            }
448            ErrorKind::TimedOut => return timeout(),
449            // WSAHOST_NOT_FOUND and WSANO_DATA: the name does not resolve.
450            #[cfg(windows)]
451            _ if matches!(error.raw_os_error(), Some(11001 | 11004)) => {
452                return "the host was not found".to_owned();
453            }
454            _ => error.to_string(),
455        },
456        other => other.to_string(),
457    };
458    // What is left comes as the text of the operating system or of the TLS library.
459    if text.contains("lookup address") {
460        "the host was not found".to_owned()
461    } else if text.contains("invalid peer certificate") {
462        "the certificate is not trusted on this computer".to_owned()
463    } else {
464        text
465    }
466}
467
468/// Asks an environment for everything Mortise reads: what is exposed, `health`,
469/// and `info`, `mappings` and `scheduledtasks` where they are exposed.
470///
471/// This waits for the app, for at most 10 s an endpoint: call it from a worker thread.
472pub fn ask(environment: &Environment, secret: &Secret) -> Answer {
473    match Client::new(environment, secret).everything() {
474        Ok(runtime) => Answer::Answered(Box::new(runtime)),
475        Err(answer) => answer,
476    }
477}
478
479/// Asks an environment for `health` only, which is what the regular check does.
480/// The rest is taken over from `earlier`, the last full answer.
481pub fn ask_status(environment: &Environment, secret: &Secret, earlier: &Runtime) -> Answer {
482    match Client::new(environment, secret).health() {
483        Ok((status, components)) => Answer::Answered(Box::new(Runtime {
484            status,
485            components,
486            ..earlier.clone()
487        })),
488        Err(answer) => answer,
489    }
490}
491
492/// Asks an environment for `prometheus`. `Ok` is the text of a 200 that is not empty.
493///
494/// The request carries `Accept: application/json` and the credentials, as every request does.
495/// This waits for the app, for at most 10 s: call it from a worker thread.
496pub fn ask_metrics(environment: &Environment, secret: &Secret) -> Result<String, NoMetrics> {
497    Client::new(environment, secret).metrics()
498}
499
500/// A JSON value as the app wrote it, without quotes around a string.
501fn plain(value: &Value) -> String {
502    match value {
503        Value::String(text) => text.clone(),
504        // The certificate check of the operating system said no.
505        other if other.to_string().starts_with("invalid peer certificate") => {
506            "the certificate is not trusted on this computer".to_owned()
507        }
508        other => other.to_string(),
509    }
510}
511
512fn text(value: &Value, path: &[&str]) -> Option<String> {
513    path.iter()
514        .try_fold(value, |value, key| value.get(key))?
515        .as_str()
516        .map(str::to_owned)
517}
518
519fn number(value: &Value, path: &[&str]) -> Option<i64> {
520    path.iter()
521        .try_fold(value, |value, key| value.get(key))?
522        .as_i64()
523}
524
525fn read_info(info: &Value) -> Info {
526    Info {
527        environment: text(info, &["app", "environment"]),
528        laravel: text(info, &["app", "laravel"]),
529        git_branch: text(info, &["git", "branch"]),
530        git_commit: text(info, &["git", "commit", "id"]),
531        php_version: text(info, &["php", "version"]),
532        php_sapi: text(info, &["php", "sapi"]),
533        memory_usage: number(info, &["process", "memory", "usage"]),
534        memory_peak: number(info, &["process", "memory", "peak"]),
535        memory_limit: number(info, &["process", "memory", "limit"]),
536    }
537}
538
539fn strings(value: Option<&Value>) -> Vec<String> {
540    value
541        .and_then(Value::as_array)
542        .map(|items| {
543            items
544                .iter()
545                .filter_map(Value::as_str)
546                .map(str::to_owned)
547                .collect()
548        })
549        .unwrap_or_default()
550}
551
552fn read_routes(mappings: &Value) -> Vec<Route> {
553    mappings
554        .get("routes")
555        .and_then(Value::as_array)
556        .map(|routes| {
557            routes
558                .iter()
559                .map(|route| Route {
560                    methods: strings(route.get("methods")),
561                    uri: text(route, &["uri"]).unwrap_or_default(),
562                    name: text(route, &["name"]),
563                    action: text(route, &["action"]).unwrap_or_default(),
564                    middleware: strings(route.get("middleware")),
565                })
566                .collect()
567        })
568        .unwrap_or_default()
569}
570
571fn read_tasks(tasks: &Value) -> Vec<Task> {
572    let list = |key: &str| {
573        tasks
574            .get(key)
575            .and_then(Value::as_array)
576            .cloned()
577            .unwrap_or_default()
578    };
579    let cron = list("cron").into_iter().map(|task| Task {
580        target: text(&task, &["runnable", "target"]).unwrap_or_default(),
581        expression: text(&task, &["expression"]),
582        interval_ms: None,
583        timezone: text(&task, &["timezone"]),
584        next: text(&task, &["nextExecution", "time"]),
585        module: text(&task, &["tags", "module"]),
586    });
587    let fixed = list("fixedRate").into_iter().map(|task| Task {
588        target: text(&task, &["runnable", "target"]).unwrap_or_default(),
589        expression: None,
590        interval_ms: task.get("interval").and_then(Value::as_u64),
591        timezone: None,
592        next: None,
593        module: text(&task, &["tags", "module"]),
594    });
595    cron.chain(fixed).collect()
596}
597
598/// Base64, for HTTP basic.
599fn base64(bytes: &[u8]) -> String {
600    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
601    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
602    for chunk in bytes.chunks(3) {
603        let group = u32::from(chunk[0]) << 16
604            | u32::from(*chunk.get(1).unwrap_or(&0)) << 8
605            | u32::from(*chunk.get(2).unwrap_or(&0));
606        for i in 0..4 {
607            if i <= chunk.len() {
608                out.push(ALPHABET[(group >> (18 - 6 * i) & 63) as usize] as char);
609            } else {
610                out.push('=');
611            }
612        }
613    }
614    out
615}
616
617#[cfg(test)]
618mod tests {
619    use super::*;
620
621    #[test]
622    fn base64_matches_known_values() {
623        assert_eq!(base64(b""), "");
624        assert_eq!(base64(b"f"), "Zg==");
625        assert_eq!(base64(b"fo"), "Zm8=");
626        assert_eq!(base64(b"foo"), "Zm9v");
627        assert_eq!(base64(b"mortise:secret"), "bW9ydGlzZTpzZWNyZXQ=");
628    }
629}