Files
WiseTLP/docs/API.md
2025-09-16 14:27:34 +03:00

377 lines
9.8 KiB
Markdown

# WiseTLP API Documentation
This document provides detailed information about WiseTLP's internal APIs and interfaces.
## Table of Contents
- [System Detection API](#system-detection-api)
- [AI Client API](#ai-client-api)
- [TLP Management API](#tlp-management-api)
- [Security API](#security-api)
- [Configuration API](#configuration-api)
- [Types and Structures](#types-and-structures)
## System Detection API
The system detection module provides comprehensive Linux system information gathering.
### `system.DetectSystem(ctx context.Context) (*Info, error)`
Detects basic system information including distribution, version, and package manager.
**Parameters:**
- `ctx`: Context for cancellation and timeout control
**Returns:**
- `*Info`: Basic system information structure
- `error`: Error if detection fails
**Example:**
```go
ctx := context.Background()
info, err := system.DetectSystem(ctx)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Distribution: %s %s\n", info.Distribution, info.Version)
```
### `system.GatherSystemInfo(ctx context.Context) (*types.SystemInfo, error)`
Collects comprehensive system information including hardware, power management, and kernel details.
**Parameters:**
- `ctx`: Context for cancellation and timeout control
**Returns:**
- `*types.SystemInfo`: Complete system information structure
- `error`: Error if gathering fails
**Gathered Information:**
- CPU details (model, cores, frequency, governor)
- Memory information (total, available, swap)
- Battery information (if present)
- Power supply status
- Kernel information and parameters
- Hardware details (chassis, manufacturer, storage)
- Distribution information
## AI Client API
The AI client module handles communication with various AI service providers.
### `ai.NewClient(config *types.AIConfig, logger *utils.Logger) *Client`
Creates a new AI client with the specified configuration.
**Parameters:**
- `config`: AI service configuration
- `logger`: Logger instance for structured logging
**Returns:**
- `*Client`: Configured AI client instance
### `ai.ConfigureClient(logger *utils.Logger) (*Client, error)`
Interactively configures an AI client by prompting the user for provider selection and credentials.
**Parameters:**
- `logger`: Logger instance
**Returns:**
- `*Client`: Configured AI client
- `error`: Configuration error
### `(*Client).GenerateConfig(ctx context.Context, sysInfo *types.SystemInfo, preferences *types.UserPreferences) (*types.TLPConfiguration, error)`
Generates an optimized TLP configuration using AI based on system information and user preferences.
**Parameters:**
- `ctx`: Context for request timeout
- `sysInfo`: Complete system information
- `preferences`: User power management preferences
**Returns:**
- `*types.TLPConfiguration`: Generated TLP configuration
- `error`: Generation error
## TLP Management API
The TLP management module handles TLP installation, configuration, and validation.
### `tlp.NewManager(logger *utils.Logger) *Manager`
Creates a new TLP manager instance.
**Parameters:**
- `logger`: Logger instance
**Returns:**
- `*Manager`: TLP manager instance
### `(*Manager).GetStatus(ctx context.Context) (*types.TLPStatus, error)`
Retrieves the current TLP installation and configuration status.
**Returns:**
- `*types.TLPStatus`: Current TLP status
- `error`: Status retrieval error
### `(*Manager).Install(ctx context.Context, sysInfo *system.Info) error`
Installs TLP using the appropriate package manager for the detected distribution.
**Parameters:**
- `ctx`: Context for operation timeout
- `sysInfo`: System information for package manager selection
**Returns:**
- `error`: Installation error
**Supported Package Managers:**
- apt (Ubuntu, Debian)
- dnf (Fedora, RHEL, CentOS)
- pacman (Arch, Manjaro)
- zypper (openSUSE)
- yum (Legacy RHEL/CentOS)
- apk (Alpine)
### `(*Manager).ApplyConfig(ctx context.Context, config *types.TLPConfiguration) error`
Applies a TLP configuration to the system.
**Parameters:**
- `ctx`: Context for operation timeout
- `config`: TLP configuration to apply
**Returns:**
- `error`: Application error
**Operations:**
1. Validates configuration
2. Backs up existing configuration
3. Writes new configuration
4. Reloads TLP service
### `(*Manager).ValidateConfig(config *types.TLPConfiguration) error`
Validates a TLP configuration for correctness and safety.
**Parameters:**
- `config`: Configuration to validate
**Returns:**
- `error`: Validation error
## Security API
The security module handles API key storage and privilege escalation.
### `security.NewKeyStore() (*KeyStore, error)`
Creates a new encrypted key store for API keys.
**Returns:**
- `*KeyStore`: Key store instance
- `error`: Initialization error
### `(*KeyStore).StoreAPIKey(provider, apiKey string) error`
Securely stores an API key for a provider.
**Parameters:**
- `provider`: AI service provider name
- `apiKey`: API key to store
**Returns:**
- `error`: Storage error
**Security Features:**
- AES-GCM encryption
- Master password protection
- Secure file permissions (0600)
### `(*KeyStore).RetrieveAPIKey(provider string) (string, error)`
Retrieves and decrypts an API key for a provider.
**Parameters:**
- `provider`: AI service provider name
**Returns:**
- `string`: Decrypted API key
- `error`: Retrieval error
### `security.NewPrivilegeManager(logger *utils.Logger) *PrivilegeManager`
Creates a new privilege manager for secure elevation.
### `(*PrivilegeManager).EscalateIfNeeded(args []string, operation string) error`
Escalates privileges using sudo if not already running as root.
**Parameters:**
- `args`: Command arguments for elevated execution
- `operation`: Description of operation requiring elevation
**Returns:**
- `error`: Escalation error
## Configuration API
The configuration module handles user preference gathering and processing.
### `config.GatherUserPreferences() (*types.UserPreferences, error)`
Interactively gathers user preferences for power management.
**Returns:**
- `*types.UserPreferences`: User preferences
- `error`: Gathering error
**Collected Preferences:**
- Power profile (balanced, performance, power saving, custom)
- Use case (general, development, gaming, server, multimedia, office)
- Battery priority (balanced, runtime, longevity)
- Performance mode (adaptive, maximum, efficient)
- Special requirements
- Custom settings
### `config.ValidatePreferences(preferences *types.UserPreferences) error`
Validates user preferences for consistency and conflicts.
**Parameters:**
- `preferences`: Preferences to validate
**Returns:**
- `error`: Validation error
### `config.GetRecommendedSettings(preferences *types.UserPreferences) map[string]string`
Generates recommended TLP settings based on user preferences.
**Parameters:**
- `preferences`: User preferences
**Returns:**
- `map[string]string`: Recommended TLP settings
## Types and Structures
### SystemInfo
Complete system information structure containing:
```go
type SystemInfo struct {
CPU CPUInfo `json:"cpu"`
Memory MemoryInfo `json:"memory"`
Battery *BatteryInfo `json:"battery,omitempty"`
PowerSupply PowerSupplyInfo `json:"power_supply"`
Kernel KernelInfo `json:"kernel"`
Distribution DistributionInfo `json:"distribution"`
Hardware HardwareInfo `json:"hardware"`
TLPStatus TLPStatus `json:"tlp_status"`
}
```
### UserPreferences
User power management preferences:
```go
type UserPreferences struct {
PowerProfile PowerProfile `json:"power_profile"`
UseCase UseCase `json:"use_case"`
BatteryPriority BatteryPriority `json:"battery_priority"`
PerformanceMode PerformanceMode `json:"performance_mode"`
CustomSettings map[string]interface{} `json:"custom_settings"`
SpecialRequirements []string `json:"special_requirements"`
}
```
### TLPConfiguration
Generated TLP configuration:
```go
type TLPConfiguration struct {
Settings map[string]string `json:"settings"`
Description string `json:"description"`
Rationale map[string]string `json:"rationale"`
Warnings []string `json:"warnings"`
Generated time.Time `json:"generated"`
SystemInfo *SystemInfo `json:"system_info"`
Preferences *UserPreferences `json:"preferences"`
}
```
### AIConfig
AI service configuration:
```go
type AIConfig struct {
Provider AIProvider `json:"provider"`
APIKey string `json:"-"` // Never serialized
Endpoint string `json:"endpoint"`
Model string `json:"model"`
MaxTokens int `json:"max_tokens"`
Temperature float64 `json:"temperature"`
}
```
## Error Handling
All APIs follow Go's standard error handling patterns:
- Functions return `error` as the last return value
- Errors are wrapped with context using `fmt.Errorf`
- Custom error types are used for specific error conditions
- Logging is performed at appropriate levels
## Context Usage
All long-running operations accept a `context.Context` parameter for:
- Cancellation support
- Timeout handling
- Request tracing
- Graceful shutdown
## Logging
WiseTLP uses structured logging throughout:
```go
logger := utils.NewLogger()
logger.Info("Operation completed", "duration", elapsed, "items", count)
logger.Error("Operation failed", "error", err, "context", ctx)
```
Log levels:
- `Debug`: Detailed debugging information
- `Info`: General operational information
- `Warn`: Warning conditions
- `Error`: Error conditions
## Testing
All APIs include comprehensive unit tests:
```bash
# Run API tests
go test ./internal/...
go test ./pkg/...
# Run with coverage
go test -cover ./...
```
Test patterns:
- Table-driven tests for multiple scenarios
- Mock interfaces for external dependencies
- Integration tests for component interactions
- Error condition testing