mirror of
https://github.com/Sagit-chu/flvx.git
synced 2026-11-15 01:04:22 +08:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9e6f80019d | |||
| a8fd01d4d8 | |||
| cbe2fc492e | |||
| ae370382d3 |
+10
-1
@@ -64,6 +64,14 @@ curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/panel_instal
|
||||
curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/install.sh -o install.sh && chmod +x install.sh && ./install.sh
|
||||
```
|
||||
|
||||
Alpine Linux 最小化安装若未包含 `curl`,可使用系统自带的 `wget` 下载:
|
||||
|
||||
```bash
|
||||
wget -O install.sh https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/install.sh && chmod +x install.sh && ./install.sh
|
||||
```
|
||||
|
||||
脚本会在 Alpine 上自动安装 Bash,并使用 OpenRC 注册、启动和管理 `flux_agent` 服务;其他受支持的 Linux 发行版继续使用 systemd。
|
||||
|
||||
**安装过程中会提示输入:**
|
||||
- **服务器地址**: 面板端的通信地址(通常是 `http://<面板IP>:<后端端口>`,例如 `http://1.2.3.4:6365`)。
|
||||
- **密钥**: 刚才在面板中获取的节点密钥。
|
||||
@@ -77,7 +85,8 @@ curl -L https://raw.githubusercontent.com/Sagit-chu/flux-panel/main/install.sh -
|
||||
|
||||
### 3. 验证安装
|
||||
安装完成后,服务会自动启动。
|
||||
- 查看状态: `systemctl status flux_agent`
|
||||
- systemd 查看状态: `systemctl status flux_agent`
|
||||
- Alpine/OpenRC 查看状态: `rc-service flux_agent status`
|
||||
- 回到面板 **节点管理** 页面,该节点状态应显示为 **在线**。
|
||||
|
||||
---
|
||||
|
||||
@@ -3,6 +3,7 @@ package handler
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"net/netip"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -75,6 +76,12 @@ func IsValidNodeAddress(addr string) error {
|
||||
if strings.ContainsAny(addr, "/?") {
|
||||
return fmt.Errorf("address must not contain path or query parameters")
|
||||
}
|
||||
// A bare IPv6 literal contains multiple colons, so net.SplitHostPort treats
|
||||
// it as a malformed host:port pair. Accept IP literals before attempting
|
||||
// host:port parsing; netip also handles scoped IPv6 addresses.
|
||||
if _, err := netip.ParseAddr(addr); err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
_, _, err := net.SplitHostPort(addr)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
package handler
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestIssue515IsValidNodeAddressAcceptsBareIPv6(t *testing.T) {
|
||||
for _, addr := range []string{
|
||||
"2001:db8::1",
|
||||
"::1",
|
||||
"fe80::1%eth0",
|
||||
} {
|
||||
t.Run(addr, func(t *testing.T) {
|
||||
if err := IsValidNodeAddress(addr); err != nil {
|
||||
t.Fatalf("expected bare IPv6 address %q to be accepted: %v", addr, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsValidNodeAddressKeepsExistingAddressForms(t *testing.T) {
|
||||
for _, addr := range []string{
|
||||
"203.0.113.10",
|
||||
"node.example.com",
|
||||
"node.example.com:6365",
|
||||
"[2001:db8::1]:6365",
|
||||
} {
|
||||
t.Run(addr, func(t *testing.T) {
|
||||
if err := IsValidNodeAddress(addr); err != nil {
|
||||
t.Fatalf("expected node address %q to be accepted: %v", addr, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsValidNodeAddressRejectsURLComponents(t *testing.T) {
|
||||
for _, addr := range []string{
|
||||
"https://node.example.com",
|
||||
"node.example.com/path",
|
||||
"node.example.com?transport=tcp",
|
||||
} {
|
||||
t.Run(addr, func(t *testing.T) {
|
||||
if err := IsValidNodeAddress(addr); err == nil {
|
||||
t.Fatalf("expected node address %q to be rejected", addr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
@@ -31,6 +32,26 @@ type TunnelQualityHop struct {
|
||||
TargetPort int `json:"targetPort,omitempty"`
|
||||
}
|
||||
|
||||
type TunnelQualityCandidateHop struct {
|
||||
TunnelQualityHop
|
||||
FromRole string `json:"fromRole"`
|
||||
ToRole string `json:"toRole"`
|
||||
HopIndex int `json:"hopIndex"`
|
||||
Selected bool `json:"selected"`
|
||||
ErrorMessage string `json:"errorMessage,omitempty"`
|
||||
}
|
||||
|
||||
type tunnelQualityChainDetails struct {
|
||||
PrimaryPath []TunnelQualityHop `json:"primaryPath,omitempty"`
|
||||
CandidateHops []TunnelQualityCandidateHop `json:"candidateHops,omitempty"`
|
||||
}
|
||||
|
||||
type tunnelQualityCandidateGroup struct {
|
||||
role string
|
||||
roleIndex int
|
||||
nodes []chainNodeRecord
|
||||
}
|
||||
|
||||
// tunnelQualitySnapshot is the in-memory latest probe result for a tunnel.
|
||||
type tunnelQualitySnapshot struct {
|
||||
TunnelID int64 `json:"tunnelId"`
|
||||
@@ -283,16 +304,25 @@ func (p *tunnelQualityProber) probeTunnel(tunnelID int64) {
|
||||
pingCount: 1,
|
||||
timeoutMessage: "探测超时",
|
||||
}
|
||||
p.probeBestExitOwners(tunnelID, inNodes, midNodesGrouped, outNodes, ipPreference, options, probeTarget)
|
||||
roundPinger := newBestExitRoundPinger(p.pingNode)
|
||||
p.probeBestExitOwners(tunnelID, inNodes, midNodesGrouped, outNodes, ipPreference, options, probeTarget, roundPinger)
|
||||
|
||||
entry, _, entryOnline := p.firstOnlineChainNode(inNodes)
|
||||
exit, _, exitOnline := p.firstOnlineChainNode(outNodes)
|
||||
selectedNodeIDs := make(map[string]int64, 2+len(midNodesGrouped))
|
||||
if entryOnline {
|
||||
selectedNodeIDs[tunnelQualityGroupKey("entry", 0)] = entry.NodeID
|
||||
}
|
||||
if exitOnline {
|
||||
selectedNodeIDs[tunnelQualityGroupKey("exit", 0)] = exit.NodeID
|
||||
}
|
||||
var primaryHops []TunnelQualityHop
|
||||
|
||||
switch tunnel.Type {
|
||||
case 1:
|
||||
// Port forwarding: entry → public probe target only.
|
||||
if entryOnline {
|
||||
lat, loss, err := p.pingNode(entry.NodeID, probeTarget.Host, probeTarget.Port, options)
|
||||
lat, loss, err := roundPinger(entry.NodeID, probeTarget.Host, probeTarget.Port, options)
|
||||
if err == nil {
|
||||
snap.ExitToBingLatency = lat
|
||||
snap.ExitToBingLoss = loss
|
||||
@@ -318,13 +348,12 @@ func (p *tunnelQualityProber) probeTunnel(tunnelID int64) {
|
||||
snap.EntryToExitLatency = -1
|
||||
snap.EntryToExitLoss = 100
|
||||
} else {
|
||||
var hops []TunnelQualityHop
|
||||
var totalLat float64
|
||||
remainingSuccessProb := 1.0
|
||||
|
||||
nodesInPath := make([]chainNodeRecord, 0, 2+len(midNodesGrouped))
|
||||
nodesInPath = append(nodesInPath, entry)
|
||||
for _, midGroup := range midNodesGrouped {
|
||||
for midIndex, midGroup := range midNodesGrouped {
|
||||
mid, _, online := p.firstOnlineChainNode(midGroup)
|
||||
if !online {
|
||||
probeOK = false
|
||||
@@ -332,6 +361,7 @@ func (p *tunnelQualityProber) probeTunnel(tunnelID int64) {
|
||||
break
|
||||
}
|
||||
nodesInPath = append(nodesInPath, mid)
|
||||
selectedNodeIDs[tunnelQualityGroupKey("middle", midIndex)] = mid.NodeID
|
||||
}
|
||||
if probeOK {
|
||||
nodesInPath = append(nodesInPath, exit)
|
||||
@@ -354,7 +384,7 @@ func (p *tunnelQualityProber) probeTunnel(tunnelID int64) {
|
||||
probeOK = false
|
||||
hop.Latency = -1
|
||||
hop.Loss = 100
|
||||
hops = append(hops, hop)
|
||||
primaryHops = append(primaryHops, hop)
|
||||
break
|
||||
}
|
||||
|
||||
@@ -365,25 +395,25 @@ func (p *tunnelQualityProber) probeTunnel(tunnelID int64) {
|
||||
probeOK = false
|
||||
hop.Latency = -1
|
||||
hop.Loss = 100
|
||||
hops = append(hops, hop)
|
||||
primaryHops = append(primaryHops, hop)
|
||||
break
|
||||
}
|
||||
|
||||
hop.TargetIP = targetIP
|
||||
hop.TargetPort = targetPort
|
||||
|
||||
lat, loss, err := p.pingNode(source.NodeID, targetIP, targetPort, options)
|
||||
lat, loss, err := roundPinger(source.NodeID, targetIP, targetPort, options)
|
||||
if err == nil {
|
||||
hop.Latency = lat
|
||||
hop.Loss = loss
|
||||
totalLat += lat
|
||||
remainingSuccessProb *= (1.0 - loss/100.0)
|
||||
hops = append(hops, hop)
|
||||
primaryHops = append(primaryHops, hop)
|
||||
} else {
|
||||
probeOK = false
|
||||
hop.Latency = -1
|
||||
hop.Loss = 100
|
||||
hops = append(hops, hop)
|
||||
primaryHops = append(primaryHops, hop)
|
||||
if snap.ErrorMessage == "" {
|
||||
snap.ErrorMessage = err.Error()
|
||||
}
|
||||
@@ -398,17 +428,11 @@ func (p *tunnelQualityProber) probeTunnel(tunnelID int64) {
|
||||
snap.EntryToExitLatency = -1
|
||||
snap.EntryToExitLoss = 100
|
||||
}
|
||||
|
||||
if len(hops) > 0 {
|
||||
if b, err := json.Marshal(hops); err == nil {
|
||||
snap.ChainDetails = string(b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Exit → Bing
|
||||
if exitOnline {
|
||||
lat, loss, err := p.pingNode(exit.NodeID, probeTarget.Host, probeTarget.Port, options)
|
||||
lat, loss, err := roundPinger(exit.NodeID, probeTarget.Host, probeTarget.Port, options)
|
||||
if err == nil {
|
||||
snap.ExitToBingLatency = lat
|
||||
snap.ExitToBingLoss = loss
|
||||
@@ -424,7 +448,7 @@ func (p *tunnelQualityProber) probeTunnel(tunnelID int64) {
|
||||
default:
|
||||
// Unknown type: entry → public probe target.
|
||||
if entryOnline {
|
||||
lat, loss, err := p.pingNode(entry.NodeID, probeTarget.Host, probeTarget.Port, options)
|
||||
lat, loss, err := roundPinger(entry.NodeID, probeTarget.Host, probeTarget.Port, options)
|
||||
if err == nil {
|
||||
snap.ExitToBingLatency = lat
|
||||
snap.ExitToBingLoss = loss
|
||||
@@ -437,9 +461,192 @@ func (p *tunnelQualityProber) probeTunnel(tunnelID int64) {
|
||||
}
|
||||
}
|
||||
|
||||
candidateHops := p.probeTunnelCandidateHops(
|
||||
tunnel.Type,
|
||||
inNodes,
|
||||
midNodesGrouped,
|
||||
outNodes,
|
||||
selectedNodeIDs,
|
||||
ipPreference,
|
||||
options,
|
||||
probeTarget,
|
||||
roundPinger,
|
||||
)
|
||||
if len(primaryHops) > 0 || len(candidateHops) > 0 {
|
||||
details := tunnelQualityChainDetails{
|
||||
PrimaryPath: primaryHops,
|
||||
CandidateHops: candidateHops,
|
||||
}
|
||||
if b, err := json.Marshal(details); err == nil {
|
||||
snap.ChainDetails = string(b)
|
||||
}
|
||||
}
|
||||
|
||||
p.storeResult(snap)
|
||||
}
|
||||
|
||||
func tunnelQualityGroupKey(role string, index int) string {
|
||||
return fmt.Sprintf("%s:%d", role, index)
|
||||
}
|
||||
|
||||
func (p *tunnelQualityProber) probeTunnelCandidateHops(
|
||||
tunnelType int,
|
||||
inNodes []chainNodeRecord,
|
||||
chainHops [][]chainNodeRecord,
|
||||
outNodes []chainNodeRecord,
|
||||
selectedNodeIDs map[string]int64,
|
||||
ipPreference string,
|
||||
options diagnosisExecOptions,
|
||||
probeTarget tunnelProbeTarget,
|
||||
ping bestExitProbeFunc,
|
||||
) []TunnelQualityCandidateHop {
|
||||
if p == nil || p.handler == nil || ping == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if tunnelType != 2 {
|
||||
return p.probePublicTargetCandidates("entry", 0, inNodes, selectedNodeIDs, options, probeTarget, ping)
|
||||
}
|
||||
|
||||
groups := make([]tunnelQualityCandidateGroup, 0, 2+len(chainHops))
|
||||
groups = append(groups, tunnelQualityCandidateGroup{role: "entry", roleIndex: 0, nodes: inNodes})
|
||||
for i, hop := range chainHops {
|
||||
groups = append(groups, tunnelQualityCandidateGroup{role: "middle", roleIndex: i, nodes: hop})
|
||||
}
|
||||
groups = append(groups, tunnelQualityCandidateGroup{role: "exit", roleIndex: 0, nodes: outNodes})
|
||||
|
||||
var items []TunnelQualityCandidateHop
|
||||
for i := 0; i < len(groups)-1; i++ {
|
||||
items = append(items, p.probeCandidateGroupLinks(
|
||||
groups[i],
|
||||
groups[i+1],
|
||||
i,
|
||||
selectedNodeIDs,
|
||||
ipPreference,
|
||||
options,
|
||||
ping,
|
||||
)...)
|
||||
}
|
||||
items = append(items, p.probePublicTargetCandidates(
|
||||
"exit",
|
||||
0,
|
||||
outNodes,
|
||||
selectedNodeIDs,
|
||||
options,
|
||||
probeTarget,
|
||||
ping,
|
||||
)...)
|
||||
return items
|
||||
}
|
||||
|
||||
func (p *tunnelQualityProber) probeCandidateGroupLinks(
|
||||
fromGroup tunnelQualityCandidateGroup,
|
||||
toGroup tunnelQualityCandidateGroup,
|
||||
hopIndex int,
|
||||
selectedNodeIDs map[string]int64,
|
||||
ipPreference string,
|
||||
options diagnosisExecOptions,
|
||||
ping bestExitProbeFunc,
|
||||
) []TunnelQualityCandidateHop {
|
||||
items := make([]TunnelQualityCandidateHop, 0, len(fromGroup.nodes)*len(toGroup.nodes))
|
||||
for _, source := range fromGroup.nodes {
|
||||
for _, target := range toGroup.nodes {
|
||||
item := TunnelQualityCandidateHop{
|
||||
TunnelQualityHop: TunnelQualityHop{
|
||||
FromNodeID: source.NodeID,
|
||||
FromNodeName: source.NodeName,
|
||||
ToNodeID: target.NodeID,
|
||||
ToNodeName: target.NodeName,
|
||||
Latency: -1,
|
||||
Loss: 100,
|
||||
},
|
||||
FromRole: fromGroup.role,
|
||||
ToRole: toGroup.role,
|
||||
HopIndex: hopIndex,
|
||||
Selected: selectedNodeIDs[tunnelQualityGroupKey(fromGroup.role, fromGroup.roleIndex)] == source.NodeID &&
|
||||
selectedNodeIDs[tunnelQualityGroupKey(toGroup.role, toGroup.roleIndex)] == target.NodeID,
|
||||
}
|
||||
|
||||
sourceNode, sourceErr := p.handler.getNodeRecord(source.NodeID)
|
||||
if sourceErr != nil || !isTunnelProbeNodeOnline(sourceNode) {
|
||||
item.ErrorMessage = "来源节点不在线"
|
||||
items = append(items, item)
|
||||
continue
|
||||
}
|
||||
targetNode, targetErr := p.handler.getNodeRecord(target.NodeID)
|
||||
if targetErr != nil || !isTunnelProbeNodeOnline(targetNode) {
|
||||
item.ErrorMessage = "目标节点不在线"
|
||||
items = append(items, item)
|
||||
continue
|
||||
}
|
||||
|
||||
targetIP, targetPort, resolveErr := resolveChainProbeTarget(sourceNode, targetNode, target.Port, ipPreference, target.ConnectIP)
|
||||
if resolveErr != nil {
|
||||
item.ErrorMessage = resolveErr.Error()
|
||||
items = append(items, item)
|
||||
continue
|
||||
}
|
||||
item.TargetIP = targetIP
|
||||
item.TargetPort = targetPort
|
||||
latency, loss, probeErr := ping(source.NodeID, targetIP, targetPort, options)
|
||||
if probeErr != nil {
|
||||
item.ErrorMessage = probeErr.Error()
|
||||
items = append(items, item)
|
||||
continue
|
||||
}
|
||||
item.Latency = latency
|
||||
item.Loss = loss
|
||||
items = append(items, item)
|
||||
}
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func (p *tunnelQualityProber) probePublicTargetCandidates(
|
||||
fromRole string,
|
||||
fromIndex int,
|
||||
nodes []chainNodeRecord,
|
||||
selectedNodeIDs map[string]int64,
|
||||
options diagnosisExecOptions,
|
||||
probeTarget tunnelProbeTarget,
|
||||
ping bestExitProbeFunc,
|
||||
) []TunnelQualityCandidateHop {
|
||||
items := make([]TunnelQualityCandidateHop, 0, len(nodes))
|
||||
for _, source := range nodes {
|
||||
item := TunnelQualityCandidateHop{
|
||||
TunnelQualityHop: TunnelQualityHop{
|
||||
FromNodeID: source.NodeID,
|
||||
FromNodeName: source.NodeName,
|
||||
ToNodeName: formatTunnelProbeTarget(probeTarget),
|
||||
Latency: -1,
|
||||
Loss: 100,
|
||||
TargetIP: probeTarget.Host,
|
||||
TargetPort: probeTarget.Port,
|
||||
},
|
||||
FromRole: fromRole,
|
||||
ToRole: "target",
|
||||
HopIndex: fromIndex,
|
||||
Selected: selectedNodeIDs[tunnelQualityGroupKey(fromRole, fromIndex)] == source.NodeID,
|
||||
}
|
||||
sourceNode, sourceErr := p.handler.getNodeRecord(source.NodeID)
|
||||
if sourceErr != nil || !isTunnelProbeNodeOnline(sourceNode) {
|
||||
item.ErrorMessage = "来源节点不在线"
|
||||
items = append(items, item)
|
||||
continue
|
||||
}
|
||||
latency, loss, probeErr := ping(source.NodeID, probeTarget.Host, probeTarget.Port, options)
|
||||
if probeErr != nil {
|
||||
item.ErrorMessage = probeErr.Error()
|
||||
items = append(items, item)
|
||||
continue
|
||||
}
|
||||
item.Latency = latency
|
||||
item.Loss = loss
|
||||
items = append(items, item)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func isTunnelProbeNodeOnline(node *nodeRecord) bool {
|
||||
return node != nil && (node.IsRemote == 1 || node.Status == 1)
|
||||
}
|
||||
@@ -457,7 +664,7 @@ func (p *tunnelQualityProber) firstOnlineChainNode(nodes []chainNodeRecord) (cha
|
||||
return chainNodeRecord{}, nil, false
|
||||
}
|
||||
|
||||
func (p *tunnelQualityProber) probeBestExitOwners(tunnelID int64, inNodes []chainNodeRecord, chainHops [][]chainNodeRecord, outNodes []chainNodeRecord, ipPreference string, options diagnosisExecOptions, probeTarget tunnelProbeTarget) {
|
||||
func (p *tunnelQualityProber) probeBestExitOwners(tunnelID int64, inNodes []chainNodeRecord, chainHops [][]chainNodeRecord, outNodes []chainNodeRecord, ipPreference string, options diagnosisExecOptions, probeTarget tunnelProbeTarget, roundPinger bestExitProbeFunc) {
|
||||
if p == nil || p.handler == nil || p.handler.bestExit == nil || len(outNodes) <= 1 {
|
||||
return
|
||||
}
|
||||
@@ -479,9 +686,6 @@ func (p *tunnelQualityProber) probeBestExitOwners(tunnelID int64, inNodes []chai
|
||||
nodeMap[exit.NodeID] = node
|
||||
}
|
||||
}
|
||||
// This best-exit decision cache is per decision round; the display-oriented
|
||||
// tunnel quality snapshot may still collect its own first-exit public probe.
|
||||
roundPinger := newBestExitRoundPinger(p.pingNode)
|
||||
for _, owner := range owners {
|
||||
if nodeMap[owner.NodeID] == nil {
|
||||
continue
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
"testing"
|
||||
@@ -106,6 +107,57 @@ func TestTunnelQualityProberUsesOnlineBackupExit(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestTunnelQualityProberReportsAllExitCandidateLatencies(t *testing.T) {
|
||||
h := setupProbeTargetTunnelHandler(t)
|
||||
seedQualityForwardTunnel(t, h, 83, []int{1, 1})
|
||||
|
||||
p := newTunnelQualityProber(h)
|
||||
p.probeNode = func(nodeID int64, ip string, port int, options diagnosisExecOptions) (float64, float64, error) {
|
||||
switch fmt.Sprintf("%d|%s|%d", nodeID, ip, port) {
|
||||
case "10|10.0.0.30|30030":
|
||||
return 20, 0, nil
|
||||
case "10|10.0.0.31|30031":
|
||||
return 35, 0, nil
|
||||
case "30|www.bing.com|443":
|
||||
return 50, 0, nil
|
||||
case "31|www.bing.com|443":
|
||||
return 65, 0, nil
|
||||
default:
|
||||
return 0, 100, fmt.Errorf("unexpected probe node=%d target=%s:%d", nodeID, ip, port)
|
||||
}
|
||||
}
|
||||
p.probeTunnel(83)
|
||||
|
||||
snaps := p.GetAll()
|
||||
if len(snaps) != 1 {
|
||||
t.Fatalf("expected one quality snapshot, got %+v", snaps)
|
||||
}
|
||||
if snaps[0].EntryToExitLatency != 20 || snaps[0].ExitToBingLatency != 50 {
|
||||
t.Fatalf("expected primary path metrics to remain unchanged, got %+v", snaps[0])
|
||||
}
|
||||
|
||||
var details tunnelQualityChainDetails
|
||||
if err := json.Unmarshal([]byte(snaps[0].ChainDetails), &details); err != nil {
|
||||
t.Fatalf("decode chain details: %v", err)
|
||||
}
|
||||
assertCandidateHop := func(fromID, toID int64, latency float64, selected bool) {
|
||||
t.Helper()
|
||||
for _, hop := range details.CandidateHops {
|
||||
if hop.FromNodeID == fromID && hop.ToNodeID == toID {
|
||||
if hop.Latency != latency || hop.Selected != selected || hop.ErrorMessage != "" {
|
||||
t.Fatalf("unexpected candidate hop: %+v", hop)
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
t.Fatalf("candidate hop %d -> %d not found in %+v", fromID, toID, details.CandidateHops)
|
||||
}
|
||||
assertCandidateHop(10, 30, 20, true)
|
||||
assertCandidateHop(10, 31, 35, false)
|
||||
assertCandidateHop(30, 0, 50, true)
|
||||
assertCandidateHop(31, 0, 65, false)
|
||||
}
|
||||
|
||||
func TestTunnelQualityProberStoresProbeTargetWhenChainIncomplete(t *testing.T) {
|
||||
h := setupProbeTargetTunnelHandler(t)
|
||||
seedProbeTargetTunnel(t, h, 78, "quality-target-incomplete", "speed.example.com", 8443)
|
||||
|
||||
@@ -132,3 +132,31 @@ func TestUpsertTunnelMetricBucketsIsSafeUnderConcurrency(t *testing.T) {
|
||||
t.Fatalf("expected bytesOut %d, got %d", wantOut, rows[0].BytesOut)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetLatestTunnelQualitiesIncludesChainDetails(t *testing.T) {
|
||||
r, err := Open(":memory:")
|
||||
if err != nil {
|
||||
t.Fatalf("open repo: %v", err)
|
||||
}
|
||||
defer r.Close()
|
||||
|
||||
if err := r.InsertTunnelQuality(&model.TunnelQuality{
|
||||
TunnelID: 7,
|
||||
Timestamp: time.Now().UnixMilli(),
|
||||
Success: 1,
|
||||
ChainDetails: `{"primaryPath":[],"candidateHops":[{"fromNodeId":10,"toNodeId":31}]}`,
|
||||
}); err != nil {
|
||||
t.Fatalf("insert tunnel quality: %v", err)
|
||||
}
|
||||
|
||||
items, err := r.GetLatestTunnelQualities()
|
||||
if err != nil {
|
||||
t.Fatalf("get latest tunnel qualities: %v", err)
|
||||
}
|
||||
if len(items) != 1 {
|
||||
t.Fatalf("expected one latest tunnel quality, got %+v", items)
|
||||
}
|
||||
if items[0].ChainDetails == "" {
|
||||
t.Fatalf("expected chain details in latest quality row, got %+v", items[0])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,8 @@ func (r *Repository) GetLatestTunnelQualities() ([]model.TunnelQuality, error) {
|
||||
// Use window function (works on modern SQLite 3.25+ and PostgreSQL).
|
||||
q := `
|
||||
SELECT id, tunnel_id, entry_to_exit_latency, exit_to_bing_latency,
|
||||
entry_to_exit_loss, exit_to_bing_loss, success, error_message, timestamp
|
||||
entry_to_exit_loss, exit_to_bing_loss, success, error_message, timestamp,
|
||||
chain_details
|
||||
FROM (
|
||||
SELECT *, ROW_NUMBER() OVER (PARTITION BY tunnel_id ORDER BY timestamp DESC, id DESC) AS rn
|
||||
FROM tunnel_quality
|
||||
|
||||
+247
-40
@@ -1,4 +1,31 @@
|
||||
#!/bin/bash
|
||||
#!/bin/sh
|
||||
# shellcheck shell=bash
|
||||
|
||||
# Alpine 默认不带 Bash。先用系统自带的 /bin/sh 安装/切换到 Bash,
|
||||
# 后续主体继续使用 Bash 语法,避免要求用户手动准备运行环境。
|
||||
if [ -z "${BASH_VERSION:-}" ]; then
|
||||
if command -v bash >/dev/null 2>&1; then
|
||||
exec bash "$0" "$@"
|
||||
fi
|
||||
|
||||
if [ -f /etc/alpine-release ] && command -v apk >/dev/null 2>&1; then
|
||||
if [ "$(id -u)" -eq 0 ]; then
|
||||
apk add --no-cache bash
|
||||
elif command -v sudo >/dev/null 2>&1; then
|
||||
sudo apk add --no-cache bash
|
||||
elif command -v doas >/dev/null 2>&1; then
|
||||
doas apk add --no-cache bash
|
||||
else
|
||||
echo "❌ Alpine 安装需要 root 权限,或已配置 sudo/doas。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
exec bash "$0" "$@"
|
||||
fi
|
||||
|
||||
echo "❌ 此安装脚本需要 Bash。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# GitHub repo used for release downloads
|
||||
REPO="Sagit-chu/flux-panel"
|
||||
@@ -24,11 +51,14 @@ get_architecture() {
|
||||
|
||||
# 安装目录
|
||||
INSTALL_DIR="/etc/flux_agent"
|
||||
FLUX_AGENT_SYSTEMD_SERVICE_FILE="/etc/systemd/system/flux_agent.service"
|
||||
FLUX_AGENT_OPENRC_SERVICE_FILE="/etc/init.d/flux_agent"
|
||||
LEGACY_GOST_BINARY="/usr/local/bin/gost"
|
||||
LEGACY_GOST_CONFIG_DIR="/etc/gost"
|
||||
LEGACY_GOST_SERVICE_FILE_ETC="/etc/systemd/system/gost.service"
|
||||
LEGACY_GOST_SERVICE_FILE_LIB="/lib/systemd/system/gost.service"
|
||||
LEGACY_GOST_SERVICE_FILE_USR_LIB="/usr/lib/systemd/system/gost.service"
|
||||
SERVICE_MANAGER="${SERVICE_MANAGER:-}"
|
||||
|
||||
# 镜像加速配置(可由面板传入或交互式询问)
|
||||
PROXY_ENABLED="${PROXY_ENABLED:-}"
|
||||
@@ -256,6 +286,199 @@ write_flux_agent_config() {
|
||||
"$(json_escape "$SECRET")" > "$path"
|
||||
}
|
||||
|
||||
ensure_service_manager() {
|
||||
if [[ -n "$SERVICE_MANAGER" ]]; then
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd|openrc)
|
||||
return 0
|
||||
;;
|
||||
*)
|
||||
echo "❌ 不支持的服务管理器: $SERVICE_MANAGER" >&2
|
||||
return 1
|
||||
;;
|
||||
esac
|
||||
fi
|
||||
|
||||
if command -v systemctl >/dev/null 2>&1 && [[ -d /run/systemd/system ]]; then
|
||||
SERVICE_MANAGER="systemd"
|
||||
return 0
|
||||
fi
|
||||
if command -v rc-service >/dev/null 2>&1 && command -v rc-update >/dev/null 2>&1; then
|
||||
SERVICE_MANAGER="openrc"
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "❌ 未检测到受支持的服务管理器(systemd 或 OpenRC)。" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
flux_agent_service_exists() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
[[ -f "$FLUX_AGENT_SYSTEMD_SERVICE_FILE" ]] || \
|
||||
systemctl list-units --full -all 2>/dev/null | grep -Fq "flux_agent.service"
|
||||
;;
|
||||
openrc)
|
||||
[[ -f "$FLUX_AGENT_OPENRC_SERVICE_FILE" ]]
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
stop_flux_agent_service() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
systemctl stop flux_agent 2>/dev/null || true
|
||||
;;
|
||||
openrc)
|
||||
rc-service flux_agent stop 2>/dev/null || true
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
disable_flux_agent_service() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
systemctl disable flux_agent 2>/dev/null || true
|
||||
;;
|
||||
openrc)
|
||||
rc-update del flux_agent default 2>/dev/null || true
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
write_flux_agent_service() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
mkdir -p "$(dirname "$FLUX_AGENT_SYSTEMD_SERVICE_FILE")"
|
||||
cat > "$FLUX_AGENT_SYSTEMD_SERVICE_FILE" <<EOF
|
||||
[Unit]
|
||||
Description=Flux_agent Proxy Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
WorkingDirectory=$INSTALL_DIR
|
||||
ExecStart=$INSTALL_DIR/flux_agent
|
||||
Restart=on-failure
|
||||
StandardOutput=null
|
||||
StandardError=null
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
;;
|
||||
openrc)
|
||||
mkdir -p "$(dirname "$FLUX_AGENT_OPENRC_SERVICE_FILE")"
|
||||
cat > "$FLUX_AGENT_OPENRC_SERVICE_FILE" <<EOF
|
||||
#!/sbin/openrc-run
|
||||
|
||||
name="flux_agent"
|
||||
description="Flux_agent Proxy Service"
|
||||
command="$INSTALL_DIR/flux_agent"
|
||||
directory="$INSTALL_DIR"
|
||||
command_background="yes"
|
||||
pidfile="/run/\${RC_SVCNAME}.pid"
|
||||
output_log="/dev/null"
|
||||
error_log="/dev/null"
|
||||
|
||||
depend() {
|
||||
need net
|
||||
}
|
||||
EOF
|
||||
chmod +x "$FLUX_AGENT_OPENRC_SERVICE_FILE"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
enable_and_start_flux_agent_service() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
systemctl daemon-reload
|
||||
systemctl enable flux_agent
|
||||
systemctl start flux_agent
|
||||
;;
|
||||
openrc)
|
||||
rc-update add flux_agent default
|
||||
rc-service flux_agent start
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
start_flux_agent_service() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
systemctl start flux_agent
|
||||
;;
|
||||
openrc)
|
||||
rc-service flux_agent start
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
flux_agent_service_is_active() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
systemctl is-active --quiet flux_agent
|
||||
;;
|
||||
openrc)
|
||||
rc-service flux_agent status >/dev/null 2>&1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
flux_agent_service_status() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
systemctl is-active flux_agent 2>/dev/null || true
|
||||
;;
|
||||
openrc)
|
||||
rc-service flux_agent status 2>/dev/null || true
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
remove_flux_agent_service() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
rm -f "$FLUX_AGENT_SYSTEMD_SERVICE_FILE"
|
||||
systemctl daemon-reload 2>/dev/null || true
|
||||
;;
|
||||
openrc)
|
||||
rm -f "$FLUX_AGENT_OPENRC_SERVICE_FILE"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
flux_agent_service_status_hint() {
|
||||
ensure_service_manager || return 1
|
||||
|
||||
case "$SERVICE_MANAGER" in
|
||||
systemd)
|
||||
echo "systemctl status flux_agent --no-pager"
|
||||
;;
|
||||
openrc)
|
||||
echo "rc-service flux_agent status"
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
cleanup_legacy_gost_installation() {
|
||||
local matched_service_files=()
|
||||
local service_file=""
|
||||
@@ -341,19 +564,21 @@ install_flux_agent() {
|
||||
|
||||
get_config_params
|
||||
|
||||
# 检查并安装 tcpkill
|
||||
# 检查并安装 tcpkill
|
||||
check_and_install_tcpkill
|
||||
|
||||
ensure_service_manager || exit 1
|
||||
|
||||
mkdir -p "$INSTALL_DIR"
|
||||
|
||||
local tmp_binary="$INSTALL_DIR/flux_agent.new"
|
||||
|
||||
# 停止并禁用已有服务
|
||||
if systemctl list-units --full -all | grep -Fq "flux_agent.service"; then
|
||||
if flux_agent_service_exists; then
|
||||
echo "🔍 检测到已存在的flux_agent服务"
|
||||
systemctl stop flux_agent 2>/dev/null && echo "🛑 停止服务"
|
||||
systemctl disable flux_agent 2>/dev/null && echo "🚫 禁用自启"
|
||||
stop_flux_agent_service
|
||||
echo "🛑 停止服务"
|
||||
disable_flux_agent_service
|
||||
echo "🚫 禁用自启"
|
||||
fi
|
||||
|
||||
# 下载 flux_agent
|
||||
@@ -392,38 +617,21 @@ EOF
|
||||
# 加强权限
|
||||
chmod 600 "$INSTALL_DIR"/*.json
|
||||
|
||||
# 创建 systemd 服务
|
||||
SERVICE_FILE="/etc/systemd/system/flux_agent.service"
|
||||
cat > "$SERVICE_FILE" <<EOF
|
||||
[Unit]
|
||||
Description=Flux_agent Proxy Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
WorkingDirectory=$INSTALL_DIR
|
||||
ExecStart=$INSTALL_DIR/flux_agent
|
||||
Restart=on-failure
|
||||
StandardOutput=null
|
||||
StandardError=null
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
# 创建 systemd 或 OpenRC 服务
|
||||
write_flux_agent_service
|
||||
|
||||
# 启动服务
|
||||
systemctl daemon-reload
|
||||
systemctl enable flux_agent
|
||||
systemctl start flux_agent
|
||||
enable_and_start_flux_agent_service
|
||||
|
||||
# 检查状态
|
||||
echo "🔄 检查服务状态..."
|
||||
if systemctl is-active --quiet flux_agent; then
|
||||
if flux_agent_service_is_active; then
|
||||
echo "✅ 安装完成,flux_agent服务已启动并设置为开机启动。"
|
||||
echo "📁 配置目录: $INSTALL_DIR"
|
||||
echo "🔧 服务状态: $(systemctl is-active flux_agent)"
|
||||
echo "🔧 服务状态: $(flux_agent_service_status)"
|
||||
else
|
||||
echo "❌ flux_agent服务启动失败,请执行以下命令查看状态:"
|
||||
echo "systemctl status flux_agent --no-pager"
|
||||
flux_agent_service_status_hint
|
||||
fi
|
||||
}
|
||||
|
||||
@@ -443,6 +651,7 @@ update_flux_agent() {
|
||||
|
||||
# 检查并安装 tcpkill
|
||||
check_and_install_tcpkill
|
||||
ensure_service_manager || return 1
|
||||
|
||||
# 先下载新版本
|
||||
echo "⬇️ 下载最新版本..."
|
||||
@@ -455,9 +664,9 @@ update_flux_agent() {
|
||||
cleanup_legacy_gost_installation
|
||||
|
||||
# 停止服务
|
||||
if systemctl list-units --full -all | grep -Fq "flux_agent.service"; then
|
||||
if flux_agent_service_exists; then
|
||||
echo "🛑 停止 flux_agent 服务..."
|
||||
systemctl stop flux_agent
|
||||
stop_flux_agent_service
|
||||
fi
|
||||
|
||||
# 替换文件
|
||||
@@ -469,7 +678,7 @@ update_flux_agent() {
|
||||
|
||||
# 重启服务
|
||||
echo "🔄 重启服务..."
|
||||
systemctl start flux_agent
|
||||
start_flux_agent_service
|
||||
|
||||
echo "✅ 更新完成,服务已重新启动。"
|
||||
}
|
||||
@@ -477,6 +686,7 @@ update_flux_agent() {
|
||||
# 卸载功能
|
||||
uninstall_flux_agent() {
|
||||
echo "🗑️ 开始卸载 flux_agent..."
|
||||
ensure_service_manager || return 1
|
||||
|
||||
read -p "确认卸载 flux_agent 吗?此操作将删除所有相关文件 (y/N): " confirm
|
||||
if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
|
||||
@@ -485,15 +695,15 @@ uninstall_flux_agent() {
|
||||
fi
|
||||
|
||||
# 停止并禁用服务
|
||||
if systemctl list-units --full -all | grep -Fq "flux_agent.service"; then
|
||||
if flux_agent_service_exists; then
|
||||
echo "🛑 停止并禁用服务..."
|
||||
systemctl stop flux_agent 2>/dev/null
|
||||
systemctl disable flux_agent 2>/dev/null
|
||||
stop_flux_agent_service
|
||||
disable_flux_agent_service
|
||||
fi
|
||||
|
||||
# 删除服务文件
|
||||
if [[ -f "/etc/systemd/system/flux_agent.service" ]]; then
|
||||
rm -f "/etc/systemd/system/flux_agent.service"
|
||||
if [[ -f "$FLUX_AGENT_SYSTEMD_SERVICE_FILE" || -f "$FLUX_AGENT_OPENRC_SERVICE_FILE" ]]; then
|
||||
remove_flux_agent_service
|
||||
echo "🧹 删除服务文件"
|
||||
fi
|
||||
|
||||
@@ -503,9 +713,6 @@ uninstall_flux_agent() {
|
||||
echo "🧹 删除安装目录: $INSTALL_DIR"
|
||||
fi
|
||||
|
||||
# 重载 systemd
|
||||
systemctl daemon-reload
|
||||
|
||||
echo "✅ 卸载完成"
|
||||
}
|
||||
|
||||
|
||||
@@ -90,6 +90,7 @@ test_update_flux_agent_asks_for_proxy_config() (
|
||||
set -euo pipefail
|
||||
load_script_without_main "$ROOT_DIR/install.sh"
|
||||
|
||||
SERVICE_MANAGER="systemd"
|
||||
INSTALL_DIR=$(mktemp -d)
|
||||
cat > "$INSTALL_DIR/flux_agent" <<'EOF'
|
||||
#!/bin/bash
|
||||
@@ -165,6 +166,7 @@ test_install_flux_agent_preserves_legacy_gost_when_download_fails() (
|
||||
set -euo pipefail
|
||||
load_script_without_main "$ROOT_DIR/install.sh"
|
||||
|
||||
SERVICE_MANAGER="systemd"
|
||||
INSTALL_DIR=$(mktemp -d)
|
||||
cat > "$INSTALL_DIR/flux_agent" <<'EOF'
|
||||
#!/bin/bash
|
||||
@@ -199,6 +201,7 @@ test_update_flux_agent_preserves_legacy_gost_when_download_fails() (
|
||||
set -euo pipefail
|
||||
load_script_without_main "$ROOT_DIR/install.sh"
|
||||
|
||||
SERVICE_MANAGER="systemd"
|
||||
INSTALL_DIR=$(mktemp -d)
|
||||
cat > "$INSTALL_DIR/flux_agent" <<'EOF'
|
||||
#!/bin/bash
|
||||
@@ -236,7 +239,9 @@ test_install_flux_agent_writes_json_safe_config() (
|
||||
set -euo pipefail
|
||||
load_script_without_main "$ROOT_DIR/install.sh"
|
||||
|
||||
SERVICE_MANAGER="systemd"
|
||||
INSTALL_DIR=$(mktemp -d)
|
||||
FLUX_AGENT_SYSTEMD_SERVICE_FILE="$INSTALL_DIR/flux_agent.service"
|
||||
SERVER_ADDR='panel"addr'
|
||||
SECRET='sec\ret"1'
|
||||
DOWNLOAD_URL="https://example.com/gost"
|
||||
@@ -274,6 +279,117 @@ EOF
|
||||
assert_equals "$expected" "$actual" "install_flux_agent should JSON-escape config values"
|
||||
)
|
||||
|
||||
test_install_script_bootstraps_bash_for_alpine() (
|
||||
set -euo pipefail
|
||||
|
||||
local shebang
|
||||
shebang=$(head -n 1 "$ROOT_DIR/install.sh")
|
||||
assert_equals "#!/bin/sh" "$shebang" "install.sh should start with Alpine's default shell"
|
||||
|
||||
grep -Fq 'apk add --no-cache bash' "$ROOT_DIR/install.sh" || \
|
||||
fail "install.sh should bootstrap Bash through apk on Alpine"
|
||||
)
|
||||
|
||||
test_install_flux_agent_uses_openrc() (
|
||||
set -euo pipefail
|
||||
load_script_without_main "$ROOT_DIR/install.sh"
|
||||
|
||||
local temp_root
|
||||
temp_root=$(mktemp -d)
|
||||
INSTALL_DIR="$temp_root/flux_agent"
|
||||
FLUX_AGENT_OPENRC_SERVICE_FILE="$temp_root/init.d/flux_agent"
|
||||
SERVICE_MANAGER="openrc"
|
||||
SERVER_ADDR="panel.example.com:443"
|
||||
SECRET="secret"
|
||||
DOWNLOAD_URL="https://example.com/gost"
|
||||
|
||||
local rc_service_calls=""
|
||||
local rc_update_calls=""
|
||||
|
||||
ask_proxy_config() { :; }
|
||||
ensure_download_url_initialized() { :; }
|
||||
get_config_params() { :; }
|
||||
check_and_install_tcpkill() { :; }
|
||||
cleanup_legacy_gost_installation() { :; }
|
||||
curl() {
|
||||
local output=""
|
||||
while [[ $# -gt 0 ]]; do
|
||||
if [[ "$1" == "-o" ]]; then
|
||||
output="$2"
|
||||
shift 2
|
||||
continue
|
||||
fi
|
||||
shift
|
||||
done
|
||||
|
||||
cat > "$output" <<'EOF'
|
||||
#!/bin/sh
|
||||
echo "new version"
|
||||
EOF
|
||||
chmod +x "$output"
|
||||
}
|
||||
rc-service() {
|
||||
rc_service_calls+=$'\n'"$*"
|
||||
if [[ "$2" == "status" ]]; then
|
||||
echo "status: started"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
rc-update() {
|
||||
rc_update_calls+=$'\n'"$*"
|
||||
return 0
|
||||
}
|
||||
|
||||
install_flux_agent >/dev/null
|
||||
|
||||
[[ -x "$FLUX_AGENT_OPENRC_SERVICE_FILE" ]] || fail "OpenRC service file should be executable"
|
||||
grep -Fq '#!/sbin/openrc-run' "$FLUX_AGENT_OPENRC_SERVICE_FILE" || \
|
||||
fail "OpenRC service should use openrc-run"
|
||||
grep -Fq "command=\"$INSTALL_DIR/flux_agent\"" "$FLUX_AGENT_OPENRC_SERVICE_FILE" || \
|
||||
fail "OpenRC service should launch the installed flux_agent binary"
|
||||
grep -Fq 'command_background="yes"' "$FLUX_AGENT_OPENRC_SERVICE_FILE" || \
|
||||
fail "OpenRC service should run flux_agent in the background"
|
||||
if command -v openrc-run >/dev/null 2>&1; then
|
||||
"$FLUX_AGENT_OPENRC_SERVICE_FILE" describe >/dev/null 2>&1
|
||||
fi
|
||||
[[ "$rc_update_calls" == *"add flux_agent default"* ]] || \
|
||||
fail "OpenRC install should enable flux_agent in the default runlevel"
|
||||
[[ "$rc_service_calls" == *"start"* ]] || fail "OpenRC install should start flux_agent"
|
||||
[[ "$rc_service_calls" == *"status"* ]] || fail "OpenRC install should verify flux_agent status"
|
||||
)
|
||||
|
||||
test_remove_flux_agent_service_uses_openrc() (
|
||||
set -euo pipefail
|
||||
load_script_without_main "$ROOT_DIR/install.sh"
|
||||
|
||||
local temp_root
|
||||
temp_root=$(mktemp -d)
|
||||
SERVICE_MANAGER="openrc"
|
||||
FLUX_AGENT_OPENRC_SERVICE_FILE="$temp_root/init.d/flux_agent"
|
||||
mkdir -p "$(dirname "$FLUX_AGENT_OPENRC_SERVICE_FILE")"
|
||||
: > "$FLUX_AGENT_OPENRC_SERVICE_FILE"
|
||||
|
||||
local rc_service_calls=""
|
||||
local rc_update_calls=""
|
||||
rc-service() {
|
||||
rc_service_calls+=$'\n'"$*"
|
||||
return 0
|
||||
}
|
||||
rc-update() {
|
||||
rc_update_calls+=$'\n'"$*"
|
||||
return 0
|
||||
}
|
||||
|
||||
stop_flux_agent_service
|
||||
disable_flux_agent_service
|
||||
remove_flux_agent_service
|
||||
|
||||
[[ "$rc_service_calls" == *"stop"* ]] || fail "OpenRC uninstall should stop flux_agent"
|
||||
[[ "$rc_update_calls" == *"del flux_agent default"* ]] || \
|
||||
fail "OpenRC uninstall should remove flux_agent from the default runlevel"
|
||||
[[ ! -e "$FLUX_AGENT_OPENRC_SERVICE_FILE" ]] || fail "OpenRC uninstall should remove its service file"
|
||||
)
|
||||
|
||||
test_cleanup_legacy_gost_installation_removes_service_and_binary() (
|
||||
set -euo pipefail
|
||||
load_script_without_main "$ROOT_DIR/install.sh"
|
||||
@@ -504,6 +620,9 @@ test_update_flux_agent_skips_proxy_prompt_when_not_installed
|
||||
test_install_flux_agent_preserves_legacy_gost_when_download_fails
|
||||
test_update_flux_agent_preserves_legacy_gost_when_download_fails
|
||||
test_install_flux_agent_writes_json_safe_config
|
||||
test_install_script_bootstraps_bash_for_alpine
|
||||
test_install_flux_agent_uses_openrc
|
||||
test_remove_flux_agent_service_uses_openrc
|
||||
test_cleanup_legacy_gost_installation_removes_service_and_binary
|
||||
test_cleanup_legacy_gost_installation_preserves_unrelated_gost
|
||||
test_install_script_accepts_proxy_url_env_without_prompt
|
||||
@@ -514,4 +633,4 @@ test_panel_install_script_uses_default_proxy
|
||||
test_panel_install_script_accepts_proxy_url_env_without_prompt
|
||||
test_panel_install_script_defaults_proxy_on_eof
|
||||
|
||||
echo "install script proxy tests passed"
|
||||
echo "install script tests passed"
|
||||
|
||||
@@ -595,6 +595,20 @@ export interface TunnelQualityHopApiItem {
|
||||
targetPort?: number;
|
||||
}
|
||||
|
||||
export interface TunnelQualityCandidateHopApiItem
|
||||
extends TunnelQualityHopApiItem {
|
||||
fromRole: "entry" | "middle" | "exit";
|
||||
toRole: "middle" | "exit" | "target";
|
||||
hopIndex: number;
|
||||
selected: boolean;
|
||||
errorMessage?: string;
|
||||
}
|
||||
|
||||
export interface TunnelQualityChainDetailsApiItem {
|
||||
primaryPath?: TunnelQualityHopApiItem[];
|
||||
candidateHops?: TunnelQualityCandidateHopApiItem[];
|
||||
}
|
||||
|
||||
export interface TunnelQualityApiItem {
|
||||
tunnelId: number;
|
||||
entryToExitLatency: number;
|
||||
|
||||
@@ -2,6 +2,8 @@ import type {
|
||||
MonitorTunnelApiItem,
|
||||
TunnelMetricApiItem,
|
||||
TunnelQualityApiItem,
|
||||
TunnelQualityCandidateHopApiItem,
|
||||
TunnelQualityChainDetailsApiItem,
|
||||
TunnelQualityHopApiItem,
|
||||
} from "@/api/types";
|
||||
|
||||
@@ -468,18 +470,249 @@ const TrafficChartCard = React.memo(function TrafficChartCard({
|
||||
);
|
||||
});
|
||||
|
||||
function ForwardingChainTopology({ hopsStr }: { hopsStr?: string }) {
|
||||
if (!hopsStr) return null;
|
||||
|
||||
let hops: TunnelQualityHopApiItem[] = [];
|
||||
|
||||
const parseTunnelQualityChainDetails = (
|
||||
raw?: string,
|
||||
): TunnelQualityChainDetailsApiItem => {
|
||||
if (!raw) return {};
|
||||
try {
|
||||
hops = JSON.parse(hopsStr);
|
||||
const parsed: unknown = JSON.parse(raw);
|
||||
|
||||
// Backward-compatible with historical rows that stored the primary path
|
||||
// directly as a JSON array.
|
||||
if (Array.isArray(parsed)) {
|
||||
return { primaryPath: parsed as TunnelQualityHopApiItem[] };
|
||||
}
|
||||
if (parsed && typeof parsed === "object") {
|
||||
return parsed as TunnelQualityChainDetailsApiItem;
|
||||
}
|
||||
} catch {
|
||||
return null;
|
||||
return {};
|
||||
}
|
||||
|
||||
if (!Array.isArray(hops) || hops.length === 0) return null;
|
||||
return {};
|
||||
};
|
||||
|
||||
type TunnelTopologyHop = TunnelQualityHopApiItem & {
|
||||
errorMessage?: string;
|
||||
};
|
||||
|
||||
interface TunnelTopologyPath {
|
||||
key: string;
|
||||
hops: TunnelTopologyHop[];
|
||||
alternativeNodeIndex?: number;
|
||||
}
|
||||
|
||||
const tunnelTopologyHopKey = (fromNodeId: number, toNodeId: number) =>
|
||||
`${fromNodeId}:${toNodeId}`;
|
||||
|
||||
const buildTunnelTopologyPaths = (
|
||||
details: TunnelQualityChainDetailsApiItem,
|
||||
): TunnelTopologyPath[] => {
|
||||
const primaryHops = details.primaryPath ?? [];
|
||||
const candidates = details.candidateHops ?? [];
|
||||
|
||||
if (primaryHops.length === 0) {
|
||||
const publicCandidates = candidates.filter(
|
||||
(candidate) => candidate.toRole === "target",
|
||||
);
|
||||
const selected = publicCandidates.find((candidate) => candidate.selected);
|
||||
const paths: TunnelTopologyPath[] = [];
|
||||
|
||||
if (selected) {
|
||||
paths.push({ key: "primary-public", hops: [selected] });
|
||||
}
|
||||
for (const candidate of publicCandidates) {
|
||||
if (candidate.selected) continue;
|
||||
paths.push({
|
||||
key: `alternative-public-${candidate.fromNodeId}`,
|
||||
hops: [candidate],
|
||||
alternativeNodeIndex: 0,
|
||||
});
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
const primaryNodeIds = [
|
||||
primaryHops[0].fromNodeId,
|
||||
...primaryHops.map((hop) => hop.toNodeId),
|
||||
];
|
||||
const internalCandidates = candidates.filter(
|
||||
(candidate) => candidate.toRole !== "target",
|
||||
);
|
||||
const candidateHopMap = new Map<string, TunnelQualityCandidateHopApiItem>();
|
||||
const alternativeNodes = new Map<
|
||||
string,
|
||||
{ column: number; nodeId: number }
|
||||
>();
|
||||
|
||||
for (const candidate of internalCandidates) {
|
||||
candidateHopMap.set(
|
||||
tunnelTopologyHopKey(candidate.fromNodeId, candidate.toNodeId),
|
||||
candidate,
|
||||
);
|
||||
|
||||
const sourceColumn = candidate.hopIndex;
|
||||
const targetColumn = candidate.hopIndex + 1;
|
||||
|
||||
if (
|
||||
sourceColumn >= 0 &&
|
||||
sourceColumn < primaryNodeIds.length &&
|
||||
candidate.fromNodeId !== primaryNodeIds[sourceColumn]
|
||||
) {
|
||||
alternativeNodes.set(`${sourceColumn}:${candidate.fromNodeId}`, {
|
||||
column: sourceColumn,
|
||||
nodeId: candidate.fromNodeId,
|
||||
});
|
||||
}
|
||||
if (
|
||||
targetColumn >= 0 &&
|
||||
targetColumn < primaryNodeIds.length &&
|
||||
candidate.toNodeId !== primaryNodeIds[targetColumn]
|
||||
) {
|
||||
alternativeNodes.set(`${targetColumn}:${candidate.toNodeId}`, {
|
||||
column: targetColumn,
|
||||
nodeId: candidate.toNodeId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const paths: TunnelTopologyPath[] = [{ key: "primary", hops: primaryHops }];
|
||||
|
||||
for (const alternative of alternativeNodes.values()) {
|
||||
const nodeIds = [...primaryNodeIds];
|
||||
|
||||
nodeIds[alternative.column] = alternative.nodeId;
|
||||
const hops: TunnelTopologyHop[] = [];
|
||||
|
||||
for (let index = 0; index < nodeIds.length - 1; index += 1) {
|
||||
const fromNodeId = nodeIds[index];
|
||||
const toNodeId = nodeIds[index + 1];
|
||||
const usesPrimaryEdge =
|
||||
fromNodeId === primaryNodeIds[index] &&
|
||||
toNodeId === primaryNodeIds[index + 1];
|
||||
const hop = usesPrimaryEdge
|
||||
? primaryHops[index]
|
||||
: candidateHopMap.get(tunnelTopologyHopKey(fromNodeId, toNodeId));
|
||||
|
||||
if (!hop) break;
|
||||
hops.push(hop);
|
||||
}
|
||||
|
||||
if (hops.length === primaryHops.length) {
|
||||
paths.push({
|
||||
key: `alternative-${alternative.column}-${alternative.nodeId}`,
|
||||
hops,
|
||||
alternativeNodeIndex: alternative.column,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return paths;
|
||||
};
|
||||
|
||||
function TunnelTopologyPathRow({ path }: { path: TunnelTopologyPath }) {
|
||||
return (
|
||||
<div className="flex min-w-max items-center py-2">
|
||||
{path.hops.map((hop, index) => {
|
||||
const hasError =
|
||||
Boolean(hop.errorMessage) || hop.latency < 0 || hop.loss > 0;
|
||||
const colorClass =
|
||||
hop.latency < 0 || hop.errorMessage
|
||||
? "text-danger"
|
||||
: hop.loss > 0
|
||||
? "text-warning"
|
||||
: "text-success";
|
||||
const borderColor = hasError ? "border-danger" : "";
|
||||
|
||||
return (
|
||||
<React.Fragment
|
||||
key={`${path.key}-${hop.fromNodeId}-${hop.toNodeId}-${index}`}
|
||||
>
|
||||
{index === 0 ? (
|
||||
<TopologyNodeChip
|
||||
isAlternative={path.alternativeNodeIndex === 0}
|
||||
name={hop.fromNodeName}
|
||||
/>
|
||||
) : null}
|
||||
<div
|
||||
className="relative mx-1 flex min-w-[70px] shrink-0 flex-col items-center justify-center"
|
||||
title={hop.errorMessage}
|
||||
>
|
||||
<span
|
||||
className={`mb-1 text-[10px] font-mono leading-none ${colorClass}`}
|
||||
>
|
||||
{hop.latency >= 0 && !hop.errorMessage
|
||||
? `${hop.latency.toFixed(0)}ms`
|
||||
: "超时"}
|
||||
</span>
|
||||
<div
|
||||
className={`relative flex h-[2px] w-full items-center justify-end bg-default-200 ${hop.latency < 0 || hop.errorMessage ? "!bg-danger" : ""}`}
|
||||
>
|
||||
<ArrowRight
|
||||
className={`absolute -right-2 z-10 h-3.5 w-3.5 rounded-full bg-background p-[1px] ${colorClass}`}
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
className={`mt-1.5 text-[10px] font-mono leading-none ${hop.errorMessage || hop.loss > 0 ? "text-warning" : "text-default-400"}`}
|
||||
>
|
||||
{hop.errorMessage ? "探测失败" : `${hop.loss.toFixed(0)}% 丢包`}
|
||||
</span>
|
||||
</div>
|
||||
<TopologyNodeChip
|
||||
borderColor={borderColor}
|
||||
isAlternative={path.alternativeNodeIndex === index + 1}
|
||||
name={hop.toNodeName}
|
||||
/>
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TopologyNodeChip({
|
||||
name,
|
||||
isAlternative = false,
|
||||
borderColor = "",
|
||||
}: {
|
||||
name: string;
|
||||
isAlternative?: boolean;
|
||||
borderColor?: string;
|
||||
}) {
|
||||
return (
|
||||
<Chip
|
||||
className={`shrink-0 font-mono shadow-sm ${borderColor}`}
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span>{name}</span>
|
||||
{isAlternative ? (
|
||||
<span className="rounded-full bg-warning/20 px-1.5 py-0.5 text-[9px] font-semibold leading-none text-warning">
|
||||
备选
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
</Chip>
|
||||
);
|
||||
}
|
||||
|
||||
const ForwardingChainTopology = React.memo(function ForwardingChainTopology({
|
||||
hopsStr,
|
||||
}: {
|
||||
hopsStr?: string;
|
||||
}) {
|
||||
const details = useMemo(
|
||||
() => parseTunnelQualityChainDetails(hopsStr),
|
||||
[hopsStr],
|
||||
);
|
||||
const topologyPaths = useMemo(
|
||||
() => buildTunnelTopologyPaths(details),
|
||||
[details],
|
||||
);
|
||||
|
||||
if (topologyPaths.length === 0) return null;
|
||||
|
||||
return (
|
||||
<Card className="border border-divider/60 shadow-sm transition-shadow bg-gradient-to-br from-background to-default-50/50 mt-4">
|
||||
@@ -490,62 +723,24 @@ function ForwardingChainTopology({ hopsStr }: { hopsStr?: string }) {
|
||||
</h3>
|
||||
</CardHeader>
|
||||
<CardBody className="py-2 px-4 pb-4">
|
||||
<div className="flex items-center overflow-x-auto pb-2 py-2">
|
||||
{hops.map((hop, index) => {
|
||||
const hasError = hop.latency < 0 || hop.loss > 0;
|
||||
const colorClass =
|
||||
hop.latency < 0
|
||||
? "text-danger"
|
||||
: hop.loss > 0
|
||||
? "text-warning"
|
||||
: "text-success";
|
||||
const borderColor = hasError ? "border-danger" : "";
|
||||
|
||||
return (
|
||||
<React.Fragment key={index}>
|
||||
{index === 0 && (
|
||||
<Chip
|
||||
className="shrink-0 font-mono shadow-sm"
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{hop.fromNodeName}
|
||||
</Chip>
|
||||
)}
|
||||
<div className="flex flex-col items-center justify-center min-w-[70px] mx-1 shrink-0 relative">
|
||||
<span
|
||||
className={`text-[10px] font-mono leading-none mb-1 ${colorClass}`}
|
||||
>
|
||||
{hop.latency >= 0 ? `${hop.latency.toFixed(0)}ms` : "超时"}
|
||||
</span>
|
||||
<div
|
||||
className={`h-[2px] w-full relative flex items-center justify-end bg-default-200 ${hop.latency < 0 ? "!bg-danger" : ""}`}
|
||||
>
|
||||
<ArrowRight
|
||||
className={`w-3.5 h-3.5 absolute -right-2 ${colorClass} bg-background rounded-full p-[1px] z-10`}
|
||||
/>
|
||||
</div>
|
||||
<span
|
||||
className={`text-[10px] font-mono leading-none mt-1.5 ${hop.loss > 0 ? "text-warning" : "text-default-400"}`}
|
||||
>
|
||||
{hop.loss.toFixed(0)}% 丢包
|
||||
</span>
|
||||
</div>
|
||||
<Chip
|
||||
className={`shrink-0 font-mono shadow-sm ${borderColor}`}
|
||||
size="sm"
|
||||
variant="flat"
|
||||
>
|
||||
{hop.toNodeName}
|
||||
</Chip>
|
||||
</React.Fragment>
|
||||
);
|
||||
})}
|
||||
<div className="max-h-80 space-y-1 overflow-auto pb-1">
|
||||
{topologyPaths.map((path, index) => (
|
||||
<div
|
||||
key={path.key}
|
||||
className={
|
||||
index === 0
|
||||
? "overflow-x-auto"
|
||||
: "overflow-x-auto border-t border-dashed border-divider/60"
|
||||
}
|
||||
>
|
||||
<TunnelTopologyPathRow path={path} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</CardBody>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export function TunnelMonitorView({
|
||||
viewMode = "grid",
|
||||
|
||||
Reference in New Issue
Block a user