Skip to content

clients.zinit #

Zinit OpenRPC Client

This is a V language client for the Zinit service manager, implementing the OpenRPC specification.

Overview

Zinit is a service manager that allows you to manage and monitor services on your system. This client provides a comprehensive API to interact with Zinit via its JSON-RPC interface.

Features

  • Complete implementation of all methods in the Zinit OpenRPC specification
  • Type-safe API with proper error handling
  • Comprehensive documentation
  • Helper functions for common operations
  • Example code for all operations

Usage

Basic Example

import freeflowuniverse.heroweb.clients.zinit

fn main() {
    // Create a new client with the default socket path
    mut client := zinit.new_default_client()

    // List all services
    services := client.service_list() or {
        println('Error: ${err}')
        return
    }

    // Print the services
    for name, state in services {
        println('${name}: ${state}')
    }

    // Get status of a specific service
    if services.len > 0 {
        service_name := services.keys()[0]
        status := client.service_status(service_name) or {
            println('Error: ${err}')
            return
        }

        println('Service: ${status.name}')
        println('State: ${status.state}')
        println('PID: ${status.pid}')
    }
}

Creating and Managing Services

import freeflowuniverse.heroweb.clients.zinit

fn main() {
    mut client := zinit.new_default_client()

    // Create a new service configuration
    config := zinit.ServiceConfig{
        exec: '/bin/echo "Hello, World!"'
        oneshot: true
        log: zinit.log_stdout
        env: {
            'ENV_VAR': 'value'
        }
    }

    // Create the service
    client.service_create('hello', config) or {
        println('Error creating service: ${err}')
        return
    }

    // Start the service
    client.service_start('hello') or {
        println('Error starting service: ${err}')
        return
    }

    // Get the service logs
    logs := client.stream_current_logs('hello') or {
        println('Error getting logs: ${err}')
        return
    }

    for log in logs {
        println(log)
    }

    // Clean up
    client.service_stop('hello') or {}
    client.service_forget('hello') or {}
    client.service_delete('hello') or {}
}

API Reference

Client Creation

  • new_client(socket_path string) &Client - Create a new client with a custom socket path
  • new_default_client() &Client - Create a new client with the default socket path (/tmp/zinit.sock)

Service Management

  • service_list() !map[string]string - List all services and their states
  • service_status(name string) !ServiceStatus - Get detailed status of a service
  • service_start(name string) ! - Start a service
  • service_stop(name string) ! - Stop a service
  • service_monitor(name string) ! - Start monitoring a service
  • service_forget(name string) ! - Stop monitoring a service
  • service_kill(name string, signal string) ! - Send a signal to a service
  • service_create(name string, config ServiceConfig) !string - Create a new service
  • service_delete(name string) !string - Delete a service
  • service_get(name string) !ServiceConfig - Get a service configuration
  • service_stats(name string) !ServiceStats - Get memory and CPU usage statistics

System Operations

  • system_shutdown() ! - Stop all services and power off the system
  • system_reboot() ! - Stop all services and reboot the system
  • system_start_http_server(address string) !string - Start an HTTP/RPC server
  • system_stop_http_server() ! - Stop the HTTP/RPC server

Logs

  • stream_current_logs(name ?string) ![]string - Get current logs
  • stream_subscribe_logs(name ?string) !string - Subscribe to log messages

Constants

  • default_socket_path - Default Unix socket path (/tmp/zinit.sock)
  • state_running, state_success, state_error, etc. - Common service states
  • target_up, target_down - Common service targets
  • log_null, log_ring, log_stdout - Common log types
  • signal_term, signal_kill, etc. - Common signals

Helper Functions

  • new_service_config(exec string) ServiceConfig - Create a basic service configuration
  • new_oneshot_service_config(exec string) ServiceConfig - Create a oneshot service configuration
  • is_service_not_found_error(err IError) bool - Check if an error is a "service not found" error
  • format_memory_usage(bytes i64) string - Format memory usage in human-readable format
  • format_cpu_usage(cpu_percent f64) string - Format CPU usage

License

MIT

Constants #

const version = '1.0.0'

Module version information

const author = 'Hero Code'
const license = 'MIT'
const default_socket_path = '/tmp/zinit.sock'

Default socket path for zinit

const state_running = 'Running'

Common service states

