zinit 0.3.6

Process supervisor with dependency management
Documentation
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
//! Command handlers for zinit CLI.

use std::collections::HashMap;
use std::path::PathBuf;

use crate::sdk::{
    DependencyDef, LifecycleDef, LoggingDef, RestartPolicy, ServiceConfig, ServiceDef, State,
    ZinitClient,
    xinet::{ProxyStatus, SocketAddr as XinetSocketAddr, XinetConfig},
};

/// Get state symbol for display.
fn state_symbol(state: State) -> &'static str {
    match state {
        State::Running => "",
        State::Starting => "",
        State::Stopping => "",
        State::Blocked => "",
        State::Inactive => "",
        State::Exited => "",
        State::Failed => "",
    }
}

pub fn cmd_list(client: &mut ZinitClient) -> Result<(), String> {
    let names = client.list().map_err(|e| e.to_string())?;

    if names.is_empty() {
        println!("No services configured");
        return Ok(());
    }

    // Get status for each service
    let max_name_len = names.iter().map(|n| n.len()).max().unwrap_or(10);

    for name in names {
        if let Ok(status) = client.status(&name) {
            let pid_str = if status.pid > 0 {
                format!(" (pid: {})", status.pid)
            } else {
                String::new()
            };
            println!(
                "{} {:<width$} {:?}{}",
                state_symbol(status.state),
                status.name,
                status.state,
                pid_str,
                width = max_name_len
            );
        } else {
            println!("? {:<width$} unknown", name, width = max_name_len);
        }
    }

    Ok(())
}

pub fn cmd_status(client: &mut ZinitClient, name: &str) -> Result<(), String> {
    let status = client.status(name).map_err(|e| e.to_string())?;

    println!("Service: {}", status.name);
    println!("State:   {} {:?}", state_symbol(status.state), status.state);

    if status.pid > 0 {
        println!("PID:     {}", status.pid);
    }

    if let Some(code) = status.exit_code {
        println!("Exit:    {}", code);
    }

    if let Some(ref err) = status.error {
        println!("Error:   {}", err);
    }

    Ok(())
}

pub fn cmd_start(client: &mut ZinitClient, name: &str, tree: bool) -> Result<(), String> {
    if tree {
        // Use why to get dependency info and start them first
        if let Ok(why) = client.why(name) {
            for dep_name in &why.waiting_on {
                println!("Starting dependency: {}", dep_name);
                client.start(dep_name).map_err(|e| e.to_string())?;
                // Give it a moment to start
                std::thread::sleep(std::time::Duration::from_millis(100));
            }
        }
    }

    // Start this service
    client.start(name).map_err(|e| e.to_string())?;
    println!("Started: {}", name);

    // Check if it's blocked and show helpful message
    std::thread::sleep(std::time::Duration::from_millis(100));
    #[allow(clippy::collapsible_if)]
    if let Ok(status) = client.status(name) {
        if status.state == State::Blocked {
            match status.error {
                Some(err) => println!("\nService is blocked: {}", err),
                None => println!("\nService is blocked"),
            }
            println!(
                "\nTip: use 'zinit start {} --tree' to start dependencies too",
                name
            );
        }
    }
    Ok(())
}

pub fn cmd_stop(client: &mut ZinitClient, name: &str) -> Result<(), String> {
    client.stop(name).map_err(|e| e.to_string())?;
    println!("Stopped: {}", name);
    Ok(())
}

pub fn cmd_restart(client: &mut ZinitClient, name: &str) -> Result<(), String> {
    client.restart(name).map_err(|e| e.to_string())?;
    println!("Restarted: {}", name);
    Ok(())
}

pub fn cmd_kill(client: &mut ZinitClient, name: &str, signal: Option<&str>) -> Result<(), String> {
    client.kill(name, signal).map_err(|e| e.to_string())?;
    let sig = signal.unwrap_or("SIGTERM");
    println!("Sent {} to: {}", sig, name);
    Ok(())
}

pub fn cmd_why(client: &mut ZinitClient, name: &str) -> Result<(), String> {
    let why = client.why(name).map_err(|e| e.to_string())?;

    if !why.blocked {
        println!("{} is not blocked", name);
        return Ok(());
    }

    println!("{}", why.ascii);

    if !why.waiting_on.is_empty() {
        println!("\nWaiting on: {}", why.waiting_on.join(", "));
    }

    if !why.conflicts_with.is_empty() {
        println!("Conflicts with: {}", why.conflicts_with.join(", "));
    }

    Ok(())
}

pub fn cmd_tree(client: &mut ZinitClient) -> Result<(), String> {
    let tree = client.tree().map_err(|e| e.to_string())?;
    println!("{}", tree);
    Ok(())
}

