This commit is contained in:
2025-07-21 06:18:46 +02:00
parent 62932976dd
commit ddf5fcbbcc
268 changed files with 1614 additions and 2271 deletions

168
lib/osal/core/readme.md Normal file
View File

@@ -0,0 +1,168 @@
# Operating System Abstraction Layer (OSAL) - Core Module
The `lib/osal/core` module provides a comprehensive, platform-independent abstraction layer for common operating system functionalities in V. It simplifies interactions with the underlying system, offering robust tools for process management, network operations, file system manipulation, environment variable handling, and more.
## Capabilities & Usage
This module encapsulates essential OS-level features, making system programming more consistent and reliable across different environments.
### 1. Process Execution (`exec.v`)
Execute shell commands with fine-grained control and robust error handling.
* **`osal.exec(cmd: Command)`**: Executes a command with extensive options.
* `Command` struct fields:
* `cmd` (string): The command string.
* `timeout` (int): Max execution time in seconds (default: 3600).
* `retry` (int): Number of retries on failure.
* `work_folder` (string): Working directory for the command.
* `environment` (map[string]string): Environment variables for the command.
* `stdout` (bool): Show command output (default: true).
* `raise_error` (bool): Raise V error on failure (default: true).
* `ignore_error` (bool): Do not raise error, just report.
* `debug` (bool): Enable debug output.
* `shell` (bool): Execute in interactive shell.
* `async` (bool): Run command asynchronously.
* `runtime` (RunTime): Specify runtime (e.g., `.bash`, `.python`).
* Returns `Job` struct with `status`, `output`, `error`, `exit_code`, etc.
* **`osal.execute_silent(cmd string)`**: Executes a command silently, returns output.
* **`osal.execute_debug(cmd string)`**: Executes a command with debug output, returns output.
* **`osal.execute_stdout(cmd string)`**: Executes a command and prints output to stdout, returns output.
* **`osal.execute_interactive(cmd string)`**: Executes a command in an interactive shell.
* **`osal.cmd_exists(cmd string)`**: Checks if a command exists in the system's PATH.
**Example: Flexible Command Execution**
```v
import freeflowuniverse.herolib.osal.core as osal
// Simple command execution
job := osal.exec(cmd: 'ls -la')!
println(job.output)
// Execute with error handling and custom options
job := osal.exec(osal.Command{
cmd: 'complex_command_that_might_fail'
timeout: 60 // seconds
retry: 2
work_folder: '/tmp'
environment: {
'MY_VAR': 'some_value'
}
stdout: true
raise_error: true
})!
// Check job status and handle specific errors
if job.status == .done {
println('Command executed successfully!')
} else if job.status == .error_timeout {
println('Command timed out.')
} else {
println('Command failed with exit code: ${job.exit_code}, Error: ${job.error}')
}
// Example of error handling with match
job_result := osal.exec(cmd: 'non_existent_command')
if job_result.is_err() {
err := job_result.err
match err.error_type {
.exec { println('Execution error: ${err.msg()}') }
.timeout { println('Command timed out: ${err.msg()}') }
.args { println('Invalid arguments: ${err.msg()}') }
else { println('An unexpected error occurred: ${err.msg()}') }
}
}
```
### 2. Network Utilities (`net.v`)
Tools for network diagnostics and information.
* **`osal.ping(args: PingArgs)`**: Checks host reachability.
* `PingArgs` struct fields: `address` (string, required), `count` (u8), `timeout` (u16), `retry` (u8).
* Returns `PingResult` enum: `.ok`, `.timeout`, `.unknownhost`.
* **`osal.tcp_port_test(args: TcpPortTestArgs)`**: Tests if a TCP port is open.
* `TcpPortTestArgs` struct fields: `address` (string, required), `port` (int), `timeout` (u16 in milliseconds).
* Returns `bool`.
* **`osal.ipaddr_pub_get()`**: Retrieves the public IP address. Returns `string`.
* **`osal.is_ip_on_local_interface(ip string)`**: Checks if an IP is on a local interface. Returns `bool`.
### 3. File System Operations (`file.v`)
Functions for managing files and directories.
* **`osal.file_write(path string, text string)`**: Writes text to a file.
* **`osal.file_read(path string)`**: Reads content from a file. Returns `string`.
* **`osal.dir_ensure(path string)`**: Ensures a directory exists, creates if not.
* **`osal.dir_delete(path string)`**: Deletes a directory if it exists.
* **`osal.dir_reset(path string)`**: Deletes and recreates a directory.
* **`osal.rm(todelete string)`**: Removes files/directories (supports `~`, comma/newline separated paths, sudo).
### 4. Environment Variables (`env.v`)
Manage system environment variables.
* **`osal.env_set(args: EnvSet)`**: Sets an environment variable.
* `EnvSet` struct fields: `key` (string, required), `value` (string, required), `overwrite` (bool).
* **`osal.env_unset(key string)`**: Unsets an environment variable.
* **`osal.env_unset_all()`**: Unsets all environment variables.
* **`osal.env_set_all(args: EnvSetAll)`**: Sets multiple environment variables.
* `EnvSetAll` struct fields: `env` (map[string]string), `clear_before_set` (bool), `overwrite_if_exists` (bool).
* **`osal.env_get(key string)`**: Retrieves an environment variable's value. Returns `string`.
* **`osal.env_exists(key string)`**: Checks if an environment variable exists. Returns `bool`.
* **`osal.env_get_default(key string, def string)`**: Gets an environment variable or a default value. Returns `string`.
* **`osal.load_env_file(file_path string)`**: Loads environment variables from a file.
### 5. Command & Profile Management (`cmds.v`)
Manage system commands and shell profile paths.
* **`osal.cmd_add(args: CmdAddArgs)`**: Adds a binary to system paths and updates profiles.
* `CmdAddArgs` struct fields: `cmdname` (string), `source` (string, required), `symlink` (bool), `reset` (bool).
* **`osal.profile_path_add_hero()`**: Adds `~/hero/bin` to profile. Returns `string` (path).
* **`osal.bin_path()`**: Returns the preferred binary installation path. Returns `string`.
* **`osal.hero_path()`**: Returns the `~/hero` directory path. Returns `string`.
* **`osal.usr_local_path()`**: Returns `/usr/local` (Linux) or `~/hero` (macOS). Returns `string`.
* **`osal.profile_path_source()`**: Returns a source command for the preferred profile. Returns `string`.
* **`osal.profile_path_source_and()`**: Returns a source command followed by `&&`. Returns `string`.
* **`osal.profile_path_add_remove(args: ProfilePathAddRemoveArgs)`**: Adds/removes paths from profiles.
* `ProfilePathAddRemoveArgs` struct fields: `paths_profile` (string), `paths2add` (string), `paths2delete` (string), `allprofiles` (bool).
* **`osal.cmd_path(cmd string)`**: Returns the full path of an executable command. Returns `string`.
* **`osal.cmd_delete(cmd string)`**: Deletes commands from their locations.
* **`osal.profile_paths_all()`**: Lists all possible profile file paths. Returns `[]string`.
* **`osal.profile_paths_preferred()`**: Lists preferred profile file paths for the OS. Returns `[]string`.
* **`osal.profile_path()`**: Returns the most preferred profile file path. Returns `string`.
### 6. System Information & Utilities (`ps_tool.v`, `sleep.v`, `downloader.v`, `users.v`, etc.)
Miscellaneous system functionalities.
* **`osal.processmap_get()`**: Gets a map of all running processes. Returns `ProcessMap`.
* **`osal.processinfo_get(pid int)`**: Gets info for a specific process. Returns `ProcessInfo`.
* **`osal.processinfo_get_byname(name string)`**: Gets info for processes by name. Returns `[]ProcessInfo`.
* **`osal.process_exists(pid int)`**: Checks if a process exists by PID. Returns `bool`.
* **`osal.processinfo_with_children(pid int)`**: Gets a process and its children. Returns `ProcessMap`.
* **`osal.processinfo_children(pid int)`**: Gets children of a process. Returns `ProcessMap`.
* **`osal.process_kill_recursive(args: ProcessKillArgs)`**: Kills a process and its children.
* `ProcessKillArgs` struct fields: `name` (string), `pid` (int).
* **`osal.whoami()`**: Returns the current username. Returns `string`.
* **`osal.sleep(duration int)`**: Pauses execution for `duration` seconds.
* **`osal.download(args: DownloadArgs)`**: Downloads a file from a URL.
* `DownloadArgs` struct fields: `url` (string), `name` (string), `reset` (bool), `hash` (string), `dest` (string), `timeout` (int), `retry` (int), `minsize_kb` (u32), `maxsize_kb` (u32), `expand_dir` (string), `expand_file` (string).
* Returns `pathlib.Path`.
* **`osal.user_exists(username string)`**: Checks if a user exists. Returns `bool`.
* **`osal.user_id_get(username string)`**: Gets user ID. Returns `int`.
* **`osal.user_add(args: UserArgs)`**: Adds a user.
* `UserArgs` struct fields: `name` (string, required). Returns `int` (user ID).
## Notes on the CMD Job Execution
* Commands are executed from temporary scripts in `/tmp/execscripts`.
* Failed script executions are preserved for debugging.
* Successful script executions are automatically cleaned up.
* Platform-specific behavior is automatically handled.
* Timeout and retry mechanisms are available for robust execution.
* Environment variables and working directories can be specified per command.
* Interactive and non-interactive modes are supported.

