Refactor Nginx references to OpenResty throughout the codebase

- Updated all instances of "nginx" to "openresty" in log messages, error messages, and comments.
- Changed paths and Docker image names to reflect OpenResty usage.
- Modified test cases to align with OpenResty commands and configurations.
- Adjusted documentation to replace Nginx mentions with OpenResty, including setup instructions and configuration details.
- Ensured that version detection and runtime commands are consistent with OpenResty.
This commit is contained in:
ryan
2026-03-12 09:48:38 +08:00
parent 22eb563939
commit 29a0c64ba3
15 changed files with 247 additions and 182 deletions
+2 -2
View File
@@ -2,8 +2,8 @@
"server_url": "http://127.0.0.1:3000",
"agent_token": "123",
"data_dir": "./data",
"nginx_container_name": "atsflare-nginx",
"nginx_docker_image": "nginx:stable-alpine",
"openresty_container_name": "atsflare-openresty",
"openresty_docker_image": "openresty/openresty:alpine",
"heartbeat_interval": 30000,
"sync_interval": 30000,
"request_timeout": 10000
+9 -9
View File
@@ -28,13 +28,13 @@ func main() {
cfg.NginxVersion = nginx.DetectVersion(
context.Background(),
nginx.ExecutorOptions{
NginxPath: cfg.NginxPath,
NginxPath: cfg.OpenrestyPath,
DockerBinary: cfg.DockerBinary,
ContainerName: cfg.NginxContainerName,
Image: cfg.NginxDockerImage,
ContainerName: cfg.OpenrestyContainerName,
Image: cfg.OpenrestyDockerImage,
RouteConfigPath: cfg.RouteConfigPath,
CertDir: cfg.CertDir,
NginxCertDir: cfg.NginxCertDir,
NginxCertDir: cfg.OpenrestyCertDir,
},
)
log.Printf("agent config loaded: server=%s node=%s ip=%s heartbeat_interval=%s sync_interval=%s route_config=%s cert_dir=%s", cfg.ServerURL, cfg.NodeName, cfg.NodeIP, cfg.HeartbeatInterval, cfg.SyncInterval, cfg.RouteConfigPath, cfg.CertDir)
@@ -48,15 +48,15 @@ func main() {
SyncService: syncservice.New(client, &nginx.Manager{
RouteConfigPath: cfg.RouteConfigPath,
CertDir: cfg.CertDir,
NginxCertDir: cfg.NginxCertDir,
NginxCertDir: cfg.OpenrestyCertDir,
Executor: nginx.NewExecutor(nginx.ExecutorOptions{
NginxPath: cfg.NginxPath,
NginxPath: cfg.OpenrestyPath,
DockerBinary: cfg.DockerBinary,
ContainerName: cfg.NginxContainerName,
Image: cfg.NginxDockerImage,
ContainerName: cfg.OpenrestyContainerName,
Image: cfg.OpenrestyDockerImage,
RouteConfigPath: cfg.RouteConfigPath,
CertDir: cfg.CertDir,
NginxCertDir: cfg.NginxCertDir,
NginxCertDir: cfg.OpenrestyCertDir,
}),
}, stateStore),
Updater: updater.New(),
+8 -8
View File
@@ -95,7 +95,7 @@ func TestRunnerKeepsHeartbeatWhenStartupSyncFails(t *testing.T) {
},
}
syncService := &fakeSyncService{
startupErr: errors.New("当前没有激活版本,保持当前 Nginx 配置"),
startupErr: errors.New("当前没有激活版本,保持当前 OpenResty 配置"),
}
runner := &Runner{
Config: &config.Config{
@@ -103,7 +103,7 @@ func TestRunnerKeepsHeartbeatWhenStartupSyncFails(t *testing.T) {
NodeName: "edge-01",
NodeIP: "10.0.0.8",
AgentVersion: config.AgentVersion,
NginxVersion: "1.25.5",
NginxVersion: "1.27.1.2",
HeartbeatInterval: config.MillisecondDuration(10 * time.Millisecond),
SyncInterval: config.MillisecondDuration(20 * time.Millisecond),
},
@@ -126,7 +126,7 @@ func TestRunnerKeepsHeartbeatWhenStartupSyncFails(t *testing.T) {
if loadErr != nil {
t.Fatalf("failed to load state: %v", loadErr)
}
if snapshot.LastError != "当前没有激活版本,保持当前 Nginx 配置" {
if snapshot.LastError != "当前没有激活版本,保持当前 OpenResty 配置" {
t.Fatalf("expected startup sync error to be recorded, got %q", snapshot.LastError)
}
}
@@ -141,7 +141,7 @@ func TestRunnerDoesNotExitOnHeartbeatOrSyncError(t *testing.T) {
heartbeatErrs: []error{errors.New("heartbeat timeout")},
}
syncService := &fakeSyncService{
syncOnceErr: errors.New("nginx reload failed"),
syncOnceErr: errors.New("openresty reload failed"),
onSyncOnceCall: func(callCount int) {
if callCount >= 1 {
cancel()
@@ -154,7 +154,7 @@ func TestRunnerDoesNotExitOnHeartbeatOrSyncError(t *testing.T) {
NodeName: "edge-01",
NodeIP: "10.0.0.8",
AgentVersion: config.AgentVersion,
NginxVersion: "1.25.5",
NginxVersion: "1.27.1.2",
HeartbeatInterval: config.MillisecondDuration(10 * time.Millisecond),
SyncInterval: config.MillisecondDuration(10 * time.Millisecond),
},
@@ -177,7 +177,7 @@ func TestRunnerDoesNotExitOnHeartbeatOrSyncError(t *testing.T) {
if loadErr != nil {
t.Fatalf("failed to load state: %v", loadErr)
}
if snapshot.LastError != "nginx reload failed" {
if snapshot.LastError != "openresty reload failed" {
t.Fatalf("expected sync error to be recorded, got %q", snapshot.LastError)
}
}
@@ -215,7 +215,7 @@ func TestRunnerDiscoveryRegisterUpdatesTokenAndNodeID(t *testing.T) {
NodeName: cfg.NodeName,
NodeIP: cfg.NodeIP,
AgentVersion: config.AgentVersion,
NginxVersion: "1.25.5",
NginxVersion: "1.27.1.2",
HeartbeatInterval: config.MillisecondDuration(10 * time.Millisecond),
SyncInterval: config.MillisecondDuration(20 * time.Millisecond),
},
@@ -225,7 +225,7 @@ func TestRunnerDiscoveryRegisterUpdatesTokenAndNodeID(t *testing.T) {
}
runner.Config = cfg
runner.Config.AgentVersion = config.AgentVersion
runner.Config.NginxVersion = "1.25.5"
runner.Config.NginxVersion = "1.27.1.2"
runner.Config.HeartbeatInterval = config.MillisecondDuration(10 * time.Millisecond)
runner.Config.SyncInterval = config.MillisecondDuration(20 * time.Millisecond)
+55 -16
View File
@@ -15,7 +15,7 @@ const (
defaultDockerRouteConfigRelativePath = "etc/nginx/conf.d/atsflare_routes.conf"
defaultCertDirRelativePath = "etc/nginx/certs"
defaultDockerStateRelativePath = "var/lib/atsflare/agent-state.json"
defaultDockerNginxCertDir = "/etc/nginx/atsflare-certs"
defaultDockerOpenRestyCertDir = "/etc/nginx/atsflare-certs"
)
type Config struct {
@@ -26,14 +26,14 @@ type Config struct {
NodeIP string `json:"node_ip"`
AgentVersion string `json:"-"`
NginxVersion string `json:"-"`
NginxPath string `json:"nginx_path"`
NginxContainerName string `json:"nginx_container_name"`
NginxDockerImage string `json:"nginx_docker_image"`
OpenrestyPath string `json:"openresty_path"`
OpenrestyContainerName string `json:"openresty_container_name"`
OpenrestyDockerImage string `json:"openresty_docker_image"`
DockerBinary string `json:"docker_binary"`
DataDir string `json:"data_dir"`
RouteConfigPath string `json:"route_config_path"`
CertDir string `json:"cert_dir"`
NginxCertDir string `json:"nginx_cert_dir"`
OpenrestyCertDir string `json:"openresty_cert_dir"`
StatePath string `json:"state_path"`
HeartbeatInterval MillisecondDuration `json:"heartbeat_interval"`
SyncInterval MillisecondDuration `json:"sync_interval"`
@@ -41,15 +41,54 @@ type Config struct {
configPath string
}
type configFile struct {
ServerURL string `json:"server_url"`
AgentToken string `json:"agent_token"`
DiscoveryToken string `json:"discovery_token"`
NodeName string `json:"node_name"`
NodeIP string `json:"node_ip"`
OpenrestyPath string `json:"openresty_path"`
OpenrestyContainerName string `json:"openresty_container_name"`
OpenrestyDockerImage string `json:"openresty_docker_image"`
DockerBinary string `json:"docker_binary"`
DataDir string `json:"data_dir"`
RouteConfigPath string `json:"route_config_path"`
CertDir string `json:"cert_dir"`
OpenrestyCertDir string `json:"openresty_cert_dir"`
StatePath string `json:"state_path"`
HeartbeatInterval MillisecondDuration `json:"heartbeat_interval"`
SyncInterval MillisecondDuration `json:"sync_interval"`
RequestTimeout MillisecondDuration `json:"request_timeout"`
}
func Load(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
cfg := &Config{}
if err = json.Unmarshal(data, cfg); err != nil {
file := &configFile{}
if err = json.Unmarshal(data, file); err != nil {
return nil, err
}
cfg := &Config{
ServerURL: file.ServerURL,
AgentToken: file.AgentToken,
DiscoveryToken: file.DiscoveryToken,
NodeName: file.NodeName,
NodeIP: file.NodeIP,
OpenrestyPath: file.OpenrestyPath,
OpenrestyContainerName: file.OpenrestyContainerName,
OpenrestyDockerImage: file.OpenrestyDockerImage,
DockerBinary: file.DockerBinary,
DataDir: file.DataDir,
RouteConfigPath: file.RouteConfigPath,
CertDir: file.CertDir,
OpenrestyCertDir: file.OpenrestyCertDir,
StatePath: file.StatePath,
HeartbeatInterval: file.HeartbeatInterval,
SyncInterval: file.SyncInterval,
RequestTimeout: file.RequestTimeout,
}
cfg.configPath = path
applyDefaults(cfg, filepath.Dir(path))
if err = validate(cfg); err != nil {
@@ -61,11 +100,11 @@ func Load(path string) (*Config, error) {
func applyDefaults(cfg *Config, baseDir string) {
baseDir = filepath.Clean(baseDir)
cfg.AgentVersion = AgentVersion
if cfg.NginxContainerName == "" {
cfg.NginxContainerName = "atsflare-nginx"
if cfg.OpenrestyContainerName == "" {
cfg.OpenrestyContainerName = "atsflare-openresty"
}
if cfg.NginxDockerImage == "" {
cfg.NginxDockerImage = "nginx:stable-alpine"
if cfg.OpenrestyDockerImage == "" {
cfg.OpenrestyDockerImage = "openresty/openresty:alpine"
}
if cfg.DockerBinary == "" {
cfg.DockerBinary = "docker"
@@ -79,7 +118,7 @@ func applyDefaults(cfg *Config, baseDir string) {
if cfg.NodeIP == "" {
cfg.NodeIP = detectNodeIP()
}
if cfg.NginxPath == "" {
if cfg.OpenrestyPath == "" {
cfg.RouteConfigPath = joinManagedPath(cfg.DataDir, defaultDockerRouteConfigRelativePath)
cfg.StatePath = joinManagedPath(cfg.DataDir, defaultDockerStateRelativePath)
} else {
@@ -93,11 +132,11 @@ func applyDefaults(cfg *Config, baseDir string) {
if cfg.CertDir == "" {
cfg.CertDir = joinManagedPath(cfg.DataDir, defaultCertDirRelativePath)
}
if cfg.NginxCertDir == "" {
if cfg.NginxPath != "" {
cfg.NginxCertDir = cfg.CertDir
if cfg.OpenrestyCertDir == "" {
if cfg.OpenrestyPath != "" {
cfg.OpenrestyCertDir = cfg.CertDir
} else {
cfg.NginxCertDir = defaultDockerNginxCertDir
cfg.OpenrestyCertDir = defaultDockerOpenRestyCertDir
}
}
if cfg.HeartbeatInterval <= 0 {
+15 -6
View File
@@ -39,8 +39,14 @@ func TestLoadDockerModeUsesManagedPaths(t *testing.T) {
if cfg.CertDir != filepath.Join(dir, "data", defaultCertDirRelativePath) {
t.Fatalf("unexpected cert dir: %s", cfg.CertDir)
}
if cfg.NginxCertDir != defaultDockerNginxCertDir {
t.Fatalf("unexpected nginx cert dir: %s", cfg.NginxCertDir)
if cfg.OpenrestyContainerName != "atsflare-openresty" {
t.Fatalf("unexpected openresty container name: %s", cfg.OpenrestyContainerName)
}
if cfg.OpenrestyDockerImage != "openresty/openresty:alpine" {
t.Fatalf("unexpected openresty image: %s", cfg.OpenrestyDockerImage)
}
if cfg.OpenrestyCertDir != defaultDockerOpenRestyCertDir {
t.Fatalf("unexpected openresty cert dir: %s", cfg.OpenrestyCertDir)
}
if cfg.StatePath != filepath.Join(dir, "data", defaultDockerStateRelativePath) {
t.Fatalf("unexpected state path: %s", cfg.StatePath)
@@ -55,7 +61,7 @@ func TestLoadPathModeKeepsExplicitPaths(t *testing.T) {
"agent_token": "token",
"node_name": "edge-01",
"node_ip": "10.0.0.8",
"nginx_path": "/opt/nginx/sbin/nginx",
"openresty_path": "/usr/local/openresty/nginx/sbin/openresty",
"route_config_path": "/tmp/routes.conf",
"state_path": "/tmp/agent-state.json",
}
@@ -78,8 +84,8 @@ func TestLoadPathModeKeepsExplicitPaths(t *testing.T) {
if cfg.StatePath != "/tmp/agent-state.json" {
t.Fatalf("unexpected state path: %s", cfg.StatePath)
}
if cfg.NginxCertDir != cfg.CertDir {
t.Fatalf("expected path mode nginx cert dir to equal cert dir, got %s / %s", cfg.NginxCertDir, cfg.CertDir)
if cfg.OpenrestyCertDir != cfg.CertDir {
t.Fatalf("expected path mode openresty cert dir to equal cert dir, got %s / %s", cfg.OpenrestyCertDir, cfg.CertDir)
}
}
@@ -164,7 +170,7 @@ func TestSavePersistsMillisecondsAndOmitsRuntimeVersions(t *testing.T) {
if err != nil {
t.Fatalf("Load failed: %v", err)
}
cfg.NginxVersion = "1.25.5"
cfg.NginxVersion = "1.27.1.2"
cfg.HeartbeatInterval = MillisecondDuration(5 * time.Second)
cfg.SyncInterval = MillisecondDuration(6 * time.Second)
cfg.RequestTimeout = MillisecondDuration(7 * time.Second)
@@ -196,6 +202,9 @@ func TestSavePersistsMillisecondsAndOmitsRuntimeVersions(t *testing.T) {
if decoded["request_timeout"] != float64(7000) {
t.Fatalf("unexpected request timeout: %#v", decoded["request_timeout"])
}
if _, ok := decoded["nginx_path"]; ok {
t.Fatal("legacy nginx_path should not be persisted")
}
}
func TestInitialAuthToken(t *testing.T) {
+58 -45
View File
@@ -19,6 +19,8 @@ import (
const CertDirPlaceholder = "__ATSF_CERT_DIR__"
const dockerRuntimeCommand = "openresty"
type Executor interface {
Test(ctx context.Context) error
Reload(ctx context.Context) error
@@ -43,22 +45,22 @@ type PathExecutor struct {
}
func (e *PathExecutor) Test(ctx context.Context) error {
log.Printf("running nginx test with binary: %s", e.Path)
log.Printf("running openresty test with binary: %s", e.Path)
output, err := e.Runner.Run(ctx, e.Path, "-t")
if err != nil {
return fmt.Errorf("nginx -t failed: %w: %s", err, string(output))
return fmt.Errorf("openresty -t failed: %w: %s", err, string(output))
}
log.Printf("nginx test succeeded with binary: %s", e.Path)
log.Printf("openresty test succeeded with binary: %s", e.Path)
return nil
}
func (e *PathExecutor) Reload(ctx context.Context) error {
log.Printf("running nginx reload with binary: %s", e.Path)
log.Printf("running openresty reload with binary: %s", e.Path)
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 fmt.Errorf("openresty reload failed: %w: %s", err, string(output))
}
log.Printf("nginx reload succeeded with binary: %s", e.Path)
log.Printf("openresty reload succeeded with binary: %s", e.Path)
return nil
}
@@ -77,24 +79,12 @@ type DockerExecutor struct {
}
func (e *DockerExecutor) Test(ctx context.Context) error {
log.Printf("running docker nginx test: container=%s image=%s", e.ContainerName, e.Image)
output, err := e.Runner.Run(
ctx,
e.DockerBinary,
"run",
"--rm",
"-v",
fmt.Sprintf("%s:/etc/nginx/conf.d", e.RouteConfigDir),
"-v",
fmt.Sprintf("%s:%s", e.CertDir, e.NginxCertDir),
e.Image,
"nginx",
"-t",
)
log.Printf("running docker openresty test: container=%s image=%s", e.ContainerName, e.Image)
output, err := e.runEphemeralRuntimeCommand(ctx, "-t")
if err != nil {
return fmt.Errorf("docker nginx -t failed: %w: %s", err, string(output))
return fmt.Errorf("docker %s -t failed: %w: %s", dockerRuntimeCommand, err, string(output))
}
log.Printf("docker nginx test succeeded: container=%s", e.ContainerName)
log.Printf("docker openresty test succeeded: container=%s runtime=%s", e.ContainerName, dockerRuntimeCommand)
return nil
}
@@ -103,7 +93,7 @@ func (e *DockerExecutor) Reload(ctx context.Context) error {
}
func (e *DockerExecutor) EnsureRuntime(ctx context.Context, recreate bool) error {
log.Printf("ensuring docker nginx runtime: container=%s recreate=%t", e.ContainerName, recreate)
log.Printf("ensuring docker openresty runtime: container=%s recreate=%t", e.ContainerName, recreate)
output, err := e.Runner.Run(ctx, e.DockerBinary, "inspect", "-f", "{{.State.Running}}", e.ContainerName)
if err == nil {
if recreate {
@@ -113,7 +103,7 @@ func (e *DockerExecutor) EnsureRuntime(ctx context.Context, recreate bool) error
return e.runContainer(ctx)
}
if strings.TrimSpace(string(output)) == "true" {
log.Printf("docker nginx runtime already healthy: container=%s", e.ContainerName)
log.Printf("docker openresty runtime already healthy: container=%s", e.ContainerName)
return nil
}
if err := e.removeContainer(ctx); err != nil {
@@ -125,21 +115,21 @@ func (e *DockerExecutor) EnsureRuntime(ctx context.Context, recreate bool) error
}
func (e *DockerExecutor) removeContainer(ctx context.Context) error {
log.Printf("removing docker nginx container: container=%s", e.ContainerName)
log.Printf("removing docker openresty container: container=%s", e.ContainerName)
output, err := e.Runner.Run(ctx, e.DockerBinary, "rm", "-f", e.ContainerName)
if err != nil {
text := string(output)
if strings.Contains(text, "No such container") {
return nil
}
return fmt.Errorf("docker rm nginx failed: %w: %s", err, text)
return fmt.Errorf("docker rm openresty failed: %w: %s", err, text)
}
log.Printf("docker nginx container removed: container=%s", e.ContainerName)
log.Printf("docker openresty container removed: container=%s", e.ContainerName)
return nil
}
func (e *DockerExecutor) runContainer(ctx context.Context) error {
log.Printf("starting docker nginx container: container=%s image=%s", e.ContainerName, e.Image)
log.Printf("starting docker openresty container: container=%s image=%s", e.ContainerName, e.Image)
runArgs := []string{
"run", "-d",
"--name", e.ContainerName,
@@ -151,9 +141,9 @@ func (e *DockerExecutor) runContainer(ctx context.Context) error {
}
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 fmt.Errorf("docker run openresty failed: %w: %s", runErr, string(runOutput))
}
log.Printf("docker nginx container started: container=%s", e.ContainerName)
log.Printf("docker openresty container started: container=%s", e.ContainerName)
return nil
}
@@ -165,7 +155,7 @@ type Manager struct {
}
func (m *Manager) Apply(ctx context.Context, content string, supportFiles []protocol.SupportFile) error {
log.Printf("nginx apply started: route_config=%s support_files=%d", m.RouteConfigPath, len(supportFiles))
log.Printf("openresty apply started: route_config=%s support_files=%d", m.RouteConfigPath, len(supportFiles))
backup, err := m.backup()
if err != nil {
return err
@@ -177,21 +167,21 @@ func (m *Manager) Apply(ctx context.Context, content string, supportFiles []prot
}
renderedContent := m.renderConfig(content)
if err = os.WriteFile(m.RouteConfigPath, []byte(renderedContent), 0o644); err != nil {
log.Printf("writing nginx route config failed, restoring backup: error=%v", err)
log.Printf("writing openresty route config failed, restoring backup: error=%v", err)
_ = m.restore(backup)
return err
}
if err = m.Executor.Test(ctx); err != nil {
log.Printf("nginx test failed after config write, restoring backup: error=%v", err)
log.Printf("openresty test failed after config write, restoring backup: error=%v", err)
_ = m.restore(backup)
return err
}
if err = m.Executor.Reload(ctx); err != nil {
log.Printf("nginx reload failed after config write, restoring backup: error=%v", err)
log.Printf("openresty reload failed after config write, restoring backup: error=%v", err)
_ = m.restore(backup)
return err
}
log.Printf("nginx apply completed successfully: route_config=%s", m.RouteConfigPath)
log.Printf("openresty apply completed successfully: route_config=%s", m.RouteConfigPath)
return nil
}
@@ -199,7 +189,7 @@ func (m *Manager) EnsureRuntime(ctx context.Context, recreate bool) error {
if m.Executor == nil {
return errors.New("executor 未配置")
}
log.Printf("nginx ensure runtime requested: recreate=%t", recreate)
log.Printf("openresty ensure runtime requested: recreate=%t", recreate)
return m.Executor.EnsureRuntime(ctx, recreate)
}
@@ -223,7 +213,7 @@ func (m *Manager) CurrentChecksum() (string, error) {
return "", err
}
result := bundleChecksum(normalized, files)
log.Printf("nginx current checksum calculated: route_config=%s checksum=%s support_files=%d", m.RouteConfigPath, result, len(files))
log.Printf("openresty current checksum calculated: route_config=%s checksum=%s support_files=%d", m.RouteConfigPath, result, len(files))
return result, nil
}
@@ -267,10 +257,10 @@ func NewExecutor(options ExecutorOptions) Executor {
func DetectVersion(ctx context.Context, options ExecutorOptions) string {
version, err := detectVersion(ctx, options, &OSCommandRunner{})
if err != nil {
log.Printf("detect nginx version failed: %v", err)
log.Printf("detect openresty version failed: %v", err)
return ""
}
log.Printf("detected nginx version: %s", version)
log.Printf("detected openresty version: %s", version)
return version
}
@@ -281,21 +271,21 @@ func detectVersion(ctx context.Context, options ExecutorOptions, runner CommandR
if options.NginxPath != "" {
output, err := runner.Run(ctx, options.NginxPath, "-v")
if err != nil {
return "", fmt.Errorf("run nginx -v failed: %w: %s", err, string(output))
return "", fmt.Errorf("run runtime -v failed: %w: %s", err, string(output))
}
version := parseNginxVersion(string(output))
if version == "" {
return "", errors.New("cannot parse nginx version from binary output")
return "", errors.New("cannot parse runtime version from binary output")
}
return version, nil
}
output, err := runner.Run(ctx, options.DockerBinary, "run", "--rm", options.Image, "nginx", "-v")
output, err := runDockerVersionProbe(ctx, runner, options.DockerBinary, options.Image)
if err != nil {
return "", fmt.Errorf("run docker nginx -v failed: %w: %s", err, string(output))
return "", fmt.Errorf("run docker %s -v failed: %w: %s", dockerRuntimeCommand, err, string(output))
}
version := parseNginxVersion(string(output))
if version == "" {
return "", errors.New("cannot parse nginx version from docker output")
return "", errors.New("cannot parse runtime version from docker output")
}
return version, nil
}
@@ -308,7 +298,30 @@ func parseNginxVersion(output string) string {
return matches[1]
}
var nginxVersionPattern = regexp.MustCompile(`(?im)nginx version:\s*nginx/([^\s]+)`)
var nginxVersionPattern = regexp.MustCompile(`(?im)(?:nginx|openresty) version:\s*(?:nginx|openresty)/([^\s]+)`)
func (e *DockerExecutor) runEphemeralRuntimeCommand(ctx context.Context, args ...string) ([]byte, error) {
return e.runEphemeralRuntimeCommandWithBinary(ctx, dockerRuntimeCommand, args...)
}
func (e *DockerExecutor) runEphemeralRuntimeCommandWithBinary(ctx context.Context, runtimeBinary string, args ...string) ([]byte, error) {
runtimeArgs := []string{
"run",
"--rm",
"-v",
fmt.Sprintf("%s:/etc/nginx/conf.d", e.RouteConfigDir),
"-v",
fmt.Sprintf("%s:%s", e.CertDir, e.NginxCertDir),
e.Image,
runtimeBinary,
}
runtimeArgs = append(runtimeArgs, args...)
return e.Runner.Run(ctx, e.DockerBinary, runtimeArgs...)
}
func runDockerVersionProbe(ctx context.Context, runner CommandRunner, dockerBinary string, image string) ([]byte, error) {
return runner.Run(ctx, dockerBinary, "run", "--rm", image, dockerRuntimeCommand, "-v")
}
type backupState struct {
RouteExisted bool
+25 -22
View File
@@ -50,7 +50,7 @@ func (e *fakeExecutor) EnsureRuntime(ctx context.Context, recreate bool) error {
func TestPathExecutorCommands(t *testing.T) {
runner := &fakeRunner{}
executor := &PathExecutor{
Path: "/opt/nginx/sbin/nginx",
Path: "/usr/local/openresty/nginx/sbin/openresty",
Runner: runner,
}
@@ -62,8 +62,8 @@ func TestPathExecutorCommands(t *testing.T) {
}
expected := []runCall{
{name: "/opt/nginx/sbin/nginx", args: []string{"-t"}},
{name: "/opt/nginx/sbin/nginx", args: []string{"-s", "reload"}},
{name: "/usr/local/openresty/nginx/sbin/openresty", args: []string{"-t"}},
{name: "/usr/local/openresty/nginx/sbin/openresty", args: []string{"-s", "reload"}},
}
if !reflect.DeepEqual(runner.calls, expected) {
t.Fatalf("unexpected calls: %#v", runner.calls)
@@ -72,7 +72,7 @@ func TestPathExecutorCommands(t *testing.T) {
func TestPathExecutorEnsureRuntimeNoop(t *testing.T) {
executor := &PathExecutor{
Path: "/opt/nginx/sbin/nginx",
Path: "/usr/local/openresty/nginx/sbin/openresty",
Runner: &fakeRunner{},
}
if err := executor.EnsureRuntime(context.Background(), true); err != nil {
@@ -91,8 +91,8 @@ func TestDockerExecutorStartsContainerWhenMissing(t *testing.T) {
}
executor := &DockerExecutor{
DockerBinary: "docker",
ContainerName: "atsflare-nginx",
Image: "nginx:stable-alpine",
ContainerName: "atsflare-openresty",
Image: "openresty/openresty:alpine",
RouteConfigDir: filepath.Clean("/tmp/routes"),
CertDir: filepath.Clean("/tmp/certs"),
NginxCertDir: "/etc/nginx/atsflare-certs",
@@ -109,6 +109,9 @@ func TestDockerExecutorStartsContainerWhenMissing(t *testing.T) {
if runner.calls[0].args[0] != "run" || runner.calls[0].args[1] != "--rm" {
t.Fatalf("expected docker run --rm for test, got %#v", runner.calls[0])
}
if runner.calls[0].args[len(runner.calls[0].args)-2] != "openresty" {
t.Fatalf("expected docker test command to invoke openresty, got %#v", runner.calls[0])
}
}
func TestDockerExecutorStartsStoppedContainer(t *testing.T) {
@@ -122,8 +125,8 @@ func TestDockerExecutorStartsStoppedContainer(t *testing.T) {
}
executor := &DockerExecutor{
DockerBinary: "docker",
ContainerName: "atsflare-nginx",
Image: "nginx:stable-alpine",
ContainerName: "atsflare-openresty",
Image: "openresty/openresty:alpine",
RouteConfigDir: filepath.Clean("/tmp/routes"),
CertDir: filepath.Clean("/tmp/certs"),
NginxCertDir: "/etc/nginx/atsflare-certs",
@@ -159,8 +162,8 @@ func TestDockerExecutorRecreatesContainerOnStartup(t *testing.T) {
}
executor := &DockerExecutor{
DockerBinary: "docker",
ContainerName: "atsflare-nginx",
Image: "nginx:stable-alpine",
ContainerName: "atsflare-openresty",
Image: "openresty/openresty:alpine",
RouteConfigDir: filepath.Clean("/tmp/routes"),
CertDir: filepath.Clean("/tmp/certs"),
NginxCertDir: "/etc/nginx/atsflare-certs",
@@ -184,8 +187,8 @@ func TestDockerExecutorRecreatesContainerOnStartup(t *testing.T) {
func TestNewExecutorUsesAbsoluteDockerMountPath(t *testing.T) {
executor := NewExecutor(ExecutorOptions{
DockerBinary: "docker",
ContainerName: "atsflare-nginx",
Image: "nginx:stable-alpine",
ContainerName: "atsflare-openresty",
Image: "openresty/openresty:alpine",
RouteConfigPath: "./data/etc/nginx/conf.d/atsflare_routes.conf",
CertDir: "./data/etc/nginx/certs",
NginxCertDir: "/etc/nginx/atsflare-certs",
@@ -205,16 +208,16 @@ func TestNewExecutorUsesAbsoluteDockerMountPath(t *testing.T) {
func TestDetectVersionFromBinary(t *testing.T) {
version, err := detectVersion(context.Background(), ExecutorOptions{
NginxPath: "/opt/nginx/sbin/nginx",
NginxPath: "/usr/local/openresty/nginx/sbin/openresty",
}, &fakeRunner{
runFn: func(name string, args ...string) ([]byte, error) {
return []byte("nginx version: nginx/1.25.5\n"), nil
return []byte("nginx version: openresty/1.27.1.2\n"), nil
},
})
if err != nil {
t.Fatalf("detectVersion failed: %v", err)
}
if version != "1.25.5" {
if version != "1.27.1.2" {
t.Fatalf("unexpected version: %s", version)
}
}
@@ -222,23 +225,23 @@ func TestDetectVersionFromBinary(t *testing.T) {
func TestDetectVersionFromDockerImage(t *testing.T) {
runner := &fakeRunner{
runFn: func(name string, args ...string) ([]byte, error) {
return []byte("nginx version: nginx/1.27.4\n"), nil
return []byte("nginx version: openresty/1.27.1.2\n"), nil
},
}
version, err := detectVersion(context.Background(), ExecutorOptions{
DockerBinary: "docker",
Image: "nginx:stable-alpine",
Image: "openresty/openresty:alpine",
}, runner)
if err != nil {
t.Fatalf("detectVersion failed: %v", err)
}
if version != "1.27.4" {
if version != "1.27.1.2" {
t.Fatalf("unexpected version: %s", version)
}
if len(runner.calls) != 1 {
t.Fatalf("expected one command call, got %d", len(runner.calls))
}
expectedArgs := []string{"run", "--rm", "nginx:stable-alpine", "nginx", "-v"}
expectedArgs := []string{"run", "--rm", "openresty/openresty:alpine", "openresty", "-v"}
if !reflect.DeepEqual(runner.calls[0].args, expectedArgs) {
t.Fatalf("unexpected docker args: %#v", runner.calls[0].args)
}
@@ -247,11 +250,11 @@ func TestDetectVersionFromDockerImage(t *testing.T) {
func TestParseNginxVersionIgnoresDockerEntrypointPaths(t *testing.T) {
output := strings.Join([]string{
"/docker-entrypoint.sh: /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh: info: can not modify /etc/nginx/conf.d/default.conf (read-only file system?)",
"nginx version: nginx/1.27.4",
"nginx version: openresty/1.27.1.2",
}, "\n")
version := parseNginxVersion(output)
if version != "1.27.4" {
if version != "1.27.1.2" {
t.Fatalf("unexpected version: %s", version)
}
}
@@ -307,7 +310,7 @@ func TestManagerRollbackRestoresSupportFiles(t *testing.T) {
CertDir: certDir,
NginxCertDir: "/etc/nginx/atsflare-certs",
Executor: &fakeExecutor{
testErr: errors.New("nginx test failed"),
testErr: errors.New("openresty test failed"),
},
}
+6 -6
View File
@@ -68,13 +68,13 @@ func (s *Service) sync(ctx context.Context, startup bool) error {
}
log.Printf("current local checksum loaded: mode=%s checksum=%s", mode, currentChecksum)
if currentChecksum == config.Checksum {
log.Printf("local nginx config already up to date: mode=%s version=%s", mode, config.Version)
log.Printf("local openresty config already up to date: mode=%s version=%s", mode, config.Version)
if startup {
log.Printf("ensuring nginx runtime on startup: version=%s", config.Version)
log.Printf("ensuring openresty runtime on startup: version=%s", config.Version)
if err = s.nginxManager.EnsureRuntime(ctx, true); err != nil {
return err
}
log.Printf("nginx runtime ensured on startup: version=%s", config.Version)
log.Printf("openresty runtime ensured on startup: version=%s", config.Version)
}
snapshot.CurrentVersion = config.Version
snapshot.CurrentChecksum = config.Checksum
@@ -86,9 +86,9 @@ func (s *Service) sync(ctx context.Context, startup bool) error {
log.Printf("skipping apply because state already records target version/checksum: version=%s checksum=%s", config.Version, config.Checksum)
return nil
}
log.Printf("applying new nginx config: mode=%s from_version=%s to_version=%s old_checksum=%s new_checksum=%s", mode, snapshot.CurrentVersion, config.Version, currentChecksum, config.Checksum)
log.Printf("applying new openresty config: mode=%s from_version=%s to_version=%s old_checksum=%s new_checksum=%s", mode, snapshot.CurrentVersion, config.Version, currentChecksum, config.Checksum)
if err = s.nginxManager.Apply(ctx, config.RenderedConfig, config.SupportFiles); err != nil {
log.Printf("apply nginx config failed: mode=%s version=%s error=%v", mode, config.Version, err)
log.Printf("apply openresty config failed: mode=%s version=%s error=%v", mode, config.Version, err)
snapshot.LastError = err.Error()
_ = s.stateStore.Save(snapshot)
reportErr := s.client.ReportApplyLog(ctx, protocol.ApplyLogPayload{
@@ -104,7 +104,7 @@ func (s *Service) sync(ctx context.Context, startup bool) error {
log.Printf("failed apply log reported: version=%s", config.Version)
return err
}
log.Printf("nginx config applied successfully: mode=%s version=%s", mode, config.Version)
log.Printf("openresty config applied successfully: mode=%s version=%s", mode, config.Version)
snapshot.CurrentVersion = config.Version
snapshot.CurrentChecksum = config.Checksum
snapshot.LastError = ""