292 lines
8.2 KiB
Go
292 lines
8.2 KiB
Go
package main
|
|
|
|
import (
|
|
"bufio"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"os/exec"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// gpuInfo holds detected GPU hardware information.
|
|
type gpuInfo struct {
|
|
Name string
|
|
MemoryTotal string
|
|
}
|
|
|
|
// detectGPUs runs nvidia-smi to detect available GPU hardware.
|
|
func detectGPUs() ([]gpuInfo, error) {
|
|
out, err := exec.Command("nvidia-smi",
|
|
"--query-gpu=name,memory.total",
|
|
"--format=csv,noheader").Output()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("nvidia-smi failed (is an NVIDIA GPU installed?): %w", err)
|
|
}
|
|
|
|
var gpus []gpuInfo
|
|
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
|
|
line = strings.TrimSpace(line)
|
|
if line == "" {
|
|
continue
|
|
}
|
|
parts := strings.SplitN(line, ", ", 2)
|
|
info := gpuInfo{Name: strings.TrimSpace(parts[0])}
|
|
if len(parts) > 1 {
|
|
info.MemoryTotal = strings.TrimSpace(parts[1])
|
|
}
|
|
gpus = append(gpus, info)
|
|
}
|
|
return gpus, nil
|
|
}
|
|
|
|
// promptString reads a line from stdin with a default value.
|
|
func promptString(reader *bufio.Reader, prompt, defaultVal string) string {
|
|
if defaultVal != "" {
|
|
fmt.Printf("%s [%s]: ", prompt, defaultVal)
|
|
} else {
|
|
fmt.Printf("%s: ", prompt)
|
|
}
|
|
line, _ := reader.ReadString('\n')
|
|
line = strings.TrimSpace(line)
|
|
if line == "" {
|
|
return defaultVal
|
|
}
|
|
return line
|
|
}
|
|
|
|
// generateConfigTOML creates a config.toml file with the provided settings.
|
|
func generateConfigTOML(path string, cfg Config, providerName string, gpus []gpuInfo) error {
|
|
var gpuNames []string
|
|
for _, g := range gpus {
|
|
gpuNames = append(gpuNames, fmt.Sprintf("%s (%s)", g.Name, g.MemoryTotal))
|
|
}
|
|
gpuList := strings.Join(gpuNames, ", ")
|
|
|
|
content := fmt.Sprintf(`# ClawChain GPU Provider Configuration
|
|
# Generated by onboarding wizard on %s
|
|
|
|
[chain]
|
|
# REST API endpoint for the chain node
|
|
rest_url = "%s"
|
|
# RPC endpoint for CometBFT (used for WebSocket events and tx broadcast)
|
|
rpc_url = "%s"
|
|
# Chain ID
|
|
chain_id = "%s"
|
|
# Token denomination
|
|
denom = "%s"
|
|
|
|
[provider]
|
|
# Provider display name
|
|
name = "%s"
|
|
# Bech32 provider address (must match the mnemonic)
|
|
address = "%s"
|
|
# BIP39 mnemonic for signing transactions (KEEP SECRET)
|
|
# Alternatively set via MNEMONIC environment variable
|
|
mnemonic = "%s"
|
|
# On-chain resource ID (obtained after listing your GPU resource)
|
|
resource_id = %d
|
|
# Detected GPUs: %s
|
|
|
|
[jobs]
|
|
# Maximum number of concurrent jobs
|
|
max_concurrent = %d
|
|
# Enable Docker job execution
|
|
docker_enabled = %v
|
|
# Working directory for temporary job files
|
|
work_dir = "%s"
|
|
# Job execution timeout in seconds (0 = no timeout)
|
|
job_timeout_sec = %d
|
|
|
|
[events]
|
|
# Use WebSocket events for real-time job dispatch (recommended)
|
|
websocket_enabled = %v
|
|
# Fallback to HTTP polling when WebSocket disconnects
|
|
poll_fallback = %v
|
|
# HTTP polling interval in seconds (only used when WebSocket is unavailable)
|
|
poll_interval_sec = %d
|
|
# WebSocket reconnect delay in seconds
|
|
ws_reconnect_sec = %d
|
|
|
|
[heartbeat]
|
|
# Interval between heartbeat/metric reports in seconds
|
|
interval_sec = %d
|
|
|
|
[metrics]
|
|
# Port for the Prometheus metrics and health endpoints
|
|
port = %d
|
|
|
|
[dantegpu]
|
|
# Enable DanteGPU integration for advanced job orchestration
|
|
enabled = false
|
|
# DanteGPU API gateway endpoint
|
|
api_url = "http://localhost:8080"
|
|
# DanteGPU API key (obtain from provider registration)
|
|
api_key = ""
|
|
# Use DanteGPU for job output storage (MinIO/S3)
|
|
use_remote_storage = false
|
|
# Storage endpoint for large job outputs
|
|
storage_url = "http://localhost:9000"
|
|
`,
|
|
time.Now().Format(time.RFC3339),
|
|
cfg.ChainREST,
|
|
cfg.ChainRPC,
|
|
cfg.ChainID,
|
|
cfg.Denom,
|
|
providerName,
|
|
cfg.ProviderAddress,
|
|
cfg.Mnemonic,
|
|
cfg.ResourceID,
|
|
gpuList,
|
|
cfg.MaxConcurrent,
|
|
cfg.DockerEnabled,
|
|
cfg.WorkDir,
|
|
cfg.JobTimeoutSec,
|
|
cfg.WSEnabled,
|
|
cfg.PollFallback,
|
|
cfg.JobPollSec,
|
|
cfg.WSReconnectSec,
|
|
cfg.HeartbeatSec,
|
|
cfg.MetricsPort,
|
|
)
|
|
|
|
return os.WriteFile(path, []byte(content), 0600)
|
|
}
|
|
|
|
// runOnboarding guides the user through GPU provider setup, detects hardware,
|
|
// collects configuration, generates config.toml, and registers the provider
|
|
// on-chain via MsgListComputeResource.
|
|
func runOnboarding() {
|
|
reader := bufio.NewReader(os.Stdin)
|
|
cfg := DefaultConfig()
|
|
|
|
fmt.Println("==========================================================")
|
|
fmt.Println(" ClawChain GPU Provider — Onboarding Wizard")
|
|
fmt.Println("==========================================================")
|
|
fmt.Println()
|
|
|
|
// Step 1: Detect GPU hardware.
|
|
fmt.Println("[1/6] Detecting GPU hardware...")
|
|
gpus, err := detectGPUs()
|
|
if err != nil {
|
|
fmt.Printf(" Warning: %v\n", err)
|
|
fmt.Println(" No NVIDIA GPU detected. You can still register as a provider,")
|
|
fmt.Println(" but GPU compute jobs will not be available.")
|
|
fmt.Println()
|
|
} else {
|
|
fmt.Printf(" Found %d GPU(s):\n", len(gpus))
|
|
for i, g := range gpus {
|
|
fmt.Printf(" [%d] %s — %s\n", i+1, g.Name, g.MemoryTotal)
|
|
}
|
|
fmt.Println()
|
|
}
|
|
|
|
// Step 2: Chain RPC endpoint.
|
|
fmt.Println("[2/6] Chain connection")
|
|
cfg.ChainREST = promptString(reader, " Chain REST endpoint", cfg.ChainREST)
|
|
cfg.ChainRPC = promptString(reader, " Chain RPC endpoint", cfg.ChainRPC)
|
|
cfg.ChainID = promptString(reader, " Chain ID", cfg.ChainID)
|
|
fmt.Println()
|
|
|
|
// Step 3: Provider name.
|
|
fmt.Println("[3/6] Provider identity")
|
|
providerName := promptString(reader, " Provider name", "my-gpu-provider")
|
|
fmt.Println()
|
|
|
|
// Step 4: Key material (mnemonic).
|
|
fmt.Println("[4/6] Signing key")
|
|
fmt.Println(" Enter your BIP39 mnemonic to derive the signing key.")
|
|
fmt.Println(" This will NOT be transmitted over the network.")
|
|
cfg.Mnemonic = promptString(reader, " Mnemonic", "")
|
|
if cfg.Mnemonic == "" {
|
|
fmt.Println(" Error: mnemonic is required for transaction signing.")
|
|
fmt.Println(" You can also set it via the MNEMONIC environment variable.")
|
|
os.Exit(1)
|
|
}
|
|
|
|
cfg.ProviderAddress = promptString(reader, " Provider bech32 address", cfg.ProviderAddress)
|
|
if cfg.ProviderAddress == "" {
|
|
fmt.Println(" Error: provider address is required.")
|
|
os.Exit(1)
|
|
}
|
|
fmt.Println()
|
|
|
|
// Step 5: Generate config.toml.
|
|
fmt.Println("[5/6] Generating configuration...")
|
|
configPath := "config.toml"
|
|
if err := generateConfigTOML(configPath, cfg, providerName, gpus); err != nil {
|
|
fmt.Printf(" Error writing config: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Printf(" Configuration written to %s\n", configPath)
|
|
fmt.Println()
|
|
|
|
// Step 6: Register on-chain.
|
|
fmt.Println("[6/6] Registering provider on-chain...")
|
|
|
|
chainClient, err := NewChainClient(cfg)
|
|
if err != nil {
|
|
fmt.Printf(" Error creating chain client: %v\n", err)
|
|
os.Exit(1)
|
|
}
|
|
|
|
// Build MsgListComputeResource payload.
|
|
gpuName := "unknown"
|
|
gpuMemory := "0"
|
|
if len(gpus) > 0 {
|
|
gpuName = gpus[0].Name
|
|
gpuMemory = gpus[0].MemoryTotal
|
|
}
|
|
|
|
msgPayload, _ := json.Marshal(map[string]interface{}{
|
|
"provider": cfg.ProviderAddress,
|
|
"name": providerName,
|
|
"gpu_model": gpuName,
|
|
"gpu_memory": gpuMemory,
|
|
"gpu_count": len(gpus),
|
|
"price_per_hour": map[string]string{
|
|
"denom": cfg.Denom,
|
|
"amount": "1000000",
|
|
},
|
|
"max_concurrent_jobs": cfg.MaxConcurrent,
|
|
"docker_enabled": cfg.DockerEnabled,
|
|
})
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
|
defer cancel()
|
|
|
|
err = chainClient.BroadcastMsg(
|
|
ctx,
|
|
"/clawchain.marketplace.v1.MsgListComputeResource",
|
|
json.RawMessage(msgPayload),
|
|
)
|
|
if err != nil {
|
|
fmt.Printf(" Warning: on-chain registration failed: %v\n", err)
|
|
fmt.Println(" You can register later by running the provider daemon.")
|
|
fmt.Println(" Make sure the chain node is running and your account is funded.")
|
|
} else {
|
|
fmt.Println(" Provider registered on-chain successfully!")
|
|
}
|
|
|
|
fmt.Println()
|
|
fmt.Println("==========================================================")
|
|
fmt.Println(" Onboarding complete!")
|
|
fmt.Println()
|
|
fmt.Println(" Next steps:")
|
|
fmt.Println(" 1. Review and adjust config.toml as needed")
|
|
fmt.Println(" 2. Fund your provider account with uclaw tokens")
|
|
fmt.Println(" 3. Start the provider daemon:")
|
|
fmt.Println(" ./claw-gpu-provider")
|
|
fmt.Println()
|
|
fmt.Println(" Your provider will automatically:")
|
|
fmt.Println(" - Send GPU heartbeat metrics to the chain")
|
|
fmt.Println(" - Listen for compute job assignments")
|
|
fmt.Println(" - Execute jobs in Docker containers")
|
|
fmt.Println("==========================================================")
|
|
|
|
log.Println("[Onboarding] Wizard completed successfully")
|
|
}
|