View File

@@ -3,7 +3,7 @@
This module provides functionality for managing DNS records in Redis for use with CoreDNS. It supports various DNS record types and provides a simple interface for adding and managing DNS records.
```v
import freeflowuniverse.herolib.osal.coredns
import freeflowuniverse.herolib.osal.core as osal.coredns
// Create a new DNS record set
mut rs := coredns.new_dns_record_set()

View File

@@ -1,4 +1,4 @@
module osal
module done
import freeflowuniverse.herolib.core.base
import freeflowuniverse.herolib.data.dbfs

View File

@@ -1,4 +1,4 @@
module osal
module done
fn test_done_set() ! {
done_set('mykey', 'myvalue')!

View File

@@ -19,7 +19,7 @@ Create a file `example.vsh`:
```v
#!/usr/bin/env -S v -n -w -gc none -cc tcc -d use_openssl -enable-globals run
import freeflowuniverse.herolib.osal.hostsfile
import freeflowuniverse.herolib.osal.core as osal.hostsfile
import os
// Create a new instance by reading the hosts file

View File

@@ -1,7 +1,7 @@
module hostsfile
import os
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
const hosts_file_path = '/etc/hosts'

View File

@@ -16,7 +16,7 @@ A file system notification system for V that provides real-time monitoring of fi
## Usage Example
```v
import freeflowuniverse.herolib.osal.notifier
import freeflowuniverse.herolib.osal.core as osal.notifier
// Define callback function for file events
fn on_file_change(event notifier.NotifyEvent, path string) {

View File

@@ -1,200 +0,0 @@
# Operating System Abstraction Layer (OSAL)
A comprehensive operating system abstraction layer for V that provides platform-independent system operations, process management, and network utilities.
## Features
- Platform detection and system information
- Process execution and management
- Network utilities (ping, TCP port testing)
- Environment variable handling
- File system operations
- SSH key management
- Profile path management
## Platform Detection
```v
import freeflowuniverse.herolib.osal
// Get platform type
platform := core.platform()!
if platform == .osx {
// macOS specific code
}
// Platform-specific checks
if core.is_linux()! {
// Linux specific code
}
if core.is_osx_arm()! {
// Apple Silicon specific code
}
// CPU architecture
cpu := core.cputype()!
if cpu == .arm {
// ARM specific code
}
// System information
hostname := core.hostname()!!
init_system := core.initname()! // e.g., systemd, bash, zinit
```
## Process Execution
The module provides flexible process execution with extensive configuration options:
```v
// Simple command execution
job := osal.exec(cmd: 'ls -la')!
println(job.output)
// Execute with error handling
job := osal.exec(Command{
cmd: 'complex_command'
timeout: 3600 // timeout in seconds
retry: 3 // retry count
work_folder: '/tmp' // working directory
environment: { // environment variables
'PATH': '/usr/local/bin'
}
stdout: true // show output
raise_error: true // raise error on failure
})!
// Silent execution
output := osal.execute_silent('command')!
// Interactive shell execution
osal.execute_interactive('bash command')!
// Debug mode execution
output := osal.execute_debug('command')!
```
### Job Status and Error Handling
```v
// Check job status
if job.status == .done {
println('Success!')
} else if job.status == .error_timeout {
println('Command timed out')
}
// Error handling with specific error types
job := osal.exec(cmd: 'invalid_command') or {
match err.error_type {
.exec { println('Execution error') }
.timeout { println('Command timed out') }
.args { println('Invalid arguments') }
else { println(err) }
}
return
}
```
## Network Utilities
### Ping
```v
// Simple ping
result := osal.ping(address: '8.8.8.8')!
assert result == .ok
// Advanced ping configuration
result := osal.ping(PingArgs{
address: '8.8.8.8'
count: 3 // number of pings
timeout: 2 // timeout in seconds
retry: 1 // retry attempts
})!
match result {
.ok { println('Host is reachable') }
.timeout { println('Host timed out') }
.unknownhost { println('Unknown host') }
}
```
### TCP Port Testing
```v
// Test if port is open
is_open := osal.tcp_port_test(TcpPortTestArgs{
address: '192.168.1.1'
port: 22
timeout: 2000 // milliseconds
})
if is_open {
println('Port is open')
}
// Get public IP address
pub_ip := osal.ipaddr_pub_get()!
println('Public IP: ${pub_ip}')
```
## Profile Management
Manage system PATH and other profile settings:
```v
// Add/remove paths from system PATH
osal.profile_path_add_remove(
paths2delete: 'go/bin',
paths2add: '~/hero/bin,~/usr/local/bin'
)!
```
## Environment Variables
```v
// Get environment variable
value := osal.env_get('PATH')!
// Set environment variable
osal.env_set('MY_VAR', 'value')!
// Check if environment variable exists
exists := osal.env_exists('MY_VAR')
```
## Notes
- All commands are executed from temporary scripts in `/tmp/execscripts`
- Failed script executions are preserved for debugging
- Successful script executions are automatically cleaned up
- Platform-specific behavior is automatically handled
- Timeout and retry mechanisms are available for robust execution
- Environment variables and working directories can be specified per command
- Interactive and non-interactive modes are supported
- Debug mode provides additional execution information
## Error Handling
The module provides detailed error information:
- Exit codes
- Standard output and error streams
- Execution time and duration
- Process status
- Retry counts
- Error types (execution, timeout, arguments)
## Platform Support
- macOS (Intel and ARM)
- Ubuntu
- Alpine Linux
- Arch Linux
- SUSE (partial)
CPU architectures:
- Intel (x86_64)
- ARM (arm64/aarch64)
- 32-bit variants (intel32, arm32)

View File

@@ -2,7 +2,7 @@ module rsync
import freeflowuniverse.herolib.core.pathlib
import freeflowuniverse.herolib.ui.console
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
@[params]
pub struct RsyncArgs {

View File

@@ -1,6 +1,6 @@
module screen
// import freeflowuniverse.herolib.osal
// import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.core.texttools
// import freeflowuniverse.herolib.screen
import os

View File

@@ -9,7 +9,7 @@ Create a file `screen_example.vsh`:
```v
#!/usr/bin/env -S v run
import freeflowuniverse.herolib.osal.screen
import freeflowuniverse.herolib.osal.core as osal.screen
// Create a new screen factory
mut sf := screen.new()!

