arcnix 0.3.6

A friendly desktop workspace for managing servers over SSH
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
use arcnix_core::host::HostOs;
use arcnix_core::host_capabilities::NativeServicePlan;
use arcnix_core::operations::{Intent, Service, ServiceAction, Snippet};

use crate::operations_worker::{Action as OpAction, Event as OpEvent, Kind};
use crate::*;

#[derive(Clone, Default)]
pub(crate) struct OperationsState {
    service_view: u8,
    startup: arcnix_core::startup_services::Definition,
    loaded: bool,
    platform: Option<HostOs>,
    services: Vec<Service>,
    selected: String,
    inspect_after_list: bool,
    filter: String,
    pending: Option<(u64, Kind)>,
    output: String,
    status: String,
    error: String,
    review: Option<(u64, NativeServicePlan)>,
    pub(crate) editor: Option<Snippet>,
}
fn ready(s: &State) -> bool {
    s.connected && !s.system_task_running && s.operations.pending.is_none()
}
impl Ui {
    pub(crate) fn open_system_service(&self, unit: &str) {
        self.state.revise(|s| {
            monitor_ui::set_section(s, monitor_ui::Section::Services);
            s.operations.service_view = 0;
            s.operations.filter.clear();
            s.operations.selected = unit.to_owned();
            s.operations.inspect_after_list = true;
        });
        self.open_desktop_app(WorkspacePage::Monitor);
        self.operations_list();
    }
    pub(crate) fn operations_enter(&self) {
        if self.state.with(|s| {
            monitor_ui::active(s) == Some(monitor_ui::Section::Services)
                && !s.operations.loaded
                && ready(s)
        }) {
            self.operations_list();
        }
    }
    fn op_send(&self, action: OpAction) {
        if !self.state.with(ready) {
            return;
        }
        let kind = action.kind();
        let serial = self.send(Action::Operations(action));
        self.state.revise(|s| {
            s.operations.pending = Some((serial, kind));
            s.operations.error.clear();
            s.operations.output.clear();
            s.operations.status.clear();
        });
    }
    fn operations_list(&self) {
        self.op_send(OpAction::List);
    }
    fn new_startup_service(&self) {
        self.state.revise(|s| {
            s.operations.startup = arcnix_core::startup_services::Definition {
                user: s
                    .config
                    .servers
                    .iter()
                    .find(|p| Some(&p.id) == s.selected.as_ref())
                    .map(|p| p.username.clone())
                    .unwrap_or_default(),
                ..Default::default()
            }
        });
        self.open_dialog(Dialog::StartupService);
    }
    fn review_startup_service(&self) {
        match self.state.with(|s| s.operations.startup.template()) {
            Ok(template) => self.choose_server_script(template),
            Err(error) => self.state.revise(|s| s.dialog_error = format!("{error:#}")),
        }
    }
    fn inspect_service(&self) {
        let unit = self.state.with(|s| s.operations.selected.clone());
        if !unit.is_empty() {
            self.op_send(OpAction::Inspect(unit));
        }
    }
    fn preview_operation(&self, intent: Intent) {
        let template = match intent {
            Intent::Command(snippet) => Ok(arcnix_core::scripts::Template::custom(snippet)),
            Intent::Service { unit, action } => {
                arcnix_core::scripts::Template::service(unit, action)
            }
        };
        match template {
            Ok(template) => self.choose_server_script(template),
            Err(error) => self.error(format!("{error:#}")),
        }
    }
    fn service_action(&self, action: ServiceAction) {
        let Some((unit, platform)) = self.state.with(|s| {
            (s.dialog.is_none() && !s.operations.selected.is_empty())
                .then(|| (s.operations.selected.clone(), s.operations.platform))
        }) else {
            return;
        };
        match platform {
            Some(HostOs::Linux) => self.preview_operation(Intent::Service { unit, action }),
            Some(HostOs::MacOs | HostOs::Windows) => self.op_send(OpAction::Review(unit, action)),
            _ => (),
        }
    }

