mirror of
https://github.com/Rain-kl/OpenFlare.git
synced 2026-10-03 23:06:36 +08:00
重构 Nginx 执行器,支持通过 Docker 启动独立 Nginx 容器,更新配置结构,完善相关文档和测试用例
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"server_url": "http://127.0.0.1:3000",
|
||||
"agent_token": "123",
|
||||
"node_name": "edge-01",
|
||||
"node_ip": "10.0.0.8",
|
||||
"agent_version": "0.1.0",
|
||||
"nginx_version": "1.25.5",
|
||||
"route_config_path": "./etc/nginx/conf.d/atsflare_routes.conf",
|
||||
"state_path": "./var/lib/atsflare/agent-state.json",
|
||||
"nginx_binary": "nginx",
|
||||
"heartbeat_interval": 30000000000,
|
||||
"sync_interval": 30000000000,
|
||||
"request_timeout": 10000000000
|
||||
}
|
||||
@@ -33,9 +33,13 @@ func main() {
|
||||
HeartbeatService: heartbeat.New(client),
|
||||
SyncService: syncservice.New(client, &nginx.Manager{
|
||||
RouteConfigPath: cfg.RouteConfigPath,
|
||||
Executor: &nginx.ShellExecutor{
|
||||
Binary: cfg.NginxBinary,
|
||||
},
|
||||
Executor: nginx.NewExecutor(nginx.ExecutorOptions{
|
||||
NginxPath: cfg.NginxPath,
|
||||
DockerBinary: cfg.DockerBinary,
|
||||
ContainerName: cfg.NginxContainerName,
|
||||
Image: cfg.NginxDockerImage,
|
||||
RouteConfigPath: cfg.RouteConfigPath,
|
||||
}),
|
||||
}, stateStore),
|
||||
}
|
||||
|
||||
|
||||
@@ -9,18 +9,21 @@ import (
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
ServerURL string `json:"server_url"`
|
||||
AgentToken string `json:"agent_token"`
|
||||
NodeName string `json:"node_name"`
|
||||
NodeIP string `json:"node_ip"`
|
||||
AgentVersion string `json:"agent_version"`
|
||||
NginxVersion string `json:"nginx_version"`
|
||||
RouteConfigPath string `json:"route_config_path"`
|
||||
StatePath string `json:"state_path"`
|
||||
NginxBinary string `json:"nginx_binary"`
|
||||
HeartbeatInterval time.Duration `json:"heartbeat_interval"`
|
||||
SyncInterval time.Duration `json:"sync_interval"`
|
||||
RequestTimeout time.Duration `json:"request_timeout"`
|
||||
ServerURL string `json:"server_url"`
|
||||
AgentToken string `json:"agent_token"`
|
||||
NodeName string `json:"node_name"`
|
||||
NodeIP string `json:"node_ip"`
|
||||
AgentVersion string `json:"agent_version"`
|
||||
NginxVersion string `json:"nginx_version"`
|
||||
NginxPath string `json:"nginx_path"`
|
||||
NginxContainerName string `json:"nginx_container_name"`
|
||||
NginxDockerImage string `json:"nginx_docker_image"`
|
||||
DockerBinary string `json:"docker_binary"`
|
||||
RouteConfigPath string `json:"route_config_path"`
|
||||
StatePath string `json:"state_path"`
|
||||
HeartbeatInterval time.Duration `json:"heartbeat_interval"`
|
||||
SyncInterval time.Duration `json:"sync_interval"`
|
||||
RequestTimeout time.Duration `json:"request_timeout"`
|
||||
}
|
||||
|
||||
func Load(path string) (*Config, error) {
|
||||
@@ -49,8 +52,14 @@ func applyDefaults(cfg *Config) {
|
||||
if cfg.StatePath == "" {
|
||||
cfg.StatePath = filepath.Clean("./atsf_agent_state.json")
|
||||
}
|
||||
if cfg.NginxBinary == "" {
|
||||
cfg.NginxBinary = "nginx"
|
||||
if cfg.NginxContainerName == "" {
|
||||
cfg.NginxContainerName = "atsflare-nginx"
|
||||
}
|
||||
if cfg.NginxDockerImage == "" {
|
||||
cfg.NginxDockerImage = "nginx:stable-alpine"
|
||||
}
|
||||
if cfg.DockerBinary == "" {
|
||||
cfg.DockerBinary = "docker"
|
||||
}
|
||||
if cfg.HeartbeatInterval <= 0 {
|
||||
cfg.HeartbeatInterval = 30 * time.Second
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Executor interface {
|
||||
@@ -14,28 +15,97 @@ type Executor interface {
|
||||
Reload(ctx context.Context) error
|
||||
}
|
||||
|
||||
type ShellExecutor struct {
|
||||
Binary string
|
||||
type CommandRunner interface {
|
||||
Run(ctx context.Context, name string, args ...string) ([]byte, error)
|
||||
}
|
||||
|
||||
func (e *ShellExecutor) Test(ctx context.Context) error {
|
||||
cmd := exec.CommandContext(ctx, e.Binary, "-t")
|
||||
type OSCommandRunner struct{}
|
||||
|
||||
func (r *OSCommandRunner) Run(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
cmd := exec.CommandContext(ctx, name, args...)
|
||||
output, err := cmd.CombinedOutput()
|
||||
return output, err
|
||||
}
|
||||
|
||||
type PathExecutor struct {
|
||||
Path string
|
||||
Runner CommandRunner
|
||||
}
|
||||
|
||||
func (e *PathExecutor) Test(ctx context.Context) error {
|
||||
output, err := e.Runner.Run(ctx, e.Path, "-t")
|
||||
if err != nil {
|
||||
return fmt.Errorf("nginx -t failed: %w: %s", err, string(output))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *ShellExecutor) Reload(ctx context.Context) error {
|
||||
cmd := exec.CommandContext(ctx, e.Binary, "-s", "reload")
|
||||
output, err := cmd.CombinedOutput()
|
||||
func (e *PathExecutor) Reload(ctx context.Context) error {
|
||||
output, err := e.Runner.Run(ctx, e.Path, "-s", "reload")
|
||||
if err != nil {
|
||||
return fmt.Errorf("nginx reload failed: %w: %s", err, string(output))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type DockerExecutor struct {
|
||||
DockerBinary string
|
||||
ContainerName string
|
||||
Image string
|
||||
RouteConfigDir string
|
||||
Runner CommandRunner
|
||||
}
|
||||
|
||||
func (e *DockerExecutor) Test(ctx context.Context) error {
|
||||
if err := e.ensureContainer(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
output, err := e.Runner.Run(ctx, e.DockerBinary, "exec", e.ContainerName, "nginx", "-t")
|
||||
if err != nil {
|
||||
return fmt.Errorf("docker nginx -t failed: %w: %s", err, string(output))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *DockerExecutor) Reload(ctx context.Context) error {
|
||||
if err := e.ensureContainer(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
output, err := e.Runner.Run(ctx, e.DockerBinary, "exec", e.ContainerName, "nginx", "-s", "reload")
|
||||
if err != nil {
|
||||
return fmt.Errorf("docker nginx reload failed: %w: %s", err, string(output))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *DockerExecutor) ensureContainer(ctx context.Context) error {
|
||||
output, err := e.Runner.Run(ctx, e.DockerBinary, "inspect", "-f", "{{.State.Running}}", e.ContainerName)
|
||||
if err == nil {
|
||||
if strings.TrimSpace(string(output)) == "true" {
|
||||
return nil
|
||||
}
|
||||
startOutput, startErr := e.Runner.Run(ctx, e.DockerBinary, "start", e.ContainerName)
|
||||
if startErr != nil {
|
||||
return fmt.Errorf("docker start nginx failed: %w: %s", startErr, string(startOutput))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
runArgs := []string{
|
||||
"run", "-d",
|
||||
"--name", e.ContainerName,
|
||||
"-p", "80:80",
|
||||
"-p", "443:443",
|
||||
"-v", fmt.Sprintf("%s:/etc/nginx/conf.d", e.RouteConfigDir),
|
||||
e.Image,
|
||||
}
|
||||
runOutput, runErr := e.Runner.Run(ctx, e.DockerBinary, runArgs...)
|
||||
if runErr != nil {
|
||||
return fmt.Errorf("docker run nginx failed: %w: %s", runErr, string(runOutput))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type Manager struct {
|
||||
RouteConfigPath string
|
||||
Executor Executor
|
||||
@@ -63,6 +133,31 @@ func (m *Manager) Apply(ctx context.Context, content string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type ExecutorOptions struct {
|
||||
NginxPath string
|
||||
DockerBinary string
|
||||
ContainerName string
|
||||
Image string
|
||||
RouteConfigPath string
|
||||
}
|
||||
|
||||
func NewExecutor(options ExecutorOptions) Executor {
|
||||
runner := &OSCommandRunner{}
|
||||
if options.NginxPath != "" {
|
||||
return &PathExecutor{
|
||||
Path: options.NginxPath,
|
||||
Runner: runner,
|
||||
}
|
||||
}
|
||||
return &DockerExecutor{
|
||||
DockerBinary: options.DockerBinary,
|
||||
ContainerName: options.ContainerName,
|
||||
Image: options.Image,
|
||||
RouteConfigDir: filepath.Dir(options.RouteConfigPath),
|
||||
Runner: runner,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) backup() (string, bool, error) {
|
||||
if m.RouteConfigPath == "" {
|
||||
return "", false, errors.New("route config path 不能为空")
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package nginx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type runCall struct {
|
||||
name string
|
||||
args []string
|
||||
}
|
||||
|
||||
type fakeRunner struct {
|
||||
calls []runCall
|
||||
runFn func(name string, args ...string) ([]byte, error)
|
||||
}
|
||||
|
||||
func (r *fakeRunner) Run(ctx context.Context, name string, args ...string) ([]byte, error) {
|
||||
r.calls = append(r.calls, runCall{name: name, args: append([]string{}, args...)})
|
||||
if r.runFn != nil {
|
||||
return r.runFn(name, args...)
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestPathExecutorCommands(t *testing.T) {
|
||||
runner := &fakeRunner{}
|
||||
executor := &PathExecutor{
|
||||
Path: "/opt/nginx/sbin/nginx",
|
||||
Runner: runner,
|
||||
}
|
||||
|
||||
if err := executor.Test(context.Background()); err != nil {
|
||||
t.Fatalf("Test failed: %v", err)
|
||||
}
|
||||
if err := executor.Reload(context.Background()); err != nil {
|
||||
t.Fatalf("Reload failed: %v", err)
|
||||
}
|
||||
|
||||
expected := []runCall{
|
||||
{name: "/opt/nginx/sbin/nginx", args: []string{"-t"}},
|
||||
{name: "/opt/nginx/sbin/nginx", args: []string{"-s", "reload"}},
|
||||
}
|
||||
if !reflect.DeepEqual(runner.calls, expected) {
|
||||
t.Fatalf("unexpected calls: %#v", runner.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDockerExecutorStartsContainerWhenMissing(t *testing.T) {
|
||||
runner := &fakeRunner{
|
||||
runFn: func(name string, args ...string) ([]byte, error) {
|
||||
if len(args) >= 1 && args[0] == "inspect" {
|
||||
return []byte(""), errors.New("not found")
|
||||
}
|
||||
return []byte("ok"), nil
|
||||
},
|
||||
}
|
||||
executor := &DockerExecutor{
|
||||
DockerBinary: "docker",
|
||||
ContainerName: "atsflare-nginx",
|
||||
Image: "nginx:stable-alpine",
|
||||
RouteConfigDir: filepath.Clean("/tmp/routes"),
|
||||
Runner: runner,
|
||||
}
|
||||
|
||||
if err := executor.Test(context.Background()); err != nil {
|
||||
t.Fatalf("Test failed: %v", err)
|
||||
}
|
||||
|
||||
if len(runner.calls) != 3 {
|
||||
t.Fatalf("expected 3 calls, got %d", len(runner.calls))
|
||||
}
|
||||
if runner.calls[1].args[0] != "run" {
|
||||
t.Fatalf("expected docker run on second call, got %#v", runner.calls[1])
|
||||
}
|
||||
if runner.calls[2].args[0] != "exec" {
|
||||
t.Fatalf("expected docker exec on third call, got %#v", runner.calls[2])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDockerExecutorStartsStoppedContainer(t *testing.T) {
|
||||
runner := &fakeRunner{
|
||||
runFn: func(name string, args ...string) ([]byte, error) {
|
||||
if len(args) >= 2 && args[0] == "inspect" {
|
||||
return []byte("false"), nil
|
||||
}
|
||||
return []byte("ok"), nil
|
||||
},
|
||||
}
|
||||
executor := &DockerExecutor{
|
||||
DockerBinary: "docker",
|
||||
ContainerName: "atsflare-nginx",
|
||||
Image: "nginx:stable-alpine",
|
||||
RouteConfigDir: filepath.Clean("/tmp/routes"),
|
||||
Runner: runner,
|
||||
}
|
||||
|
||||
if err := executor.Reload(context.Background()); err != nil {
|
||||
t.Fatalf("Reload failed: %v", err)
|
||||
}
|
||||
|
||||
if len(runner.calls) != 3 {
|
||||
t.Fatalf("expected 3 calls, got %d", len(runner.calls))
|
||||
}
|
||||
if runner.calls[1].args[0] != "start" {
|
||||
t.Fatalf("expected docker start on second call, got %#v", runner.calls[1])
|
||||
}
|
||||
if runner.calls[2].args[0] != "exec" {
|
||||
t.Fatalf("expected docker exec on third call, got %#v", runner.calls[2])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"node_id": "node-272a017338e3b01c",
|
||||
"current_version": "",
|
||||
"current_checksum": "",
|
||||
"last_error": "nginx -t failed: exec: \"nginx\": executable file not found in $PATH: "
|
||||
}
|
||||
Reference in New Issue
Block a user