const state_success = 'Success'
const state_error = 'Error'
const state_stopped = 'Stopped'
const state_failed = 'Failed'
const target_up = 'Up'

Common service targets

const target_down = 'Down'
const log_null = 'null'

Common log types

const log_ring = 'ring'
const log_stdout = 'stdout'
const signal_term = 'SIGTERM'

Common signals

const signal_kill = 'SIGKILL'
const signal_hup = 'SIGHUP'
const signal_usr1 = 'SIGUSR1'
const signal_usr2 = 'SIGUSR2'
const error_service_not_found = -32000

JSON-RPC error codes as defined in the OpenRPC specification

const error_service_already_monitored = -32001
const error_service_is_up = -32002
const error_service_is_down = -32003
const error_invalid_signal = -32004
const error_config_error = -32005
const error_shutting_down = -32006
const error_service_already_exists = -32007
const error_service_file_error = -32008

fn format_cpu_usage #

fn format_cpu_usage(cpu_percent f64) string

Helper function to format CPU usage

fn format_memory_usage #

fn format_memory_usage(bytes i64) string

Helper function to format memory usage in human-readable format

fn new_client #

fn new_client(args_ ClientParams) &Client

new_client creates a new Zinit RPC client with a custom socket path

fn new_oneshot_service_config #

fn new_oneshot_service_config(exec string) ServiceConfig

Helper function to create a oneshot service configuration

fn new_service_config #

fn new_service_config(exec string) ServiceConfig

Helper function to create a basic service configuration

struct ChildStatsResponse #

struct ChildStatsResponse {
pub mut:
	pid          int // Process ID of the child process
	memory_usage i64 // Memory usage in bytes
	cpu_usage    f64 // CPU usage as a percentage (0-100)
}

ChildStatsResponse represents statistics for a child process

struct Client #

struct Client {
mut:
	rpc_client &jsonrpc.Client
}

Client is an OpenRPC client for Zinit

fn (Client) rpc_discover #

fn (mut c Client) rpc_discover() !RpcDiscoverResponse

rpc_discover returns the OpenRPC specification for the API

fn (Client) service_create #

fn (mut c Client) service_create(name string, config ServiceConfig) !ServiceCreateResponse

service_create creates a new service configuration file name: the name of the service to create config: the service configuration

fn (Client) service_delete #

fn (mut c Client) service_delete(name string) !ServiceDeleteResponse

service_delete deletes a service configuration file name: the name of the service to delete

fn (Client) service_forget #

fn (mut c Client) service_forget(name string) !

service_forget stops monitoring a service You can only forget a stopped service name: the name of the service to forget

fn (Client) service_get #

fn (mut c Client) service_get(name string) !ServiceConfigResponse

service_get gets a service configuration file name: the name of the service to get

fn (Client) service_kill #

fn (mut c Client) service_kill(name string, signal string) !

service_kill sends a signal to a running service name: the name of the service to send the signal to signal: the signal to send (e.g., SIGTERM, SIGKILL)

fn (Client) service_list #

fn (mut c Client) service_list() !map[string]string

service_list lists all services managed by Zinit Returns a map of service names to their current states

fn (Client) service_monitor #

fn (mut c Client) service_monitor(name string) !

service_monitor starts monitoring a service The service configuration is loaded from the config directory name: the name of the service to monitor

fn (Client) service_start #

fn (mut c Client) service_start(name string) !

service_start starts a service name: the name of the service to start

fn (Client) service_stats #

fn (mut c Client) service_stats(name string) !ServiceStatsResponse

service_stats gets memory and CPU usage statistics for a service name: the name of the service to get stats for

fn (Client) service_status #

fn (mut c Client) service_status(name string) !ServiceStatusResponse

service_status shows detailed status information for a specific service name: the name of the service

fn (Client) service_stop #

fn (mut c Client) service_stop(name string) !

service_stop stops a service name: the name of the service to stop

fn (Client) stream_current_logs #

fn (mut c Client) stream_current_logs(args LogParams) ![]string

stream_current_logs gets current logs from zinit and monitored services name: optional service name filter. If provided, only logs from this service will be returned

fn (Client) stream_subscribe_logs #

fn (mut c Client) stream_subscribe_logs(name ?string) !StreamSubscribeLogsResponse

