Обновлять сертификат балансировщика без перезапуска процессов

This commit is contained in:
2026-11-22 20:35:45 +03:00
parent 7e61bc4ee3
commit 341b6b887d
5 changed files with 10143 additions and 24 deletions
+104 -21
View File
@@ -4,6 +4,7 @@ package main
import (
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"encoding/binary"
@@ -40,26 +41,27 @@ type Outbound struct {
Identity string `json:"server_identity"`
}
type Config struct {
Outbounds []Outbound `json:"outbounds"`
ServeOnly bool `json:"serve_only"`
ReloadPIDOne bool `json:"reload_pid_one"`
Role string `json:"role"`
DNS []string `json:"dns"`
IP []string `json:"ip"`
Bao string `json:"bao"`
Trust string `json:"trust"`
Bootstrap string `json:"bootstrap"`
Identity string `json:"identity"`
Revoked string `json:"revoked"`
TTL string `json:"ttl"`
KV bool `json:"kv"`
Servers []Boundary `json:"servers"`
Outbounds []Outbound `json:"outbounds"`
ServeOnly bool `json:"serve_only"`
HAProxySocket string `json:"haproxy_socket"`
Role string `json:"role"`
DNS []string `json:"dns"`
IP []string `json:"ip"`
Bao string `json:"bao"`
Trust string `json:"trust"`
Bootstrap string `json:"bootstrap"`
Identity string `json:"identity"`
Revoked string `json:"revoked"`
TTL string `json:"ttl"`
KV bool `json:"kv"`
Servers []Boundary `json:"servers"`
}
type Agent struct {
c Config
mu sync.Mutex
token string
tokenUntil time.Time
c Config
mu sync.Mutex
token string
tokenUntil time.Time
lbBundleHash [32]byte
}
func event(name string) { log.Print("{\"event\":\"" + name + "\"}") }
@@ -300,10 +302,21 @@ func (a *Agent) refresh() error {
return errors.New("unparsed certificate")
}
event("identity.certificate_issued")
if a.c.ReloadPIDOne {
if e = syscall.Kill(1, syscall.SIGUSR2); e != nil {
return errors.New("certificate reload failed")
}
if a.c.HAProxySocket != "" {
bundle := filepath.Join(a.c.Identity, "current", "bundle.pem")
raw, err := os.ReadFile(bundle)
if err != nil {
return err
}
hash := sha256.Sum256(raw)
if hash != a.lbBundleHash {
if err = installHAProxyCertificate(a.c.HAProxySocket, bundle); err != nil {
return err
}
a.lbBundleHash = hash
event("identity.certificate_applied")
}
}
if a.c.KV {
@@ -334,6 +347,68 @@ func (a *Agent) refresh() error {
return atomicFile(filepath.Join(a.c.Identity, "agent.json"), []byte(`{"refreshed_at":`+strconv.FormatInt(now.Unix(), 10)+`}`))
}
// The runtime transaction replaces BOTH frontend and backend certificate
// contexts without restarting workers or discarding DNS/health-check state.
// Keep the persisted generation for native process restarts. Do not log PEM
// payloads or CLI responses, which may include sensitive material on errors.
func haProxyCommand(socketPath, request string) (string, error) {
conn, err := net.DialTimeout("unix", socketPath, 3*time.Second)
if err != nil {
return "", errors.New("HAProxy admin socket unavailable")
}
defer conn.Close()
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
if _, err = io.WriteString(conn, request); err != nil {
return "", errors.New("HAProxy admin write failed")
}
if err = conn.(*net.UnixConn).CloseWrite(); err != nil {
return "", errors.New("HAProxy admin shutdown failed")
}
response, err := io.ReadAll(io.LimitReader(conn, 64*1024))
if err != nil {
return "", errors.New("HAProxy admin response failed")
}
return string(response), nil
}
func installHAProxyCertificate(socketPath, bundlePath string) error {
// Serialize agent and explicit operator updates in their shared identity
// volume, using the same unprivileged UID as the native load balancer.
lock, err := os.OpenFile(filepath.Join(filepath.Dir(filepath.Dir(bundlePath)), ".haproxy.lock"), os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
defer lock.Close()
if err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
return err
}
defer syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
raw, err := os.ReadFile(bundlePath)
if err != nil {
return err
}
if _, err = tls.X509KeyPair(raw, raw); err != nil {
return errors.New("invalid HAProxy certificate bundle")
}
var lines []string
for _, line := range strings.Split(string(raw), "\n") {
if strings.TrimSpace(line) != "" {
lines = append(lines, line)
}
}
response, err := haProxyCommand(socketPath, "set ssl cert "+bundlePath+" <<\n"+strings.Join(lines, "\n")+"\n\n")
if err != nil || (!strings.Contains(response, "Transaction created") && !strings.Contains(response, "Transaction updated")) {
_, _ = haProxyCommand(socketPath, "abort ssl cert "+bundlePath+"\n")
return errors.New("HAProxy certificate transaction failed")
}
response, err = haProxyCommand(socketPath, "commit ssl cert "+bundlePath+"\n")
if err != nil || !strings.Contains(response, "Success!") {
_, _ = haProxyCommand(socketPath, "abort ssl cert "+bundlePath+"\n")
return errors.New("HAProxy certificate commit failed")
}
return nil
}
type boundedListener struct {
net.Listener
slots chan struct{}
@@ -601,6 +676,14 @@ func runTCP(c Config, b Boundary) error {
}
}
func main() {
if len(os.Args) == 2 && os.Args[1] == "--reload-lb-cert" {
if installHAProxyCertificate("/proc/1/root/tmp/admin.sock", "/run/identity/current/bundle.pem") != nil {
event("identity.certificate_apply_failed")
os.Exit(1)
}
event("identity.certificate_applied")
return
}
if len(os.Args) != 2 {
event("gateway.invalid_configuration")
os.Exit(2)