View File

@@ -1,7 +1,7 @@
module screen
import freeflowuniverse.herolib.ui.console
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.core
import os
import time

View File

@@ -1,7 +1,7 @@
## ssh agent
```v
import freeflowuniverse.herolib.osal.sshagent
import freeflowuniverse.herolib.osal.core as osal.sshagent
mut agent := sshagent.new()!

View File

@@ -1,7 +1,7 @@
# startup manager
```go
import freeflowuniverse.herolib.osal.startupmanager
import freeflowuniverse.herolib.osal.core as osal.startupmanager
mut sm:=startupmanager.get()!

View File

@@ -1,9 +1,9 @@
module startupmanager
import freeflowuniverse.herolib.ui.console
import freeflowuniverse.herolib.osal.screen
import freeflowuniverse.herolib.osal.systemd
import freeflowuniverse.herolib.osal.zinit
import freeflowuniverse.herolib.osal.core as osal.screen
import freeflowuniverse.herolib.osal.core as osal.systemd
import freeflowuniverse.herolib.osal.core as osal.zinit
// // TODO: check if using this interface would simplify things
// pub interface StartupManagerI {

View File

@@ -1,8 +1,8 @@
module startupmanager
import freeflowuniverse.herolib.ui.console
import freeflowuniverse.herolib.osal.screen
import freeflowuniverse.herolib.osal.systemd
import freeflowuniverse.herolib.osal.core as osal.screen
import freeflowuniverse.herolib.osal.core as osal.systemd
import os
import time

