1use std::collections::{BTreeMap, HashMap};
11use std::fmt::Write as _;
12use std::sync::Arc;
13use std::time::{Duration, Instant};
14
15use askama::Template;
16use axum::extract::State;
17use axum::http::{HeaderMap, StatusCode};
18use axum::response::Response;
19use schedr_api::views::{
20 DeploymentView, MasterView, MemoryTotals, NodeView, ProblemView, WorkerNodeView,
21};
22use schedr_client::{ClientError, Transport};
23
24use crate::Ui;
25use crate::page::Page;
26use crate::pages::render;
27
28pub const NODE_WIDTH: u32 = 200;
30pub const NODE_HEIGHT: u32 = 52;
32const PROCESS_TITLE: u32 = 24;
34const FRAME_TITLE: u32 = 30;
36const GAP: u32 = 10;
38const ROW_GAP: u32 = 40;
40const PROCESS_WIDTH: u32 = NODE_WIDTH + 2 * GAP;
42const PER_ROW: usize = 3;
44const LABEL_CHARS: usize = 24;
46const LINE_CHARS: usize = 30;
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
51pub enum Level {
52 Fine,
54 Warning,
56 Error,
58}
59
60impl Level {
61 #[must_use]
63 pub fn of(problems: &[ProblemView]) -> Self {
64 problems.iter().fold(Self::Fine, |level, problem| {
65 level.max(if problem.error {
66 Self::Error
67 } else {
68 Self::Warning
69 })
70 })
71 }
72
73 #[must_use]
75 pub const fn class(self) -> &'static str {
76 match self {
77 Self::Fine => "",
78 Self::Warning => "warning",
79 Self::Error => "error",
80 }
81 }
82}
83
84#[derive(Debug, Clone)]
86pub struct GraphNode {
87 pub anchor: String,
89 pub kind: &'static str,
91 pub label: String,
93 pub sub: String,
95 pub extra: String,
97 pub tooltip: String,
99 pub state: String,
101 pub level: Level,
103 pub x: u32,
105 pub y: u32,
107}
108
109impl GraphNode {
110 #[must_use]
112 pub fn classes(&self) -> String {
113 ["box", self.state.as_str(), self.level.class()]
114 .into_iter()
115 .filter(|class| !class.is_empty())
116 .collect::<Vec<_>>()
117 .join(" ")
118 }
119
120 #[must_use]
122 pub const fn mark(&self) -> &'static str {
123 match self.level {
124 Level::Fine => "",
125 Level::Warning => "!",
126 Level::Error => "×",
127 }
128 }
129}
130
131#[derive(Debug, Clone, PartialEq, Eq)]
133pub struct Frame {
134 pub title: String,
136 pub x: u32,
138 pub y: u32,
140 pub width: u32,
142 pub height: u32,
144}
145
146#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct Edge {
149 pub kind: &'static str,
151 pub dashed: bool,
153 pub title: String,
155 pub path: String,
157}
158
159#[derive(Debug, Clone)]
162pub struct Graph {
163 pub width: u32,
165 pub height: u32,
167 pub frames: Vec<Frame>,
169 pub processes: Vec<Frame>,
171 pub edges: Vec<Edge>,
173 pub nodes: Vec<GraphNode>,
175}
176
177#[derive(Debug, Clone)]
179pub struct NodePanel {
180 pub anchor: String,
182 pub title: String,
184 pub facts: Vec<(String, String)>,
186 pub problems: Vec<ProblemView>,
188 pub config: String,
190 pub no_config: &'static str,
192 pub connections: Vec<ConnectionRow>,
194 pub metrics: String,
197}
198
199fn metrics_query(deployment: &str, process: &str) -> String {
201 if process.is_empty() {
202 return String::new();
203 }
204 format!(
205 "deployment={}&process={}",
206 schedr_client::path_segment(deployment),
207 schedr_client::path_segment(process)
208 )
209}
210
211#[derive(Debug, Clone)]
213pub struct ConnectionRow {
214 pub name: String,
216 pub href: String,
218 pub version: String,
220 pub mismatch: bool,
222 pub latency: String,
224 pub proof: &'static str,
226 pub user: String,
228 pub error: Option<String>,
230}
231
232#[derive(Debug, Clone)]
234pub struct UiSide {
235 pub process_id: String,
237 pub host: String,
239 pub version: String,
241 pub user: String,
243 pub config: serde_json::Value,
245}
246
247#[derive(Debug, Clone)]
249pub struct Asked {
250 pub name: String,
252 pub proof: &'static str,
254 pub answer: Result<DeploymentView, String>,
256 pub took: Duration,
258 pub memory: Option<MemoryTotals>,
261}
262
263const NO_CONFIG: &str = "It sent no configuration (an older agent).";
265
266pub const UI_ANCHOR: &str = "node.ui";
268
269fn anchor_part(text: &str) -> String {
272 let mut part = String::with_capacity(text.len());
273 for byte in text.bytes() {
274 if byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-') {
275 part.push(char::from(byte));
276 } else {
277 let _ = write!(part, "%{byte:02X}");
278 }
279 }
280 part
281}
282
283#[must_use]
285pub fn webserver_anchor(deployment: &str) -> String {
286 format!("node.{}.webserver", anchor_part(deployment))
287}
288
289#[must_use]
291pub fn master_anchor(deployment: &str, master_id: &str) -> String {
292 format!(
293 "node.{}.master.{}",
294 anchor_part(deployment),
295 anchor_part(master_id)
296 )
297}
298
299#[must_use]
301pub fn worker_anchor(deployment: &str, worker_id: &str) -> String {
302 format!(
303 "node.{}.worker.{}",
304 anchor_part(deployment),
305 anchor_part(worker_id)
306 )
307}
308
309#[must_use]
312pub fn short(id: &str) -> &str {
313 id.char_indices()
314 .rev()
315 .nth(7)
316 .map_or(id, |(at, _)| &id[at..])
317}
318
319fn cut(text: &str, chars: usize) -> String {
321 if text.chars().count() <= chars {
322 return text.to_owned();
323 }
324 let mut cut: String = text.chars().take(chars.saturating_sub(1)).collect();
325 cut.push('…');
326 cut
327}
328
329fn without_nulls(value: &mut serde_json::Value) {
331 match value {
332 serde_json::Value::Object(map) => {
333 map.retain(|_, v| !v.is_null());
334 map.values_mut().for_each(without_nulls);
335 }
336 serde_json::Value::Array(items) => {
337 items.retain(|v| !v.is_null());
338 items.iter_mut().for_each(without_nulls);
339 }
340 _ => {}
341 }
342}
343
344#[must_use]
348pub fn pretty(config: &serde_json::Value) -> String {
349 let mut config = config.clone();
350 schedr_config::masked::mask(&mut config);
351 without_nulls(&mut config);
352 if config.is_object()
353 && let Ok(toml) = toml::to_string_pretty(&config)
354 {
355 return if toml.is_empty() {
357 "# nothing set".to_owned()
358 } else {
359 toml
360 };
361 }
362 serde_json::to_string_pretty(&config).unwrap_or_default()
363}
364
365struct Group {
367 key: String,
368 host: String,
369 nodes: Vec<(u8, GraphNode)>,
370}
371
372impl Group {
373 fn tier(&self) -> u8 {
374 self.nodes.first().map_or(u8::MAX, |(tier, _)| *tier)
375 }
376
377 fn height(&self) -> u32 {
378 let count = u32::try_from(self.nodes.len()).unwrap_or(u32::MAX);
379 PROCESS_TITLE + count.saturating_mul(NODE_HEIGHT + GAP)
380 }
381
382 fn title(&self) -> String {
383 let host = if self.host.is_empty() {
384 "process"
385 } else {
386 &self.host
387 };
388 if self.key.contains(':') || self.key.is_empty() {
389 host.to_owned()
390 } else {
391 format!("{host} · {}", short(&self.key))
392 }
393 }
394}
395
396#[derive(Default)]
398struct Groups {
399 list: Vec<Group>,
400 by_key: HashMap<String, usize>,
401}
402
403impl Groups {
404 fn add(&mut self, key: String, host: &str, tier: u8, node: GraphNode) {
406 if let Some(&at) = self.by_key.get(&key) {
407 let group = &mut self.list[at];
408 if group.host.is_empty() {
409 host.clone_into(&mut group.host);
410 }
411 group.nodes.push((tier, node));
412 } else {
413 self.by_key.insert(key.clone(), self.list.len());
414 self.list.push(Group {
415 key,
416 host: host.to_owned(),
417 nodes: vec![(tier, node)],
418 });
419 }
420 }
421}
422
423fn node(anchor: String, kind: &'static str, label: &str, sub: &str) -> GraphNode {
424 GraphNode {
425 anchor,
426 kind,
427 tooltip: format!("{label}\n{sub}"),
428 label: cut(label, LABEL_CHARS),
429 sub: cut(sub, LINE_CHARS),
430 extra: String::new(),
431 state: String::new(),
432 level: Level::Fine,
433 x: 0,
434 y: 0,
435 }
436}
437
438fn place(groups: Vec<Group>, x: u32, y: u32) -> (Vec<(Frame, Vec<GraphNode>)>, u32, u32) {
441 let mut rows: Vec<Vec<Group>> = Vec::new();
442 let mut groups = groups;
443 groups.sort_by_key(Group::tier);
444 for group in groups {
445 match rows.last_mut() {
446 Some(row) if row.len() < PER_ROW && row[0].tier() == group.tier() => row.push(group),
447 _ => rows.push(vec![group]),
448 }
449 }
450 let mut placed = Vec::new();
451 let (mut width, mut top) = (0, y);
452 for row in rows {
453 let tallest = row.iter().map(Group::height).max().unwrap_or(0);
454 let mut left = x;
455 for group in row {
456 let height = group.height();
457 let frame = Frame {
458 title: group.title(),
459 x: left,
460 y: top,
461 width: PROCESS_WIDTH,
462 height,
463 };
464 let nodes = group
465 .nodes
466 .into_iter()
467 .enumerate()
468 .map(|(i, (_, mut node))| {
469 node.x = left + GAP;
470 node.y = top
471 + PROCESS_TITLE
472 + u32::try_from(i)
473 .unwrap_or(0)
474 .saturating_mul(NODE_HEIGHT + GAP);
475 node
476 })
477 .collect();
478 placed.push((frame, nodes));
479 left += PROCESS_WIDTH + GAP;
480 }
481 width = width.max(left - GAP - x);
482 top += tallest + ROW_GAP;
483 }
484 (placed, width, (top - y).saturating_sub(ROW_GAP))
485}
486
487struct Link {
489 from: String,
490 to: String,
491 kind: &'static str,
492 dashed: bool,
493 title: String,
494}
495
496fn path(from: (u32, u32), to: (u32, u32)) -> String {
499 let (fx, fy) = (from.0 + NODE_WIDTH / 2, from.1 + NODE_HEIGHT);
500 let (tx, ty) = (to.0 + NODE_WIDTH / 2, to.1);
501 if ty > fy {
502 let bend = (ty - fy) / 2;
503 format!(
504 "M{fx} {fy} C{fx} {} {tx} {} {tx} {ty}",
505 fy + bend,
506 ty - bend
507 )
508 } else {
509 let (fx, fy) = (from.0 + NODE_WIDTH, from.1 + NODE_HEIGHT / 2);
510 let (tx, ty) = (to.0, to.1 + NODE_HEIGHT / 2);
511 format!("M{fx} {fy} L{tx} {ty}")
512 }
513}
514
515#[derive(Default)]
518struct Gathered {
519 panels: Vec<NodePanel>,
520 links: Vec<Link>,
521 connections: Vec<ConnectionRow>,
522 ui_problems: Vec<ProblemView>,
523}
524
525impl Gathered {
526 fn unreachable(&mut self, asked: &Asked, error: &str, groups: &mut Groups) {
528 let ws_anchor = webserver_anchor(&asked.name);
529 let latency = format!("{} ms", asked.took.as_millis());
530 self.ui_problems.push(ProblemView {
531 error: true,
532 message: format!("can't reach `{}`'s webserver: {error}", asked.name),
533 });
534 let mut placeholder = node(ws_anchor.clone(), "webserver", "webserver", "unreachable");
535 "unreachable".clone_into(&mut placeholder.state);
536 placeholder.level = Level::Error;
537 groups.add(format!("webserver:{}", asked.name), "", 1, placeholder);
538 self.panels.push(NodePanel {
539 anchor: ws_anchor.clone(),
540 title: format!("Webserver · {}", asked.name),
541 facts: vec![
542 ("The UI proves itself by".to_owned(), asked.proof.to_owned()),
543 ("Gave up after".to_owned(), latency.clone()),
544 ],
545 problems: vec![ProblemView {
546 error: true,
547 message: format!("unreachable: {error}"),
548 }],
549 config: String::new(),
550 no_config: "",
551 metrics: String::new(),
552 connections: Vec::new(),
553 });
554 self.links.push(Link {
555 from: UI_ANCHOR.to_owned(),
556 to: ws_anchor.clone(),
557 kind: "http",
558 dashed: true,
559 title: format!("HTTP: `{}` unreachable", asked.name),
560 });
561 self.connections.push(ConnectionRow {
562 name: asked.name.clone(),
563 href: format!("#{ws_anchor}"),
564 version: String::new(),
565 mismatch: false,
566 latency,
567 proof: asked.proof,
568 user: String::new(),
569 error: Some(error.to_owned()),
570 });
571 }
572
573 fn answered(
576 &mut self,
577 (ui, ui_node): (&UiSide, Option<GraphNode>),
578 asked: &Asked,
579 view: &DeploymentView,
580 groups: &mut Groups,
581 ) {
582 let ws_anchor = webserver_anchor(&asked.name);
583 let latency = format!("{} ms", asked.took.as_millis());
584 let mismatch = view.webserver.schedr_version != ui.version;
585 if mismatch {
586 self.ui_problems.push(ProblemView {
587 error: false,
588 message: format!(
589 "`{}`'s webserver is version {}; this UI is {}",
590 asked.name, view.webserver.schedr_version, ui.version
591 ),
592 });
593 }
594 self.connections.push(ConnectionRow {
595 name: asked.name.clone(),
596 href: format!("#{ws_anchor}"),
597 version: view.webserver.schedr_version.clone(),
598 mismatch,
599 latency: latency.clone(),
600 proof: asked.proof,
601 user: view.user.clone(),
602 error: None,
603 });
604 let ws_key = process_key(&view.webserver.process_id, "webserver", &asked.name);
605 if let Some(ui_node) = ui_node {
606 groups.add(ws_key.clone(), &view.webserver.host, 0, ui_node);
607 }
608 deployment_nodes(asked, view, &ws_key, groups, self);
609 if let Some(panel) = self.panels.iter_mut().find(|p| p.anchor == ws_anchor) {
610 panel.facts.extend([
611 ("Answered in".to_owned(), latency),
612 ("The UI proves itself by".to_owned(), asked.proof.to_owned()),
613 ("It took the UI's requests as".to_owned(), view.user.clone()),
614 ]);
615 }
616 self.links.push(Link {
617 from: UI_ANCHOR.to_owned(),
618 to: ws_anchor,
619 kind: "http",
620 dashed: false,
621 title: format!("HTTP: the UI reads `{}`", asked.name),
622 });
623 }
624}
625
626#[must_use]
628pub fn graph(ui: &UiSide, deployments: &[Asked]) -> (Graph, Vec<NodePanel>) {
629 let mut gathered = Gathered::default();
630 let ui_home = deployments.iter().position(|d| {
632 !ui.process_id.is_empty()
633 && d.answer
634 .as_ref()
635 .is_ok_and(|v| v.webserver.process_id == ui.process_id)
636 });
637 let mut ui_node = Some(node(
638 UI_ANCHOR.to_owned(),
639 "ui",
640 "UI",
641 &format!("signed in as {} · {}", ui.user, ui.version),
642 ));
643 let mut deployment_groups = Vec::new();
644 for (index, asked) in deployments.iter().enumerate() {
645 let mut groups = Groups::default();
646 match &asked.answer {
647 Err(error) => gathered.unreachable(asked, error, &mut groups),
648 Ok(view) => {
649 let home = if ui_home == Some(index) {
650 ui_node.take()
651 } else {
652 None
653 };
654 gathered.answered((ui, home), asked, view, &mut groups);
655 }
656 }
657 deployment_groups.push((asked.name.clone(), groups.list));
658 }
659 let Gathered {
660 mut panels,
661 links,
662 connections,
663 ui_problems,
664 } = gathered;
665 let ui_level = Level::of(&ui_problems);
666 let mut ui_facts = vec![
667 ("Signed in as".to_owned(), ui.user.clone()),
668 ("Version".to_owned(), ui.version.clone()),
669 ];
670 if !ui.host.is_empty() {
671 ui_facts.push(("Host".to_owned(), ui.host.clone()));
672 }
673 if !ui.process_id.is_empty() {
674 ui_facts.push(("Process".to_owned(), ui.process_id.clone()));
675 }
676 panels.insert(
677 0,
678 NodePanel {
679 anchor: UI_ANCHOR.to_owned(),
680 title: "UI".to_owned(),
681 facts: ui_facts,
682 problems: ui_problems,
683 config: pretty(&ui.config),
684 no_config: NO_CONFIG,
685 connections,
686 metrics: String::new(),
687 },
688 );
689 let ui_group = ui_node.map(|ui_node| Group {
690 key: process_key(&ui.process_id, "ui", ""),
691 host: ui.host.clone(),
692 nodes: vec![(0, ui_node)],
693 });
694 let mut graph = lay_out(ui_group, deployment_groups, links);
695 if let Some(ui) = graph.nodes.iter_mut().find(|n| n.anchor == UI_ANCHOR) {
696 ui.level = ui_level;
697 }
698 (graph, panels)
699}
700
701fn lay_out(ui: Option<Group>, deployments: Vec<(String, Vec<Group>)>, links: Vec<Link>) -> Graph {
704 let mut placed: Vec<(Frame, Vec<GraphNode>)> = Vec::new();
705 let mut frames = Vec::new();
706 let mut top = ROW_GAP / 2;
707 let mut width = 0;
708 if let Some(group) = ui {
709 let (mut process, w, h) = place(vec![group], ROW_GAP / 2, top);
710 placed.append(&mut process);
711 width = width.max(w);
712 top += h + ROW_GAP;
713 }
714 let mut left = ROW_GAP / 2;
715 let mut bottom = top;
716 for (name, groups) in deployments {
717 let (mut processes, w, h) = place(groups, left + GAP, top + FRAME_TITLE);
718 let frame = Frame {
719 title: name,
720 x: left,
721 y: top,
722 width: w + 2 * GAP,
723 height: FRAME_TITLE + h + GAP,
724 };
725 left += frame.width + ROW_GAP;
726 bottom = bottom.max(frame.y + frame.height);
727 frames.push(frame);
728 placed.append(&mut processes);
729 }
730 width = width.max(left.saturating_sub(ROW_GAP / 2));
731 let mut processes = Vec::new();
732 let mut nodes = Vec::new();
733 let mut at = HashMap::new();
734 for (process, process_nodes) in placed {
735 for node in &process_nodes {
736 at.insert(node.anchor.clone(), (node.x, node.y, processes.len()));
737 }
738 processes.push(process);
739 nodes.extend(process_nodes);
740 }
741 let edges = links
742 .into_iter()
743 .filter_map(|link| {
744 let (fx, fy, from_process) = *at.get(&link.from)?;
745 let (tx, ty, to_process) = *at.get(&link.to)?;
746 (from_process != to_process).then(|| Edge {
747 kind: link.kind,
748 dashed: link.dashed,
749 title: link.title,
750 path: path((fx, fy), (tx, ty)),
751 })
752 })
753 .collect();
754 Graph {
755 width: width + ROW_GAP / 2,
756 height: bottom + ROW_GAP / 2,
757 frames,
758 processes,
759 edges,
760 nodes,
761 }
762}
763
764fn process_key(process_id: &str, kind: &str, id: &str) -> String {
766 if process_id.is_empty() {
767 format!("{kind}:{id}")
768 } else {
769 process_id.to_owned()
770 }
771}
772
773fn deployment_nodes(
776 asked: &Asked,
777 view: &DeploymentView,
778 ws_key: &str,
779 groups: &mut Groups,
780 gathered: &mut Gathered,
781) {
782 let Gathered { panels, links, .. } = gathered;
783 let name = &asked.name;
784 let ws_anchor = webserver_anchor(name);
785 let ws = &view.webserver;
786 groups.add(
787 ws_key.to_owned(),
788 &ws.host,
789 1,
790 node(
791 ws_anchor.clone(),
792 "webserver",
793 "webserver",
794 &ws.schedr_version,
795 ),
796 );
797 panels.push(NodePanel {
798 anchor: ws_anchor.clone(),
799 title: format!("Webserver · {name}"),
800 facts: node_facts(ws),
801 problems: Vec::new(),
802 config: pretty(&ws.config),
803 no_config: NO_CONFIG,
804 connections: Vec::new(),
805 metrics: metrics_query(name, &ws.process_id),
806 });
807 for master in &view.masters {
808 let anchor = master_anchor(name, &master.master_id);
809 let mut graph_node = node(
810 anchor.clone(),
811 "master",
812 &format!("master {}", short(&master.master_id)),
813 &format!("{} · {}", master.role, master.node.schedr_version),
814 );
815 graph_node.state.clone_from(&master.role);
816 graph_node.level = Level::of(&master.problems);
817 groups.add(
818 process_key(&master.node.process_id, "master", &master.master_id),
819 &master.node.host,
820 2,
821 graph_node,
822 );
823 panels.push(master_panel(name, master));
824 links.push(Link {
825 from: ws_anchor.clone(),
826 to: anchor,
827 kind: "database",
828 dashed: false,
829 title: format!(
830 "database: the webserver and master {} share it",
831 short(&master.master_id)
832 ),
833 });
834 }
835 for worker in &view.workers {
836 worker_node(name, view, worker, groups, (panels, links));
837 }
838}
839
840fn worker_node(
842 name: &str,
843 view: &DeploymentView,
844 worker: &WorkerNodeView,
845 groups: &mut Groups,
846 (panels, links): (&mut Vec<NodePanel>, &mut Vec<Link>),
847) {
848 let anchor = worker_anchor(name, &worker.worker_id);
849 let mut graph_node = node(
850 anchor.clone(),
851 "worker",
852 &format!("worker {}", worker.worker_id),
853 &format!("{} · {}", worker.state, worker.schedr_version),
854 );
855 if !worker.queues.is_empty() {
856 let queues = format!("queues: {}", worker.queues.join(", "));
857 graph_node.extra = cut(&queues, LINE_CHARS);
858 graph_node.tooltip = format!("{}\n{queues}", graph_node.tooltip);
859 }
860 graph_node.state.clone_from(&worker.state);
861 graph_node.level = Level::of(&worker.problems);
862 groups.add(
863 process_key(
864 worker.process_id.as_deref().unwrap_or_default(),
865 "worker",
866 &worker.worker_id,
867 ),
868 "",
869 3,
870 graph_node,
871 );
872 panels.push(worker_panel(name, view, worker));
873 if let Some(master) = &worker.master_id
874 && view.masters.iter().any(|m| &m.master_id == master)
875 {
876 let connected = matches!(worker.state.as_str(), "active" | "draining");
877 links.push(Link {
878 from: master_anchor(name, master),
879 to: anchor,
880 kind: "grpc",
881 dashed: !connected,
882 title: format!(
883 "gRPC: worker {} {} master {}",
884 worker.worker_id,
885 if connected {
886 "is connected to"
887 } else {
888 "isn't connected to"
889 },
890 short(master)
891 ),
892 });
893 }
894}
895
896fn masked_problems(problems: &[ProblemView]) -> Vec<ProblemView> {
898 problems
899 .iter()
900 .map(|problem| ProblemView {
901 error: problem.error,
902 message: schedr_config::masked::mask_text(&problem.message),
903 })
904 .collect()
905}
906
907fn node_facts(node: &NodeView) -> Vec<(String, String)> {
908 let mut facts = Vec::new();
909 if !node.host.is_empty() {
910 facts.push(("Host".to_owned(), node.host.clone()));
911 }
912 if !node.process_id.is_empty() {
913 facts.push(("Process".to_owned(), node.process_id.clone()));
914 }
915 facts.push(("Version".to_owned(), node.schedr_version.clone()));
916 facts
917}
918
919fn master_panel(deployment: &str, master: &MasterView) -> NodePanel {
920 let mut facts = vec![
921 ("ID".to_owned(), master.master_id.clone()),
922 ("Role".to_owned(), master.role.clone()),
923 ];
924 facts.extend(node_facts(&master.node));
925 NodePanel {
926 anchor: master_anchor(deployment, &master.master_id),
927 title: format!(
928 "Master {} ({}) · {deployment}",
929 short(&master.master_id),
930 master.role
931 ),
932 facts,
933 problems: masked_problems(&master.problems),
934 config: pretty(&master.node.config),
935 no_config: NO_CONFIG,
936 connections: Vec::new(),
937 metrics: metrics_query(deployment, &master.node.process_id),
938 }
939}
940
941fn worker_panel(deployment: &str, view: &DeploymentView, worker: &WorkerNodeView) -> NodePanel {
942 let mut facts = vec![
943 ("State".to_owned(), worker.state.clone()),
944 ("Queues".to_owned(), worker.queues.join(", ")),
945 ("Version".to_owned(), worker.schedr_version.clone()),
946 ];
947 if let Some(process) = &worker.process_id {
948 facts.push(("Process".to_owned(), process.clone()));
949 }
950 if let Some(master) = &worker.master_id {
951 let heard = view.masters.iter().any(|m| &m.master_id == master);
952 facts.push((
953 "Registered with".to_owned(),
954 if heard {
955 format!("master {}", short(master))
956 } else {
957 format!("master {} (not heard from lately)", short(master))
958 },
959 ));
960 }
961 NodePanel {
962 anchor: worker_anchor(deployment, &worker.worker_id),
963 title: format!("Worker {} · {deployment}", worker.worker_id),
964 facts,
965 problems: masked_problems(&worker.problems),
966 config: worker.config.as_ref().map(pretty).unwrap_or_default(),
967 no_config: NO_CONFIG,
968 connections: Vec::new(),
969 metrics: metrics_query(deployment, worker.process_id.as_deref().unwrap_or_default()),
970 }
971}
972
973pub const WORKER_STATES: [&str; 5] = ["active", "draining", "disconnected", "lost", "offline"];
976
977#[derive(Debug, Clone, PartialEq, Eq)]
979pub struct StatusProblem {
980 pub error: bool,
982 pub node: String,
984 pub message: String,
986 pub href: String,
988}
989
990#[derive(Debug, Clone, PartialEq, Eq)]
992pub struct StatusRow {
993 pub name: String,
995 pub href: String,
997 pub unreachable: Option<String>,
999 pub took: String,
1001 pub leaders: usize,
1003 pub standbys: usize,
1005 pub workers: Vec<(&'static str, usize)>,
1008 pub running: u32,
1010 pub slots: u32,
1012 pub problems: Vec<StatusProblem>,
1014 pub versions: Vec<(String, usize)>,
1017 pub memory: String,
1019 pub sparkline: String,
1021 pub metrics_href: String,
1023}
1024
1025impl StatusRow {
1026 #[must_use]
1028 pub fn errors(&self) -> usize {
1029 self.problems.iter().filter(|p| p.error).count()
1030 }
1031
1032 #[must_use]
1034 pub fn warnings(&self) -> usize {
1035 self.problems.len() - self.errors()
1036 }
1037
1038 #[must_use]
1040 pub const fn leaderless(&self) -> bool {
1041 self.unreachable.is_none() && self.leaders == 0
1042 }
1043
1044 #[must_use]
1046 pub fn mixed(&self) -> bool {
1047 self.versions.len() > 1
1048 }
1049}
1050
1051#[must_use]
1053pub fn status(deployments: &[Asked]) -> Vec<StatusRow> {
1054 deployments.iter().map(status_row).collect()
1055}
1056
1057fn memory_now(name: &str, totals: &MemoryTotals) -> Option<(String, String)> {
1060 let last = totals.points.last()?;
1061 #[expect(clippy::cast_precision_loss, reason = "a chart's coordinates")]
1062 let points: Vec<(i64, f64)> = totals
1063 .points
1064 .iter()
1065 .map(|p| (p.at.as_second(), p.resident as f64))
1066 .collect();
1067 #[expect(clippy::cast_precision_loss, reason = "a size shown")]
1068 let now = crate::chart::bytes(last.resident as f64);
1069 let sparkline = crate::chart::sparkline(
1070 &points,
1071 totals.from.as_second(),
1072 totals.to.as_second(),
1073 i64::from(totals.step_s),
1074 &format!("{name}'s memory over 24 h, now {now}"),
1075 );
1076 Some((now, sparkline))
1077}
1078
1079fn status_row(asked: &Asked) -> StatusRow {
1080 let name = &asked.name;
1081 let mut row = StatusRow {
1082 name: name.clone(),
1083 href: format!("#{}", webserver_anchor(name)),
1084 unreachable: None,
1085 took: format!("{} ms", asked.took.as_millis()),
1086 leaders: 0,
1087 standbys: 0,
1088 workers: Vec::new(),
1089 running: 0,
1090 slots: 0,
1091 problems: Vec::new(),
1092 versions: Vec::new(),
1093 memory: String::new(),
1094 sparkline: String::new(),
1095 metrics_href: format!("metrics?deployment={}", schedr_client::path_segment(name)),
1096 };
1097 if let Some((memory, sparkline)) = asked.memory.as_ref().and_then(|t| memory_now(name, t)) {
1098 row.memory = memory;
1099 row.sparkline = sparkline;
1100 }
1101 let view = match &asked.answer {
1102 Err(error) => {
1103 row.unreachable = Some(error.clone());
1104 return row;
1105 }
1106 Ok(view) => view,
1107 };
1108 let mut versions: BTreeMap<&str, usize> = BTreeMap::new();
1109 *versions.entry(&view.webserver.schedr_version).or_default() += 1;
1110 for master in &view.masters {
1111 if master.role == "leader" {
1112 row.leaders += 1;
1113 } else {
1114 row.standbys += 1;
1115 }
1116 *versions.entry(&master.node.schedr_version).or_default() += 1;
1117 let href = format!("#{}", master_anchor(name, &master.master_id));
1118 row.problems.extend(
1119 masked_problems(&master.problems)
1120 .into_iter()
1121 .map(|p| StatusProblem {
1122 error: p.error,
1123 node: format!("master {}", short(&master.master_id)),
1124 message: p.message,
1125 href: href.clone(),
1126 }),
1127 );
1128 }
1129 let mut states: BTreeMap<usize, usize> = BTreeMap::new();
1130 for worker in &view.workers {
1131 let at = WORKER_STATES
1132 .iter()
1133 .position(|s| *s == worker.state)
1134 .unwrap_or(WORKER_STATES.len() - 1);
1135 *states.entry(at).or_default() += 1;
1136 if worker.state == "active" {
1137 row.running += worker.running;
1138 row.slots += worker.slots;
1139 }
1140 if !matches!(worker.state.as_str(), "offline" | "lost") {
1141 *versions.entry(&worker.schedr_version).or_default() += 1;
1142 }
1143 let href = format!("#{}", worker_anchor(name, &worker.worker_id));
1144 row.problems.extend(
1145 masked_problems(&worker.problems)
1146 .into_iter()
1147 .map(|p| StatusProblem {
1148 error: p.error,
1149 node: format!("worker {}", worker.worker_id),
1150 message: p.message,
1151 href: href.clone(),
1152 }),
1153 );
1154 }
1155 row.workers = states
1156 .into_iter()
1157 .map(|(at, count)| (WORKER_STATES[at], count))
1158 .collect();
1159 row.problems.sort_by_key(|p| !p.error);
1161 row.versions = versions
1162 .into_iter()
1163 .map(|(version, count)| (version.to_owned(), count))
1164 .collect();
1165 row
1166}
1167
1168async fn ask_all<T: Transport + Send + Sync + 'static>(
1171 ui: &Arc<Ui<T>>,
1172) -> Vec<(
1173 Result<DeploymentView, ClientError>,
1174 Duration,
1175 Option<MemoryTotals>,
1176)> {
1177 let mut asked = tokio::task::JoinSet::new();
1178 for index in 0..ui.deployments.len() {
1179 let ui = Arc::clone(ui);
1180 asked.spawn(schedr_client::for_same_user(async move {
1181 let started = Instant::now();
1182 let client = &ui.deployments[index].client;
1183 let (answer, memory) = tokio::join!(client.deployment(), client.memory_totals("24h"));
1184 (index, answer, started.elapsed(), memory.ok())
1185 }));
1186 }
1187 let mut answers = asked.join_all().await;
1188 answers.sort_by_key(|(index, _, _, _)| *index);
1189 answers
1190 .into_iter()
1191 .map(|(_, answer, took, memory)| (answer, took, memory))
1192 .collect()
1193}
1194
1195#[derive(Template)]
1196#[template(path = "deployments.html")]
1197struct DeploymentsPage {
1198 page: Page,
1199 status: Vec<StatusRow>,
1200 graph: Graph,
1201 panels: Vec<NodePanel>,
1202}
1203
1204pub async fn list<T: Transport + Send + Sync + 'static>(
1207 State(ui): State<Arc<Ui<T>>>,
1208 headers: HeaderMap,
1209) -> Response {
1210 let page = Page::new(&headers, ui.docs_dir.is_some()).live("kinds=workers", "/deployments");
1211 let asked: Vec<Asked> = ui
1212 .deployments
1213 .iter()
1214 .zip(ask_all(&ui).await)
1215 .map(|(deployment, (answer, took, memory))| Asked {
1216 name: deployment.name.clone(),
1217 proof: deployment.proof,
1218 answer: answer.map_err(|e| e.to_string()),
1219 took,
1220 memory,
1221 })
1222 .collect();
1223 let side = UiSide {
1224 process_id: ui.process_id.clone(),
1225 host: ui.host.clone(),
1226 version: env!("CARGO_PKG_VERSION").to_owned(),
1227 user: schedr_client::current_user().unwrap_or_else(|| "anonymous".to_owned()),
1228 config: ui.config.clone(),
1229 };
1230 let (graph, panels) = graph(&side, &asked);
1231 render(
1232 &DeploymentsPage {
1233 page,
1234 status: status(&asked),
1235 graph,
1236 panels,
1237 },
1238 StatusCode::OK,
1239 )
1240}