re-uploading work

This commit is contained in:
2026-02-04 17:46:30 -06:00
commit 3b14c65998
1388 changed files with 381262 additions and 0 deletions

591
docs/cli/cli-profiles.md Normal file
View File

@@ -0,0 +1,591 @@
# CLI Profile Management
The Attune CLI supports multiple named profiles, similar to SSH config or Kubernetes kubeconfig. This allows you to easily switch between different Attune servers (development, staging, production, etc.) without constantly changing configuration.
## Overview
Profiles are named configurations that store:
- API endpoint URL
- Authentication tokens (access and refresh)
- Output format preference (optional)
- Description (optional)
Each profile maintains its own authentication state, so you can be logged into multiple servers simultaneously.
## Configuration File
Profiles are stored in `~/.config/attune/config.yaml` (respects `$XDG_CONFIG_HOME`):
```yaml
current_profile: staging
profiles:
default:
api_url: http://localhost:8080
description: Default local server
staging:
api_url: https://staging.example.com
auth_token: eyJhbGc... # (stored securely)
refresh_token: eyJhbGc...
description: Staging environment
production:
api_url: https://api.example.com
auth_token: eyJhbGc...
refresh_token: eyJhbGc...
output_format: json
description: Production environment
default_output_format: table
```
## Profile Commands
### List All Profiles
```bash
attune config profiles
```
Output:
```
Profiles
• default
• staging (current)
• production
```
### Show Current Profile
```bash
attune config current
```
Output:
```
staging
```
### Add a Profile
```bash
attune config add-profile <name> --api-url <url> [--description <desc>]
```
Examples:
```bash
# Add staging profile
attune config add-profile staging \
--api-url https://staging.example.com \
--description "Staging environment"
# Add production profile
attune config add-profile production \
--api-url https://api.example.com \
--description "Production environment"
# Add local development profile with custom port
attune config add-profile dev \
--api-url http://localhost:3000 \
--description "Local development server"
```
### Switch Profile
```bash
attune config use <profile-name>
```
Example:
```bash
attune config use staging
# ✓ Switched to profile 'staging'
```
### Show Profile Details
```bash
attune config show-profile <profile-name>
```
Example:
```bash
attune config show-profile staging
```
Output:
```
Profile: staging
╭───────────────┬─────────────────────────────╮
│ Key ┆ Value │
╞═══════════════╪═════════════════════════════╡
│ API URL ┆ https://staging.example.com │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Auth Token ┆ *** │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Refresh Token ┆ *** │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ Description ┆ Staging environment │
╰───────────────┴─────────────────────────────╯
```
### Remove a Profile
```bash
attune config remove-profile <profile-name>
```
Example:
```bash
attune config remove-profile old-dev
# ✓ Profile 'old-dev' removed
```
**Note**: You cannot remove:
- The `default` profile
- The currently active profile (switch to another profile first)
## Using Profiles
### Runtime Profile Override
Use the `--profile` flag to temporarily use a different profile without switching:
```bash
# List packs on production without switching
attune --profile production pack list
# Execute action on staging
attune --profile staging action execute monitoring.check
# Get execution from different environment
attune --profile dev execution show 123
```
The `--profile` flag is available on all commands and does not change your current profile setting.
### Environment Variable
Set the `ATTUNE_PROFILE` environment variable:
```bash
export ATTUNE_PROFILE=staging
attune pack list # Uses staging profile
```
### Precedence
When determining which profile to use:
1. `--profile` command-line flag (highest priority)
2. `ATTUNE_PROFILE` environment variable
3. `current_profile` in config file
4. `default` profile (fallback)
## Authentication Per Profile
Each profile maintains its own authentication state. You need to log in separately for each profile:
```bash
# Login to staging
attune config use staging
attune auth login --username admin
# Login to production
attune config use production
attune auth login --username admin
# Now you're authenticated to both environments
```
### Check Authentication Status
```bash
# Check current profile authentication
attune auth whoami
# Check specific profile
attune --profile staging auth whoami
attune --profile production auth whoami
```
### Logout from Profile
```bash
# Logout from current profile
attune auth logout
# Logout from specific profile
attune --profile staging auth logout
```
## Use Cases
### Development Workflow
```bash
# Setup profiles
attune config add-profile local --api-url http://localhost:8080
attune config add-profile staging --api-url https://staging.example.com
attune config add-profile prod --api-url https://api.example.com
# Work on local
attune config use local
attune pack install https://github.com/myorg/my-pack
# Test on staging
attune --profile staging pack list
# Deploy to production
attune --profile prod pack install https://github.com/myorg/my-pack --ref v1.0.0
```
### Multi-Tenant Management
```bash
# Setup tenant profiles
attune config add-profile tenant-a --api-url https://tenant-a.example.com
attune config add-profile tenant-b --api-url https://tenant-b.example.com
# Login to each tenant
attune config use tenant-a
attune auth login --username admin
attune config use tenant-b
attune auth login --username admin
# Monitor both tenants
attune --profile tenant-a execution list --status failed
attune --profile tenant-b execution list --status failed
```
### CI/CD Integration
```bash
#!/bin/bash
# Deploy script for CI/CD
# Add ephemeral profile for CI environment
attune config add-profile ci --api-url "$CI_ATTUNE_API_URL"
# Login with CI credentials
attune --profile ci auth login \
--username "$CI_USERNAME" \
--password "$CI_PASSWORD"
# Deploy pack
attune --profile ci pack install "$PACK_REPO_URL" --ref "$GIT_TAG"
# Verify deployment
attune --profile ci pack show "$PACK_NAME"
# Cleanup (optional - config is typically ephemeral in CI)
attune config remove-profile ci
```
### Scripting with Profiles
```bash
#!/bin/bash
# Check health across all environments
PROFILES=("dev" "staging" "production")
for profile in "${PROFILES[@]}"; do
echo "Checking $profile..."
# Execute health check
result=$(attune --profile "$profile" \
action execute core.health_check \
--wait -j 2>/dev/null)
if [ $? -eq 0 ]; then
status=$(echo "$result" | jq -r '.status')
echo " $profile: $status"
else
echo " $profile: ERROR"
fi
done
```
## Profile Configuration Options
### Per-Profile Output Format
Set a default output format for a specific profile:
```bash
attune config use production
attune config set output_format json
```
Now all commands on the production profile will default to JSON output:
```bash
attune config use production
attune pack list # Outputs JSON
attune config use staging
attune pack list # Outputs table (default)
```
### Update Profile API URL
```bash
# Switch to profile
attune config use staging
# Update API URL
attune config set api_url https://new-staging.example.com
# Or update directly
attune config add-profile staging --api-url https://new-staging.example.com
```
## Best Practices
### 1. Use Descriptive Names
```bash
# Good
attune config add-profile staging-us-east --api-url ...
attune config add-profile prod-eu-west --api-url ...
# Avoid
attune config add-profile s1 --api-url ...
attune config add-profile p1 --api-url ...
```
### 2. Add Descriptions
```bash
attune config add-profile staging \
--api-url https://staging.example.com \
--description "Staging environment (US East)"
```
### 3. Keep Local as Default
Keep the `default` profile pointing to localhost for quick local testing:
```bash
# Default profile should be local
attune config use default
attune config get api_url
# http://localhost:8080
```
### 4. Profile Naming Convention
Use a consistent naming scheme:
- Environment-based: `dev`, `staging`, `prod`
- Region-based: `prod-us`, `prod-eu`, `prod-asia`
- Tenant-based: `tenant-acme`, `tenant-globex`
- Purpose-based: `local`, `ci`, `testing`
### 5. Verify Before Destructive Operations
Always verify you're on the correct profile before destructive operations:
```bash
# Check current profile
attune config current
# Or show API URL
attune config get api_url
# Then proceed
attune pack uninstall dangerous-pack
```
### 6. Use --profile for Queries
For read-only queries, use `--profile` instead of switching:
```bash
# Good - doesn't change current profile
attune --profile prod execution list
# Less ideal - changes current profile
attune config use prod
attune execution list
```
## Security Considerations
### Token Storage
Authentication tokens are stored in plaintext in the config file. Ensure proper file permissions:
```bash
chmod 600 ~/.config/attune/config.yaml
```
**Future Enhancement**: OS keyring integration for secure token storage.
### Production Profiles
For production profiles:
1. Use strong passwords
2. Enable MFA (when available)
3. Regularly rotate credentials
4. Limit token lifetime
5. Use service accounts in CI/CD
### Profile Separation
Keep credentials separated:
- Use different usernames for different environments
- Don't share production credentials with staging
- Use least-privilege access per environment
## Troubleshooting
### Profile Not Found
```
Error: Profile 'staging' does not exist
```
**Solution**: Add the profile first:
```bash
attune config add-profile staging --api-url https://staging.example.com
```
### Cannot Remove Active Profile
```
Error: Cannot remove active profile 'staging'. Switch to another profile first.
```
**Solution**: Switch to another profile:
```bash
attune config use default
attune config remove-profile staging
```
### Authentication Failed
If authentication fails after switching profiles:
```bash
# Check if logged in
attune auth whoami
# If not, login
attune auth login --username your-username
```
### Wrong API URL
If commands are hitting the wrong server:
```bash
# Check current profile
attune config current
# Check API URL
attune config get api_url
# Switch if needed
attune config use correct-profile
```
## Migration from Old Config
If you have an old single-server config, it will be migrated to a `default` profile on first run with the new version.
Old format:
```yaml
api_url: http://localhost:8080
auth_token: ...
refresh_token: ...
output_format: table
```
New format:
```yaml
current_profile: default
profiles:
default:
api_url: http://localhost:8080
auth_token: ...
refresh_token: ...
default_output_format: table
```
**Note**: Manual migration may be required. Back up your config before upgrading:
```bash
cp ~/.config/attune/config.yaml ~/.config/attune/config.yaml.backup
```
## Examples
### Complete Setup Example
```bash
# Setup local development
attune config add-profile local \
--api-url http://localhost:8080 \
--description "Local development"
# Setup staging
attune config add-profile staging \
--api-url https://staging.example.com \
--description "Staging environment"
# Setup production
attune config add-profile production \
--api-url https://api.example.com \
--description "Production environment"
# Login to each
for profile in local staging production; do
attune config use "$profile"
attune auth login --username admin
done
# Set production to always output JSON
attune config use production
attune config set output_format json
# Go back to local for development
attune config use local
# List all profiles
attune config profiles
```
### Profile Comparison Script
```bash
#!/bin/bash
# Compare pack versions across environments
PACK_NAME="monitoring"
echo "Pack: $PACK_NAME"
echo "---"
for profile in dev staging production; do
version=$(attune --profile "$profile" pack show "$PACK_NAME" -j 2>/dev/null | jq -r '.version')
if [ -n "$version" ] && [ "$version" != "null" ]; then
echo "$profile: $version"
else
echo "$profile: Not installed"
fi
done
```
## Related Commands
- `attune config list` - Show all configuration for current profile
- `attune config get <key>` - Get specific config value
- `attune config set <key> <value>` - Set config value for current profile
- `attune config path` - Show config file location
- `attune auth whoami` - Check authentication status
## See Also
- [CLI Documentation](cli.md)
- [Configuration Guide](../README.md#configuration)
- [Authentication](cli.md#authentication)

551
docs/cli/cli.md Normal file
View File

@@ -0,0 +1,551 @@
# Attune CLI
The Attune CLI is a comprehensive command-line tool for interacting with the Attune automation platform. It provides an intuitive interface for managing all aspects of the platform including packs, actions, rules, executions, and more.
## Overview
The CLI is designed to be:
- **Intuitive**: Natural command structure with helpful prompts
- **Flexible**: Multiple output formats for human and machine consumption
- **Powerful**: Full access to all API functionality
- **Scriptable**: JSON/YAML output for automation
## Installation
### From Source
```bash
cd attune
cargo install --path crates/cli
```
This will install the `attune` binary to your cargo bin directory (usually `~/.cargo/bin`).
### Development
```bash
cargo build -p attune-cli
./target/debug/attune --help
```
## Configuration
The CLI stores configuration in `~/.config/attune/config.yaml` (respects `$XDG_CONFIG_HOME`).
### Configuration Structure
```yaml
api_url: http://localhost:8080
auth_token: <jwt-access-token>
refresh_token: <jwt-refresh-token>
output_format: table
```
### Environment Variables
- `ATTUNE_API_URL`: Override the API endpoint
- `XDG_CONFIG_HOME`: Change config directory location
### Global Options
All commands support:
- `--api-url <URL>`: Override API endpoint
- `--output <format>`: Set output format (table, json, yaml)
- `-j, --json`: Output as JSON (shorthand for `--output json`)
- `-y, --yaml`: Output as YAML (shorthand for `--output yaml`)
- `-v, --verbose`: Enable debug logging
## Command Reference
### Authentication
#### Login
```bash
attune auth login --username admin
# Prompts for password securely
```
#### Logout
```bash
attune auth logout
```
#### Check Current User
```bash
attune auth whoami
```
### Pack Management
#### List Packs
```bash
attune pack list
attune pack list --name core
attune pack list --output json # Long form
attune pack list -j # Shorthand for JSON
attune pack list -y # Shorthand for YAML
```
#### Show Pack Details
```bash
attune pack show core
attune pack show 1
```
#### Install Pack
```bash
attune pack install https://github.com/example/pack-example
attune pack install https://github.com/example/pack-example --ref v1.0.0
attune pack install <url> --force
```
#### Register Local Pack
```bash
attune pack register /path/to/pack
```
#### Uninstall Pack
```bash
attune pack uninstall core
attune pack uninstall core --yes
```
### Action Management
#### List Actions
```bash
attune action list
attune action list --pack core
attune action list --name echo
```
#### Show Action Details
```bash
attune action show core.echo
attune action show 1
```
#### Execute Action
```bash
# With key=value parameters
attune action execute core.echo --param message="Hello" --param count=3
# With JSON parameters
attune action execute core.echo --params-json '{"message": "Hello", "count": 5}'
# Wait for completion
attune action execute core.long_task --wait
# Wait with timeout
attune action execute core.long_task --wait --timeout 600
```
### Rule Management
#### List Rules
```bash
attune rule list
attune rule list --pack core
attune rule list --enabled true
```
#### Show Rule Details
```bash
attune rule show core.on_webhook
attune rule show 1
```
#### Enable/Disable Rules
```bash
attune rule enable core.on_webhook
attune rule disable core.on_webhook
```
#### Create Rule
```bash
attune rule create \
--name my_rule \
--pack core \
--trigger core.webhook \
--action core.notify \
--description "Notify on webhook" \
--enabled
# With criteria
attune rule create \
--name filtered_rule \
--pack core \
--trigger core.webhook \
--action core.notify \
--criteria '{"trigger.payload.severity": "critical"}'
```
#### Delete Rule
```bash
attune rule delete core.my_rule
attune rule delete core.my_rule --yes
```
### Execution Monitoring
#### List Executions
```bash
attune execution list
attune execution list --pack core
attune execution list --action core.echo
attune execution list --status succeeded
attune execution list --result "error"
attune execution list --pack monitoring --status failed --result "timeout"
attune execution list --limit 100
```
#### Show Execution Details
```bash
attune execution show 123
```
#### View Logs
```bash
attune execution logs 123
attune execution logs 123 --follow
```
#### Cancel Execution
```bash
attune execution cancel 123
attune execution cancel 123 --yes
```
#### Get Raw Execution Result
```bash
# Get result as JSON (default)
attune execution result 123
# Get result as YAML
attune execution result 123 --format yaml
# Pipe to jq for processing
attune execution result 123 | jq '.data.field'
# Extract specific field
attune execution result 123 | jq -r '.status'
```
### Trigger Management
#### List Triggers
```bash
attune trigger list
attune trigger list --pack core
```
#### Show Trigger Details
```bash
attune trigger show core.webhook
```
### Sensor Management
#### List Sensors
```bash
attune sensor list
attune sensor list --pack core
```
#### Show Sensor Details
```bash
attune sensor show core.file_watcher
```
### Configuration Management
#### List Configuration
```bash
attune config list
```
#### Get Value
```bash
attune config get api_url
```
#### Set Value
```bash
attune config set api_url https://attune.example.com
attune config set output_format json
```
#### Show Config Path
```bash
attune config path
```
## Output Formats
### Table (Default)
Human-readable format with colors and formatting:
```bash
attune pack list
```
Output:
```
╭────┬──────┬─────────┬─────────┬─────────────────╮
│ ID │ Name │ Version │ Enabled │ Description │
├────┼──────┼─────────┼─────────┼─────────────────┤
│ 1 │ core │ 1.0.0 │ ✓ │ Core actions... │
╰────┴──────┴─────────┴─────────┴─────────────────╯
```
### JSON
Machine-readable format for scripting:
```bash
attune pack list --output json # Long form
attune pack list -j # Shorthand
```
Output:
```json
[
{
"id": 1,
"name": "core",
"version": "1.0.0",
"enabled": true,
"description": "Core actions..."
}
]
```
### YAML
Alternative structured format:
```bash
attune pack list --output yaml # Long form
attune pack list -y # Shorthand
```
Output:
```yaml
- id: 1
name: core
version: 1.0.0
enabled: true
description: Core actions...
```
## Scripting Examples
### Bash Script: Deploy Pack
```bash
#!/bin/bash
set -e
PACK_URL="https://github.com/example/monitoring-pack"
PACK_NAME="monitoring"
# Install pack
echo "Installing pack..."
PACK_ID=$(attune pack install "$PACK_URL" -j | jq -r '.id')
# Verify installation
if [ -z "$PACK_ID" ]; then
echo "Pack installation failed"
exit 1
fi
echo "Pack installed: ID=$PACK_ID"
# Enable all rules
attune rule list --pack "$PACK_NAME" -j | \
jq -r '.[].id' | \
xargs -I {} attune rule enable {}
echo "All rules enabled"
```
### Bash Script: Process Execution Results
```bash
#!/bin/bash
# Extract and process execution results
EXECUTION_ID=123
# Get raw result
RESULT=$(attune execution result $EXECUTION_ID)
# Extract specific fields
STATUS=$(echo "$RESULT" | jq -r '.status')
MESSAGE=$(echo "$RESULT" | jq -r '.message')
echo "Status: $STATUS"
echo "Message: $MESSAGE"
# Or pipe directly
attune execution result $EXECUTION_ID | jq -r '.errors[]'
```
### Python Script: Monitor Executions
```python
#!/usr/bin/env python3
import json
import subprocess
import time
def get_executions(status=None, pack=None, result_contains=None, limit=10):
cmd = ["attune", "execution", "list", "-j", f"--limit={limit}"]
if status:
cmd.extend(["--status", status])
if pack:
cmd.extend(["--pack", pack])
if result_contains:
cmd.extend(["--result", result_contains])
result = subprocess.run(cmd, capture_output=True, text=True)
return json.loads(result.stdout)
def main():
print("Monitoring failed executions with errors...")
while True:
# Find failed executions containing "error" in result
failed = get_executions(status="failed", result_contains="error", limit=5)
if failed:
print(f"Found {len(failed)} failed executions:")
for exec in failed:
print(f" - ID {exec['id']}: {exec['action_name']}")
time.sleep(30)
if __name__ == "__main__":
main()
```
## Troubleshooting
### Authentication Issues
**Problem**: "Not logged in" error
**Solution**:
```bash
# Check auth status
attune auth whoami
# Login again
attune auth login --username admin
```
### Connection Issues
**Problem**: Cannot connect to API
**Solution**:
```bash
# Check API URL
attune config get api_url
# Override temporarily
attune --api-url http://localhost:8080 auth whoami
# Update permanently
attune config set api_url http://localhost:8080
```
### Token Expiration
**Problem**: "Invalid token" error
**Solution**:
```bash
# Login again to refresh token
attune auth login --username admin
```
### Verbose Debugging
Enable verbose output to see HTTP requests:
```bash
attune --verbose pack list
```
## Best Practices
### Security
1. **Never hardcode passwords**: Use interactive prompts
2. **Protect config file**: Contains JWT tokens
3. **Use environment variables** for CI/CD: `ATTUNE_API_URL`
### Scripting
1. **Use JSON output** for parsing: `--output json`
2. **Check exit codes**: Non-zero on error
3. **Handle errors**: Use `set -e` in bash scripts
4. **Use jq** for JSON processing
### Performance
1. **Limit results**: Use `--limit` for large lists
2. **Filter server-side**: Use `--pack`, `--action`, `--status`, `--result` filters
3. **Avoid polling**: Use `--wait` for action execution
4. **Use specific filters**: Narrow results with combined filters for faster queries
## Architecture
### Components
```
attune-cli/
├── src/
│ ├── main.rs # Entry point, CLI structure
│ ├── client.rs # HTTP client wrapper
│ ├── config.rs # Config file management
│ ├── output.rs # Output formatting
│ └── commands/ # Command implementations
│ ├── auth.rs
│ ├── pack.rs
│ ├── action.rs
│ ├── rule.rs
│ ├── execution.rs
│ ├── trigger.rs
│ ├── sensor.rs
│ └── config.rs
```
### Key Dependencies
- **clap**: CLI argument parsing
- **reqwest**: HTTP client
- **serde_json/yaml**: Serialization
- **colored**: Terminal colors
- **comfy-table**: Table formatting
- **dialoguer**: Interactive prompts
### API Communication
The CLI communicates with the Attune API using:
- REST endpoints at `/api/v1/*`
- JWT bearer token authentication
- Standard JSON request/response format
## Future Enhancements
Potential future features:
- Shell completion (bash, zsh, fish)
- Interactive TUI mode
- Execution streaming (real-time logs)
- Bulk operations
- Pack development commands
- Workflow visualization
- Config profiles (dev, staging, prod)
## Related Documentation
- [Main README](../README.md)
- [API Documentation](api-overview.md)
- [Pack Development](packs.md)
- [Configuration Guide](configuration.md)