onex-cli 1.0.1
Official CLI for deploying and managing services on OneXERP Platform
Requires Python: >=3.12
Keywords: onexerp platform cli deployment serverless microservices vpn wireguard

# OneXERP Platform CLI (`onex`)

**Official CLI for deploying and managing services on the OneXERP Platform**

[![PyPI version](https://badge.fury.io/py/onex-cli.svg)](https://pypi.org/project/onex-cli/)
[![Python 3.12+](https://img.shields.io/badge/python-3.12+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)

---

## 📋 Table of Contents

- [Overview](#overview)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Commands](#commands)
- [VPN Setup](#vpn-setup)
- [Environment Management](#environment-management)
- [Configuration](#configuration)
- [Development](#development)
- [For Platform Developers](#for-platform-developers)
- [Troubleshooting](#troubleshooting)

---

## Overview

The `onex` CLI provides a unified interface for:

- 🚀 **One-command setup**: VPN + login + .env generation (`onex init`)
- 🔐 **VPN management**: Cross-platform WireGuard VPN setup (Mac, Linux, Windows)
- 📦 **Service deployment**: Deploy to local/dev/staging/prod environments
- 🐛 **Visual debugging**: VS Code debugging with breakpoints (`onex debug`)
- 🔍 **Request tracing**: End-to-end request debugging with trace_id
- 📊 **Monitoring**: View logs, status, and health checks
- ⚡ **Hot reload**: Auto-reload on code changes during development
- 🔧 **Resource management**: Provision MongoDB, Redis, Elasticsearch resources

---

## Installation

### For Service Developers (PyPI)

```bash
# Install from PyPI (recommended)
pip install onex-cli

# Or add to requirements.txt
onex-cli>=1.0.0

# Verify installation
onex --version
```

**That's it!** No platform repository access needed.

### For Platform Developers

```bash
# Install from source (development)
cd onexerp-platform-NEW/onex-cli
pip install -e .
```

---

## Quick Start

### First-Time Setup (2 Steps)

```bash
# Step 1: Install CLI
pip install onex-cli

# Step 2: Initialize environment (VPN + login + .env)
onex init
```

**What `onex init` does:**
1. ✅ Sets up VPN from config file (if you have one)
2. ✅ Logs into platform
3. ✅ Downloads credentials (MongoDB, Redis, JWT secrets)
4. ✅ Auto-generates `.env` file
5. ✅ Verifies connectivity

**You're ready to develop!** 🎉

### Deploy Your First Service

```bash
cd services/demo
onex deploy
```

### Debug Locally with VS Code

```bash
# Start service with debugger
onex debug --service demo

# Output:
# 🐛 VS Code debugging enabled on port 5678
#    Press F5 in VS Code to attach debugger
#
# 📦 Loading service: demo
# ✅ Loaded demo: 7 routes
# 📡 Access at: http://localhost:8001/docs

# Press F5 in VS Code → Set breakpoints → Make request
```

---

## Commands

### Core Commands

```bash
onex init                          # Setup VPN + login + .env (one command!)
onex deploy                        # Deploy service to platform
onex debug --service <name>        # Debug service locally (VS Code ready)
onex trace <trace_id>              # Trace request through platform
onex logs <service> --follow       # Stream service logs
onex status <service>              # Check service health
```

### All Commands

| Command | Description |
|---------|-------------|
| **Setup & Auth** |
| `onex init` | Initialize environment (VPN + login + .env) |
| `onex login` | Login to platform and download credentials |
| `onex logout` | Logout and remove stored credentials |
| **VPN Management** (NEW v1.0.0) |
| `onex vpn setup <file>` | Setup VPN from WireGuard config file |
| `onex vpn connect <env>` | Connect to VPN (dev/staging/prod) |
| `onex vpn disconnect <env>` | Disconnect from VPN |
| `onex vpn status` | Show VPN connection status |
| `onex vpn list` | List all configured VPNs |
| **Environment** |
| `onex env` | Show active environment |
| `onex env list` | List all configured environments |
| `onex env show <env>` | Show environment details |
| `onex env sync` | Regenerate .env file |
| `onex use <env>` | Switch active environment |
| **Development** |
| `onex debug --service <name>` | Debug service locally (VS Code + hot reload) |
| `onex dev` | Run service locally with hot-reload (deprecated, use debug) |
| **Deployment** |
| `onex deploy` | Deploy service to active environment |
| `onex validate` | Validate service.yml schema |
| `onex provision` | Manually provision MongoDB resources |
| **Monitoring** |
| `onex logs <service>` | View service logs |
| `onex status <service>` | Check service status |
| `onex trace <trace_id>` | Debug request flow end-to-end |
| **Invocation** |
| `onex invoke <service>:<fn>` | Invoke function directly |
| **Platform** |
| `onex platform check` | Check platform health |

---

## VPN Setup

**NEW in v1.0.0**: Built-in VPN management for dev/staging/prod access.

### Automatic Setup (Recommended)

```bash
# One command does everything
onex init

# Prompts:
# - Do you have a VPN config file? [Y/n]: y
# - VPN config file path: ~/Downloads/alice-dev.conf
#
# Then automatically:
# ✅ Installs WireGuard (if needed)
# ✅ Imports config
# ✅ Connects to VPN
# ✅ Verifies connectivity
# ✅ Logs into platform
# ✅ Generates .env file
```

### Manual VPN Management

```bash
# Setup VPN from config file
onex vpn setup ~/Downloads/alice-dev.conf

# Connect to VPN
onex vpn connect dev

# Check status
onex vpn status

# Disconnect
onex vpn disconnect dev
```

### Platform-Specific Instructions

**macOS:**
- Uses Homebrew + wg-quick
- Requires sudo for VPN operations

**Linux:**
- Auto-installs WireGuard (Ubuntu/Debian/CentOS/RHEL)
- Uses systemd for VPN management

**Windows:**
- GUI app recommended: https://www.wireguard.com/install/
- Or use manual import in WireGuard app

See service repository's `docs/platform/VPN_SETUP_DEVELOPER.md` for detailed guide.

---

## Environment Management

### Active Environment Concept

The **active environment** determines where commands deploy to:

```bash
# Show active environment
onex env
# ✅ Active environment: local

# Switch to dev
onex use dev
# ✅ Switched to: dev

# Now all commands use dev
onex deploy  # Deploys to dev
onex logs    # Shows dev logs
```

### Available Environments

| Environment | Platform URL | VPN Required | Access |
|------------|--------------|--------------|---------|
| `local` | http://localhost:8000 | No | Full (contact platform team for setup) |
| `dev` | http://10.0.0.1:8000 | Yes | Deploy + Read |
| `staging` | http://10.0.1.1:8000 | Yes | Read only |
| `prod` | http://10.0.2.1:8000 | Yes | Read only |

**Note:** IP addresses are examples and can be customized for your deployment.

### Login to Environment

```bash
# Login to local (no VPN needed)
onex login --env local

# Login to dev (VPN required)
onex vpn connect dev
onex login --env dev
# Prompts for email/password
# ✅ Downloads credentials
# ✅ Generates .env file
```

---

## Configuration

### Credential Storage

Credentials stored securely in `~/.onex/`:

```
~/.onex/
├── environments.json    # Environment credentials (MongoDB, Redis, JWT, etc.)
└── active-env          # Currently active environment
```

**Security:**
- Never commit `.env` files
- Never share `~/.onex/` directory
- Files automatically created with restrictive permissions (600)

### Auto-Generated .env File

When you run `onex login` or `onex init`, a `.env` file is automatically created in your service repository:

```bash
# MongoDB
MONGODB_URI=mongodb://user:pass@host:27017/db?authSource=admin
MONGODB_DATABASE=onexerp

# Redis
REDIS_URI=redis://:password@host:6379/0

# JWT
JWT_SECRET=<auto-downloaded-secret>
JWT_ALGORITHM=HS256

# Platform
PLATFORM_URL=http://10.0.0.1:8000

# Development
DEBUG=true
ENV=dev
```

---

## Development

### Debug Workflow

```bash
# Navigate to service directory
cd services/product

# Start debugging (VS Code ready!)
onex debug --service product

# Output:
# 🐛 VS Code debugging enabled on port 5678
#    Press F5 in VS Code to attach debugger
#
# 📦 Loading service: product
#    ✅ POST   /products                → src.handlers.create_product
#    ✅ GET    /products/{id}           → src.handlers.get_product
#
# ✅ Loaded product: 5 routes
# 📡 Access at: http://localhost:8001/docs

# In VS Code:
# 1. Set breakpoints (click left margin)
# 2. Press F5 → Select "Attach to Runtime"
# 3. Make request: curl http://localhost:8001/products/123
# 4. VS Code pauses at your breakpoints!
```

**Features:**
- ✅ Hot reload on code changes
- ✅ VS Code breakpoint debugging
- ✅ Interactive API docs at /docs
- ✅ Auto-registers routes with platform gateway

### Request Tracing

Every request gets a unique `trace_id`:

```bash
# 1. Make request
curl -D /tmp/headers.txt http://localhost:8001/products/123

# 2. Extract trace_id from response header
grep x-trace-id /tmp/headers.txt
# x-trace-id: 550e8400-e29b-41d4-a716-446655440000

# 3. View complete request timeline
onex trace 550e8400-e29b-41d4-a716-446655440000

# Output shows Gateway → Runtime → Service flow:
# 🔍 Querying trace: 550e8400-e29b-41d4-a716-446655440000
#
# ✅ Found 12 log entries
# ⏱️  Total Duration: 456ms
#
# 📦 GATEWAY
#   14:23:45.123 INFO    POST /products/123
#   14:23:45.145 INFO    Forwarding to product service
#
# 📦 RUNTIME
#   14:23:45.156 INFO    Executing product:get_product
#
# 📦 SERVICE
#   14:23:45.267 INFO    Product found: 123
#   14:23:45.456 INFO    POST /products/123 200 456ms
```

---

## For Platform Developers

**This CLI is maintained by the platform team.**

### Development Setup

```bash
cd onexerp-platform-NEW/onex-cli
pip install -e .

# Make changes to CLI
vim onex/commands/mycommand.py

# Test immediately (editable mode)
onex mycommand
```

### Publishing to PyPI

See [PUBLISHING.md](PUBLISHING.md) for complete guide.

**Quick reference:**

```bash
# 1. Update version and changelog
vim setup.py CHANGELOG.md

# 2. Run verification script
./verify-package.sh

# 3. Build and test on TestPyPI
rm -rf dist/
python -m build
twine upload --repository testpypi dist/*

# 4. Test installation
pip install --index-url https://test.pypi.org/simple/ onex-cli

# 5. Publish to production PyPI
twine upload dist/*

# 6. Tag release
git tag -a v1.0.1 -m "Release 1.0.1"
git push origin v1.0.1
```

### Adding New Commands

1. **Create command file** in `onex/commands/`:

```python
# onex/commands/mycommand.py
import click
from onex.utils import print_success, print_error

@click.command()
@click.option('--env', default='local', help='Environment')
def mycommand(env):
    """Description of new command"""
    print_success("Command completed!")
```

2. **Register in `onex/__main__.py`**:

```python
from onex.commands import mycommand
cli.add_command(mycommand.mycommand)
```

3. **Test**:

```bash
onex mycommand --help
```

### Directory Structure

```
onex-cli/
├── setup.py                 # PyPI package configuration
├── MANIFEST.in             # Package files to include
├── LICENSE                 # MIT License
├── CHANGELOG.md            # Version history
├── PUBLISHING.md           # Publishing guide
├── README.md               # This file
└── onex/
    ├── __init__.py
    ├── __main__.py         # CLI entry point
    ├── config.py           # Configuration management
    ├── utils.py            # Shared utilities
    ├── commands/           # Command implementations
    │   ├── debug.py       # Debug service locally
    │   ├── deploy.py      # Deploy to platform
    │   ├── dev.py         # Development mode (deprecated)
    │   ├── env.py         # Environment management
    │   ├── init.py        # VPN + login + .env setup
    │   ├── invoke.py      # Function invocation
    │   ├── login.py       # Platform authentication
    │   ├── logout.py      # Logout
    │   ├── logs.py        # View service logs
    │   ├── platform.py    # Platform management
    │   ├── provision.py   # Resource provisioning
    │   ├── status.py      # Service health
    │   ├── trace.py       # Request tracing
    │   ├── validate.py    # Schema validation
    │   └── vpn.py         # VPN management (NEW)
    ├── runtime/
    │   └── local_runtime.py  # Local service runtime
    ├── schema/
    │   └── service_descriptor.py  # Service schema
    └── vpn/               # VPN module (NEW)
        ├── __init__.py
        ├── platform_detector.py    # OS/environment detection
        ├── setup_vpn.py           # VPN orchestration
        └── wireguard_manager.py   # WireGuard operations
```

---

## Troubleshooting

### Command not found: onex

```bash
# Reinstall from PyPI
pip install --upgrade onex-cli

# Verify installation
which onex
onex --version
```

### Platform connection failed

```bash
# Check VPN connection
onex vpn status

# Reconnect if needed
onex vpn connect dev

# Verify platform health
onex platform check
```

### VPN setup failed

**macOS:**
```bash
# Install WireGuard via Homebrew
brew install wireguard-tools

# Try setup again
onex vpn setup ~/Downloads/alice-dev.conf
```

**Linux:**
```bash
# Ubuntu/Debian
sudo apt update
sudo apt install wireguard wireguard-tools

# CentOS/RHEL
sudo yum install epel-release
sudo yum install wireguard-tools

# Try setup again
onex vpn setup ~/Downloads/alice-dev.conf
```

**Windows:**
Download WireGuard GUI: https://www.wireguard.com/install/

### "Module not found" errors

```bash
# Reinstall dependencies
pip install --upgrade onex-cli

# Or reinstall everything
pip install -r requirements.txt --upgrade
```

### Deployment failed

```bash
# Validate service.yml first
onex validate

# Check platform health
onex platform check

# View detailed logs
onex logs deployment-controller --follow
```

---

## Version History

See [CHANGELOG.md](CHANGELOG.md) for detailed version history.

**Current Version: 1.0.1**
- ✅ VPN module (cross-platform support)
- ✅ One-command setup (`onex init`)
- ✅ VS Code debugging with debugpy
- ✅ Auto-generated .env files
- ✅ Published to PyPI
- ✅ Comprehensive documentation

---

## Support

### For Service Developers

- **Installation**: `pip install onex-cli`
- **Documentation**: This README + service repo docs
- **Issues**: Contact platform team

### For Platform Developers

- **Development**: Install from source (`pip install -e .`)
- **Publishing**: See [PUBLISHING.md](PUBLISHING.md)
- **Issues**: GitHub issues in platform repository

---

## Related Documentation

**Service Developers:**
- [Developer Guide](https://github.com/onexerp/onexerp-services/blob/main/DEVELOPER_GUIDE.md)
- [VPN Setup Guide](https://github.com/onexerp/onexerp-services/blob/main/docs/platform/VPN_SETUP_DEVELOPER.md)
- [Quick Start](https://github.com/onexerp/onexerp-services/blob/main/README.md#quick-start)

**Platform Developers:**
- [Publishing Guide](PUBLISHING.md)
- [Changelog](CHANGELOG.md)
- [Platform Architecture](../docs/ARCHITECTURE.md)

---

## License

MIT License - See [LICENSE](LICENSE) file.

---

## Links

- **PyPI**: https://pypi.org/project/onex-cli/
- **GitHub**: https://github.com/onexerp/onex-cli
- **Issues**: https://github.com/onexerp/onex-cli/issues

---

**Maintained by**: OneXERP Platform Team
**Used by**: Service Developers (no platform repo access needed!)
**Version**: 1.0.1