mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-09-28 05:46:36 +08:00
feat: add OperationSetting component and integrate into settings page
- Introduced OperationSetting component for managing agent configurations. - Updated settings page to include a new tab for operation settings. - Implemented functionality to fetch and update agent parameters such as heartbeat interval, sync interval, and auto-update settings. docs: enhance deployment documentation for agent installation - Added detailed instructions for agent installation using a script. - Included examples for using discovery and agent tokens. - Updated sections on global discovery tokens and agent auto-update features. docs: revise design and development guidelines for V3 - Updated design document to reflect the current state and goals for V3. - Clarified development guidelines to focus on operational experience improvements. ci: add GitHub Actions workflow for agent releases - Created a new workflow to automate the release of agent binaries on GitHub. - Configured the workflow to build binaries for multiple platforms and publish them as releases. feat: implement self-update mechanism for agent - Added updater module to handle checking for and applying updates from GitHub releases. - Implemented logic to restart the agent after a successful update. chore: create install script for agent deployment - Developed a bash script to facilitate the installation of the ATSFlare agent. - The script supports automatic configuration and systemd service creation.
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
name: Agent Release
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "*"
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
reason:
|
||||
description: "Reason for manual trigger"
|
||||
required: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: ">=1.18.0"
|
||||
|
||||
- name: Build Agent (linux/amd64)
|
||||
working-directory: atsf_agent
|
||||
run: |
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -ldflags "-s -w" -o ../atsflare-agent-linux-amd64 ./cmd/agent
|
||||
|
||||
- name: Build Agent (linux/arm64)
|
||||
working-directory: atsf_agent
|
||||
run: |
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w" -o ../atsflare-agent-linux-arm64 ./cmd/agent
|
||||
|
||||
- name: Build Agent (darwin/arm64)
|
||||
working-directory: atsf_agent
|
||||
run: |
|
||||
CGO_ENABLED=0 GOOS=darwin GOARCH=arm64 go build -ldflags "-s -w" -o ../atsflare-agent-darwin-arm64 ./cmd/agent
|
||||
|
||||
- name: Determine prerelease
|
||||
id: prerelease
|
||||
run: |
|
||||
TAG="${GITHUB_REF#refs/tags/}"
|
||||
if [[ "$TAG" == *alpha* ]] || [[ "$TAG" == *beta* ]] || [[ "$TAG" == *rc* ]]; then
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
with:
|
||||
files: |
|
||||
atsflare-agent-linux-amd64
|
||||
atsflare-agent-linux-arm64
|
||||
atsflare-agent-darwin-arm64
|
||||
draft: false
|
||||
prerelease: ${{ steps.prerelease.outputs.is_prerelease }}
|
||||
generate_release_notes: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
@@ -5,8 +5,7 @@ permissions:
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- '*'
|
||||
- '!*-alpha*'
|
||||
- "*"
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -22,24 +21,36 @@ jobs:
|
||||
env:
|
||||
CI: ""
|
||||
run: |
|
||||
cd web
|
||||
cd atsf_server/web
|
||||
npm install
|
||||
REACT_APP_VERSION=$(git describe --tags) npm run build
|
||||
cd ..
|
||||
cd ../..
|
||||
- name: Set up Go
|
||||
uses: actions/setup-go@v3
|
||||
with:
|
||||
go-version: '>=1.18.0'
|
||||
- name: Build Backend (amd64)
|
||||
go-version: ">=1.18.0"
|
||||
- name: Build Server (amd64)
|
||||
working-directory: atsf_server
|
||||
run: |
|
||||
go mod download
|
||||
go build -ldflags "-s -w -X 'atsflare/common.Version=$(git describe --tags)' -extldflags '-static'" -o atsflare
|
||||
go build -ldflags "-s -w -X 'atsflare/common.Version=$(git describe --tags)' -extldflags '-static'" -o ../atsflare
|
||||
|
||||
- name: Build Backend (arm64)
|
||||
- name: Build Server (arm64)
|
||||
working-directory: atsf_server
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install gcc-aarch64-linux-gnu
|
||||
CC=aarch64-linux-gnu-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -X 'atsflare/common.Version=$(git describe --tags)' -extldflags '-static'" -o atsflare-arm64
|
||||
CC=aarch64-linux-gnu-gcc CGO_ENABLED=1 GOOS=linux GOARCH=arm64 go build -ldflags "-s -w -X 'atsflare/common.Version=$(git describe --tags)' -extldflags '-static'" -o ../atsflare-arm64
|
||||
|
||||
- name: Determine prerelease
|
||||
id: prerelease
|
||||
run: |
|
||||
TAG="${GITHUB_REF#refs/tags/}"
|
||||
if [[ "$TAG" == *alpha* ]] || [[ "$TAG" == *beta* ]] || [[ "$TAG" == *rc* ]]; then
|
||||
echo "is_prerelease=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "is_prerelease=false" >> "$GITHUB_OUTPUT"
|
||||
fi
|
||||
|
||||
- name: Release
|
||||
uses: softprops/action-gh-release@v1
|
||||
@@ -49,6 +60,7 @@ jobs:
|
||||
atsflare
|
||||
atsflare-arm64
|
||||
draft: false
|
||||
prerelease: ${{ steps.prerelease.outputs.is_prerelease }}
|
||||
generate_release_notes: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"atsflare-agent/internal/nginx"
|
||||
"atsflare-agent/internal/state"
|
||||
syncservice "atsflare-agent/internal/sync"
|
||||
"atsflare-agent/internal/updater"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -58,6 +59,7 @@ func main() {
|
||||
NginxCertDir: cfg.NginxCertDir,
|
||||
}),
|
||||
}, stateStore),
|
||||
Updater: updater.New(),
|
||||
}
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
@@ -14,7 +14,7 @@ import (
|
||||
|
||||
type HeartbeatService interface {
|
||||
Register(ctx context.Context, payload protocol.NodePayload) (*protocol.RegisterNodeResponse, error)
|
||||
Heartbeat(ctx context.Context, payload protocol.NodePayload) error
|
||||
Heartbeat(ctx context.Context, payload protocol.NodePayload) (*protocol.AgentSettings, error)
|
||||
SetToken(token string)
|
||||
}
|
||||
|
||||
@@ -23,11 +23,19 @@ type SyncService interface {
|
||||
SyncOnce(ctx context.Context) error
|
||||
}
|
||||
|
||||
type Updater interface {
|
||||
CheckAndUpdate(ctx context.Context, repo string) error
|
||||
}
|
||||
|
||||
type Runner struct {
|
||||
Config *config.Config
|
||||
StateStore *state.Store
|
||||
HeartbeatService HeartbeatService
|
||||
SyncService SyncService
|
||||
Updater Updater
|
||||
|
||||
autoUpdate bool
|
||||
updateRepo string
|
||||
}
|
||||
|
||||
func (r *Runner) Run(ctx context.Context) error {
|
||||
@@ -43,10 +51,12 @@ func (r *Runner) Run(ctx context.Context) error {
|
||||
} else {
|
||||
log.Printf("agent startup sync completed")
|
||||
}
|
||||
if err = r.HeartbeatService.Heartbeat(ctx, r.nodePayload(nodeID)); err != nil {
|
||||
log.Printf("agent startup heartbeat failed: %v", err)
|
||||
settings, hbErr := r.HeartbeatService.Heartbeat(ctx, r.nodePayload(nodeID))
|
||||
if hbErr != nil {
|
||||
log.Printf("agent startup heartbeat failed: %v", hbErr)
|
||||
} else {
|
||||
log.Printf("agent startup heartbeat succeeded: node_id=%s", nodeID)
|
||||
r.applySettings(settings)
|
||||
}
|
||||
} else if err = r.tryRegister(ctx, &nodeID); err != nil {
|
||||
log.Printf("agent initial discovery register failed: %v", err)
|
||||
@@ -69,8 +79,15 @@ func (r *Runner) Run(ctx context.Context) error {
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err = r.HeartbeatService.Heartbeat(ctx, r.nodePayload(nodeID)); err != nil {
|
||||
log.Printf("agent heartbeat failed: %v", err)
|
||||
settings, hbErr := r.HeartbeatService.Heartbeat(ctx, r.nodePayload(nodeID))
|
||||
if hbErr != nil {
|
||||
log.Printf("agent heartbeat failed: %v", hbErr)
|
||||
} else {
|
||||
if changed := r.applySettings(settings); changed {
|
||||
heartbeatTicker.Reset(r.Config.HeartbeatInterval.Duration())
|
||||
syncTicker.Reset(r.Config.SyncInterval.Duration())
|
||||
}
|
||||
r.tryAutoUpdate(ctx)
|
||||
}
|
||||
case <-syncTicker.C:
|
||||
if !r.hasAgentToken() {
|
||||
@@ -91,6 +108,41 @@ func (r *Runner) hasAgentToken() bool {
|
||||
return strings.TrimSpace(r.Config.AgentToken) != ""
|
||||
}
|
||||
|
||||
func (r *Runner) applySettings(settings *protocol.AgentSettings) bool {
|
||||
if settings == nil {
|
||||
return false
|
||||
}
|
||||
changed := false
|
||||
if settings.HeartbeatInterval > 0 {
|
||||
newInterval := config.MillisecondDuration(time.Duration(settings.HeartbeatInterval) * time.Millisecond)
|
||||
if newInterval != r.Config.HeartbeatInterval {
|
||||
log.Printf("agent heartbeat interval updated: %s -> %s", r.Config.HeartbeatInterval, newInterval)
|
||||
r.Config.HeartbeatInterval = newInterval
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if settings.SyncInterval > 0 {
|
||||
newInterval := config.MillisecondDuration(time.Duration(settings.SyncInterval) * time.Millisecond)
|
||||
if newInterval != r.Config.SyncInterval {
|
||||
log.Printf("agent sync interval updated: %s -> %s", r.Config.SyncInterval, newInterval)
|
||||
r.Config.SyncInterval = newInterval
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
r.autoUpdate = settings.AutoUpdate
|
||||
r.updateRepo = settings.UpdateRepo
|
||||
return changed
|
||||
}
|
||||
|
||||
func (r *Runner) tryAutoUpdate(ctx context.Context) {
|
||||
if !r.autoUpdate || r.Updater == nil || r.updateRepo == "" {
|
||||
return
|
||||
}
|
||||
if err := r.Updater.CheckAndUpdate(ctx, r.updateRepo); err != nil {
|
||||
log.Printf("agent auto-update check failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runner) tryRegister(ctx context.Context, nodeID *string) error {
|
||||
if strings.TrimSpace(r.Config.DiscoveryToken) == "" {
|
||||
return errors.New("agent_token 为空且未配置 discovery_token")
|
||||
|
||||
@@ -32,7 +32,7 @@ func (f *fakeHeartbeatService) Register(ctx context.Context, payload protocol.No
|
||||
return f.registerResp, f.registerErr
|
||||
}
|
||||
|
||||
func (f *fakeHeartbeatService) Heartbeat(ctx context.Context, payload protocol.NodePayload) error {
|
||||
func (f *fakeHeartbeatService) Heartbeat(ctx context.Context, payload protocol.NodePayload) (*protocol.AgentSettings, error) {
|
||||
f.mu.Lock()
|
||||
f.heartbeatCalls++
|
||||
callIndex := f.heartbeatCalls
|
||||
@@ -45,7 +45,7 @@ func (f *fakeHeartbeatService) Heartbeat(ctx context.Context, payload protocol.N
|
||||
if onHeartbeat != nil {
|
||||
onHeartbeat(callIndex)
|
||||
}
|
||||
return err
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (f *fakeHeartbeatService) SetToken(token string) {
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
package config
|
||||
|
||||
const AgentVersion = "0.2.0"
|
||||
const AgentVersion = "0.3.0"
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
type Client interface {
|
||||
RegisterNode(ctx context.Context, payload protocol.NodePayload) (*protocol.RegisterNodeResponse, error)
|
||||
Heartbeat(ctx context.Context, payload protocol.NodePayload) error
|
||||
Heartbeat(ctx context.Context, payload protocol.NodePayload) (*protocol.AgentSettings, error)
|
||||
SetToken(token string)
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ func (s *Service) Register(ctx context.Context, payload protocol.NodePayload) (*
|
||||
return s.client.RegisterNode(ctx, payload)
|
||||
}
|
||||
|
||||
func (s *Service) Heartbeat(ctx context.Context, payload protocol.NodePayload) error {
|
||||
func (s *Service) Heartbeat(ctx context.Context, payload protocol.NodePayload) (*protocol.AgentSettings, error) {
|
||||
return s.client.Heartbeat(ctx, payload)
|
||||
}
|
||||
|
||||
|
||||
@@ -42,8 +42,15 @@ func (c *Client) RegisterNode(ctx context.Context, payload protocol.NodePayload)
|
||||
return &resp.Data, nil
|
||||
}
|
||||
|
||||
func (c *Client) Heartbeat(ctx context.Context, payload protocol.NodePayload) error {
|
||||
return c.postJSON(ctx, "/api/agent/nodes/heartbeat", payload, nil)
|
||||
func (c *Client) Heartbeat(ctx context.Context, payload protocol.NodePayload) (*protocol.AgentSettings, error) {
|
||||
resp := protocol.HeartbeatAPIResponse{}
|
||||
if err := c.postJSON(ctx, "/api/agent/nodes/heartbeat", payload, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !resp.Success {
|
||||
return nil, errors.New(resp.Message)
|
||||
}
|
||||
return resp.AgentSettings, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetActiveConfig(ctx context.Context) (*protocol.ActiveConfigResponse, error) {
|
||||
|
||||
@@ -6,6 +6,20 @@ type APIResponse[T any] struct {
|
||||
Data T `json:"data"`
|
||||
}
|
||||
|
||||
type HeartbeatAPIResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
Data any `json:"data"`
|
||||
AgentSettings *AgentSettings `json:"agent_settings,omitempty"`
|
||||
}
|
||||
|
||||
type AgentSettings struct {
|
||||
HeartbeatInterval int `json:"heartbeat_interval"`
|
||||
SyncInterval int `json:"sync_interval"`
|
||||
AutoUpdate bool `json:"auto_update"`
|
||||
UpdateRepo string `json:"update_repo"`
|
||||
}
|
||||
|
||||
type NodePayload struct {
|
||||
NodeID string `json:"node_id"`
|
||||
Name string `json:"name"`
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
package updater
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"atsflare-agent/internal/config"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
httpClient *http.Client
|
||||
lastCheckTag string
|
||||
}
|
||||
|
||||
func New() *Service {
|
||||
return &Service{
|
||||
httpClient: &http.Client{Timeout: 30 * time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
type githubRelease struct {
|
||||
TagName string `json:"tag_name"`
|
||||
Assets []githubAsset `json:"assets"`
|
||||
}
|
||||
|
||||
type githubAsset struct {
|
||||
Name string `json:"name"`
|
||||
BrowserDownloadURL string `json:"browser_download_url"`
|
||||
}
|
||||
|
||||
func (s *Service) CheckAndUpdate(ctx context.Context, repo string) error {
|
||||
release, err := s.getLatestRelease(ctx, repo)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check latest release: %w", err)
|
||||
}
|
||||
if release == nil || release.TagName == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
remoteVersion := normalizeVersion(release.TagName)
|
||||
localVersion := normalizeVersion(config.AgentVersion)
|
||||
|
||||
if remoteVersion == localVersion || remoteVersion == s.lastCheckTag {
|
||||
return nil
|
||||
}
|
||||
if !isNewer(localVersion, remoteVersion) {
|
||||
s.lastCheckTag = remoteVersion
|
||||
return nil
|
||||
}
|
||||
|
||||
log.Printf("agent update available: %s -> %s", localVersion, remoteVersion)
|
||||
assetName := fmt.Sprintf("atsflare-agent-%s-%s", runtime.GOOS, runtime.GOARCH)
|
||||
|
||||
var downloadURL string
|
||||
for _, asset := range release.Assets {
|
||||
if asset.Name == assetName {
|
||||
downloadURL = asset.BrowserDownloadURL
|
||||
break
|
||||
}
|
||||
}
|
||||
if downloadURL == "" {
|
||||
s.lastCheckTag = remoteVersion
|
||||
return fmt.Errorf("no matching asset %q in release %s", assetName, release.TagName)
|
||||
}
|
||||
|
||||
execPath, err := os.Executable()
|
||||
if err != nil {
|
||||
return fmt.Errorf("get executable path: %w", err)
|
||||
}
|
||||
if err = s.downloadAndReplace(ctx, downloadURL, execPath); err != nil {
|
||||
return fmt.Errorf("download and replace: %w", err)
|
||||
}
|
||||
|
||||
log.Printf("agent binary updated, restarting...")
|
||||
return s.restart(execPath)
|
||||
}
|
||||
|
||||
func (s *Service) getLatestRelease(ctx context.Context, repo string) (*githubRelease, error) {
|
||||
url := fmt.Sprintf("https://api.github.com/repos/%s/releases/latest", repo)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/vnd.github+json")
|
||||
|
||||
resp, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
return nil, nil
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("github api returned %s", resp.Status)
|
||||
}
|
||||
|
||||
var release githubRelease
|
||||
if err = json.NewDecoder(resp.Body).Decode(&release); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &release, nil
|
||||
}
|
||||
|
||||
func (s *Service) downloadAndReplace(ctx context.Context, url string, targetPath string) error {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("download returned %s", resp.Status)
|
||||
}
|
||||
|
||||
tmpPath := targetPath + ".update"
|
||||
tmpFile, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o755)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = io.Copy(tmpFile, resp.Body); err != nil {
|
||||
tmpFile.Close()
|
||||
os.Remove(tmpPath)
|
||||
return err
|
||||
}
|
||||
tmpFile.Close()
|
||||
|
||||
backupPath := targetPath + ".bak"
|
||||
os.Remove(backupPath)
|
||||
if err = os.Rename(targetPath, backupPath); err != nil {
|
||||
os.Remove(tmpPath)
|
||||
return fmt.Errorf("backup current binary: %w", err)
|
||||
}
|
||||
if err = os.Rename(tmpPath, targetPath); err != nil {
|
||||
// Attempt to restore backup
|
||||
os.Rename(backupPath, targetPath)
|
||||
return fmt.Errorf("replace binary: %w", err)
|
||||
}
|
||||
os.Remove(backupPath)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) restart(execPath string) error {
|
||||
argv := os.Args
|
||||
if err := syscall.Exec(execPath, argv, os.Environ()); err != nil {
|
||||
return fmt.Errorf("exec restart: %w", err)
|
||||
}
|
||||
return errors.New("unreachable after exec")
|
||||
}
|
||||
|
||||
func normalizeVersion(v string) string {
|
||||
v = strings.TrimSpace(v)
|
||||
v = strings.TrimPrefix(v, "v")
|
||||
return v
|
||||
}
|
||||
|
||||
func isNewer(local, remote string) bool {
|
||||
localParts := strings.Split(local, ".")
|
||||
remoteParts := strings.Split(remote, ".")
|
||||
maxLen := len(localParts)
|
||||
if len(remoteParts) > maxLen {
|
||||
maxLen = len(remoteParts)
|
||||
}
|
||||
for i := 0; i < maxLen; i++ {
|
||||
lp, rp := "0", "0"
|
||||
if i < len(localParts) {
|
||||
lp = localParts[i]
|
||||
}
|
||||
if i < len(remoteParts) {
|
||||
rp = remoteParts[i]
|
||||
}
|
||||
if rp > lp {
|
||||
return true
|
||||
}
|
||||
if rp < lp {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -50,6 +50,12 @@ var AgentToken = ""
|
||||
var AgentDiscoveryToken = ""
|
||||
var NodeOfflineThreshold = 2 * time.Minute
|
||||
|
||||
// V3 operational settings (hot-reloadable via Option table)
|
||||
var AgentHeartbeatInterval = 30000 // milliseconds
|
||||
var AgentSyncInterval = 30000 // milliseconds
|
||||
var AgentAutoUpdate = false
|
||||
var AgentUpdateRepo = "Rain-kl/ATSFlare"
|
||||
|
||||
const (
|
||||
RoleGuestUser = 0
|
||||
RoleCommonUser = 1
|
||||
|
||||
@@ -4,8 +4,9 @@ import (
|
||||
"atsflare/model"
|
||||
"atsflare/service"
|
||||
"encoding/json"
|
||||
"github.com/gin-gonic/gin"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func AgentRegister(c *gin.Context) {
|
||||
@@ -66,9 +67,10 @@ func AgentHeartbeat(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": node,
|
||||
"success": true,
|
||||
"message": "",
|
||||
"data": node.Node,
|
||||
"agent_settings": node.AgentSettings,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"atsflare/common"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Option struct {
|
||||
@@ -50,6 +51,11 @@ func InitOptionMap() {
|
||||
common.OptionMap["TurnstileSiteKey"] = ""
|
||||
common.OptionMap["TurnstileSecretKey"] = ""
|
||||
common.OptionMap["AgentDiscoveryToken"] = ""
|
||||
common.OptionMap["AgentHeartbeatInterval"] = strconv.Itoa(common.AgentHeartbeatInterval)
|
||||
common.OptionMap["AgentSyncInterval"] = strconv.Itoa(common.AgentSyncInterval)
|
||||
common.OptionMap["NodeOfflineThreshold"] = strconv.Itoa(int(common.NodeOfflineThreshold.Milliseconds()))
|
||||
common.OptionMap["AgentAutoUpdate"] = strconv.FormatBool(common.AgentAutoUpdate)
|
||||
common.OptionMap["AgentUpdateRepo"] = common.AgentUpdateRepo
|
||||
common.OptionMapRWMutex.Unlock()
|
||||
options, _ := AllOption()
|
||||
for _, option := range options {
|
||||
@@ -144,5 +150,23 @@ func updateOptionMap(key string, value string) {
|
||||
common.TurnstileSecretKey = value
|
||||
case "AgentDiscoveryToken":
|
||||
common.AgentDiscoveryToken = value
|
||||
case "AgentHeartbeatInterval":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.AgentHeartbeatInterval = v
|
||||
}
|
||||
case "AgentSyncInterval":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.AgentSyncInterval = v
|
||||
}
|
||||
case "NodeOfflineThreshold":
|
||||
if v, err := strconv.Atoi(value); err == nil && v > 0 {
|
||||
common.NodeOfflineThreshold = time.Duration(v) * time.Millisecond
|
||||
}
|
||||
case "AgentAutoUpdate":
|
||||
common.AgentAutoUpdate = value == "true"
|
||||
case "AgentUpdateRepo":
|
||||
if value != "" {
|
||||
common.AgentUpdateRepo = value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,6 +44,18 @@ type AgentConfigResponse struct {
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type AgentSettings struct {
|
||||
HeartbeatInterval int `json:"heartbeat_interval"`
|
||||
SyncInterval int `json:"sync_interval"`
|
||||
AutoUpdate bool `json:"auto_update"`
|
||||
UpdateRepo string `json:"update_repo"`
|
||||
}
|
||||
|
||||
type HeartbeatResponse struct {
|
||||
Node *model.Node `json:"node"`
|
||||
AgentSettings *AgentSettings `json:"agent_settings"`
|
||||
}
|
||||
|
||||
type NodeView struct {
|
||||
ID uint `json:"id"`
|
||||
NodeID string `json:"node_id"`
|
||||
@@ -68,7 +80,7 @@ func RegisterNode(node *model.Node, payload AgentNodePayload) (*AgentRegistratio
|
||||
return RegisterNodeWithAgentToken(node, payload)
|
||||
}
|
||||
|
||||
func HeartbeatNode(node *model.Node, payload AgentNodePayload) (*model.Node, error) {
|
||||
func HeartbeatNode(node *model.Node, payload AgentNodePayload) (*HeartbeatResponse, error) {
|
||||
common.SysLog("agent heartbeat received: node_id=" + node.NodeID + " current_version=" + strings.TrimSpace(payload.CurrentVersion))
|
||||
payload.NodeID = node.NodeID
|
||||
payload = normalizeAgentNodePayload(payload)
|
||||
@@ -79,7 +91,15 @@ func HeartbeatNode(node *model.Node, payload AgentNodePayload) (*model.Node, err
|
||||
if err := model.DB.Model(node).Select("ip", "agent_version", "nginx_version", "status", "current_version", "last_seen_at", "last_error").Updates(node).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return node, nil
|
||||
return &HeartbeatResponse{
|
||||
Node: node,
|
||||
AgentSettings: &AgentSettings{
|
||||
HeartbeatInterval: common.AgentHeartbeatInterval,
|
||||
SyncInterval: common.AgentSyncInterval,
|
||||
AutoUpdate: common.AgentAutoUpdate,
|
||||
UpdateRepo: common.AgentUpdateRepo,
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func GetActiveConfigForAgent() (*AgentConfigResponse, error) {
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Divider,
|
||||
Form,
|
||||
Grid,
|
||||
Header,
|
||||
Icon,
|
||||
Label,
|
||||
Message,
|
||||
Segment,
|
||||
} from 'semantic-ui-react';
|
||||
import { API, copy, showError, showSuccess } from '../helpers';
|
||||
|
||||
const OperationSetting = () => {
|
||||
const [inputs, setInputs] = useState({
|
||||
AgentHeartbeatInterval: '30000',
|
||||
AgentSyncInterval: '30000',
|
||||
NodeOfflineThreshold: '120000',
|
||||
AgentAutoUpdate: 'false',
|
||||
AgentUpdateRepo: 'Rain-kl/ATSFlare',
|
||||
ServerAddress: '',
|
||||
AgentDiscoveryToken: '',
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const getOptions = async () => {
|
||||
const res = await API.get('/api/option/');
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
let newInputs = {};
|
||||
data.forEach((item) => {
|
||||
if (item.key in inputs) {
|
||||
newInputs[item.key] = item.value;
|
||||
}
|
||||
});
|
||||
setInputs((prev) => ({ ...prev, ...newInputs }));
|
||||
} else {
|
||||
showError(message);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
getOptions();
|
||||
getDiscoveryToken();
|
||||
}, []);
|
||||
|
||||
const getDiscoveryToken = async () => {
|
||||
try {
|
||||
const res = await API.get('/api/nodes/bootstrap-token');
|
||||
const { success, data } = res.data;
|
||||
if (success && data) {
|
||||
setInputs((prev) => ({
|
||||
...prev,
|
||||
AgentDiscoveryToken: data.discovery_token,
|
||||
}));
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
};
|
||||
|
||||
const updateOption = async (key, value) => {
|
||||
setLoading(true);
|
||||
const res = await API.put('/api/option', { key, value });
|
||||
const { success, message } = res.data;
|
||||
if (success) {
|
||||
showSuccess('设置已保存');
|
||||
setInputs((prev) => ({ ...prev, [key]: value }));
|
||||
} else {
|
||||
showError(message);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const handleInputChange = (e, { name, value }) => {
|
||||
setInputs((prev) => ({ ...prev, [name]: value }));
|
||||
};
|
||||
|
||||
const handleCheckboxChange = (e, { name, checked }) => {
|
||||
setInputs((prev) => ({ ...prev, [name]: checked ? 'true' : 'false' }));
|
||||
};
|
||||
|
||||
const submitAgentIntervals = async () => {
|
||||
const hb = parseInt(inputs.AgentHeartbeatInterval, 10);
|
||||
const sync = parseInt(inputs.AgentSyncInterval, 10);
|
||||
const offline = parseInt(inputs.NodeOfflineThreshold, 10);
|
||||
if (isNaN(hb) || hb < 5000) {
|
||||
showError('心跳间隔不能小于 5000 毫秒');
|
||||
return;
|
||||
}
|
||||
if (isNaN(sync) || sync < 5000) {
|
||||
showError('同步间隔不能小于 5000 毫秒');
|
||||
return;
|
||||
}
|
||||
if (isNaN(offline) || offline < 10000) {
|
||||
showError('离线阈值不能小于 10000 毫秒');
|
||||
return;
|
||||
}
|
||||
await updateOption('AgentHeartbeatInterval', String(hb));
|
||||
await updateOption('AgentSyncInterval', String(sync));
|
||||
await updateOption('NodeOfflineThreshold', String(offline));
|
||||
};
|
||||
|
||||
const submitAutoUpdate = async () => {
|
||||
await updateOption('AgentAutoUpdate', inputs.AgentAutoUpdate);
|
||||
await updateOption('AgentUpdateRepo', inputs.AgentUpdateRepo);
|
||||
};
|
||||
|
||||
const rotateDiscoveryToken = async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const res = await API.post('/api/nodes/bootstrap-token/rotate');
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
showSuccess('Discovery Token 已重新生成');
|
||||
setInputs((prev) => ({
|
||||
...prev,
|
||||
AgentDiscoveryToken: data.discovery_token,
|
||||
}));
|
||||
} else {
|
||||
showError(message);
|
||||
}
|
||||
} catch (e) {
|
||||
showError('操作失败');
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
const formatMs = (ms) => {
|
||||
const val = parseInt(ms, 10);
|
||||
if (isNaN(val)) return ms;
|
||||
if (val >= 60000) return `${val / 60000} 分钟`;
|
||||
return `${val / 1000} 秒`;
|
||||
};
|
||||
|
||||
const serverAddr = inputs.ServerAddress || window.location.origin;
|
||||
const curlCommand = inputs.AgentDiscoveryToken
|
||||
? `curl -fsSL https://raw.githubusercontent.com/Rain-kl/ATSFlare/main/scripts/install-agent.sh | bash -s -- --server-url ${serverAddr} --discovery-token ${inputs.AgentDiscoveryToken}`
|
||||
: '';
|
||||
|
||||
return (
|
||||
<Grid columns={1}>
|
||||
<Grid.Column>
|
||||
<Form loading={loading}>
|
||||
<Header as='h3'>Agent 运行参数</Header>
|
||||
<Message info size='small'>
|
||||
<p>这些参数通过心跳响应下发到所有 Agent,修改后下次心跳即生效。</p>
|
||||
</Message>
|
||||
<Form.Group widths='equal'>
|
||||
<Form.Input
|
||||
label={`心跳间隔 (${formatMs(inputs.AgentHeartbeatInterval)})`}
|
||||
placeholder='30000'
|
||||
value={inputs.AgentHeartbeatInterval}
|
||||
name='AgentHeartbeatInterval'
|
||||
onChange={handleInputChange}
|
||||
type='number'
|
||||
/>
|
||||
<Form.Input
|
||||
label={`同步间隔 (${formatMs(inputs.AgentSyncInterval)})`}
|
||||
placeholder='30000'
|
||||
value={inputs.AgentSyncInterval}
|
||||
name='AgentSyncInterval'
|
||||
onChange={handleInputChange}
|
||||
type='number'
|
||||
/>
|
||||
<Form.Input
|
||||
label={`离线阈值 (${formatMs(inputs.NodeOfflineThreshold)})`}
|
||||
placeholder='120000'
|
||||
value={inputs.NodeOfflineThreshold}
|
||||
name='NodeOfflineThreshold'
|
||||
onChange={handleInputChange}
|
||||
type='number'
|
||||
/>
|
||||
</Form.Group>
|
||||
<Form.Button onClick={submitAgentIntervals} primary>
|
||||
保存运行参数
|
||||
</Form.Button>
|
||||
|
||||
<Divider />
|
||||
<Header as='h3'>Agent 自动更新</Header>
|
||||
<Form.Group>
|
||||
<Form.Checkbox
|
||||
label='启用 Agent 自动更新'
|
||||
checked={inputs.AgentAutoUpdate === 'true'}
|
||||
name='AgentAutoUpdate'
|
||||
onChange={handleCheckboxChange}
|
||||
/>
|
||||
</Form.Group>
|
||||
<Form.Group widths='equal'>
|
||||
<Form.Input
|
||||
label='更新仓库'
|
||||
placeholder='Rain-kl/ATSFlare'
|
||||
value={inputs.AgentUpdateRepo}
|
||||
name='AgentUpdateRepo'
|
||||
onChange={handleInputChange}
|
||||
/>
|
||||
</Form.Group>
|
||||
<Form.Button onClick={submitAutoUpdate} primary>
|
||||
保存更新设置
|
||||
</Form.Button>
|
||||
|
||||
<Divider />
|
||||
<Header as='h3'>节点接入</Header>
|
||||
<Form.Group widths='equal'>
|
||||
<Form.Field>
|
||||
<label>全局 Discovery Token</label>
|
||||
<Segment>
|
||||
<Label basic>{inputs.AgentDiscoveryToken || '(未设置)'}</Label>
|
||||
<Button
|
||||
size='mini'
|
||||
icon
|
||||
style={{ marginLeft: '8px' }}
|
||||
onClick={() =>
|
||||
copy(inputs.AgentDiscoveryToken, 'Discovery Token')
|
||||
}
|
||||
title='复制'
|
||||
>
|
||||
<Icon name='copy' />
|
||||
</Button>
|
||||
<Button
|
||||
size='mini'
|
||||
color='orange'
|
||||
style={{ marginLeft: '4px' }}
|
||||
onClick={rotateDiscoveryToken}
|
||||
>
|
||||
重新生成
|
||||
</Button>
|
||||
</Segment>
|
||||
</Form.Field>
|
||||
</Form.Group>
|
||||
|
||||
{curlCommand && (
|
||||
<>
|
||||
<Header as='h4'>Agent 一键部署命令</Header>
|
||||
<Message>
|
||||
<pre
|
||||
style={{
|
||||
whiteSpace: 'pre-wrap',
|
||||
wordBreak: 'break-all',
|
||||
fontFamily: 'JetBrains Mono, Consolas, monospace',
|
||||
fontSize: '12px',
|
||||
margin: 0,
|
||||
}}
|
||||
>
|
||||
{curlCommand}
|
||||
</pre>
|
||||
</Message>
|
||||
<Button
|
||||
size='small'
|
||||
icon
|
||||
labelPosition='left'
|
||||
onClick={() => copy(curlCommand, '部署命令')}
|
||||
>
|
||||
<Icon name='copy' />
|
||||
复制部署命令
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</Form>
|
||||
</Grid.Column>
|
||||
</Grid>
|
||||
);
|
||||
};
|
||||
|
||||
export default OperationSetting;
|
||||
@@ -25,7 +25,7 @@ export function getFooterHTML() {
|
||||
return localStorage.getItem('footer_html');
|
||||
}
|
||||
|
||||
export async function copy(text) {
|
||||
export async function copy(text, label) {
|
||||
let okay = true;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
@@ -33,6 +33,9 @@ export async function copy(text) {
|
||||
okay = false;
|
||||
console.error(e);
|
||||
}
|
||||
if (okay && label) {
|
||||
showSuccess(`${label} 已复制`);
|
||||
}
|
||||
return okay;
|
||||
}
|
||||
|
||||
@@ -151,3 +154,15 @@ export function formatDateTime(value) {
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
return date.toLocaleString('zh-CN', { hour12: false });
|
||||
}
|
||||
|
||||
export function timeAgo(value) {
|
||||
if (!value) return '暂无';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
const diff = Math.floor((Date.now() - date.getTime()) / 1000);
|
||||
if (diff < 0) return '刚刚';
|
||||
if (diff < 60) return `${diff} 秒前`;
|
||||
if (diff < 3600) return `${Math.floor(diff / 60)} 分钟前`;
|
||||
if (diff < 86400) return `${Math.floor(diff / 3600)} 小时前`;
|
||||
return `${Math.floor(diff / 86400)} 天前`;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { useEffect, useState } from 'react';
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Button, Form, Header, Label, Segment, Table } from 'semantic-ui-react';
|
||||
import { API, formatDateTime, showError, showSuccess } from '../../helpers';
|
||||
import { API, showError, showSuccess, timeAgo } from '../../helpers';
|
||||
|
||||
const initialForm = {
|
||||
name: '',
|
||||
@@ -33,9 +33,11 @@ const Node = () => {
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [form, setForm] = useState(initialForm);
|
||||
const [editingId, setEditingId] = useState(null);
|
||||
const [, setTick] = useState(0);
|
||||
const refreshTimer = useRef(null);
|
||||
|
||||
const loadNodes = async () => {
|
||||
setLoading(true);
|
||||
const loadNodes = useCallback(async (silent) => {
|
||||
if (!silent) setLoading(true);
|
||||
const res = await API.get('/api/nodes/');
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
@@ -43,8 +45,8 @@ const Node = () => {
|
||||
} else {
|
||||
showError(message);
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
if (!silent) setLoading(false);
|
||||
}, []);
|
||||
|
||||
const loadBootstrapToken = async () => {
|
||||
const res = await API.get('/api/nodes/bootstrap-token');
|
||||
@@ -71,8 +73,14 @@ const Node = () => {
|
||||
|
||||
useEffect(() => {
|
||||
loadBootstrapToken().then();
|
||||
loadNodes().then();
|
||||
}, []);
|
||||
loadNodes(false).then();
|
||||
// Refresh node list and relative time every 30s
|
||||
refreshTimer.current = setInterval(() => {
|
||||
loadNodes(true);
|
||||
setTick((t) => t + 1);
|
||||
}, 30000);
|
||||
return () => clearInterval(refreshTimer.current);
|
||||
}, [loadNodes]);
|
||||
|
||||
const resetForm = () => {
|
||||
setForm(initialForm);
|
||||
@@ -91,7 +99,7 @@ const Node = () => {
|
||||
if (success) {
|
||||
showSuccess(editingId ? '节点已更新' : '节点已创建');
|
||||
resetForm();
|
||||
await loadNodes();
|
||||
await loadNodes(false);
|
||||
} else {
|
||||
showError(message);
|
||||
}
|
||||
@@ -106,7 +114,11 @@ const Node = () => {
|
||||
};
|
||||
|
||||
const deleteNode = async (node) => {
|
||||
if (!window.confirm(`确认删除节点“${node.name}”吗?删除后该节点需要重新创建并重新接入。`)) {
|
||||
if (
|
||||
!window.confirm(
|
||||
`确认删除节点“${node.name}”吗?删除后该节点需要重新创建并重新接入。`
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const res = await API.delete(`/api/nodes/${node.id}`);
|
||||
@@ -116,7 +128,7 @@ const Node = () => {
|
||||
if (editingId === node.id) {
|
||||
resetForm();
|
||||
}
|
||||
await loadNodes();
|
||||
await loadNodes(false);
|
||||
} else {
|
||||
showError(message);
|
||||
}
|
||||
@@ -125,7 +137,10 @@ const Node = () => {
|
||||
return (
|
||||
<Segment loading={loading}>
|
||||
<Header as='h3'>节点管理</Header>
|
||||
<p className='page-subtitle'>创建节点后会直接生成节点专属 auth token;批量部署时可复用全局 discovery token 自动注册。</p>
|
||||
<p className='page-subtitle'>
|
||||
创建节点后会直接生成节点专属 auth token;批量部署时可复用全局 discovery
|
||||
token 自动注册。
|
||||
</p>
|
||||
|
||||
<Form>
|
||||
<Form.Group widths='equal'>
|
||||
@@ -183,20 +198,37 @@ const Node = () => {
|
||||
<Table.Cell>
|
||||
{node.agent_token ? (
|
||||
<>
|
||||
{node.pending ? <Label color='orange'>未占用</Label> : <Label color='green'>已绑定</Label>}
|
||||
<div className='table-meta' style={{ wordBreak: 'break-all' }}>{node.agent_token}</div>
|
||||
{node.pending ? (
|
||||
<Label color='orange'>未占用</Label>
|
||||
) : (
|
||||
<Label color='green'>已绑定</Label>
|
||||
)}
|
||||
<div
|
||||
className='table-meta'
|
||||
style={{ wordBreak: 'break-all' }}
|
||||
>
|
||||
{node.agent_token}
|
||||
</div>
|
||||
</>
|
||||
) : '暂无'}
|
||||
) : (
|
||||
'暂无'
|
||||
)}
|
||||
</Table.Cell>
|
||||
<Table.Cell>{node.ip}</Table.Cell>
|
||||
<Table.Cell>{renderStatus(node.status)}</Table.Cell>
|
||||
<Table.Cell>{node.agent_version} / {node.nginx_version || 'unknown'}</Table.Cell>
|
||||
<Table.Cell>
|
||||
{node.agent_version} / {node.nginx_version || 'unknown'}
|
||||
</Table.Cell>
|
||||
<Table.Cell>{node.current_version || '未应用'}</Table.Cell>
|
||||
<Table.Cell>
|
||||
{renderApply(node.latest_apply_result)}
|
||||
<div className='table-meta'>{node.latest_apply_message || '暂无记录'}</div>
|
||||
<div className='table-meta'>
|
||||
{node.latest_apply_message || '暂无记录'}
|
||||
</div>
|
||||
</Table.Cell>
|
||||
<Table.Cell title={node.last_seen_at}>
|
||||
{node.last_seen_at ? timeAgo(node.last_seen_at) : '暂无'}
|
||||
</Table.Cell>
|
||||
<Table.Cell>{node.last_seen_at ? formatDateTime(node.last_seen_at) : '暂无'}</Table.Cell>
|
||||
<Table.Cell>{node.last_error || '无'}</Table.Cell>
|
||||
<Table.Cell>
|
||||
<Button size='small' onClick={() => beginEdit(node)}>
|
||||
|
||||
@@ -4,6 +4,7 @@ import SystemSetting from '../../components/SystemSetting';
|
||||
import { isRoot } from '../../helpers';
|
||||
import OtherSetting from '../../components/OtherSetting';
|
||||
import PersonalSetting from '../../components/PersonalSetting';
|
||||
import OperationSetting from '../../components/OperationSetting';
|
||||
|
||||
const Setting = () => {
|
||||
let panes = [
|
||||
@@ -13,18 +14,26 @@ const Setting = () => {
|
||||
<Tab.Pane attached={false}>
|
||||
<PersonalSetting />
|
||||
</Tab.Pane>
|
||||
)
|
||||
}
|
||||
),
|
||||
},
|
||||
];
|
||||
|
||||
if (isRoot()) {
|
||||
panes.push({
|
||||
menuItem: '运维设置',
|
||||
render: () => (
|
||||
<Tab.Pane attached={false}>
|
||||
<OperationSetting />
|
||||
</Tab.Pane>
|
||||
),
|
||||
});
|
||||
panes.push({
|
||||
menuItem: '系统设置',
|
||||
render: () => (
|
||||
<Tab.Pane attached={false}>
|
||||
<SystemSetting />
|
||||
</Tab.Pane>
|
||||
)
|
||||
),
|
||||
});
|
||||
panes.push({
|
||||
menuItem: '其他设置',
|
||||
@@ -32,7 +41,7 @@ const Setting = () => {
|
||||
<Tab.Pane attached={false}>
|
||||
<OtherSetting />
|
||||
</Tab.Pane>
|
||||
)
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+101
-39
@@ -63,43 +63,43 @@ go run .
|
||||
|
||||
### 3.1 节点专属 `agent_token`
|
||||
|
||||
```json
|
||||
{
|
||||
"server_url": "http://127.0.0.1:3000",
|
||||
"agent_token": "replace-with-node-auth-token",
|
||||
"data_dir": "./data",
|
||||
"nginx_container_name": "atsflare-nginx",
|
||||
"nginx_docker_image": "nginx:stable-alpine",
|
||||
"heartbeat_interval": 30000,
|
||||
"sync_interval": 30000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
```
|
||||
```json
|
||||
{
|
||||
"server_url": "http://127.0.0.1:3000",
|
||||
"agent_token": "replace-with-node-auth-token",
|
||||
"data_dir": "./data",
|
||||
"nginx_container_name": "atsflare-nginx",
|
||||
"nginx_docker_image": "nginx:stable-alpine",
|
||||
"heartbeat_interval": 30000,
|
||||
"sync_interval": 30000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
```
|
||||
|
||||
### 3.2 全局 `discovery_token`
|
||||
|
||||
```json
|
||||
{
|
||||
"server_url": "http://127.0.0.1:3000",
|
||||
"discovery_token": "replace-with-global-discovery-token",
|
||||
"data_dir": "./data",
|
||||
"nginx_container_name": "atsflare-nginx",
|
||||
"nginx_docker_image": "nginx:stable-alpine",
|
||||
"heartbeat_interval": 30000,
|
||||
"sync_interval": 30000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
* `agent_version` 由 Agent 代码内常量提供,升级时同步修改代码
|
||||
* `nginx_version` 由 Agent 启动时执行命令自动探测
|
||||
* 时间字段使用毫秒整数
|
||||
* `agent_token` 与 `discovery_token` 至少填写一个
|
||||
* 若 `agent_token` 为空且 `discovery_token` 存在,Agent 会自动注册并写回新的专属 `agent_token`
|
||||
* `node_name` 与 `node_ip` 可省略,未填写时自动探测
|
||||
* 未配置 `nginx_path` 时,默认使用 Docker Nginx 容器
|
||||
```json
|
||||
{
|
||||
"server_url": "http://127.0.0.1:3000",
|
||||
"discovery_token": "replace-with-global-discovery-token",
|
||||
"data_dir": "./data",
|
||||
"nginx_container_name": "atsflare-nginx",
|
||||
"nginx_docker_image": "nginx:stable-alpine",
|
||||
"heartbeat_interval": 30000,
|
||||
"sync_interval": 30000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
```
|
||||
|
||||
说明:
|
||||
|
||||
* `agent_version` 由 Agent 代码内常量提供,升级时同步修改代码
|
||||
* `nginx_version` 由 Agent 启动时执行命令自动探测
|
||||
* 时间字段使用毫秒整数
|
||||
* `agent_token` 与 `discovery_token` 至少填写一个
|
||||
* 若 `agent_token` 为空且 `discovery_token` 存在,Agent 会自动注册并写回新的专属 `agent_token`
|
||||
* `node_name` 与 `node_ip` 可省略,未填写时自动探测
|
||||
* 未配置 `nginx_path` 时,默认使用 Docker Nginx 容器
|
||||
|
||||
---
|
||||
|
||||
@@ -193,12 +193,74 @@ npm run build
|
||||
|
||||
---
|
||||
|
||||
## 7. 当前已知限制
|
||||
## 7. Agent 一键部署(V3)
|
||||
|
||||
* 暂未内置 systemd unit 文件
|
||||
* 暂未提供一键部署脚本
|
||||
* Docker 模式仍是 MVP 级封装
|
||||
* 联调以手工步骤为主
|
||||
### 7.1 curl 安装
|
||||
|
||||
在目标机器上运行:
|
||||
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/ATSFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--discovery-token YOUR_DISCOVERY_TOKEN
|
||||
```
|
||||
|
||||
支持参数:
|
||||
|
||||
| 参数 | 说明 | 默认值 |
|
||||
| ------------------- | -------------------- | --------------------- |
|
||||
| `--server-url` | Server 地址(必填) | - |
|
||||
| `--discovery-token` | 全局 Discovery Token | - |
|
||||
| `--agent-token` | 节点专属 Token | - |
|
||||
| `--install-dir` | 安装目录 | `/opt/atsflare-agent` |
|
||||
| `--repo` | GitHub Release 仓库 | `Rain-kl/ATSFlare` |
|
||||
| `--no-service` | 不创建 systemd 服务 | - |
|
||||
|
||||
安装脚本会:
|
||||
|
||||
1. 从 GitHub Releases 下载最新 Agent 二进制(`atsflare-agent-{os}-{arch}`)
|
||||
2. 生成 `agent.json` 配置文件
|
||||
3. 创建 systemd 服务 `atsflare-agent.service`
|
||||
4. 启动并启用自启
|
||||
|
||||
### 7.2 管理端生成部署命令
|
||||
|
||||
在管理端 **系统设置 → 运维设置** 中查看已生成的一键部署命令,直接复制到目标节点执行。
|
||||
|
||||
### 7.3 Agent 自动更新
|
||||
|
||||
在管理端 **运维设置** 中启用「Agent 自动更新」后,Agent 会在每次心跳周期检查 GitHub Releases,发现新版本时自动下载并重启。
|
||||
|
||||
---
|
||||
|
||||
## 8. Agent 二进制命名规则
|
||||
|
||||
GitHub Release 中的 Agent 二进制命名格式:
|
||||
|
||||
* `atsflare-agent-linux-amd64`
|
||||
* `atsflare-agent-linux-arm64`
|
||||
* `atsflare-agent-darwin-arm64`
|
||||
|
||||
---
|
||||
|
||||
## 9. 运维设置热更新(V3)
|
||||
|
||||
以下参数可通过管理端 **运维设置** 修改,修改后通过心跳响应下发到 Agent,无需重启:
|
||||
|
||||
| 参数 | 说明 | Agent 字段 |
|
||||
| ---------------------- | -------------------- | ------------------ |
|
||||
| AgentHeartbeatInterval | 心跳间隔(毫秒) | heartbeat_interval |
|
||||
| AgentSyncInterval | 同步间隔(毫秒) | sync_interval |
|
||||
| NodeOfflineThreshold | 节点离线阈值(毫秒) | - |
|
||||
| AgentAutoUpdate | 是否启用自动更新 | auto_update |
|
||||
| AgentUpdateRepo | 自动更新仓库 | update_repo |
|
||||
|
||||
---
|
||||
|
||||
## 10. 当前已知限制
|
||||
|
||||
* Docker 模式仍是 MVP 级封装
|
||||
* 联调以手工步骤为主
|
||||
|
||||
---
|
||||
|
||||
|
||||
+142
-3
@@ -1,14 +1,14 @@
|
||||
# ATSFlare 设计基线(V3 准备版)
|
||||
# ATSFlare 设计基线(V3)
|
||||
|
||||
## 1. 文档目的
|
||||
|
||||
本文档不再展开记录第一版、第二版的实施过程,只保留当前系统边界、稳定约束与第三版开始前必须确认的设计输入。
|
||||
本文档保留当前系统边界、稳定约束与第三版的设计输入。
|
||||
|
||||
当前结论:
|
||||
|
||||
* 第一版、第二版已完成并进入归档状态
|
||||
* 第三版进入实施阶段
|
||||
* 当前代码库的可运行能力,以本文档为唯一设计基线
|
||||
* 第三版开发前,如需扩展系统边界,先更新本文档,再开始编码
|
||||
|
||||
---
|
||||
|
||||
@@ -324,3 +324,142 @@ Agent 接口当前覆盖:
|
||||
* 设计文档只保留当前有效基线
|
||||
* 已完成阶段的细节以 Git 历史为准
|
||||
* 新阶段开始前,先把设计输入写清楚,再进入实现
|
||||
|
||||
---
|
||||
|
||||
## 11. 第三版设计输入
|
||||
|
||||
### 11.1 目标定位
|
||||
|
||||
第三版聚焦**运维体验优化**,不扩展系统功能边界,只提升已有能力的可操作性与可维护性。
|
||||
|
||||
### 11.2 启动设置热更新
|
||||
|
||||
当前状态:
|
||||
|
||||
* `SESSION_SECRET`、`SQLITE_PATH`、`PORT` 等启动参数通过环境变量注入
|
||||
* 变更需要重启 Server 进程
|
||||
|
||||
第三版变更:
|
||||
|
||||
* 将可热更新的运行时设置迁入 Option 表,通过设置页面管理
|
||||
* 以下设置在前端运维设置面板中可配置:
|
||||
* `AgentHeartbeatInterval`:Agent 心跳上报间隔(毫秒),默认 30000
|
||||
* `AgentSyncInterval`:Agent 配置同步间隔(毫秒),默认 30000
|
||||
* `NodeOfflineThreshold`:节点离线判定阈值(毫秒),默认 120000
|
||||
* `AgentAutoUpdate`:是否允许 Agent 自动更新(`true`/`false`),默认 `false`
|
||||
* `AgentUpdateRepo`:Agent 自动更新 GitHub 仓库地址,默认 `Rain-kl/ATSFlare`
|
||||
* 环境变量类设置(`SESSION_SECRET`、`SQLITE_PATH`、`PORT`)不迁移,保留原有方式
|
||||
* 前端在设置页面新增「运维设置」Tab
|
||||
|
||||
### 11.3 Server 下发 Agent 设置
|
||||
|
||||
当前状态:
|
||||
|
||||
* Agent 心跳请求只是单向上报,Server 不返回业务数据
|
||||
* Agent 的心跳间隔、同步间隔只在本地 `agent.json` 配置
|
||||
|
||||
第三版变更:
|
||||
|
||||
* 心跳响应新增 `agent_settings` 字段,包含 Server 端可控的运行时参数:
|
||||
* `heartbeat_interval`(毫秒)
|
||||
* `sync_interval`(毫秒)
|
||||
* `auto_update`(布尔值)
|
||||
* `update_repo`(GitHub 仓库名)
|
||||
* Agent 收到心跳响应后,动态调整本地定时器间隔
|
||||
* 当 Server 未返回 `agent_settings` 或字段为空时,Agent 保持本地值不变
|
||||
* Agent 不持久化 Server 下发的间隔值,重启后以本地 `agent.json` 为准,再由下次心跳覆盖
|
||||
|
||||
### 11.4 Agent 自我更新
|
||||
|
||||
当前状态:
|
||||
|
||||
* Agent 版本固定,更新需要运维手动替换二进制文件
|
||||
|
||||
第三版变更:
|
||||
|
||||
* Agent 在收到 `auto_update=true` 时:
|
||||
* 通过 GitHub Releases API 查询 `update_repo` 的最新 Release
|
||||
* 比较本地 `agent_version` 与远端 tag
|
||||
* 若存在更新,下载对应平台的二进制文件
|
||||
* 替换自身二进制并重启
|
||||
* 更新检查频率:每轮心跳周期结束后检查一次,不独立起定时器
|
||||
* 更新过程中不中断当前同步任务
|
||||
* 更新失败不影响正常心跳与同步
|
||||
* Agent 二进制文件命名约定:`atsflare-agent-{os}-{arch}`
|
||||
|
||||
### 11.5 Agent 一键部署
|
||||
|
||||
当前状态:
|
||||
|
||||
* Agent 需要手动编译或复制二进制并创建配置文件
|
||||
|
||||
第三版变更:
|
||||
|
||||
* 提供 `install-agent.sh` 脚本,支持以下方式部署:
|
||||
```bash
|
||||
curl -fsSL https://raw.githubusercontent.com/Rain-kl/ATSFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
--server-url http://your-server:3000 \
|
||||
--discovery-token your-token
|
||||
```
|
||||
* 脚本行为:
|
||||
* 检测平台架构(linux/amd64、linux/arm64)
|
||||
* 从 GitHub Releases 下载最新 Agent 二进制
|
||||
* 创建安装目录(默认 `/opt/atsflare-agent`)
|
||||
* 生成基础 `agent.json` 配置
|
||||
* 创建 systemd service 文件(可选)
|
||||
* 启动 Agent
|
||||
|
||||
### 11.6 GitHub Actions 内测发布
|
||||
|
||||
当前状态:
|
||||
|
||||
* 现有工作流只构建 Server 二进制和 Docker 镜像
|
||||
* Agent 二进制不在 CI 中构建
|
||||
* Alpha 标签在部分工作流中被排除
|
||||
|
||||
第三版变更:
|
||||
|
||||
* 新增 `agent-release.yml` 工作流:
|
||||
* 触发条件:推送任意 tag(包括 alpha)
|
||||
* 构建 Agent 二进制:`linux/amd64`、`linux/arm64`、`darwin/arm64`
|
||||
* 产物命名:`atsflare-agent-{os}-{arch}`
|
||||
* 上传至 GitHub Release
|
||||
* 修改现有工作流:
|
||||
* 统一 `linux-release.yml` 为同时构建 Server + Agent 二进制
|
||||
* Alpha 标签的发布标记为 prerelease
|
||||
* 安装脚本与自我更新共用同一 Release 产物
|
||||
|
||||
### 11.7 前端运维体验优化
|
||||
|
||||
当前状态:
|
||||
|
||||
* 时间字段使用纳秒整数,不够友好
|
||||
* 设置页面未包含运维类设置
|
||||
|
||||
第三版变更:
|
||||
|
||||
* 设置页面新增「运维设置」Tab,包含:
|
||||
* Agent 心跳间隔
|
||||
* Agent 同步间隔
|
||||
* 节点离线阈值
|
||||
* Agent 自动更新开关
|
||||
* Agent 更新仓库
|
||||
* 全局 Discovery Token 展示与重新生成
|
||||
* Agent 一键部署命令展示(根据当前 ServerAddress 和 DiscoveryToken 动态生成 curl 命令)
|
||||
* 节点列表页优化:
|
||||
* 时间显示改为友好的相对时间格式
|
||||
* 节点状态使用颜色标识
|
||||
|
||||
---
|
||||
|
||||
## 12. 第三版不做的范围
|
||||
|
||||
以下内容不在第三版范围内:
|
||||
|
||||
* 多租户
|
||||
* WAF、限流、Bot
|
||||
* 节点分组、差异化下发
|
||||
* 证书自动签发与续期
|
||||
* Agent 配置文件加密
|
||||
* Server 远程执行 Agent 命令
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
# ATSFlare 开发规范(V3 准备版)
|
||||
# ATSFlare 开发规范(V3)
|
||||
|
||||
## 1. 适用范围
|
||||
|
||||
本规范适用于当前代码基线以及第三版开始前后的所有开发工作。
|
||||
本规范适用于当前代码基线以及第三版的所有开发工作。
|
||||
|
||||
当前系统状态:
|
||||
|
||||
* 第一版、第二版功能已完成
|
||||
* 当前开发重点不再是补历史阶段细节,而是稳定基线并准备第三版
|
||||
* 第三版聚焦运维体验优化
|
||||
* 超出 `docs/design.md` 当前边界的需求,必须先补设计,再编码
|
||||
|
||||
---
|
||||
@@ -202,6 +202,14 @@ Agent 必须满足:
|
||||
* 本地状态文件损坏时允许重建,但不能破坏当前生效配置
|
||||
* Docker 容器异常时,启动阶段应自动重建
|
||||
|
||||
V3 新增行为:
|
||||
|
||||
* 心跳响应包含 `agent_settings` 时,动态调整定时器间隔
|
||||
* `auto_update=true` 时在每次心跳后检查 GitHub Releases 更新
|
||||
* 自我更新失败不影响心跳与同步
|
||||
* Server 下发的间隔值不持久化到 `agent.json`,重启后以本地为准
|
||||
* Agent 新增 `internal/updater` 模块处理自我更新逻辑
|
||||
|
||||
---
|
||||
|
||||
## 8. 前端开发规范
|
||||
|
||||
+118
-4
@@ -1,4 +1,4 @@
|
||||
# ATSFlare 开发计划(V3 准备版)
|
||||
# ATSFlare 开发计划(V3)
|
||||
|
||||
## 1. 当前状态
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
* 第一版已完成并稳定闭环
|
||||
* 第二版已完成并补齐 HTTPS、证书、域名、节点管理与预览能力
|
||||
* 下一步进入第三版准备阶段
|
||||
* 第三版进入实施阶段,聚焦运维体验优化
|
||||
|
||||
本文件不再展开第一版、第二版的详细实施步骤,只保留第三版启动前的计划骨架与准入条件。
|
||||
本文件不再展开第一版、第二版的详细实施步骤,只保留第三版实施计划与验收标准。
|
||||
|
||||
---
|
||||
|
||||
@@ -37,4 +37,118 @@
|
||||
归档原则:
|
||||
|
||||
* 已完成阶段的实现细节以代码和 Git 历史为准
|
||||
* 后续计划文档只维护当前阶段与下一阶段
|
||||
* 后续计划文档只维护当前阶段与下一阶段
|
||||
|
||||
---
|
||||
|
||||
## 3. 第三版实施计划
|
||||
|
||||
### 3.1 阶段一:Server 运维设置热更新
|
||||
|
||||
目标:将可热更新的运维相关设置迁入 Option 表,前端提供设置面板。
|
||||
|
||||
实施步骤:
|
||||
|
||||
1. 在 `common/constants.go` 新增运维设置变量:
|
||||
* `AgentHeartbeatInterval`(默认 30000ms)
|
||||
* `AgentSyncInterval`(默认 30000ms)
|
||||
* `NodeOfflineThreshold`(默认 120000ms)
|
||||
* `AgentAutoUpdate`(默认 false)
|
||||
* `AgentUpdateRepo`(默认 `Rain-kl/ATSFlare`)
|
||||
2. 在 `model/option.go` 的 `InitOptionMap()` 注册新选项
|
||||
3. 在 `model/option.go` 的 `updateOptionMap()` 增加对新选项的同步
|
||||
4. 修改 `service/agent.go` 中 `computeNodeStatus()` 使用动态 `NodeOfflineThreshold`
|
||||
5. 前端设置页新增「运维设置」Tab
|
||||
|
||||
验收标准:
|
||||
|
||||
* 运维设置在设置页面可查看和修改
|
||||
* 修改后立即生效,无需重启 Server
|
||||
* `NodeOfflineThreshold` 变更后节点状态判定使用新阈值
|
||||
|
||||
### 3.2 阶段二:Server 下发 Agent 设置 + Agent 接收
|
||||
|
||||
目标:心跳响应携带 `agent_settings`,Agent 动态调整运行参数。
|
||||
|
||||
实施步骤:
|
||||
|
||||
1. Server 端:
|
||||
* 修改 `service/agent.go` 的 `HeartbeatNode()` 返回 `AgentSettings`
|
||||
* 新增 `AgentSettings` 结构体
|
||||
* 修改 `controller/agent.go` 心跳接口返回 `agent_settings`
|
||||
2. Agent 端:
|
||||
* 修改 `protocol/agent_api.go` 新增 `HeartbeatResponse` 和 `AgentSettings`
|
||||
* 修改 `httpclient/client.go` 解析心跳响应
|
||||
* 修改 `heartbeat/service.go` 返回 `HeartbeatResponse`
|
||||
* 修改 `agent/runner.go` 根据响应动态调整 `heartbeatTicker` 和 `syncTicker`
|
||||
|
||||
验收标准:
|
||||
|
||||
* Server 心跳响应 JSON 中包含 `agent_settings`
|
||||
* Agent 收到新间隔后在下一个周期生效
|
||||
* Agent 重启后恢复 `agent.json` 配置,再由心跳覆盖
|
||||
* Server 未配置时 Agent 保持本地值不变
|
||||
|
||||
### 3.3 阶段三:Agent 自我更新
|
||||
|
||||
目标:Agent 支持从 GitHub Releases 自动更新。
|
||||
|
||||
实施步骤:
|
||||
|
||||
1. Agent 新增 `internal/updater` 模块:
|
||||
* GitHub Releases API 查询最新版本
|
||||
* 版本比较(语义化版本)
|
||||
* 下载对应平台二进制
|
||||
* 替换自身并重启(exec syscall)
|
||||
2. 在 `runner.go` 心跳循环中集成更新检查
|
||||
3. 更新触发条件:`auto_update=true` 且存在新版本
|
||||
|
||||
验收标准:
|
||||
|
||||
* Agent 能正确检测新版本
|
||||
* 能下载并替换自身二进制
|
||||
* 更新后自动重启并恢复心跳
|
||||
* 更新失败不影响正常运行
|
||||
|
||||
### 3.4 阶段四:GitHub Actions 完善与 Agent 一键部署
|
||||
|
||||
目标:CI 支持 Agent 构建发布,提供 curl 一键安装。
|
||||
|
||||
实施步骤:
|
||||
|
||||
1. 新增 `.github/workflows/agent-release.yml`
|
||||
2. 修改现有工作流支持 alpha/prerelease
|
||||
3. 创建 `scripts/install-agent.sh` 安装脚本
|
||||
4. 前端运维设置面板展示动态 curl 部署命令
|
||||
|
||||
验收标准:
|
||||
|
||||
* 推送 tag 后 Agent 二进制出现在 GitHub Release
|
||||
* Alpha tag 标记为 prerelease
|
||||
* curl 命令可在干净 Linux 机器上完成 Agent 部署
|
||||
* 前端正确展示拼接后的 curl 命令
|
||||
|
||||
### 3.5 阶段五:前端体验优化
|
||||
|
||||
目标:优化管理端操作体验。
|
||||
|
||||
实施步骤:
|
||||
|
||||
1. 节点列表时间显示改为友好格式
|
||||
2. 节点状态颜色标识
|
||||
3. Discovery Token 在运维设置面板中可查看和重新生成
|
||||
4. Agent 部署命令一键复制
|
||||
|
||||
验收标准:
|
||||
|
||||
* 时间显示为友好的相对时间(如「2 分钟前」)
|
||||
* 节点状态有颜色区分:在线(绿色)、离线(红色)、待接入(黄色)
|
||||
* curl 部署命令支持一键复制
|
||||
|
||||
---
|
||||
|
||||
## 4. 阶段执行原则
|
||||
|
||||
* 每个阶段完成后验证验收标准,再进入下一阶段
|
||||
* 阶段间的代码不相互依赖时可并行
|
||||
* 每个阶段完成后运行全量测试
|
||||
Executable
+169
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
# ATSFlare Agent Installer
|
||||
# Usage:
|
||||
# curl -fsSL https://raw.githubusercontent.com/Rain-kl/ATSFlare/main/scripts/install-agent.sh | bash -s -- \
|
||||
# --server-url http://your-server:3000 \
|
||||
# --discovery-token your-token
|
||||
|
||||
INSTALL_DIR="/opt/atsflare-agent"
|
||||
REPO="Rain-kl/ATSFlare"
|
||||
SERVER_URL=""
|
||||
DISCOVERY_TOKEN=""
|
||||
AGENT_TOKEN=""
|
||||
CREATE_SERVICE="true"
|
||||
|
||||
usage() {
|
||||
cat <<EOF
|
||||
ATSFlare Agent Installer
|
||||
|
||||
Usage:
|
||||
install-agent.sh [OPTIONS]
|
||||
|
||||
Options:
|
||||
--server-url URL Server URL (required)
|
||||
--discovery-token TOKEN Discovery token for auto-registration
|
||||
--agent-token TOKEN Node-specific agent token
|
||||
--install-dir DIR Installation directory (default: /opt/atsflare-agent)
|
||||
--repo REPO GitHub repository (default: Rain-kl/ATSFlare)
|
||||
--no-service Do not create systemd service
|
||||
-h, --help Show this help message
|
||||
|
||||
Examples:
|
||||
# Install with discovery token (auto-register)
|
||||
install-agent.sh --server-url http://10.0.0.1:3000 --discovery-token abc123
|
||||
|
||||
# Install with node-specific token
|
||||
install-agent.sh --server-url http://10.0.0.1:3000 --agent-token node-token-xyz
|
||||
EOF
|
||||
exit 0
|
||||
}
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--server-url) SERVER_URL="$2"; shift 2 ;;
|
||||
--discovery-token) DISCOVERY_TOKEN="$2"; shift 2 ;;
|
||||
--agent-token) AGENT_TOKEN="$2"; shift 2 ;;
|
||||
--install-dir) INSTALL_DIR="$2"; shift 2 ;;
|
||||
--repo) REPO="$2"; shift 2 ;;
|
||||
--no-service) CREATE_SERVICE="false"; shift ;;
|
||||
-h|--help) usage ;;
|
||||
*) echo "Unknown option: $1"; exit 1 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -z "$SERVER_URL" ]]; then
|
||||
echo "Error: --server-url is required"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ -z "$DISCOVERY_TOKEN" && -z "$AGENT_TOKEN" ]]; then
|
||||
echo "Error: either --discovery-token or --agent-token is required"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Detect platform
|
||||
OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
|
||||
ARCH="$(uname -m)"
|
||||
case "$ARCH" in
|
||||
x86_64|amd64) ARCH="amd64" ;;
|
||||
aarch64|arm64) ARCH="arm64" ;;
|
||||
*) echo "Unsupported architecture: $ARCH"; exit 1 ;;
|
||||
esac
|
||||
|
||||
if [[ "$OS" != "linux" && "$OS" != "darwin" ]]; then
|
||||
echo "Unsupported OS: $OS"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ASSET_NAME="atsflare-agent-${OS}-${ARCH}"
|
||||
echo "Detected platform: ${OS}/${ARCH}"
|
||||
|
||||
# Get latest release download URL
|
||||
echo "Fetching latest release from ${REPO}..."
|
||||
RELEASE_INFO=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest")
|
||||
DOWNLOAD_URL=$(echo "$RELEASE_INFO" | grep -o "\"browser_download_url\"[[:space:]]*:[[:space:]]*\"[^\"]*${ASSET_NAME}\"" | grep -o 'https://[^"]*' || true)
|
||||
|
||||
if [[ -z "$DOWNLOAD_URL" ]]; then
|
||||
echo "Error: no matching asset '${ASSET_NAME}' found in latest release"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
TAG=$(echo "$RELEASE_INFO" | grep -o '"tag_name"[[:space:]]*:[[:space:]]*"[^"]*"' | grep -o '"[^"]*"$' | tr -d '"')
|
||||
echo "Latest release: ${TAG}"
|
||||
|
||||
# Create install directory
|
||||
echo "Installing to ${INSTALL_DIR}..."
|
||||
mkdir -p "${INSTALL_DIR}/data"
|
||||
|
||||
# Download binary
|
||||
echo "Downloading ${ASSET_NAME}..."
|
||||
curl -fsSL -o "${INSTALL_DIR}/atsflare-agent" "$DOWNLOAD_URL"
|
||||
chmod +x "${INSTALL_DIR}/atsflare-agent"
|
||||
|
||||
# Generate config
|
||||
CONFIG_FILE="${INSTALL_DIR}/agent.json"
|
||||
if [[ ! -f "$CONFIG_FILE" ]]; then
|
||||
echo "Generating agent.json..."
|
||||
if [[ -n "$AGENT_TOKEN" ]]; then
|
||||
cat > "$CONFIG_FILE" <<CFGEOF
|
||||
{
|
||||
"server_url": "${SERVER_URL}",
|
||||
"agent_token": "${AGENT_TOKEN}",
|
||||
"data_dir": "${INSTALL_DIR}/data",
|
||||
"heartbeat_interval": 30000,
|
||||
"sync_interval": 30000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
CFGEOF
|
||||
else
|
||||
cat > "$CONFIG_FILE" <<CFGEOF
|
||||
{
|
||||
"server_url": "${SERVER_URL}",
|
||||
"discovery_token": "${DISCOVERY_TOKEN}",
|
||||
"data_dir": "${INSTALL_DIR}/data",
|
||||
"heartbeat_interval": 30000,
|
||||
"sync_interval": 30000,
|
||||
"request_timeout": 10000
|
||||
}
|
||||
CFGEOF
|
||||
fi
|
||||
else
|
||||
echo "Config file already exists, skipping generation"
|
||||
fi
|
||||
|
||||
# Create systemd service
|
||||
if [[ "$CREATE_SERVICE" == "true" && "$OS" == "linux" && -d /etc/systemd/system ]]; then
|
||||
echo "Creating systemd service..."
|
||||
cat > /etc/systemd/system/atsflare-agent.service <<SVCEOF
|
||||
[Unit]
|
||||
Description=ATSFlare Agent
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=${INSTALL_DIR}/atsflare-agent -config ${CONFIG_FILE}
|
||||
WorkingDirectory=${INSTALL_DIR}
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
SVCEOF
|
||||
|
||||
systemctl daemon-reload
|
||||
systemctl enable atsflare-agent
|
||||
systemctl start atsflare-agent
|
||||
echo "Service created and started: atsflare-agent"
|
||||
else
|
||||
echo ""
|
||||
echo "To start the agent manually:"
|
||||
echo " ${INSTALL_DIR}/atsflare-agent -config ${CONFIG_FILE}"
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "ATSFlare Agent installed successfully!"
|
||||
echo " Binary: ${INSTALL_DIR}/atsflare-agent"
|
||||
echo " Config: ${CONFIG_FILE}"
|
||||
echo " Data: ${INSTALL_DIR}/data"
|
||||
Reference in New Issue
Block a user