    fn apply_native_service(&self) {
        let plan = self.state.revise(|s| {
            if !ready(s) || s.dialog != Some(Dialog::NativeServiceConfirm) {
                return None;
            }
            let (epoch, plan) = s.operations.review.take()?;
            if epoch != s.epoch {
                s.dialog_error = "The server connection changed. Review the service again.".into();
                return None;
            }
            s.dialog_error.clear();
            Some(plan)
        });
        if let Some(plan) = plan {
            self.op_send(OpAction::Apply(plan));
        }
    }
    fn service_logs(&self) {
        let unit = self.state.with(|s| s.operations.selected.clone());
        if unit.is_empty() || !self.state.with(ready) {
            return;
        }
        self.state.revise(|s| {
            monitor_ui::set_section(s, monitor_ui::Section::Logs);
            s.system_logs.select_service(unit);
        });
        self.observability_enter();
    }
    pub(crate) fn edit_snippet(&self, snippet: Option<Snippet>) {
        self.state.revise(|s| {
            s.scripts.parameter_editor = Default::default();
            s.operations.editor = Some(snippet.unwrap_or_else(|| Snippet {
                parameters: vec![],
                id: new_id(),
                name: String::new(),
                description: String::new(),
                command: String::new(),
                administrator: false,
            }))
        });
        self.open_dialog(Dialog::SnippetEdit);
    }
    fn save_snippet(&self) {
        if let Err(error) = self.state.with(|s| {
            crate::script_parameters_ui::check_editor(
                s,
                &crate::script_parameters_ui::Owner::Command,
            )
        }) {
            self.state.revise(|s| s.dialog_error = error.to_string());
            return;
        }
        let Some(snippet) = self.state.with(|s| s.operations.editor.clone()) else {
            return;
        };
        let mut config = self.state.with(|s| s.config.clone());
        config.snippets.retain(|old| old.id != snippet.id);
        config.snippets.push(snippet);
        arcnix_core::script_parameters::reconcile(&mut config);
        match if self.writable.get() {
            self.store.save(&config)
        } else {
            Err(anyhow::anyhow!("Configuration is read-only"))
        } {
            Ok(()) => {
                self.state.revise(|s| {
                    s.config = config;
                    s.operations.editor = None;
                });
                self.close_dialog();
            }
            Err(e) => self.state.revise(|s| s.dialog_error = format!("{e:#}")),
        }
    }
    fn delete_snippet(&self, id: &str) {
        let mut config = self.state.with(|s| s.config.clone());
        config.snippets.retain(|v| v.id != id);
        arcnix_core::script_favorites::remove_user(&mut config, id);
        arcnix_core::script_parameters::reconcile(&mut config);
        match if self.writable.get() {
            self.store.save(&config)
        } else {
            Err(anyhow::anyhow!("Configuration is read-only"))
        } {
            Ok(()) => {
                self.state.revise(|s| s.config = config);
                self.close_dialog();
            }
            Err(e) => self.state.revise(|s| s.dialog_error = format!("{e:#}")),
        }
    }
}
pub(crate) fn event(ui: &Ui, serial: u64, event: OpEvent) {
    enum Next {
        None,
        Inspect,
        Review,
        Refresh,
    }
    let Some((expected, kind)) = ui.state.with(|s| s.operations.pending) else {
        return;
    };
    if expected != serial {
        return;
    }
    let next = ui.state.revise(|s| {
        let op = &mut s.operations;
        op.pending = None;
        match event {
            OpEvent::Services(platform, items) if kind == Kind::List => {
                if !items.iter().any(|v| v.unit == op.selected) {
                    op.selected.clear();
                }
                op.services = items;
                op.loaded = true;
                op.platform = Some(platform);
                if std::mem::take(&mut op.inspect_after_list) && !op.selected.is_empty() {
                    return Next::Inspect;
                }
            }
            OpEvent::Details(text) if kind == Kind::Inspect => {
                op.output = text;
                op.status = "Service details".into();
            }
            OpEvent::Review(plan) if kind == Kind::Review && s.dialog.is_none() => {
                op.review = Some((s.epoch, plan));
                return Next::Review;
            }
            OpEvent::Applied if kind == Kind::Apply => {
                return Next::Refresh;
            }
            OpEvent::Failed(failed, error) if failed == kind => {
                if kind == Kind::List {
                    op.inspect_after_list = false;
                }
                if kind == Kind::Apply && s.dialog == Some(Dialog::NativeServiceConfirm) {
                    s.dialog_error = error.clone();
                }
                op.error = error;
            }
            _ => {}
        }
        Next::None
    });
    match next {
        Next::Inspect => ui.inspect_service(),
        Next::Review => ui.open_dialog(Dialog::NativeServiceConfirm),
        Next::Refresh => {
            if ui
                .state
                .with(|s| s.dialog == Some(Dialog::NativeServiceConfirm))
            {
                ui.close_dialog();
            }
            ui.operations_list();
            ui.log("Service change completed");
        }
        Next::None => {
            if kind != Kind::List && ui.state.with(|s| s.operations.inspect_after_list) {
                ui.operations_list();
            }
        }
    }
}
pub(crate) fn connection_lost(ui: &Ui) {
    ui.state.revise(|s| {
        s.operations = OperationsState::default();
        if s.dialog == Some(Dialog::NativeServiceConfirm) {
            s.dialog = None;
            s.dialog_error.clear();
        }
    });
}
fn service_button(
    state: Cage<State>,
    label: &'static str,
    changing: bool,
    action: impl FnMut() + 'static,
) -> impl Widget {
    btn(label, action).enabled(state.map(move |s| {
        ready(s) && (!changing || !scripts_ui::busy(s)) && !s.operations.selected.is_empty()
    }))
}