pub fn cmd_remove(client: &mut ZinitClient, name: &str) -> Result<(), String> {
    client.remove(name).map_err(|e| e.to_string())?;
    println!("Removed: {}", name);
    Ok(())
}

pub fn cmd_reload(client: &mut ZinitClient) -> Result<(), String> {
    let result = client.reload().map_err(|e| e.to_string())?;

    if result.added.is_empty() && result.removed.is_empty() && result.changed.is_empty() {
        println!("No changes detected");
        return Ok(());
    }

    if !result.added.is_empty() {
        println!("Added:   {}", result.added.join(", "));
    }
    if !result.removed.is_empty() {
        println!("Removed: {}", result.removed.join(", "));
    }
    if !result.changed.is_empty() {
        println!("Changed: {}", result.changed.join(", "));
    }

    Ok(())
}

pub fn cmd_logs(
    client: &mut ZinitClient,
    name: &str,
    lines: usize,
    follow: bool,
) -> Result<(), String> {
    if follow {
        return Err("--follow is not yet implemented".to_string());
    }

    let logs = client.logs(name, Some(lines)).map_err(|e| e.to_string())?;

    if logs.is_empty() {
        println!("No logs available for {}", name);
        return Ok(());
    }

    for log in logs {
        println!("{}", log);
    }

    Ok(())
}

pub fn cmd_ping(client: &mut ZinitClient) -> Result<(), String> {
    let version = client.ping().map_err(|e| e.to_string())?;
    println!("zinit daemon v{} is running", version);
    Ok(())
}

pub fn cmd_shutdown(client: &mut ZinitClient) -> Result<(), String> {
    client.shutdown().map_err(|e| e.to_string())?;
    println!("Shutdown requested");
    Ok(())
}

pub fn cmd_poweroff() -> Result<(), String> {
    // Send SIGTERM to PID 1 to trigger poweroff
    let result = unsafe { libc::kill(1, libc::SIGTERM) };
    if result == 0 {
        println!("Poweroff signal sent to init");
        Ok(())
    } else {
        Err(format!(
            "Failed to signal init: {}",
            std::io::Error::last_os_error()
        ))
    }
}

pub fn cmd_reboot() -> Result<(), String> {
    // Send SIGINT to PID 1 to trigger reboot
    let result = unsafe { libc::kill(1, libc::SIGINT) };
    if result == 0 {
        println!("Reboot signal sent to init");
        Ok(())
    } else {
        Err(format!(
            "Failed to signal init: {}",
            std::io::Error::last_os_error()
        ))
    }
}

#[allow(clippy::too_many_arguments)]
pub fn cmd_add_service(
    client: &mut ZinitClient,
    file: Option<PathBuf>,
    name: Option<String>,
    exec: Option<String>,
    dir: String,
    oneshot: bool,
    envs: Vec<String>,
    after: Vec<String>,
    requires: Vec<String>,
    wants: Vec<String>,
    conflicts: Vec<String>,
    restart: String,
    restart_delay: u64,
    restart_delay_max: u64,
    max_restarts: u32,
    persist: bool,
) -> Result<(), String> {
    // Build config from file or flags
    let config = if let Some(path) = file {
        let content = std::fs::read_to_string(&path)
            .map_err(|e| format!("Failed to read {}: {}", path.display(), e))?;
        toml::from_str(&content)
            .map_err(|e| format!("Failed to parse {}: {}", path.display(), e))?
    } else {
        let name = name.ok_or("--name required when not using file")?;
        let exec = exec.ok_or("--exec required when not using file")?;

        // Parse env vars
        let env: HashMap<String, String> = envs
            .iter()
            .map(|s| {
                let (k, v) = s
                    .split_once('=')
                    .ok_or_else(|| format!("Invalid env format: {} (expected KEY=VALUE)", s))?;
                Ok((k.to_string(), v.to_string()))
            })
            .collect::<Result<_, String>>()?;

        // Parse restart policy
        let restart_policy = match restart.as_str() {
            "always" => RestartPolicy::Always,
            "on-failure" => RestartPolicy::OnFailure,
            "never" => RestartPolicy::Never,
            other => {
                return Err(format!(
                    "Invalid restart policy: {} (use always, on-failure, or never)",
                    other
                ));
            }
        };

        // Convert "/" to None (default), otherwise Some
        let dir_opt = if dir == "/" { None } else { Some(dir) };

        ServiceConfig {
            service: ServiceDef {
                name,
                exec,
                dir: dir_opt,
                oneshot,
                env,
                status: crate::sdk::Status::default(),
                class: crate::sdk::ServiceClass::default(),
                critical: false,
            },
            dependencies: DependencyDef {
                after,
                requires,
                wants,
                conflicts,
            },
            lifecycle: LifecycleDef {
                restart: restart_policy,
                restart_delay_ms: restart_delay,
                restart_delay_max_ms: restart_delay_max,
                max_restarts,
                ..Default::default()
            },
            health: None,
            logging: LoggingDef::default(),
        }
    };

    let service_name = config.service.name.clone();
    let result = client
        .add_service(&config, persist)
        .map_err(|e| e.to_string())?;

    let persist_msg = if let Some(path) = result.path {
        format!(" (saved to {})", path)
    } else {
        " (ephemeral)".to_string()
    };

    println!("Service '{}' added{}", service_name, persist_msg);

    if !result.warnings.is_empty() {
        for warning in result.warnings {
            println!("Warning: {}", warning);
        }
    }

    Ok(())
}

