chore(cleanup): remove obsolete scripts and update paths for production deployment
- Remove dev/scripts/check-file-organization.sh (obsolete organization checker) - Remove dev/scripts/community_onboarding.py (unused 559-line automation script) - Update gpu_miner_host.py log path from /home/oib/windsurf/aitbc to /opt/aitbc - Add service status and standardization badges to README.md
This commit is contained in:
126
dev/scripts/development/aitbc-cli.sh
Executable file
126
dev/scripts/development/aitbc-cli.sh
Executable file
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
CLI_PY="$ROOT_DIR/cli/client.py"
|
||||
|
||||
AITBC_URL="${AITBC_URL:-http://localhost:8000}"
|
||||
CLIENT_KEY="${CLIENT_KEY:?Set CLIENT_KEY env var}"
|
||||
ADMIN_KEY="${ADMIN_KEY:?Set ADMIN_KEY env var}"
|
||||
MINER_KEY="${MINER_KEY:?Set MINER_KEY env var}"
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
AITBC CLI wrapper
|
||||
|
||||
Usage:
|
||||
aitbc-cli.sh submit <type> [--prompt TEXT] [--model NAME] [--ttl SECONDS]
|
||||
aitbc-cli.sh status <job_id>
|
||||
aitbc-cli.sh browser [--block-limit N] [--tx-limit N] [--receipt-limit N] [--job-id ID]
|
||||
aitbc-cli.sh blocks [--limit N]
|
||||
aitbc-cli.sh receipts [--limit N] [--job-id ID]
|
||||
aitbc-cli.sh cancel <job_id>
|
||||
aitbc-cli.sh admin-miners
|
||||
aitbc-cli.sh admin-jobs
|
||||
aitbc-cli.sh admin-stats
|
||||
aitbc-cli.sh admin-cancel-running
|
||||
aitbc-cli.sh health
|
||||
|
||||
Environment overrides:
|
||||
AITBC_URL (default: http://localhost:8000)
|
||||
CLIENT_KEY (required)
|
||||
ADMIN_KEY (required)
|
||||
MINER_KEY (required)
|
||||
EOF
|
||||
}
|
||||
|
||||
if [[ $# -lt 1 ]]; then
|
||||
usage
|
||||
exit 1
|
||||
fi
|
||||
|
||||
cmd="$1"
|
||||
shift
|
||||
|
||||
case "$cmd" in
|
||||
submit)
|
||||
python3 "$CLI_PY" --url "$AITBC_URL" --api-key "$CLIENT_KEY" submit "$@"
|
||||
;;
|
||||
status)
|
||||
python3 "$CLI_PY" --url "$AITBC_URL" --api-key "$CLIENT_KEY" status "$@"
|
||||
;;
|
||||
browser)
|
||||
python3 "$CLI_PY" --url "$AITBC_URL" --api-key "$CLIENT_KEY" browser "$@"
|
||||
;;
|
||||
blocks)
|
||||
python3 "$CLI_PY" --url "$AITBC_URL" --api-key "$CLIENT_KEY" blocks "$@"
|
||||
;;
|
||||
receipts)
|
||||
limit=10
|
||||
job_id=""
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--limit)
|
||||
limit="$2"
|
||||
shift 2
|
||||
;;
|
||||
--job-id)
|
||||
job_id="$2"
|
||||
shift 2
|
||||
;;
|
||||
*)
|
||||
echo "Unknown option: $1" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
if [[ -n "$job_id" ]]; then
|
||||
curl -sS "$AITBC_URL/v1/explorer/receipts?limit=${limit}&job_id=${job_id}"
|
||||
else
|
||||
curl -sS "$AITBC_URL/v1/explorer/receipts?limit=${limit}"
|
||||
fi
|
||||
;;
|
||||
cancel)
|
||||
if [[ $# -lt 1 ]]; then
|
||||
echo "Usage: aitbc-cli.sh cancel <job_id>" >&2
|
||||
exit 1
|
||||
fi
|
||||
job_id="$1"
|
||||
curl -sS -X POST -H "X-Api-Key: ${CLIENT_KEY}" "$AITBC_URL/v1/jobs/${job_id}/cancel"
|
||||
;;
|
||||
admin-miners)
|
||||
curl -sS -H "X-Api-Key: ${ADMIN_KEY}" "$AITBC_URL/v1/admin/miners"
|
||||
;;
|
||||
admin-jobs)
|
||||
curl -sS -H "X-Api-Key: ${ADMIN_KEY}" "$AITBC_URL/v1/admin/jobs"
|
||||
;;
|
||||
admin-stats)
|
||||
curl -sS -H "X-Api-Key: ${ADMIN_KEY}" "$AITBC_URL/v1/admin/stats"
|
||||
;;
|
||||
admin-cancel-running)
|
||||
echo "Fetching running jobs..."
|
||||
running_jobs=$(curl -sS -H "X-Api-Key: ${ADMIN_KEY}" "$AITBC_URL/v1/admin/jobs" | jq -r '.[] | select(.state == "running") | .id')
|
||||
if [[ -z "$running_jobs" ]]; then
|
||||
echo "No running jobs found."
|
||||
else
|
||||
count=0
|
||||
for job_id in $running_jobs; do
|
||||
echo "Cancelling job: $job_id"
|
||||
curl -sS -X POST -H "X-Api-Key: ${CLIENT_KEY}" "$AITBC_URL/v1/jobs/${job_id}/cancel" > /dev/null
|
||||
((count++))
|
||||
done
|
||||
echo "Cancelled $count running jobs."
|
||||
fi
|
||||
;;
|
||||
health)
|
||||
curl -sS "$AITBC_URL/v1/health"
|
||||
;;
|
||||
help|-h|--help)
|
||||
usage
|
||||
;;
|
||||
*)
|
||||
echo "Unknown command: $cmd" >&2
|
||||
usage
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
17
dev/scripts/development/aitbc-pythonpath.pth
Normal file
17
dev/scripts/development/aitbc-pythonpath.pth
Normal file
@@ -0,0 +1,17 @@
|
||||
# Add project paths to Python path for imports
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Get the directory where this .pth file is located
|
||||
project_root = Path(__file__).parent
|
||||
|
||||
# Add package source directories
|
||||
sys.path.insert(0, str(project_root / "packages" / "py" / "aitbc-core" / "src"))
|
||||
sys.path.insert(0, str(project_root / "packages" / "py" / "aitbc-crypto" / "src"))
|
||||
sys.path.insert(0, str(project_root / "packages" / "py" / "aitbc-p2p" / "src"))
|
||||
sys.path.insert(0, str(project_root / "packages" / "py" / "aitbc-sdk" / "src"))
|
||||
|
||||
# Add app source directories
|
||||
sys.path.insert(0, str(project_root / "apps" / "coordinator-api" / "src"))
|
||||
sys.path.insert(0, str(project_root / "apps" / "wallet-daemon" / "src"))
|
||||
sys.path.insert(0, str(project_root / "apps" / "blockchain-node" / "src"))
|
||||
151
dev/scripts/development/exchange-router-fixed.py
Normal file
151
dev/scripts/development/exchange-router-fixed.py
Normal file
@@ -0,0 +1,151 @@
|
||||
"""
|
||||
Bitcoin Exchange Router for AITBC
|
||||
"""
|
||||
|
||||
from typing import Dict, Any
|
||||
from fastapi import APIRouter, HTTPException, BackgroundTasks
|
||||
from sqlmodel import Session
|
||||
import uuid
|
||||
import time
|
||||
import json
|
||||
import os
|
||||
|
||||
from ..deps import require_admin_key, require_client_key
|
||||
from ..domain import Wallet
|
||||
from ..schemas import ExchangePaymentRequest, ExchangePaymentResponse
|
||||
|
||||
router = APIRouter(tags=["exchange"])
|
||||
|
||||
# In-memory storage for demo (use database in production)
|
||||
payments: Dict[str, Dict] = {}
|
||||
|
||||
# Bitcoin configuration
|
||||
BITCOIN_CONFIG = {
|
||||
'testnet': True,
|
||||
'main_address': 'tb1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh', # Testnet address
|
||||
'exchange_rate': 100000, # 1 BTC = 100,000 AITBC
|
||||
'min_confirmations': 1,
|
||||
'payment_timeout': 3600 # 1 hour
|
||||
}
|
||||
|
||||
@router.post("/exchange/create-payment", response_model=ExchangePaymentResponse)
|
||||
async def create_payment(
|
||||
request: ExchangePaymentRequest,
|
||||
background_tasks: BackgroundTasks,
|
||||
api_key: str = require_client_key()
|
||||
) -> Dict[str, Any]:
|
||||
"""Create a new Bitcoin payment request"""
|
||||
|
||||
# Validate request
|
||||
if request.aitbc_amount <= 0 or request.btc_amount <= 0:
|
||||
raise HTTPException(status_code=400, detail="Invalid amount")
|
||||
|
||||
# Calculate expected BTC amount
|
||||
expected_btc = request.aitbc_amount / BITCOIN_CONFIG['exchange_rate']
|
||||
|
||||
# Allow small difference for rounding
|
||||
if abs(request.btc_amount - expected_btc) > 0.00000001:
|
||||
raise HTTPException(status_code=400, detail="Amount mismatch")
|
||||
|
||||
# Create payment record
|
||||
payment_id = str(uuid.uuid4())
|
||||
payment = {
|
||||
'payment_id': payment_id,
|
||||
'user_id': request.user_id,
|
||||
'aitbc_amount': request.aitbc_amount,
|
||||
'btc_amount': request.btc_amount,
|
||||
'payment_address': BITCOIN_CONFIG['main_address'],
|
||||
'status': 'pending',
|
||||
'created_at': int(time.time()),
|
||||
'expires_at': int(time.time()) + BITCOIN_CONFIG['payment_timeout'],
|
||||
'confirmations': 0,
|
||||
'tx_hash': None
|
||||
}
|
||||
|
||||
# Store payment
|
||||
payments[payment_id] = payment
|
||||
|
||||
# Start payment monitoring in background
|
||||
background_tasks.add_task(monitor_payment, payment_id)
|
||||
|
||||
return payment
|
||||
|
||||
@router.get("/exchange/payment-status/{payment_id}")
|
||||
async def get_payment_status(payment_id: str) -> Dict[str, Any]:
|
||||
"""Get payment status"""
|
||||
|
||||
if payment_id not in payments:
|
||||
raise HTTPException(status_code=404, detail="Payment not found")
|
||||
|
||||
payment = payments[payment_id]
|
||||
|
||||
# Check if expired
|
||||
if payment['status'] == 'pending' and time.time() > payment['expires_at']:
|
||||
payment['status'] = 'expired'
|
||||
|
||||
return payment
|
||||
|
||||
@router.post("/exchange/confirm-payment/{payment_id}")
|
||||
async def confirm_payment(
|
||||
payment_id: str,
|
||||
tx_hash: str,
|
||||
api_key: str = require_admin_key()
|
||||
) -> Dict[str, Any]:
|
||||
"""Confirm payment (webhook from payment processor)"""
|
||||
|
||||
if payment_id not in payments:
|
||||
raise HTTPException(status_code=404, detail="Payment not found")
|
||||
|
||||
payment = payments[payment_id]
|
||||
|
||||
if payment['status'] != 'pending':
|
||||
raise HTTPException(status_code=400, detail="Payment not in pending state")
|
||||
|
||||
# Verify transaction (in production, verify with blockchain API)
|
||||
# For demo, we'll accept any tx_hash
|
||||
|
||||
payment['status'] = 'confirmed'
|
||||
payment['tx_hash'] = tx_hash
|
||||
payment['confirmed_at'] = int(time.time())
|
||||
|
||||
# Mint AITBC tokens to user's wallet
|
||||
try:
|
||||
from ..services.blockchain import mint_tokens
|
||||
await mint_tokens(payment['user_id'], payment['aitbc_amount'])
|
||||
except Exception as e:
|
||||
print(f"Error minting tokens: {e}")
|
||||
# In production, handle this error properly
|
||||
|
||||
return {
|
||||
'status': 'ok',
|
||||
'payment_id': payment_id,
|
||||
'aitbc_amount': payment['aitbc_amount']
|
||||
}
|
||||
|
||||
@router.get("/exchange/rates")
|
||||
async def get_exchange_rates() -> Dict[str, float]:
|
||||
"""Get current exchange rates"""
|
||||
|
||||
return {
|
||||
'btc_to_aitbc': BITCOIN_CONFIG['exchange_rate'],
|
||||
'aitbc_to_btc': 1.0 / BITCOIN_CONFIG['exchange_rate'],
|
||||
'fee_percent': 0.5
|
||||
}
|
||||
|
||||
async def monitor_payment(payment_id: str):
|
||||
"""Monitor payment for confirmation (background task)"""
|
||||
|
||||
import asyncio
|
||||
|
||||
while payment_id in payments:
|
||||
payment = payments[payment_id]
|
||||
|
||||
# Check if expired
|
||||
if payment['status'] == 'pending' and time.time() > payment['expires_at']:
|
||||
payment['status'] = 'expired'
|
||||
break
|
||||
|
||||
# In production, check blockchain for payment
|
||||
# For demo, we'll wait for manual confirmation
|
||||
|
||||
await asyncio.sleep(30) # Check every 30 seconds
|
||||
99
dev/scripts/development/generate_openapi.py
Executable file
99
dev/scripts/development/generate_openapi.py
Executable file
@@ -0,0 +1,99 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Generate OpenAPI specifications from FastAPI services
|
||||
"""
|
||||
|
||||
import json
|
||||
import sys
|
||||
import subprocess
|
||||
import requests
|
||||
from pathlib import Path
|
||||
|
||||
def extract_openapi_spec(service_name: str, base_url: str, output_file: str):
|
||||
"""Extract OpenAPI spec from a running FastAPI service"""
|
||||
try:
|
||||
# Get OpenAPI spec from the service
|
||||
response = requests.get(f"{base_url}/openapi.json")
|
||||
response.raise_for_status()
|
||||
|
||||
spec = response.json()
|
||||
|
||||
# Add service-specific metadata
|
||||
spec["info"]["title"] = f"AITBC {service_name} API"
|
||||
spec["info"]["description"] = f"OpenAPI specification for AITBC {service_name} service"
|
||||
spec["info"]["version"] = "1.0.0"
|
||||
|
||||
# Add servers configuration
|
||||
spec["servers"] = [
|
||||
{
|
||||
"url": "https://aitbc.bubuit.net/api",
|
||||
"description": "Production server"
|
||||
},
|
||||
{
|
||||
"url": "https://staging-api.aitbc.io",
|
||||
"description": "Staging server"
|
||||
},
|
||||
{
|
||||
"url": "http://localhost:8011",
|
||||
"description": "Development server"
|
||||
}
|
||||
]
|
||||
|
||||
# Save the spec
|
||||
output_path = Path(output_file)
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
with open(output_path, 'w') as f:
|
||||
json.dump(spec, f, indent=2)
|
||||
|
||||
print(f"✓ Generated {service_name} OpenAPI spec: {output_file}")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Failed to generate {service_name} spec: {e}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
"""Generate OpenAPI specs for all AITBC services"""
|
||||
services = [
|
||||
{
|
||||
"name": "Coordinator API",
|
||||
"base_url": "http://127.0.0.2:8011",
|
||||
"output": "api/coordinator/openapi.json"
|
||||
},
|
||||
{
|
||||
"name": "Blockchain Node API",
|
||||
"base_url": "http://127.0.0.2:8080",
|
||||
"output": "api/blockchain/openapi.json"
|
||||
},
|
||||
{
|
||||
"name": "Wallet Daemon API",
|
||||
"base_url": "http://127.0.0.2:8071",
|
||||
"output": "api/wallet/openapi.json"
|
||||
}
|
||||
]
|
||||
|
||||
print("Generating OpenAPI specifications...")
|
||||
|
||||
all_success = True
|
||||
for service in services:
|
||||
success = extract_openapi_spec(
|
||||
service["name"],
|
||||
service["base_url"],
|
||||
service["output"]
|
||||
)
|
||||
if not success:
|
||||
all_success = False
|
||||
|
||||
if all_success:
|
||||
print("\n✓ All OpenAPI specifications generated successfully!")
|
||||
print("\nNext steps:")
|
||||
print("1. Review the generated specs")
|
||||
print("2. Commit them to the documentation repository")
|
||||
print("3. Update the API reference documentation")
|
||||
else:
|
||||
print("\n✗ Some specifications failed to generate")
|
||||
sys.exit(1)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
135
dev/scripts/development/local-domain-proxy.py
Executable file
135
dev/scripts/development/local-domain-proxy.py
Executable file
@@ -0,0 +1,135 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Local proxy to simulate domain routing for development
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import time
|
||||
import os
|
||||
import signal
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Configuration
|
||||
DOMAIN = "aitbc.bubuit.net"
|
||||
SERVICES = {
|
||||
"api": {"port": 8000, "path": "/v1"},
|
||||
"rpc": {"port": 9080, "path": "/rpc"},
|
||||
"marketplace": {"port": 3001, "path": "/"},
|
||||
"exchange": {"port": 3002, "path": "/"},
|
||||
}
|
||||
|
||||
def start_services():
|
||||
"""Start all AITBC services"""
|
||||
print("🚀 Starting AITBC Services")
|
||||
print("=" * 40)
|
||||
|
||||
# Change to project directory
|
||||
os.chdir("/home/oib/windsurf/aitbc")
|
||||
|
||||
processes = {}
|
||||
|
||||
# Start Coordinator API
|
||||
print("\n1. Starting Coordinator API...")
|
||||
api_proc = subprocess.Popen([
|
||||
"python", "-m", "uvicorn",
|
||||
"src.app.main:app",
|
||||
"--host", "127.0.0.1",
|
||||
"--port", "8000"
|
||||
], cwd="apps/coordinator-api")
|
||||
processes["api"] = api_proc
|
||||
print(f" PID: {api_proc.pid}")
|
||||
|
||||
# Start Blockchain Node (if not running)
|
||||
print("\n2. Checking Blockchain Node...")
|
||||
result = subprocess.run(["lsof", "-i", ":9080"], capture_output=True)
|
||||
if not result.stdout:
|
||||
print(" Starting Blockchain Node...")
|
||||
node_proc = subprocess.Popen([
|
||||
"python", "-m", "uvicorn",
|
||||
"aitbc_chain.app:app",
|
||||
"--host", "127.0.0.1",
|
||||
"--port", "9080"
|
||||
], cwd="apps/blockchain-node")
|
||||
processes["blockchain"] = node_proc
|
||||
print(f" PID: {node_proc.pid}")
|
||||
else:
|
||||
print(" ✅ Already running")
|
||||
|
||||
# Start Marketplace UI
|
||||
print("\n3. Starting Marketplace UI...")
|
||||
market_proc = subprocess.Popen([
|
||||
"python", "server.py",
|
||||
"--port", "3001"
|
||||
], cwd="apps/marketplace-ui")
|
||||
processes["marketplace"] = market_proc
|
||||
print(f" PID: {market_proc.pid}")
|
||||
|
||||
# Start Trade Exchange
|
||||
print("\n4. Starting Trade Exchange...")
|
||||
exchange_proc = subprocess.Popen([
|
||||
"python", "server.py",
|
||||
"--port", "3002"
|
||||
], cwd="apps/trade-exchange")
|
||||
processes["exchange"] = exchange_proc
|
||||
print(f" PID: {exchange_proc.pid}")
|
||||
|
||||
# Wait for services to start
|
||||
print("\n⏳ Waiting for services to start...")
|
||||
time.sleep(5)
|
||||
|
||||
# Test endpoints
|
||||
print("\n🧪 Testing Services:")
|
||||
test_endpoints()
|
||||
|
||||
print("\n✅ All services started!")
|
||||
print("\n📋 Local URLs:")
|
||||
print(f" API: http://127.0.0.1:8000/v1")
|
||||
print(f" RPC: http://127.0.0.1:9080/rpc")
|
||||
print(f" Marketplace: http://127.0.0.1:3001")
|
||||
print(f" Exchange: http://127.0.0.1:3002")
|
||||
|
||||
print("\n🌐 Domain URLs (when proxied):")
|
||||
print(f" API: https://{DOMAIN}/api")
|
||||
print(f" RPC: https://{DOMAIN}/rpc")
|
||||
print(f" Marketplace: https://{DOMAIN}/Marketplace")
|
||||
print(f" Exchange: https://{DOMAIN}/Exchange")
|
||||
print(f" Admin: https://{DOMAIN}/admin")
|
||||
|
||||
print("\n🛑 Press Ctrl+C to stop all services")
|
||||
|
||||
try:
|
||||
# Keep running
|
||||
while True:
|
||||
time.sleep(1)
|
||||
except KeyboardInterrupt:
|
||||
print("\n\n🛑 Stopping services...")
|
||||
for name, proc in processes.items():
|
||||
print(f" Stopping {name}...")
|
||||
proc.terminate()
|
||||
proc.wait()
|
||||
print("✅ All services stopped!")
|
||||
|
||||
def test_endpoints():
|
||||
"""Test if services are responding"""
|
||||
import requests
|
||||
|
||||
endpoints = [
|
||||
("API Health", "http://127.0.0.1:8000/v1/health"),
|
||||
("Admin Stats", "http://127.0.0.1:8000/v1/admin/stats"),
|
||||
("Marketplace", "http://127.0.0.1:3001"),
|
||||
("Exchange", "http://127.0.0.1:3002"),
|
||||
]
|
||||
|
||||
for name, url in endpoints:
|
||||
try:
|
||||
if "admin" in url:
|
||||
response = requests.get(url, headers={"X-Api-Key": "${ADMIN_API_KEY}"}, timeout=2)
|
||||
else:
|
||||
response = requests.get(url, timeout=2)
|
||||
print(f" {name}: ✅ {response.status_code}")
|
||||
except Exception as e:
|
||||
print(f" {name}: ❌ {str(e)[:50]}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
start_services()
|
||||
177
dev/scripts/system/dev_services.sh
Executable file
177
dev/scripts/system/dev_services.sh
Executable file
@@ -0,0 +1,177 @@
|
||||
#!/bin/bash
|
||||
|
||||
# AITBC Development Services Manager
|
||||
# Starts AITBC services for development and provides cleanup option
|
||||
|
||||
set -e
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
|
||||
LOG_DIR="$PROJECT_ROOT/logs"
|
||||
PID_FILE="$PROJECT_ROOT/.aitbc_dev_pids"
|
||||
|
||||
# Create logs directory if it doesn't exist
|
||||
mkdir -p "$LOG_DIR"
|
||||
|
||||
# Color codes for output
|
||||
RED='\033[0;31m'
|
||||
GREEN='\033[0;32m'
|
||||
YELLOW='\033[1;33m'
|
||||
BLUE='\033[0;34m'
|
||||
NC='\033[0m' # No Color
|
||||
|
||||
# Services to manage
|
||||
SERVICES=(
|
||||
"aitbc-blockchain-node.service"
|
||||
"aitbc-blockchain-rpc.service"
|
||||
"aitbc-gpu-miner.service"
|
||||
"aitbc-mock-coordinator.service"
|
||||
)
|
||||
|
||||
start_services() {
|
||||
echo -e "${BLUE}Starting AITBC development services...${NC}"
|
||||
|
||||
# Check if services are already running
|
||||
for service in "${SERVICES[@]}"; do
|
||||
if systemctl is-active --quiet "$service"; then
|
||||
echo -e "${YELLOW}Warning: $service is already running${NC}"
|
||||
fi
|
||||
done
|
||||
|
||||
# Start all services
|
||||
for service in "${SERVICES[@]}"; do
|
||||
echo -e "Starting $service..."
|
||||
sudo systemctl start "$service"
|
||||
|
||||
# Wait a moment and check if it started successfully
|
||||
sleep 2
|
||||
if systemctl is-active --quiet "$service"; then
|
||||
echo -e "${GREEN}✓ $service started successfully${NC}"
|
||||
echo "$service" >> "$PID_FILE"
|
||||
else
|
||||
echo -e "${RED}✗ Failed to start $service${NC}"
|
||||
echo -e "${RED}Check logs: sudo journalctl -u $service${NC}"
|
||||
fi
|
||||
done
|
||||
|
||||
echo -e "\n${GREEN}AITBC services started!${NC}"
|
||||
echo -e "Use '$0 stop' to stop all services"
|
||||
echo -e "Use '$0 status' to check service status"
|
||||
}
|
||||
|
||||
stop_services() {
|
||||
echo -e "${BLUE}Stopping AITBC development services...${NC}"
|
||||
|
||||
for service in "${SERVICES[@]}"; do
|
||||
if systemctl is-active --quiet "$service"; then
|
||||
echo -e "Stopping $service..."
|
||||
sudo systemctl stop "$service"
|
||||
echo -e "${GREEN}✓ $service stopped${NC}"
|
||||
else
|
||||
echo -e "${YELLOW}$service was not running${NC}"
|
||||
fi
|
||||
done
|
||||
|
||||
# Clean up PID file
|
||||
rm -f "$PID_FILE"
|
||||
echo -e "\n${GREEN}All AITBC services stopped${NC}"
|
||||
}
|
||||
|
||||
show_status() {
|
||||
echo -e "${BLUE}AITBC Service Status:${NC}\n"
|
||||
|
||||
for service in "${SERVICES[@]}"; do
|
||||
if systemctl is-active --quiet "$service"; then
|
||||
echo -e "${GREEN}● $service: RUNNING${NC}"
|
||||
# Show uptime
|
||||
uptime=$(systemctl show "$service" --property=ActiveEnterTimestamp --value)
|
||||
echo -e " Running since: $uptime"
|
||||
else
|
||||
echo -e "${RED}● $service: STOPPED${NC}"
|
||||
fi
|
||||
done
|
||||
|
||||
# Show recent logs if any services are running
|
||||
echo -e "\n${BLUE}Recent logs (last 10 lines each):${NC}"
|
||||
for service in "${SERVICES[@]}"; do
|
||||
if systemctl is-active --quiet "$service"; then
|
||||
echo -e "\n${YELLOW}--- $service ---${NC}"
|
||||
sudo journalctl -u "$service" -n 5 --no-pager | tail -n 5
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
show_logs() {
|
||||
local service="$1"
|
||||
if [ -z "$service" ]; then
|
||||
echo -e "${BLUE}Following logs for all AITBC services...${NC}"
|
||||
sudo journalctl -f -u aitbc-blockchain-node.service -u aitbc-blockchain-rpc.service -u aitbc-gpu-miner.service -u aitbc-mock-coordinator.service
|
||||
else
|
||||
echo -e "${BLUE}Following logs for $service...${NC}"
|
||||
sudo journalctl -f -u "$service"
|
||||
fi
|
||||
}
|
||||
|
||||
restart_services() {
|
||||
echo -e "${BLUE}Restarting AITBC services...${NC}"
|
||||
stop_services
|
||||
sleep 3
|
||||
start_services
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
echo -e "${BLUE}Performing cleanup...${NC}"
|
||||
stop_services
|
||||
|
||||
# Additional cleanup
|
||||
echo -e "Cleaning up temporary files..."
|
||||
rm -f "$PROJECT_ROOT/.aitbc_dev_pids"
|
||||
|
||||
# Clear any lingering processes (optional)
|
||||
echo -e "Checking for lingering processes..."
|
||||
pkill -f "aitbc" || echo "No lingering processes found"
|
||||
|
||||
echo -e "${GREEN}Cleanup complete${NC}"
|
||||
}
|
||||
|
||||
# Handle script interruption for Ctrl+C only
|
||||
trap cleanup INT
|
||||
|
||||
# Main script logic
|
||||
case "$1" in
|
||||
start)
|
||||
start_services
|
||||
;;
|
||||
stop)
|
||||
stop_services
|
||||
;;
|
||||
restart)
|
||||
restart_services
|
||||
;;
|
||||
status)
|
||||
show_status
|
||||
;;
|
||||
logs)
|
||||
show_logs "$2"
|
||||
;;
|
||||
cleanup)
|
||||
cleanup
|
||||
;;
|
||||
*)
|
||||
echo -e "${BLUE}AITBC Development Services Manager${NC}"
|
||||
echo -e "\nUsage: $0 {start|stop|restart|status|logs|cleanup}"
|
||||
echo -e "\nCommands:"
|
||||
echo -e " start - Start all AITBC services"
|
||||
echo -e " stop - Stop all AITBC services"
|
||||
echo -e " restart - Restart all AITBC services"
|
||||
echo -e " status - Show service status"
|
||||
echo -e " logs - Follow logs (optional: specify service name)"
|
||||
echo -e " cleanup - Stop services and clean up"
|
||||
echo -e "\nExamples:"
|
||||
echo -e " $0 start # Start all services"
|
||||
echo -e " $0 logs # Follow all logs"
|
||||
echo -e " $0 logs node # Follow node logs only"
|
||||
echo -e " $0 stop # Stop all services"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
98
dev/scripts/system/manage_services.sh
Executable file
98
dev/scripts/system/manage_services.sh
Executable file
@@ -0,0 +1,98 @@
|
||||
#!/bin/bash
|
||||
|
||||
# AITBC Service Management Script
|
||||
|
||||
case "$1" in
|
||||
status)
|
||||
echo "=== AITBC Service Status ==="
|
||||
for service in aitbc-coordinator-api aitbc-exchange-api aitbc-exchange-frontend aitbc-wallet aitbc-node; do
|
||||
status=$(sudo systemctl is-active $service 2>/dev/null || echo "inactive")
|
||||
enabled=$(sudo systemctl is-enabled $service 2>/dev/null || echo "disabled")
|
||||
echo "$service: $status ($enabled)"
|
||||
done
|
||||
;;
|
||||
|
||||
start)
|
||||
echo "Starting AITBC services..."
|
||||
sudo systemctl start aitbc-coordinator-api
|
||||
sudo systemctl start aitbc-exchange-api
|
||||
sudo systemctl start aitbc-exchange-frontend
|
||||
sudo systemctl start aitbc-wallet
|
||||
sudo systemctl start aitbc-node
|
||||
echo "Done!"
|
||||
;;
|
||||
|
||||
stop)
|
||||
echo "Stopping AITBC services..."
|
||||
sudo systemctl stop aitbc-coordinator-api
|
||||
sudo systemctl stop aitbc-exchange-api
|
||||
sudo systemctl stop aitbc-exchange-frontend
|
||||
sudo systemctl stop aitbc-wallet
|
||||
sudo systemctl stop aitbc-node
|
||||
echo "Done!"
|
||||
;;
|
||||
|
||||
restart)
|
||||
echo "Restarting AITBC services..."
|
||||
sudo systemctl restart aitbc-coordinator-api
|
||||
sudo systemctl restart aitbc-exchange-api
|
||||
sudo systemctl restart aitbc-exchange-frontend
|
||||
sudo systemctl restart aitbc-wallet
|
||||
sudo systemctl restart aitbc-node
|
||||
echo "Done!"
|
||||
;;
|
||||
|
||||
logs)
|
||||
if [ -z "$2" ]; then
|
||||
echo "Usage: $0 logs <service-name>"
|
||||
echo "Available services: coordinator-api, exchange-api, exchange-frontend, wallet, node"
|
||||
exit 1
|
||||
fi
|
||||
case "$2" in
|
||||
coordinator-api) sudo journalctl -u aitbc-coordinator-api -f ;;
|
||||
exchange-api) sudo journalctl -u aitbc-exchange-api -f ;;
|
||||
exchange-frontend) sudo journalctl -u aitbc-exchange-frontend -f ;;
|
||||
wallet) sudo journalctl -u aitbc-wallet -f ;;
|
||||
node) sudo journalctl -u aitbc-node -f ;;
|
||||
*) echo "Unknown service: $2" ;;
|
||||
esac
|
||||
;;
|
||||
|
||||
enable)
|
||||
echo "Enabling AITBC services to start on boot..."
|
||||
sudo systemctl enable aitbc-coordinator-api
|
||||
sudo systemctl enable aitbc-exchange-api
|
||||
sudo systemctl enable aitbc-exchange-frontend
|
||||
sudo systemctl enable aitbc-wallet
|
||||
sudo systemctl enable aitbc-node
|
||||
echo "Done!"
|
||||
;;
|
||||
|
||||
disable)
|
||||
echo "Disabling AITBC services from starting on boot..."
|
||||
sudo systemctl disable aitbc-coordinator-api
|
||||
sudo systemctl disable aitbc-exchange-api
|
||||
sudo systemctl disable aitbc-exchange-frontend
|
||||
sudo systemctl disable aitbc-wallet
|
||||
sudo systemctl disable aitbc-node
|
||||
echo "Done!"
|
||||
;;
|
||||
|
||||
*)
|
||||
echo "Usage: $0 {status|start|stop|restart|logs|enable|disable}"
|
||||
echo ""
|
||||
echo "Commands:"
|
||||
echo " status - Show status of all AITBC services"
|
||||
echo " start - Start all AITBC services"
|
||||
echo " stop - Stop all AITBC services"
|
||||
echo " restart - Restart all AITBC services"
|
||||
echo " logs - View logs for a specific service"
|
||||
echo " enable - Enable services to start on boot"
|
||||
echo " disable - Disable services from starting on boot"
|
||||
echo ""
|
||||
echo "Examples:"
|
||||
echo " $0 status"
|
||||
echo " $0 logs exchange-api"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
70
dev/scripts/system/setup_systemd.sh
Executable file
70
dev/scripts/system/setup_systemd.sh
Executable file
@@ -0,0 +1,70 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Setup AITBC Systemd Services
|
||||
# Requirements: Python 3.11+, systemd, sudo access
|
||||
|
||||
echo "🔧 Setting up AITBC systemd services..."
|
||||
|
||||
# Validate Python version
|
||||
echo "🐍 Checking Python version..."
|
||||
if ! python3.11 --version >/dev/null 2>&1; then
|
||||
echo "❌ Error: Python 3.11+ is required but not found"
|
||||
echo " Please install Python 3.11+ and try again"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
PYTHON_VERSION=$(python3.11 --version | cut -d' ' -f2)
|
||||
echo "✅ Found Python $PYTHON_VERSION"
|
||||
|
||||
# Validate systemctl is available
|
||||
if ! command -v systemctl >/dev/null 2>&1; then
|
||||
echo "❌ Error: systemctl not found. This script requires systemd."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "✅ Systemd available"
|
||||
|
||||
# Copy service files
|
||||
echo "📁 Copying service files..."
|
||||
sudo cp systemd/aitbc-*.service /etc/systemd/system/
|
||||
|
||||
# Reload systemd daemon
|
||||
echo "🔄 Reloading systemd daemon..."
|
||||
sudo systemctl daemon-reload
|
||||
|
||||
# Stop existing processes
|
||||
echo "⏹️ Stopping existing processes..."
|
||||
pkill -f "coordinator-api" || true
|
||||
pkill -f "simple_exchange_api.py" || true
|
||||
pkill -f "server.py --port 3002" || true
|
||||
pkill -f "wallet_daemon" || true
|
||||
pkill -f "node.main" || true
|
||||
|
||||
# Enable services
|
||||
echo "✅ Enabling services..."
|
||||
sudo systemctl enable aitbc-coordinator-api.service
|
||||
sudo systemctl enable aitbc-exchange-api.service
|
||||
sudo systemctl enable aitbc-exchange-frontend.service
|
||||
sudo systemctl enable aitbc-wallet.service
|
||||
sudo systemctl enable aitbc-node.service
|
||||
|
||||
# Start services
|
||||
echo "🚀 Starting services..."
|
||||
sudo systemctl start aitbc-coordinator-api.service
|
||||
sudo systemctl start aitbc-exchange-api.service
|
||||
sudo systemctl start aitbc-exchange-frontend.service
|
||||
sudo systemctl start aitbc-wallet.service
|
||||
sudo systemctl start aitbc-node.service
|
||||
|
||||
# Check status
|
||||
echo ""
|
||||
echo "📊 Service Status:"
|
||||
for service in aitbc-coordinator-api aitbc-exchange-api aitbc-exchange-frontend aitbc-wallet aitbc-node; do
|
||||
status=$(sudo systemctl is-active $service)
|
||||
echo " $service: $status"
|
||||
done
|
||||
|
||||
echo ""
|
||||
echo "📝 To view logs: sudo journalctl -u <service-name> -f"
|
||||
echo "📝 To restart: sudo systemctl restart <service-name>"
|
||||
echo "📝 To stop: sudo systemctl stop <service-name>"
|
||||
Reference in New Issue
Block a user