stream_subscribe_logs subscribes to log messages generated by zinit and monitored services name: optional service name filter. If provided, only logs from this service will be returned

fn (Client) system_reboot #

fn (mut c Client) system_reboot() !

system_reboot stops all services and reboots the system

fn (Client) system_shutdown #

fn (mut c Client) system_shutdown() !

system_shutdown stops all services and powers off the system

fn (Client) system_start_http_server #

fn (mut c Client) system_start_http_server(address string) !SystemStartHttpServerResponse

system_start_http_server starts an HTTP/RPC server at the specified address address: the network address to bind the server to (e.g., '127.0.0.1:8080')

fn (Client) system_stop_http_server #

fn (mut c Client) system_stop_http_server() !

system_stop_http_server stops the HTTP/RPC server if running

struct ClientParams #

@[params]
struct ClientParams {
	path string = '/tmp/zinit.sock' // Path to the Zinit RPC socket
}

struct KillParams #

struct KillParams {
pub:
	name   string // Name of the service to kill
	signal string // Signal to send (e.g., SIGTERM, SIGKILL)
}

KillParams represents the parameters for the service_kill method

struct LogParams #

@[params]
struct LogParams {
	name string
}

struct RpcDiscoverResponse #

struct RpcDiscoverResponse {
pub mut:
	spec map[string]string // OpenRPC specification
}

RpcDiscoverResponse represents the response from rpc.discover

struct ServiceConfig #

struct ServiceConfig {
pub mut:
	exec             string            // Command to run
	oneshot          bool              // Whether the service should be restarted
	after            []string          // Services that must be running before this one starts
	log              string            // How to handle service output (null, ring, stdout)
	env              map[string]string // Environment variables for the service
	shutdown_timeout int               // Maximum time to wait for service to stop during shutdown
}

ServiceConfig represents the configuration for a zinit service

struct ServiceConfigResponse #

struct ServiceConfigResponse {
pub mut:
	exec             string            // Command to run
	oneshot          bool              // Whether the service should be restarted
	after            []string          // Services that must be running before this one starts
	log              string            // How to handle service output (null, ring, stdout)
	env              map[string]string // Environment variables for the service
	shutdown_timeout int               // Maximum time to wait for service to stop during shutdown
}

struct ServiceCreateResponse #

struct ServiceCreateResponse {
pub mut:
	path string // Path to the created service file
}

ServiceCreateResponse represents the response from service_create

struct ServiceDeleteResponse #

struct ServiceDeleteResponse {
pub mut:
	result string // Result of the delete operation
}

ServiceDeleteResponse represents the response from service_delete

struct ServiceStatsResponse #

struct ServiceStatsResponse {
pub mut:
	name         string               // Service name
	pid          int                  // Process ID of the service
	memory_usage i64                  // Memory usage in bytes
	cpu_usage    f64                  // CPU usage as a percentage (0-100)
	children     []ChildStatsResponse // Stats for child processes
}

ServiceStatsResponse represents the response from service_stats

struct ServiceStatusResponse #

struct ServiceStatusResponse {
pub mut:
	name   string            // Service name
	pid    int               // Process ID of the running service (if running)
	state  string            // Current state of the service (Running, Success, Error, etc.)
	target string            // Target state of the service (Up, Down)
	after  map[string]string // Dependencies of the service and their states
}

ServiceStatusResponse represents the response from service_status

struct StreamCurrentLogsResponse #

struct StreamCurrentLogsResponse {
pub mut:
	logs []string // Log entries
}

StreamCurrentLogsResponse represents the response from stream_currentLogs

struct StreamSubscribeLogsResponse #

struct StreamSubscribeLogsResponse {
pub mut:
	subscription_id string // ID of the log subscription
}

StreamSubscribeLogsResponse represents the response from stream_subscribeLogs

struct SystemStartHttpServerResponse #

struct SystemStartHttpServerResponse {
pub mut:
	result string // Result of starting the HTTP server
}

SystemStartHttpServerResponse represents the response from system_start_http_server

struct ZinitError #

struct ZinitError {
pub mut:
	code    int    // Error code
	message string // Error message
	data    string // Additional error data
}

ZinitError represents an error returned by the zinit API

fn (ZinitError) msg #

fn (e ZinitError) msg() string

Error implements the error interface for ZinitError