pub fn cmd_debug_state(client: &mut ZinitClient) -> Result<(), String> {
    let response = client
        .call("debug.state", serde_json::json!({}))
        .map_err(|e| e.to_string())?;

    let result: serde_json::Value = response.into_result().map_err(|e| e.to_string())?;
    if let Some(output) = result.get("output").and_then(|v| v.as_str()) {
        println!("{}", output);
    }
    Ok(())
}

pub fn cmd_debug_procs(client: &mut ZinitClient, name: &str) -> Result<(), String> {
    let response = client
        .call("debug.process_tree", serde_json::json!({ "name": name }))
        .map_err(|e| e.to_string())?;

    let result: serde_json::Value = response.into_result().map_err(|e| e.to_string())?;
    if let Some(output) = result.get("output").and_then(|v| v.as_str()) {
        println!("{}", output);
    }
    Ok(())
}

// ==================== Xinet Commands ====================

fn parse_socket_addr(s: &str) -> Result<XinetSocketAddr, String> {
    if let Some(path) = s.strip_prefix("unix:") {
        Ok(XinetSocketAddr::Unix(path.into()))
    } else if let Some(addr) = s.strip_prefix("tcp:") {
        Ok(XinetSocketAddr::Tcp(addr.to_string()))
    } else {
        // Default to TCP if no prefix
        Ok(XinetSocketAddr::Tcp(s.to_string()))
    }
}

#[allow(clippy::too_many_arguments)]
pub fn cmd_xinet_register(
    client: &mut ZinitClient,
    name: String,
    listen: Vec<String>,
    backend: String,
    service: String,
    connect_timeout: u64,
    idle_timeout: u64,
    single: bool,
) -> Result<(), String> {
    let listen_addrs: Vec<XinetSocketAddr> = listen
        .iter()
        .map(|s| parse_socket_addr(s))
        .collect::<Result<_, _>>()?;

    let backend_addr = parse_socket_addr(&backend)?;

    let config = XinetConfig {
        name: name.clone(),
        listen: listen_addrs,
        backend: backend_addr,
        service,
        connect_timeout,
        idle_timeout,
        single_connection: single,
    };

    client.xinet_register(&config).map_err(|e| e.to_string())?;
    println!("Registered xinet proxy '{}'", name);
    Ok(())
}

pub fn cmd_xinet_unregister(client: &mut ZinitClient, name: &str) -> Result<(), String> {
    client.xinet_unregister(name).map_err(|e| e.to_string())?;
    println!("Unregistered xinet proxy '{}'", name);
    Ok(())
}

pub fn cmd_xinet_list(client: &mut ZinitClient) -> Result<(), String> {
    let proxies = client.xinet_list().map_err(|e| e.to_string())?;
    if proxies.is_empty() {
        println!("No xinet proxies registered");
    } else {
        println!("Registered xinet proxies:");
        for name in proxies {
            println!("  {}", name);
        }
    }
    Ok(())
}

pub fn cmd_xinet_status(client: &mut ZinitClient, name: Option<&str>) -> Result<(), String> {
    match name {
        Some(n) => {
            let status = client.xinet_status(n).map_err(|e| e.to_string())?;
            print_proxy_status(&status);
        }
        None => {
            let statuses = client.xinet_status_all().map_err(|e| e.to_string())?;
            if statuses.is_empty() {
                println!("No xinet proxies registered");
            } else {
                for (i, status) in statuses.iter().enumerate() {
                    if i > 0 {
                        println!();
                    }
                    print_proxy_status(status);
                }
            }
        }
    }
    Ok(())
}

fn print_proxy_status(status: &ProxyStatus) {
    println!("Proxy: {}", status.name);
    println!("  Listen:  {}", status.listen);
    println!("  Backend: {}", status.backend);
    println!("  Service: {}", status.service);
    println!(
        "  Status:  {}",
        if status.running { "running" } else { "stopped" }
    );
    println!(
        "  Connections: {} active, {} total",
        status.active_connections, status.total_connections
    );
    println!(
        "  Traffic: {} bytes in, {} bytes out",
        status.bytes_to_backend, status.bytes_from_backend
    );
}