sal/service_manager
2025-07-02 05:50:18 +02:00
..
examples service manager add examples and improvements 2025-07-02 05:50:18 +02:00
src service manager add examples and improvements 2025-07-02 05:50:18 +02:00
Cargo.toml add service manager sal 2025-07-01 09:11:45 +02:00
README.md service manager add examples and improvements 2025-07-02 05:50:18 +02:00

Service Manager

This crate provides a unified interface for managing system services across different platforms. It abstracts the underlying service management system (like launchctl on macOS or zinit on Linux), allowing you to create, start, stop, remove, and monitor services with a consistent API.

The service lifecycle is managed in two distinct steps:

  1. create: Creates the service definition on the system (e.g., writes a .plist file on macOS).
  2. start: Starts a service that has already been created.

This separation ensures that service management is more explicit and robust.

Features

  • A ServiceManager trait defining a common interface for service operations.
  • Platform-specific implementations for:
    • macOS (launchctl)
    • Linux (zinit) (via the zinit feature flag)
  • A factory function create_service_manager that returns the appropriate manager for the current platform.

Usage

Add this to your Cargo.toml:

[dependencies]
sal-service-manager = { path = "./", features = ["zinit"] }

Here is an example of how to use the ServiceManager:

use sal_service_manager::{create_service_manager, ServiceConfig, ServiceManager};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // On linux, this will default to zinit. On macos, to launchctl.
    let service_manager = create_service_manager(None)?;

    let config = ServiceConfig {
        name: "my-service".to_string(),
        binary_path: "/usr/local/bin/my-service-executable".to_string(),
        args: vec!["--config".to_string(), "/etc/my-service.conf".to_string()],
        working_directory: Some("/var/tmp".to_string()),
        environment: None,
        auto_restart: true,
    };

    // Create the service definition
    service_manager.create(&config)?;
    println!("Service 'my-service' created.");

    // Start the service
    service_manager.start("my-service")?;
    println!("Service 'my-service' started.");

    // Get the status of the service
    let status = service_manager.status("my-service")?;
    println!("Service status: {:?}", status);

    // Stop the service
    service_manager.stop("my-service")?;
    println!("Service 'my-service' stopped.");

    // Remove the service
    service_manager.remove("my-service")?;
    println!("Service 'my-service' removed.");

    Ok(())
}