View File

@@ -1,6 +1,6 @@
module systemd
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
pub struct JournalArgs {
pub:

View File

@@ -1,6 +1,6 @@
module systemd
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.core.pathlib
import freeflowuniverse.herolib.core.texttools
import freeflowuniverse.herolib.ui.console

View File

@@ -2,7 +2,7 @@ module systemd
// import os
import maps
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.core.pathlib
import freeflowuniverse.herolib.ui.console
import os

View File

@@ -2,7 +2,7 @@ module systemd
// import os
import maps
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.core.pathlib
import freeflowuniverse.herolib.ui.console
import os

View File

@@ -1,6 +1,6 @@
module tmux
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
// import freeflowuniverse.herolib.session
import os
import time

View File

@@ -1,6 +1,6 @@
module tmux
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.core.texttools
import freeflowuniverse.herolib.ui.console

View File

@@ -1,6 +1,6 @@
module tmux
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.core.texttools
import os
import freeflowuniverse.herolib.ui.console

View File

@@ -1,6 +1,6 @@
module tmux
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
// import freeflowuniverse.herolib.installers.tmux
// fn testsuite_end() {

View File

@@ -1,6 +1,6 @@
module tmux
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
// import freeflowuniverse.herolib.installers.tmux
import os
import freeflowuniverse.herolib.ui.console

View File

@@ -1,7 +1,7 @@
module tmux
import os
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.core.texttools
import freeflowuniverse.herolib.data.ourtime
import time

View File

@@ -1,6 +1,6 @@
module tmux
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.ui.console
import time

View File

@@ -14,7 +14,7 @@ The module allows you to:
## Usage Example
```v
import freeflowuniverse.herolib.osal.traefik
import freeflowuniverse.herolib.osal.core as osal.traefik
fn main() ! {
// Create a new Traefik configuration

View File

@@ -20,7 +20,7 @@ Returns the name of an available TUN interface:
#!/usr/bin/env -S v -n -w -gc none -cc tcc -d use_openssl -enable-globals run
import freeflowuniverse.herolib.osal.tun
import freeflowuniverse.herolib.osal.core as osal.tun
// Check if TUN is available

View File

@@ -1,6 +1,6 @@
module ufw
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.ui.console
import os

View File

@@ -22,7 +22,7 @@ Zinit is a process manager that allows you to manage services on a system. This
### Basic Usage
```v
import freeflowuniverse.herolib.osal.zinit
import freeflowuniverse.herolib.osal.core as osal.zinit
fn main() {
// Create a new Zinit client with the default socket path
@@ -47,7 +47,7 @@ fn main() {
### Creating a New Service
```v
import freeflowuniverse.herolib.osal.zinit
import freeflowuniverse.herolib.osal.core as osal.zinit
fn main() {
mut zinit_client := zinit.new_stateless()!
@@ -77,7 +77,7 @@ fn main() {
### Getting Service Statistics
```v
import freeflowuniverse.herolib.osal.zinit
import freeflowuniverse.herolib.osal.core as osal.zinit
fn main() {
mut zinit_client := zinit.new_stateless()!
@@ -98,7 +98,7 @@ fn main() {
### Retrieving Logs
```v
import freeflowuniverse.herolib.osal.zinit
import freeflowuniverse.herolib.osal.core as osal.zinit
fn main() {
mut zinit_client := zinit.new_stateless()!

View File

@@ -3,7 +3,7 @@ module zinit
import os
import time
import freeflowuniverse.herolib.core
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
fn test_zinit() {
if !core.is_linux()! {

View File

@@ -2,7 +2,7 @@ module zinit
import freeflowuniverse.herolib.core.pathlib
import freeflowuniverse.herolib.ui.console
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
__global (
zinit_global_manager []&Zinit

View File

@@ -1,7 +1,7 @@
module zinit
import os
import freeflowuniverse.herolib.osal
import freeflowuniverse.herolib.osal.core as osal
import freeflowuniverse.herolib.data.ourtime
import freeflowuniverse.herolib.ui.console
import time