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
//! `procserv-rs` — Rust port of the EPICS procServ daemon.
//!
//! Drop-in for `epics-modules/procServ` deployments: same flag set,
//! same `PROCSERV_INFO` env contract, same per-line PTY behaviour.
//! See [`epics_tools_rs::procserv`] for architectural notes.
#[cfg(not(unix))]
fn main() {
eprintln!("procserv-rs is Unix-only (requires forkpty)");
std::process::exit(2);
}
#[cfg(unix)]
mod app {
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;
use clap::Parser;
use epics_tools_rs::procserv::{
ProcServ, ProcServConfig,
config::{ChildConfig, KeyBindings, ListenConfig, LoggingConfig},
daemon::{fork_and_go, install_signal_handlers},
restart::{RestartMode, RestartPolicy},
};
/// CLI flags chosen to match C procServ verbatim where possible.
/// Operators porting wrapper scripts should not need to relearn
/// the surface.
#[derive(Parser, Debug)]
#[command(
name = "procserv-rs",
about = "Pure-Rust port of the EPICS procServ process supervisor",
version
)]
struct Args {
/// TCP port to listen on (`-p` / `--port` in C procServ).
#[arg(short = 'p', long)]
port: Option<u16>,
/// Bind to all interfaces; default is localhost only.
/// (C procServ `--allow`).
#[arg(long)]
allow: bool,
/// Read-only viewer/log TCP port (`-l` / `--logport` in C).
/// Clients here see all output but cannot inject input.
#[arg(short = 'l', long = "logport")]
log_port: Option<u16>,
/// Restrict the log/viewer port to localhost (C `--restrict`).
/// Unlike the control port, the log port binds all interfaces by
/// default (C `logPortLocal` defaults false); this flag mirrors
/// C flipping it to localhost-only.
#[arg(long)]
restrict: bool,
/// UNIX-domain socket path (`--unixpath`).
#[arg(long = "unixpath")]
unix_path: Option<PathBuf>,
/// Run in foreground (don't daemonize) — `-f` in C.
#[arg(short = 'f', long)]
foreground: bool,
/// Log file (`-L` / `--logfile`).
#[arg(short = 'L', long)]
logfile: Option<PathBuf>,
/// Prefix log lines with a timestamp (`-S` / `--logstamp` in C).
/// Off by default (C `stampLog` defaults false → log written
/// verbatim). The flag alone uses the bracketed default stamp
/// format; an optional strftime value (`--logstamp=<FMT>`) is used
/// raw. Mirrors C's `optional_argument` getopt: the value must be
/// attached with `=`, never space-separated.
#[arg(
short = 'S',
long = "logstamp",
value_name = "FMT",
require_equals = true
)]
logstamp: Option<Option<String>>,
/// strftime format for banner / start-time lines (`-F` /
/// `--timefmt` in C, default `%c`). Sets C `timeFormat`
/// (procServ.cc:80,254,303-305) and is also the base for the
/// default log stamp, "[" + timefmt + "] " (procServ.cc:464-468).
/// C exposes this long-only (`--timefmt`); `-F` is a Rust
/// convenience, as 'F' is absent from C's getopt optstring
/// (procServ.cc:264).
#[arg(short = 'F', long = "timefmt", value_name = "FMT")]
timefmt: Option<String>,
/// PID file (`--pidfile`).
#[arg(long)]
pidfile: Option<PathBuf>,
/// Info file (`--info-file`).
#[arg(long)]
info_file: Option<PathBuf>,
/// Hold-off time between restarts in seconds (`--holdoff`).
#[arg(long, default_value_t = 15)]
holdoff: u64,
/// Wait for manual start (don't launch the child until a
/// connected user issues the restart key).
#[arg(short = 'w', long)]
wait: bool,
/// chdir to this directory before exec'ing the child.
#[arg(long)]
chdir: Option<PathBuf>,
/// Display name for the child in banners.
#[arg(long)]
name: Option<String>,
/// Restart-policy max attempts inside `--restart-window`.
/// Unset means unlimited: C procServ has no restart-count cap —
/// `processFactoryNeedsRestart()` (processFactory.cc:48-56) gates
/// only on mode + holdoff, and the main loop `while(!shutdownServer)`
/// (procServ.cc:599) never gives up on a count. The count limiter
/// is a Rust-only opt-in (shared `RestartPolicy` with ca-gateway);
/// leaving it unset preserves C's never-give-up behaviour.
#[arg(long)]
max_restarts: Option<u32>,
/// Restart-policy sliding window in seconds.
#[arg(long, default_value_t = 600)]
restart_window: u64,
/// Kill character (Ctrl-X = 24). Use 0 to disable.
#[arg(long, default_value_t = 24)]
kill_char: u8,
/// Toggle restart-mode character (Ctrl-T = 20). 0 to disable.
#[arg(long, default_value_t = 20)]
toggle_restart_char: u8,
/// Logout character (Ctrl-] = 29). 0 to disable.
#[arg(long, default_value_t = 29)]
logout_char: u8,
/// Program to launch + its arguments. Everything after `--`.
#[arg(trailing_var_arg = true, allow_hyphen_values = true, required = true)]
cmd: Vec<String>,
}
fn build_config(args: Args) -> Result<ProcServConfig, String> {
if args.cmd.is_empty() {
return Err("missing child command".into());
}
let mut iter = args.cmd.into_iter();
let program = PathBuf::from(iter.next().unwrap());
let argv: Vec<String> = iter.collect();
let display_name = args.name.unwrap_or_else(|| {
program
.file_name()
.map_or("child".into(), |s| s.to_string_lossy().into())
});
let listen = ListenConfig {
tcp_port: args.port,
tcp_bind: args.port.map(|p| {
if args.allow {
std::net::SocketAddr::from(([0, 0, 0, 0], p))
} else {
std::net::SocketAddr::from(([127, 0, 0, 1], p))
}
}),
log_port: args.log_port,
// C `logPortLocal` defaults false → all interfaces; `--restrict`
// flips it to localhost (acceptFactory.cc:116, procServ.cc:377).
log_bind: args.log_port.map(|p| {
if args.restrict {
std::net::SocketAddr::from(([127, 0, 0, 1], p))
} else {
std::net::SocketAddr::from(([0, 0, 0, 0], p))
}
}),
unix_path: args.unix_path,
};
let child = ChildConfig {
name: display_name,
program,
args: argv,
cwd: args.chdir,
kill_signal: 9, // SIGKILL — match C default
ignore_chars: Vec::new(),
};
// C `timeFormat` defaults to "%c" (procServ.cc:80), overridable by
// -F/--timefmt (procServ.cc:254,303-305). Used for banner /
// start-time rendering and as the base for the default log stamp.
let time_format = args.timefmt.unwrap_or_else(|| "%c".into());
// C `--logstamp [<FMT>]` (procServ.cc:307-311): the flag sets
// stampLog=true; an attached value overrides stampFormat (raw),
// the bare flag keeps the default. Absent → unstamped.
let stamp_log = args.logstamp.is_some();
let stamp_format = match args.logstamp {
Some(Some(fmt)) => fmt,
// C's default stampFormat = "[" + timeFormat + "] ", built from
// the (possibly --timefmt-overridden) timeFormat so the flag
// propagates to the log stamp exactly as in C (procServ.cc:464-468).
_ => format!("[{time_format}] "),
};
let logging = LoggingConfig {
log_path: args.logfile,
pid_path: args.pidfile,
info_path: args.info_file,
stamp_log,
time_format,
stamp_format,
};
let nz = |c: u8| if c == 0 { None } else { Some(c) };
Ok(ProcServConfig {
foreground: args.foreground,
listen,
keys: KeyBindings {
kill: nz(args.kill_char),
toggle_restart: nz(args.toggle_restart_char),
restart: Some(0x12), // Ctrl-R when child dead
quit: None,
logout: nz(args.logout_char),
},
child,
logging,
restart: RestartPolicy {
// Unlimited unless the operator opts in: matches C procServ
// which never caps restarts on a count (processFactory.cc:48-56,
// procServ.cc:599). `u32::MAX` is the "no cap" sentinel the
// shared RestartPolicy already treats as effectively unbounded.
max_restarts: args.max_restarts.unwrap_or(u32::MAX),
window: Duration::from_secs(args.restart_window),
delay: Duration::from_secs(1),
},
restart_mode: RestartMode::OnExit,
holdoff: Duration::from_secs(args.holdoff),
wait_for_manual_start: args.wait,
})
}
pub fn entry() -> ExitCode {
let _ = tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.try_init();
let args = Args::parse();
let foreground = args.foreground;
let cfg = match build_config(args) {
Ok(c) => c,
Err(e) => {
tracing::error!(error = %e, "procserv-rs: invalid config");
return ExitCode::FAILURE;
}
};
// Daemonize BEFORE starting the tokio runtime — the runtime's
// worker threads don't survive fork(). After fork_and_go
// returns we're in the grandchild (or directly in foreground
// mode) and safe to start tokio.
if !foreground && let Err(e) = fork_and_go() {
eprintln!("procserv-rs: daemonize failed: {e}");
return ExitCode::FAILURE;
}
let runtime = match tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
{
Ok(r) => r,
Err(e) => {
tracing::error!(error = %e, "procserv-rs: tokio runtime build failed");
return ExitCode::FAILURE;
}
};
runtime.block_on(async move {
let server = match ProcServ::new(cfg) {
Ok(s) => s,
Err(e) => {
tracing::error!(error = %e, "procserv-rs: build failed");
return ExitCode::FAILURE;
}
};
let shutdown = match install_signal_handlers().await {
Ok(s) => s,
Err(e) => {
tracing::error!(error = %e, "procserv-rs: signal handler install failed");
return ExitCode::FAILURE;
}
};
// Race the supervisor against the shutdown signal. The
// supervisor's own `quit` keystroke also returns Ok(())
// from .run(), so either branch ends the process cleanly.
tokio::select! {
res = server.run() => match res {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
tracing::error!(error = %e, "procserv-rs: runtime error");
ExitCode::FAILURE
}
},
reason = shutdown.wait() => {
tracing::info!(reason = ?reason.ok(), "procserv-rs: shutdown signal");
ExitCode::SUCCESS
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
/// With no `--max-restarts`, the count limiter is unlimited
/// (`u32::MAX`) so the supervisor never gives up on a count —
/// matching C procServ (processFactory.cc:48-56, procServ.cc:599).
#[test]
fn max_restarts_defaults_to_unlimited() {
let args = Args::try_parse_from(["procserv-rs", "/bin/echo"]).unwrap();
let cfg = build_config(args).unwrap();
assert_eq!(cfg.restart.max_restarts, u32::MAX);
}
/// Opting in caps the count at the requested value.
#[test]
fn max_restarts_opt_in_is_honored() {
let args =
Args::try_parse_from(["procserv-rs", "--max-restarts", "5", "/bin/echo"]).unwrap();
let cfg = build_config(args).unwrap();
assert_eq!(cfg.restart.max_restarts, 5);
}
/// The log/viewer port binds all interfaces by default (C
/// `logPortLocal` defaults false), the inverse of the control
/// port's localhost default.
#[test]
fn log_port_binds_all_interfaces_by_default() {
let args =
Args::try_parse_from(["procserv-rs", "--logport", "7000", "/bin/echo"]).unwrap();
let cfg = build_config(args).unwrap();
assert_eq!(cfg.listen.log_port, Some(7000));
assert_eq!(
cfg.listen.log_bind,
Some(std::net::SocketAddr::from(([0, 0, 0, 0], 7000)))
);
}
/// `--restrict` flips the log port to localhost-only (C 'R').
#[test]
fn restrict_binds_log_port_to_localhost() {
let args = Args::try_parse_from([
"procserv-rs",
"--logport",
"7000",
"--restrict",
"/bin/echo",
])
.unwrap();
let cfg = build_config(args).unwrap();
assert_eq!(
cfg.listen.log_bind,
Some(std::net::SocketAddr::from(([127, 0, 0, 1], 7000)))
);
}
/// No `--logstamp` → unstamped log (C `stampLog` defaults false).
#[test]
fn logstamp_absent_is_unstamped_by_default() {
let args = Args::try_parse_from(["procserv-rs", "/bin/echo"]).unwrap();
let cfg = build_config(args).unwrap();
assert!(!cfg.logging.stamp_log);
}
/// `--logstamp` alone enables stamping with the bracketed default
/// stamp format, built from the default timeFormat "%c"
/// (C 'S' with no optarg, procServ.cc:307-311,464-468).
#[test]
fn logstamp_flag_enables_stamping_with_default_format() {
let args = Args::try_parse_from(["procserv-rs", "--logstamp", "/bin/echo"]).unwrap();
let cfg = build_config(args).unwrap();
assert!(cfg.logging.stamp_log);
assert_eq!(cfg.logging.stamp_format, "[%c] ");
}
/// `--logstamp=<FMT>` enables stamping and uses FMT raw (C 'S'
/// with optarg sets stampFormat, procServ.cc:309-310).
#[test]
fn logstamp_with_value_sets_raw_format() {
let args =
Args::try_parse_from(["procserv-rs", "--logstamp=%H:%M:%S ", "/bin/echo"]).unwrap();
let cfg = build_config(args).unwrap();
assert!(cfg.logging.stamp_log);
assert_eq!(cfg.logging.stamp_format, "%H:%M:%S ");
}
/// No `--timefmt` → C's default timeFormat "%c" (procServ.cc:80).
#[test]
fn timefmt_absent_uses_c_default() {
let args = Args::try_parse_from(["procserv-rs", "/bin/echo"]).unwrap();
let cfg = build_config(args).unwrap();
assert_eq!(cfg.logging.time_format, "%c");
}
/// `--timefmt <FMT>` sets the banner format and (per C
/// procServ.cc:464-468) also rebases the default log stamp
/// "[" + timeFormat + "] ".
#[test]
fn timefmt_sets_banner_and_rebases_default_stamp() {
let args = Args::try_parse_from([
"procserv-rs",
"--timefmt",
"%H:%M",
"--logstamp",
"/bin/echo",
])
.unwrap();
let cfg = build_config(args).unwrap();
assert_eq!(cfg.logging.time_format, "%H:%M");
assert_eq!(cfg.logging.stamp_format, "[%H:%M] ");
}
/// An explicit `--logstamp=<FMT>` still wins over the
/// timefmt-derived default stamp (C uses the optarg verbatim).
#[test]
fn logstamp_value_overrides_timefmt_derived_stamp() {
let args = Args::try_parse_from([
"procserv-rs",
"--timefmt",
"%H:%M",
"--logstamp=RAW ",
"/bin/echo",
])
.unwrap();
let cfg = build_config(args).unwrap();
assert_eq!(cfg.logging.time_format, "%H:%M");
assert_eq!(cfg.logging.stamp_format, "RAW ");
}
}
}
#[cfg(unix)]
fn main() -> std::process::ExitCode {
app::entry()
}