fn linux_services(s: &State) -> bool {
    s.operations.platform == Some(HostOs::Linux)
}
fn services(ui: Ui) -> impl Widget {
    let state = ui.state;
    let refresh = ui.clone();
    let inspect = ui.clone();
    let logs = ui.clone();
    let start = ui.clone();
    let stop = ui.clone();
    let request_stop = ui.clone();
    let restart = ui.clone();
    let enable = ui.clone();
    let disable = ui.clone();
    let startup = ui.clone();
    col().class("operation-services").fill((
        row().class("operations-toolbar").fill((
            row().class("server-search service-search").fill((
                input()
                    .class("service-filter")
                    .name(i18n::bind("Filter services"))
                    .value(state.map(|s| s.operations.filter.clone()))
                    .on(value_changed, move |e| {
                        if let Event::ValueChanged { value, .. } = e {
                            state.revise(|s| s.operations.filter = value);
                        }
                    }),
                text()
                    .class("action-glyph glyph-search server-search-icon")
                    .content(""),
            )),
            icon_action("刷新服务", Icon::Refresh)
                .enabled(state.map(ready))
                .on_press(move || refresh.operations_list()),
            service_button(state, "Status", false, move || inspect.inspect_service()),
            when(state.map(linux_services), move || {
                let logs = logs.clone();
                service_button(state, "Logs", false, move || logs.service_logs())
            }),
            service_button(state, "Start…", true, move || {
                start.service_action(ServiceAction::Start)
            }),
            when(state.map(|s| s.operations.platform != Some(HostOs::MacOs)), move || {
                let stop = stop.clone();
                service_button(state, "Stop…", true, move || stop.service_action(ServiceAction::Stop))
            }),
            when(state.map(|s| s.operations.platform == Some(HostOs::MacOs)), move || {
                let stop = request_stop.clone();
                service_button(state, "Request stop…", true, move || stop.service_action(ServiceAction::Stop))
            }),
            service_button(state, "Restart…", true, move || {
                restart.service_action(ServiceAction::Restart)
            }),
            service_button(state, "Enable at boot…", true, move || enable.service_action(ServiceAction::Enable)),
            service_button(state, "Disable at boot…", true, move || disable.service_action(ServiceAction::Disable)),
            when(state.map(linux_services), move || {
                let startup = startup.clone();
                text_action("New startup task", Icon::Plus).enabled(state.map(|s| ready(s) && !scripts_ui::busy(s))).on_press(move || startup.new_startup_service())
            }),
        )),
        row().class("services-filters").fill((
            fragment([(0,"All services"),(1,"Active services"),(2,"Start at boot")].into_iter().map(move |(view,label)| sapid::button().class("button compact").label(i18n::bind(label)).pressed(state.map(move |s| s.operations.service_view == view)).on_press(move || state.revise(|s| s.operations.service_view = view))).collect::<Vec<_>>()),
            help_ui::tip("Services", "Running state and startup configuration are shown separately. Review the selected service and action before applying a change."),
        )),
        col().class("service-list").fill(
            each(state.map(|s| {
                let filter = s.operations.filter.to_lowercase();
                s.operations
                    .services
                    .iter()
                    .filter(|v| {
                        (s.operations.service_view == 0 || s.operations.service_view == 1 && v.active == "active" || s.operations.service_view == 2 && v.startup == "enabled") && format!("{} {} {} {}", v.unit, v.description, v.active, v.startup)
                            .to_lowercase()
                            .contains(&filter)
                    })
                    .cloned()
                    .collect::<Vec<_>>()
            }))
            .key(|v| v.unit.clone())
            .children(move |item| {
                let value = item.value;
                let select = ui.clone();
                sapid::button()
                    .class(state.map(move |s| {
                        if s.operations.selected == value.get().unit {
                            "service-row selected"
                        } else {
                            "service-row"
                        }
                        .to_owned()
                    }))
                    .name(value.map(|v| v.unit.clone()))
                    .fill((
                        text()
                            .class("service-name")
                            .content(value.map(|v| v.unit.clone())),
                        text()
                            .class("service-state")
                            .content(value.map(|v| format!("{} · {} · {}", v.active, v.sub, v.startup))),
                        text()
                            .class("service-description")
                            .content(value.map(|v| v.description.clone())),
                    ))
                    .enabled(state.map(ready))
                    .on_press(move || {
                        select.state.revise(|s| {
                            s.operations.selected = value.get().unit;
                            s.operations.output.clear();
                            s.operations.status.clear();
                        })
                    })
            }),
        ),
        text().class("subtle").content(i18n::bind(state.map(|s| {
            if s.operations.pending.is_some() {
                "Loading…"
            } else if s.operations.loaded && s.operations.services.is_empty() {
                "No loaded services"
            } else {
                ""
            }
            .to_owned()
        }))),
    ))
}
pub(crate) fn page(ui: Ui) -> impl Widget {
    let state = ui.state;
    col().class("operations-page services-page").fill((
        text()
            .class("software-error")
            .content(i18n::bind(state.map(|s| s.operations.error.clone()))),
        services(ui.clone()),
        when(state.map(|s| !s.operations.output.is_empty()), move || {
            col().class("operations-details").fill((
                text().class("section-title").content(i18n::bind("Output")),
                text()
                    .class("operations-output")
                    .selectable(true)
                    .content(state.map(|s| s.operations.output.clone())),
            ))
        }),
    ))
}
fn command_dialogs(ui: Ui) -> impl Widget {
    let state = ui.state;
    fragment((
        when(state.map(|s| s.dialog == Some(Dialog::SnippetEdit)), {
            let ui = ui.clone();
            move || {
                let save = ui.clone();
                let cancel = ui.clone();
                let admin = ui.clone();
                modal(
                    ui.clone(),
                    "Save command",
                    col().class("form-stack").fill((
                        field(
                            "Command name",
                            &ui,
                            |s| {
                                s.operations
                                    .editor
                                    .as_ref()
                                    .map(|e| e.name.clone())
                                    .unwrap_or_default()
                            },
                            |s, v| {
                                if let Some(e) = &mut s.operations.editor {
                                    e.name = v;
                                }
                            },
                        ),
                        field(
                            "Description",
                            &ui,
                            |s| {
                                s.operations
                                    .editor
                                    .as_ref()
                                    .map(|e| e.description.clone())
                                    .unwrap_or_default()
                            },
                            |s, v| {
                                if let Some(e) = &mut s.operations.editor {
                                    e.description = v;
                                }
                            },
                        ),
                        text()
                            .class("field-label")
                            .content(i18n::bind("Shell command")),
                        input()
                            .class("command-editor")
                            .name(i18n::bind("Shell command"))
                            .multiline(true)
                            .value(state.map(|s| {
                                s.operations
                                    .editor
                                    .as_ref()
                                    .map(|e| e.command.clone())
                                    .unwrap_or_default()
                            }))
                            .on(value_changed, move |e| {
                                if let Event::ValueChanged { value, .. } = e {
                                    state.revise(|s| {
                                        if let Some(e) = &mut s.operations.editor {
                                            e.command = value.replace("\r\n", "\n");
                                        }
                                    });
                                }
                            }),
                        btn("Run as administrator", move || {
                            admin.state.revise(|s| {
                                if let Some(e) = &mut s.operations.editor {
                                    e.administrator = !e.administrator;
                                }
                            })
                        })
                        .class(state.map(|s| {
                            if s.operations
                                .editor
                                .as_ref()
                                .is_some_and(|e| e.administrator)
                            {
                                "choice active"
                            } else {
                                "choice"
                            }
                            .to_owned()
                        })),
                        text().class("hint").content(i18n::bind(
                            "Command text is saved locally. Do not include passwords or tokens.",
                        )),
                        crate::script_parameters_ui::editor(
                            ui.clone(),
                            crate::script_parameters_ui::Owner::Command,
                        ),
                    )),
                    (
                        btn("取消", move || cancel.close_dialog()),
                        btn("Save command", move || save.save_snippet()).class("button primary"),
                    ),
                )
            }
        }),
        when(
            state.map(|s| matches!(s.dialog, Some(Dialog::SnippetDelete(_)))),
            {
                let ui = ui.clone();
                move || {
                    let submit = ui.clone();
                    let cancel = ui.clone();
                    modal(
                        ui.clone(),
                        "Delete command",
                        text().content(state.map(|s| {
                            if let Some(Dialog::SnippetDelete(id)) = &s.dialog {
                                s.config
                                    .snippets
                                    .iter()
                                    .find(|e| &e.id == id)
                                    .map(|e| e.name.clone())
                                    .unwrap_or_default()
                            } else {
                                String::new()
                            }
                        })),
                        (
                            btn("取消", move || cancel.close_dialog()),
                            btn("Delete command", move || {
                                let id = submit.state.with(|s| {
                                    if let Some(Dialog::SnippetDelete(id)) = &s.dialog {
                                        Some(id.clone())
                                    } else {
                                        None
                                    }
                                });
                                if let Some(id) = id {
                                    submit.delete_snippet(&id);
                                }
                            })
                            .class("button danger"),
                        ),
                    )
                }
            },
        ),
    ))
}

