feat(controller): hot-reload the notification pipes
Email, ntfy and webhook kept their settings in a plain struct field copied at construction, so editing controllerMethod in config.json wrote the file and replaced the in-memory configuration while the running channels stayed on their boot values. Add Reload to the Controller interface and implement it for the three notification pipes; Manager.ReloadAll fans an update out to every registered controller and is wired into the reload hook from main. Reload runs on the goroutine serving the settings update while the send methods run on the status-change and incoming-webhook goroutines, so storing the new settings in a plain field would be a data race. Each pipe publishes its settings — and the HTTP client derived from them — through atomic pointers, and every send takes one snapshot so a reload landing mid-send cannot split it across two configurations. Only a change to networkUseProxy rebuilds the client; everything else is read from the settings at send time, so a reload that changes nothing relevant leaves the client alone. Email needed one more fix: gomail exposes its dial hook as a package-level variable with no unset, and the constructor only installed the proxy dialer when the flag was set, so turning networkUseProxy off left SMTP tunnelled through a proxy. applyEmailProxy now restores net.DialTimeout, which is gomail's own default. QQ (Napcat) and Telegram implement Reload because the interface requires it, but neither can apply a change in place: the NapCat client is stopped through a sync.Once and the Telegram polling context is created with the controller, so both need to be rebuilt and swapped into the manager. Rather than no-op silently and let an edit look applied, they log a warning while their settings diverge. That rebuild is the next step.
This commit is contained in:
@@ -5,6 +5,8 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"nukumizu-backend/config"
|
||||
@@ -16,17 +18,33 @@ import (
|
||||
)
|
||||
|
||||
// WebhookController handles notifications via generic HTTP webhooks.
|
||||
//
|
||||
// Both fields are held behind atomic pointers rather than in plain fields:
|
||||
// Reload replaces them on the settings-update goroutine while the send methods
|
||||
// read them on the status-change and incoming-webhook goroutines.
|
||||
type WebhookController struct {
|
||||
cfg config.WebhookConfig
|
||||
httpClient *http.Client
|
||||
cfg atomic.Pointer[config.WebhookConfig]
|
||||
httpClient atomic.Pointer[http.Client]
|
||||
}
|
||||
|
||||
// NewWebhookController creates a new Webhook controller.
|
||||
func NewWebhookController(cfg config.WebhookConfig) *WebhookController {
|
||||
return &WebhookController{
|
||||
cfg: cfg,
|
||||
httpClient: netproxy.HTTPClient(cfg.NetworkUseProxy, 10*time.Second),
|
||||
}
|
||||
w := &WebhookController{}
|
||||
w.cfg.Store(&cfg)
|
||||
w.httpClient.Store(netproxy.HTTPClient(cfg.NetworkUseProxy, 10*time.Second))
|
||||
return w
|
||||
}
|
||||
|
||||
// settings returns the configuration currently in effect. The value it points
|
||||
// at is never mutated after being stored, so a caller can hold the pointer for
|
||||
// one whole send without a concurrent Reload disturbing it.
|
||||
func (w *WebhookController) settings() *config.WebhookConfig {
|
||||
return w.cfg.Load()
|
||||
}
|
||||
|
||||
// client returns the HTTP client built for the current proxy setting.
|
||||
func (w *WebhookController) client() *http.Client {
|
||||
return w.httpClient.Load()
|
||||
}
|
||||
|
||||
// Name returns the controller name.
|
||||
@@ -36,7 +54,7 @@ func (w *WebhookController) Name() string {
|
||||
|
||||
// Start initializes the Webhook controller.
|
||||
func (w *WebhookController) Start() error {
|
||||
if !w.cfg.Enabled {
|
||||
if !w.settings().Enabled {
|
||||
postLog.Info("Webhook controller is disabled")
|
||||
return nil
|
||||
}
|
||||
@@ -49,26 +67,51 @@ func (w *WebhookController) Stop() {
|
||||
postLog.Info("Webhook controller stopped")
|
||||
}
|
||||
|
||||
// Reload applies the current configuration. Everything the sender reads is
|
||||
// taken from the settings at send time, so only a change to the proxy flag
|
||||
// needs more than the swap: that one is baked into the HTTP client's transport
|
||||
// when the client is built.
|
||||
func (w *WebhookController) Reload() {
|
||||
global := config.Current()
|
||||
if global == nil {
|
||||
return
|
||||
}
|
||||
|
||||
current := w.settings()
|
||||
updated := global.ControllerMethod.Webhook
|
||||
// WebhookConfig carries a header map, so it is not comparable with ==.
|
||||
if reflect.DeepEqual(*current, updated) {
|
||||
return
|
||||
}
|
||||
|
||||
if current.NetworkUseProxy != updated.NetworkUseProxy {
|
||||
w.httpClient.Store(netproxy.HTTPClient(updated.NetworkUseProxy, 10*time.Second))
|
||||
}
|
||||
w.cfg.Store(&updated)
|
||||
postLog.Debug("Webhook controller reloaded")
|
||||
}
|
||||
|
||||
// IsEnabled returns whether the controller is enabled.
|
||||
func (w *WebhookController) IsEnabled() bool {
|
||||
return w.cfg.Enabled
|
||||
return w.settings().Enabled
|
||||
}
|
||||
|
||||
// IsMarkdown returns whether the channel renders Markdown, per its markdown
|
||||
// setting in config.json.
|
||||
func (w *WebhookController) IsMarkdown() bool {
|
||||
return w.cfg.Markdown
|
||||
return w.settings().Markdown
|
||||
}
|
||||
|
||||
// SendStatusChange sends a status change notification via Webhook.
|
||||
func (w *WebhookController) SendStatusChange(change node.StatusChange) error {
|
||||
if !w.cfg.Enabled {
|
||||
s := w.settings()
|
||||
if !s.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
cfg := config.Current()
|
||||
params := template.BuildParamsFromStatusChange(change)
|
||||
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, w.cfg.Markdown)
|
||||
message := template.Render(cfg.ControllerMessage.ServerStatusChanged, params, s.Markdown)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"event": change.Event,
|
||||
@@ -83,13 +126,14 @@ func (w *WebhookController) SendStatusChange(change node.StatusChange) error {
|
||||
|
||||
// SendServerList sends the server list via Webhook.
|
||||
func (w *WebhookController) SendServerList(onlineServers, offlineServers string) error {
|
||||
if !w.cfg.Enabled {
|
||||
s := w.settings()
|
||||
if !s.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
cfg := config.Current()
|
||||
params := template.BuildParamsFromServerList()
|
||||
message := template.Render(cfg.ControllerMessage.ServerList, params, w.cfg.Markdown)
|
||||
message := template.Render(cfg.ControllerMessage.ServerList, params, s.Markdown)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"type": "serverList",
|
||||
@@ -104,13 +148,14 @@ func (w *WebhookController) SendServerList(onlineServers, offlineServers string)
|
||||
|
||||
// SendExecuteResult sends a command execution result via Webhook.
|
||||
func (w *WebhookController) SendExecuteResult(serverName, serverUUID, command, result string) error {
|
||||
if !w.cfg.Enabled {
|
||||
s := w.settings()
|
||||
if !s.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
cfg := config.Current()
|
||||
params := template.BuildParamsFromExecResult(serverName, serverUUID, command, result)
|
||||
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, w.cfg.Markdown)
|
||||
message := template.Render(cfg.ControllerMessage.ServerExecuteResult, params, s.Markdown)
|
||||
|
||||
payload := map[string]interface{}{
|
||||
"type": "executeResult",
|
||||
@@ -128,7 +173,8 @@ func (w *WebhookController) SendExecuteResult(serverName, serverUUID, command, r
|
||||
// SendAlert sends an alert submitted through the incoming webhook API to the
|
||||
// configured URL.
|
||||
func (w *WebhookController) SendAlert(alert controller.Alert) error {
|
||||
if !w.cfg.Enabled {
|
||||
s := w.settings()
|
||||
if !s.Enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -137,15 +183,20 @@ func (w *WebhookController) SendAlert(alert controller.Alert) error {
|
||||
"subject": alert.Subject,
|
||||
"source": alert.Source,
|
||||
"content": alert.Content,
|
||||
"message": alert.Render(w.cfg.Markdown),
|
||||
"message": alert.Render(s.Markdown),
|
||||
"time": alert.Time,
|
||||
}
|
||||
|
||||
return w.send(payload)
|
||||
}
|
||||
|
||||
// send posts one payload using the settings in effect at the moment it is
|
||||
// called, so the URL, method and headers all come from the same configuration
|
||||
// even if a reload lands mid-send.
|
||||
func (w *WebhookController) send(payload map[string]interface{}) error {
|
||||
method := w.cfg.Method
|
||||
s := w.settings()
|
||||
|
||||
method := s.Method
|
||||
if method == "" {
|
||||
method = "POST"
|
||||
}
|
||||
@@ -155,17 +206,17 @@ func (w *WebhookController) send(payload map[string]interface{}) error {
|
||||
return fmt.Errorf("failed to marshal webhook payload: %w", err)
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(method, w.cfg.URL, bytes.NewReader(bodyJSON))
|
||||
req, err := http.NewRequest(method, s.URL, bytes.NewReader(bodyJSON))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create webhook request: %w", err)
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
for key, value := range w.cfg.Headers {
|
||||
for key, value := range s.Headers {
|
||||
req.Header.Set(key, value)
|
||||
}
|
||||
|
||||
resp, err := w.httpClient.Do(req)
|
||||
resp, err := w.client().Do(req)
|
||||
if err != nil {
|
||||
postLog.Warning("Failed to send webhook: " + err.Error())
|
||||
return err
|
||||
@@ -176,6 +227,6 @@ func (w *WebhookController) send(payload map[string]interface{}) error {
|
||||
postLog.Warning(fmt.Sprintf("Webhook returned status %d", resp.StatusCode))
|
||||
}
|
||||
|
||||
postLog.Debug("Webhook notification sent to " + w.cfg.URL)
|
||||
postLog.Debug("Webhook notification sent to " + s.URL)
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user