pub(crate) fn dialogs(ui: Ui) -> impl Widget {
    let state = ui.state;
    let commands = ui.clone();
    let native = ui.clone();
    fragment((
        command_dialogs(commands),
        when(
            state.map(|s| s.dialog == Some(Dialog::NativeServiceConfirm)),
            move || {
                let apply = native.clone();
                modal(
                    native.clone(),
                    "Review service change",
                    col().class("form-stack").fill((
                        text().content(state.map(|s| {
                            s.operations.review.as_ref().map_or_else(String::new, |(_, plan)| {
                                format!("{} {}\nCurrent state: {}\nStartup configuration: {}", plan.action().verb(), plan.unit(), plan.state(), plan.startup())
                            })
                        })),
                        text().class("subtle").content(i18n::bind(state.map(|s| {
                            let platform = s.operations.platform;
                            let action = s.operations.review.as_ref().map(|(_, plan)| plan.action());
                            match (platform, action) {
                                (Some(HostOs::Windows), Some(ServiceAction::Disable)) => "A disabled Windows service cannot be started until its startup type changes.",
                                (Some(HostOs::MacOs), Some(ServiceAction::Stop)) => "Sends SIGTERM. launchd may relaunch the daemon on demand or because of its KeepAlive policy.",
                                (Some(HostOs::MacOs), Some(_)) => "Uses the SSH account’s launchd permissions or noninteractive sudo.",
                                (_, _) => "Uses the connected account’s service permissions.",
                            }.to_owned()
                        }))),
                    )),
                    btn("Apply service change", move || apply.apply_native_service())
                        .class("button primary")
                        .enabled(state.map(|s| ready(s) && s.operations.review.is_some())),
                )
            },
        ),
        when(
            state.map(|s| s.dialog == Some(Dialog::StartupService)),
            move || {
                let review = ui.clone();
                modal(ui.clone(), "New startup task", col().class("form-stack").fill((
            field("Task name", &ui, |s| s.operations.startup.name.clone(), |s,v| s.operations.startup.name = v),
            field("Run as user", &ui, |s| s.operations.startup.user.clone(), |s,v| s.operations.startup.user = v),
            col().class("field").fill((text().class("field-label").content(i18n::bind("Startup command")),
                input().multiline(true).class("command-input").name(i18n::bind("Startup command")).value(state.map(|s| s.operations.startup.command.clone())).on(value_changed,move |e| if let Event::ValueChanged {value,..}=e { state.revise(|s| s.operations.startup.command = value); })
            )),
            sapid::checkbox().label(i18n::bind("Keep running and restart on failure")).checked(state.map(|s| s.operations.startup.continuous)).on_checked_change(move |v| state.revise(|s| s.operations.startup.continuous = v)),
            help_ui::tip("Startup task", "Creates a systemd service enabled for boot. The script is private to the selected Linux user in ~/.arcnix/services. Root or sudo is required to install the unit. Start it separately to run it immediately."),
        )), btn("Review startup task", move || review.review_startup_service()).class("button primary"))
            },
        ),
    ))
}