Skip to content

Modern Docker Management, Designed for Everyone

fix: handle unchecked error returns across backend and CLI

Kyle Mendelle4a54203bc95
diff --git a/backend/api/ws/diagnostics.go b/backend/api/ws/diagnostics.go
index 06768aa91..e76c96764 100644
--- a/backend/api/ws/diagnostics.go
+++ b/backend/api/ws/diagnostics.go
@@ -2,6 +2,7 @@ package ws
import (
"encoding/json/v2"
+ "log/slog"
"net/http"
"net/http/pprof"
"time"
@@ -64,7 +65,11 @@ func (h *WebSocketHandler) DiagnosticsStream(c *echo.Context) error {
if err != nil {
return nil
}
- defer conn.Close()
+ defer func() {
+ if err := conn.Close(); err != nil {
+ slog.Debug("Failed to close diagnostics websocket connection", "error", err)
+ }
+ }()
done := diagnosticsReadLoopInternal(conn)
write := func() bool {
@@ -98,7 +103,11 @@ func (h *WebSocketHandler) ServerLogsStream(c *echo.Context) error {
if err != nil {
return nil
}
- defer conn.Close()
+ defer func() {
+ if err := conn.Close(); err != nil {
+ slog.Debug("Failed to close server logs websocket connection", "error", err)
+ }
+ }()
// Subscribe before replaying the backlog so no entry is missed in the gap; at
// worst the newest backlog entry is delivered twice, which is harmless.
diff --git a/backend/api/ws/handler_test.go b/backend/api/ws/handler_test.go
index 5e5feb080..4e973f617 100644
--- a/backend/api/ws/handler_test.go
+++ b/backend/api/ws/handler_test.go
@@ -232,7 +232,9 @@ func TestWebSocketHandler_ProjectLogs_CompletedSourceStartsFreshStream(t *testin
path := "/api/environments/0/ws/projects/project-1/logs?follow=false"
conn1 := dialWebSocket(t, server.URL, path)
- defer conn1.Close()
+ defer func() {
+ require.NoError(t, conn1.Close())
+ }()
_ = conn1.SetReadDeadline(time.Now().Add(2 * time.Second))
_, msg1, err := conn1.ReadMessage()
@@ -246,7 +248,9 @@ func TestWebSocketHandler_ProjectLogs_CompletedSourceStartsFreshStream(t *testin
}
conn2 := dialWebSocket(t, server.URL, path)
- defer conn2.Close()
+ defer func() {
+ require.NoError(t, conn2.Close())
+ }()
_ = conn2.SetReadDeadline(time.Now().Add(2 * time.Second))
_, msg2, err := conn2.ReadMessage()
@@ -276,7 +280,9 @@ func TestWebSocketHandler_ContainerLogs_BroadcastsStreamErrors(t *testing.T) {
defer server.Close()
conn := dialWebSocket(t, server.URL, "/api/environments/0/ws/containers/container-1/logs")
- defer conn.Close()
+ defer func() {
+ require.NoError(t, conn.Close())
+ }()
var got []string
@@ -317,7 +323,9 @@ func TestWebSocketHandler_ContainerLogs_ErrorStartsFreshStreamForNewSubscribers(
path := "/api/environments/0/ws/containers/container-1/logs"
conn1 := dialWebSocket(t, server.URL, path)
- defer conn1.Close()
+ defer func() {
+ require.NoError(t, conn1.Close())
+ }()
got1 := make([]string, 0, 2)
for range 2 {
@@ -332,7 +340,9 @@ func TestWebSocketHandler_ContainerLogs_ErrorStartsFreshStreamForNewSubscribers(
}, got1)
conn2 := dialWebSocket(t, server.URL, path)
- defer conn2.Close()
+ defer func() {
+ require.NoError(t, conn2.Close())
+ }()
got2 := make([]string, 0, 2)
for range 2 {
diff --git a/backend/cli/config_schema.go b/backend/cli/config_schema.go
index 1c5a9238e..ae09acbf8 100644
--- a/backend/cli/config_schema.go
+++ b/backend/cli/config_schema.go
@@ -1,7 +1,6 @@
package cli
import (
- "fmt"
"os"
"github.com/getarcaneapp/arcane/backend/v2/internal/configschema"
@@ -15,38 +14,38 @@ var configSchemaCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {
outputFile, err := cmd.Flags().GetString("output")
if err != nil {
- fmt.Fprintf(os.Stderr, "Error reading --output flag: %v\n", err)
+ cmd.PrintErrf("Error reading --output flag: %v\n", err)
os.Exit(1)
}
sourceRoot, err := cmd.Flags().GetString("source-root")
if err != nil {
- fmt.Fprintf(os.Stderr, "Error reading --source-root flag: %v\n", err)
+ cmd.PrintErrf("Error reading --source-root flag: %v\n", err)
os.Exit(1)
}
doc, err := configschema.GenerateWithSourceRoot(sourceRoot)
if err != nil {
- fmt.Fprintf(os.Stderr, "Error generating config schema: %v\n", err)
+ cmd.PrintErrf("Error generating config schema: %v\n", err)
os.Exit(1)
}
output, err := configschema.MarshalJSON(doc)
if err != nil {
- fmt.Fprintf(os.Stderr, "Error encoding config schema: %v\n", err)
+ cmd.PrintErrf("Error encoding config schema: %v\n", err)
os.Exit(1)
}
if outputFile != "" {
if err := os.WriteFile(outputFile, output, 0o600); err != nil {
- fmt.Fprintf(os.Stderr, "Error writing file: %v\n", err)
+ cmd.PrintErrf("Error writing file: %v\n", err)
os.Exit(1)
}
- fmt.Fprintf(os.Stderr, "Config schema written to %s\n", outputFile)
+ cmd.PrintErrf("Config schema written to %s\n", outputFile)
return
}
- fmt.Print(string(output))
+ cmd.Print(string(output))
},
}
diff --git a/backend/cli/openapi.go b/backend/cli/openapi.go
index 9ae0f08f3..12a286ff2 100644
--- a/backend/cli/openapi.go
+++ b/backend/cli/openapi.go
@@ -1,7 +1,6 @@
package cli
import (
- "fmt"
"os"
"github.com/getarcaneapp/arcane/backend/v2/api"
@@ -35,19 +34,19 @@ var openapiCmd = &cobra.Command{
}
if err != nil {
- fmt.Fprintf(os.Stderr, "Error generating OpenAPI spec: %v\n", err)
+ cmd.PrintErrf("Error generating OpenAPI spec: %v\n", err)
os.Exit(1)
}
// Write to file or stdout
if outputFile != "" {
if err := os.WriteFile(outputFile, output, 0o600); err != nil {
- fmt.Fprintf(os.Stderr, "Error writing file: %v\n", err)
+ cmd.PrintErrf("Error writing file: %v\n", err)
os.Exit(1)
}
- fmt.Fprintf(os.Stderr, "OpenAPI spec written to %s\n", outputFile)
+ cmd.PrintErrf("OpenAPI spec written to %s\n", outputFile)
} else {
- fmt.Println(string(output))
+ cmd.Println(string(output))
}
},
}
diff --git a/backend/pkg/gitutil/git.go b/backend/pkg/gitutil/git.go
index d9ebf708a..793cc5bd1 100644
--- a/backend/pkg/gitutil/git.go
+++ b/backend/pkg/gitutil/git.go
@@ -3,9 +3,9 @@ package git
import (
"context"
stderrors "errors"
- "fmt"
"io"
"io/fs"
+ "log/slog"
"net"
nethttp "net/http"
"os"
@@ -181,7 +181,7 @@ func (c *Client) createAcceptNewHostKeyCallback() (gossh.HostKeyCallback, error)
return nil, errors.WrapIf(err, "failed to create known_hosts file")
}
if err := file.Close(); err != nil {
- fmt.Fprintf(os.Stderr, "Warning: failed to close known_hosts file %s: %v\n", knownHostsPath, err)
+ slog.Warn("Failed to close known_hosts file", "path", knownHostsPath, "error", err)
}
}
@@ -210,7 +210,7 @@ func (c *Client) createAcceptNewHostKeyCallback() (gossh.HostKeyCallback, error)
if err := addHostKey(knownHostsPath, hostname, key); err != nil {
// Log the error but don't fail - still allow the connection
// The host key just won't be remembered for next time
- fmt.Fprintf(os.Stderr, "Warning: failed to save host key for %s: %v\n", hostname, err)
+ slog.Warn("Failed to save host key", "hostname", hostname, "error", err)
}
return nil
diff --git a/backend/pkg/libarcane/startup/runtime_identity.go b/backend/pkg/libarcane/startup/runtime_identity.go
index c5eb1bed9..4866b29cb 100644
--- a/backend/pkg/libarcane/startup/runtime_identity.go
+++ b/backend/pkg/libarcane/startup/runtime_identity.go
@@ -2,7 +2,7 @@ package startup
import (
"context"
- "fmt"
+ "log/slog"
"net/url"
"os"
"path/filepath"
@@ -61,7 +61,7 @@ func ApplyRequestedRuntimeIdentity(ctx context.Context, cfg *RuntimeIdentityConf
inContainer := runningInContainerInternal(os.Getenv, os.Stat)
req, warning, err := loadRuntimeIdentityRequestInternal(cfg, inContainer)
if warning != "" {
- fmt.Fprintf(os.Stderr, "Runtime identity warning: %s\n", warning)
+ slog.WarnContext(ctx, "Runtime identity warning", "warning", warning)
}
if err != nil {
return err
@@ -82,8 +82,8 @@ func ApplyRequestedRuntimeIdentity(ctx context.Context, cfg *RuntimeIdentityConf
}
if os.Geteuid() != 0 {
- fmt.Fprintf(os.Stderr, "Runtime identity warning: process is not root (euid=%d), cannot switch to PUID=%d PGID=%d; continuing as current user\n",
- os.Geteuid(), runtimeUID, runtimeGID)
+ slog.WarnContext(ctx, "Runtime identity warning: process is not root, continuing as current user",
+ "euid", os.Geteuid(), "puid", runtimeUID, "pgid", runtimeGID)
if err := ensureRuntimeDockerConfigInternal(cfg, os.Setenv, runtimeUID, runtimeGID, inContainer); err != nil {
return err
}
diff --git a/backend/pkg/libarcane/ws/benchmark_test.go b/backend/pkg/libarcane/ws/benchmark_test.go
index e7f4fa380..48419ff7b 100644
--- a/backend/pkg/libarcane/ws/benchmark_test.go
+++ b/backend/pkg/libarcane/ws/benchmark_test.go
@@ -35,7 +35,9 @@ func benchWSServer(b *testing.B) (url string, cleanup func()) {
}
}()
<-ctx.Done()
- conn.Close()
+ if err := conn.Close(); err != nil {
+ b.Logf("close websocket connection: %v", err)
+ }
}))
wsURL := "ws" + strings.TrimPrefix(server.URL, "http")
@@ -63,7 +65,9 @@ func benchHub(b *testing.B, numClients int, hubBuf int) (*Hub, context.CancelFun
b.Fatal(err)
}
if resp != nil {
- resp.Body.Close()
+ if err := resp.Body.Close(); err != nil {
+ b.Logf("close dial response body: %v", err)
+ }
}
conns = append(conns, conn)
@@ -85,7 +89,9 @@ func benchHub(b *testing.B, numClients int, hubBuf int) (*Hub, context.CancelFun
return h, cancel, func() {
cancel()
for _, c := range conns {
- c.Close()
+ if err := c.Close(); err != nil {
+ b.Logf("close websocket connection: %v", err)
+ }
}
serverCleanup()
}
@@ -308,7 +314,9 @@ func BenchmarkHub_MemoryPerClient(b *testing.B) {
b.Fatal(err)
}
if resp != nil {
- resp.Body.Close()
+ if err := resp.Body.Close(); err != nil {
+ b.Logf("close dial response body: %v", err)
+ }
}
c := NewClient(conn, sendBuf)
h.register <- c
diff --git a/backend/pkg/libarcane/ws/client_test.go b/backend/pkg/libarcane/ws/client_test.go
index 29b4b944b..f31a6ecee 100644
--- a/backend/pkg/libarcane/ws/client_test.go
+++ b/backend/pkg/libarcane/ws/client_test.go
@@ -47,9 +47,11 @@ func TestServeClient_ReceivesBroadcast(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
- defer clientConn.Close()
+ defer func() {
+ require.NoError(t, clientConn.Close())
+ }()
<-serverReady
@@ -87,7 +89,7 @@ func TestServeClient_ClientDisconnect(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
require.Eventually(t, func() bool {
@@ -95,7 +97,7 @@ func TestServeClient_ClientDisconnect(t *testing.T) {
}, time.Second, 5*time.Millisecond)
// Close the client connection
- clientConn.Close()
+ require.NoError(t, clientConn.Close())
// The hub should eventually remove the client
require.Eventually(t, func() bool {
@@ -124,9 +126,11 @@ func TestServeClient_ContextCancellation(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
- defer clientConn.Close()
+ defer func() {
+ require.NoError(t, clientConn.Close())
+ }()
require.Eventually(t, func() bool {
return h.ClientCount() == 1
@@ -223,9 +227,11 @@ func TestServeClient_MultipleMessages(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
- defer clientConn.Close()
+ defer func() {
+ require.NoError(t, clientConn.Close())
+ }()
<-serverReady
diff --git a/backend/pkg/libarcane/ws/cpu_regression_test.go b/backend/pkg/libarcane/ws/cpu_regression_test.go
index a0d866d95..de0250cc2 100644
--- a/backend/pkg/libarcane/ws/cpu_regression_test.go
+++ b/backend/pkg/libarcane/ws/cpu_regression_test.go
@@ -110,13 +110,13 @@ func BenchmarkCPU_PageReloadSimulation(b *testing.B) {
b.Fatal(err)
}
if resp != nil {
- resp.Body.Close()
+ require.NoError(b, resp.Body.Close())
}
// Read one message to exercise the pipeline
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
_, _, _ = conn.ReadMessage()
- conn.Close()
+ require.NoError(b, conn.Close())
// Brief settle for cleanup
time.Sleep(50 * time.Millisecond)
@@ -203,12 +203,12 @@ func BenchmarkCPU_ContainerLogReloadSimulation(b *testing.B) {
b.Fatal(err)
}
if resp != nil {
- resp.Body.Close()
+ require.NoError(b, resp.Body.Close())
}
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
_, _, _ = conn.ReadMessage()
- conn.Close()
+ require.NoError(b, conn.Close())
time.Sleep(50 * time.Millisecond)
if (i+1)%10 == 0 || i == b.N-1 {
current := runtime.NumGoroutine()
@@ -262,7 +262,7 @@ func BenchmarkCPU_GoroutineScaling(b *testing.B) {
b.Fatal(err)
}
if resp != nil {
- resp.Body.Close()
+ require.NoError(b, resp.Body.Close())
}
conns[j] = conn
}
@@ -274,7 +274,7 @@ func BenchmarkCPU_GoroutineScaling(b *testing.B) {
// Close all
for _, conn := range conns {
- conn.Close()
+ require.NoError(b, conn.Close())
}
time.Sleep(100 * time.Millisecond)
@@ -317,7 +317,7 @@ func BenchmarkCPU_SustainedStreaming(b *testing.B) {
b.Fatal(err)
}
if resp != nil {
- resp.Body.Close()
+ require.NoError(b, resp.Body.Close())
}
for range 10 {
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
@@ -325,7 +325,7 @@ func BenchmarkCPU_SustainedStreaming(b *testing.B) {
break
}
}
- conn.Close()
+ require.NoError(b, conn.Close())
time.Sleep(50 * time.Millisecond)
}
}
@@ -359,11 +359,11 @@ func TestCPU_GoroutineCountReport(t *testing.T) {
conn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
_, _, _ = conn.ReadMessage()
- conn.Close()
+ require.NoError(t, conn.Close())
time.Sleep(50 * time.Millisecond)
current := runtime.NumGoroutine()
if current > peakGoroutines {
diff --git a/backend/pkg/libarcane/ws/goroutine_leak_test.go b/backend/pkg/libarcane/ws/goroutine_leak_test.go
index 857ea33bb..77c95bb33 100644
--- a/backend/pkg/libarcane/ws/goroutine_leak_test.go
+++ b/backend/pkg/libarcane/ws/goroutine_leak_test.go
@@ -146,7 +146,7 @@ func TestLeak_ServeClientFullLifecycle(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
require.Eventually(t, func() bool {
@@ -159,7 +159,7 @@ func TestLeak_ServeClientFullLifecycle(t *testing.T) {
assert.Greater(t, midpoint, baseline, "should have active goroutines while connected")
// Client disconnects (simulates browser close/reload)
- clientConn.Close()
+ require.NoError(t, clientConn.Close())
require.Eventually(t, func() bool {
return h.ClientCount() == 0
@@ -201,7 +201,7 @@ func TestLeak_OnEmptyCallbackCancelsContext(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
require.Eventually(t, func() bool {
@@ -209,7 +209,7 @@ func TestLeak_OnEmptyCallbackCancelsContext(t *testing.T) {
}, time.Second, 5*time.Millisecond)
// Close client -> triggers safeRemove -> hub.remove -> OnEmpty -> cancel()
- clientConn.Close()
+ require.NoError(t, clientConn.Close())
// Hub.Run should exit because OnEmpty called cancel()
actual := waitForGoroutineCount(t, baseline, 3, 5*time.Second)
@@ -246,14 +246,14 @@ func TestLeak_RepeatedConnectDisconnect(t *testing.T) {
conn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err, "iteration %d", i)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
// Brief moment to let registration happen
time.Sleep(10 * time.Millisecond)
// Close (simulates page reload)
- conn.Close()
+ require.NoError(t, conn.Close())
// Brief moment for cleanup
time.Sleep(20 * time.Millisecond)
@@ -321,7 +321,7 @@ func TestLeak_HubWithForwardLinesLifecycle(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
// Read a few messages to confirm the pipeline works
@@ -330,7 +330,7 @@ func TestLeak_HubWithForwardLinesLifecycle(t *testing.T) {
require.NoError(t, err)
// Close client -> OnEmpty -> cancel() -> all goroutines should exit
- clientConn.Close()
+ require.NoError(t, clientConn.Close())
actual := waitForGoroutineCount(t, baseline, 3, 5*time.Second)
assert.LessOrEqual(t, actual, baseline+3,
@@ -401,7 +401,7 @@ func TestLeak_HubWithForwardLogJSONBatchedLifecycle(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
// Read a message to confirm the full pipeline works
@@ -415,7 +415,7 @@ func TestLeak_HubWithForwardLogJSONBatchedLifecycle(t *testing.T) {
assert.NotEmpty(t, batch)
// Disconnect
- clientConn.Close()
+ require.NoError(t, clientConn.Close())
actual := waitForGoroutineCount(t, baseline, 3, 5*time.Second)
assert.LessOrEqual(t, actual, baseline+3,
@@ -523,14 +523,14 @@ func TestLeak_ContainerStatsHubPattern(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
_ = clientConn.SetReadDeadline(time.Now().Add(2 * time.Second))
_, raw, err := clientConn.ReadMessage()
require.NoError(t, err)
var stats map[string]any
require.NoError(t, json.Unmarshal(raw, &stats))
- clientConn.Close()
+ require.NoError(t, clientConn.Close())
actual := waitForGoroutineCount(t, baseline, 3, 5*time.Second)
assert.LessOrEqual(t, actual, baseline+3,
@@ -563,12 +563,12 @@ func TestLeak_RepeatedStatsHubCycles(t *testing.T) {
conn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err, "iteration %d", i)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
_ = conn.SetReadDeadline(time.Now().Add(2 * time.Second))
_, _, _ = conn.ReadMessage()
- conn.Close()
+ require.NoError(t, conn.Close())
time.Sleep(30 * time.Millisecond)
}
@@ -622,7 +622,7 @@ func TestLeak_MultipleClientsOnSameHub(t *testing.T) {
conn, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
clients = append(clients, conn)
}
@@ -633,7 +633,7 @@ func TestLeak_MultipleClientsOnSameHub(t *testing.T) {
// Close all clients
for _, c := range clients {
- c.Close()
+ require.NoError(t, c.Close())
}
// OnEmpty should fire after last client leaves, cancelling context
diff --git a/backend/pkg/libarcane/ws/hub_test.go b/backend/pkg/libarcane/ws/hub_test.go
index d420e32c5..7c2483617 100644
--- a/backend/pkg/libarcane/ws/hub_test.go
+++ b/backend/pkg/libarcane/ws/hub_test.go
@@ -3,7 +3,9 @@ package ws
import (
"bytes"
"context"
+ "errors"
"log/slog"
+ "net"
"net/http"
"net/http/httptest"
"strings"
@@ -35,14 +37,18 @@ func newTestWSPair(t *testing.T) (clientConn *websocket.Conn, serverConn *websoc
cc, resp, err := websocket.DefaultDialer.Dial(url, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
sc := <-serverReady
return cc, sc, func() {
- cc.Close()
- sc.Close()
+ require.NoError(t, cc.Close())
+ // The hub and the forwarders own the server side and may already have
+ // closed it, so only an unexpected failure is worth reporting.
+ if err := sc.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
+ t.Errorf("close server websocket connection: %v", err)
+ }
server.Close()
}
}
diff --git a/backend/pkg/libarcane/ws/proxy_test.go b/backend/pkg/libarcane/ws/proxy_test.go
index a1d27b302..28bf4d8ed 100644
--- a/backend/pkg/libarcane/ws/proxy_test.go
+++ b/backend/pkg/libarcane/ws/proxy_test.go
@@ -20,7 +20,11 @@ func TestProxyHTTP_BidirectionalMessages(t *testing.T) {
if err != nil {
return
}
- defer conn.Close()
+ defer func() {
+ if err := conn.Close(); err != nil {
+ t.Logf("close websocket connection: %v", err)
+ }
+ }()
for {
mt, msg, err := conn.ReadMessage()
@@ -48,9 +52,11 @@ func TestProxyHTTP_BidirectionalMessages(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(proxyURL, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
- defer clientConn.Close()
+ defer func() {
+ require.NoError(t, clientConn.Close())
+ }()
// 4. Send messages and verify they get proxied and echoed
testMessages := []string{"hello", "world", "test123"}
@@ -76,7 +82,9 @@ func TestProxyHTTP_RemoteClose(t *testing.T) {
// Close immediately
_ = conn.WriteMessage(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, "bye"))
- conn.Close()
+ if err := conn.Close(); err != nil {
+ t.Logf("close websocket connection: %v", err)
+ }
}))
defer remoteServer.Close()
@@ -92,9 +100,11 @@ func TestProxyHTTP_RemoteClose(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(proxyURL, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
- defer clientConn.Close()
+ defer func() {
+ require.NoError(t, clientConn.Close())
+ }()
// The proxy should complete (not hang)
select {
@@ -116,9 +126,11 @@ func TestProxyHTTP_InvalidRemoteURL(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(proxyURL, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
- defer clientConn.Close()
+ defer func() {
+ require.NoError(t, clientConn.Close())
+ }()
select {
case err := <-proxyDone:
@@ -136,7 +148,11 @@ func TestProxyHTTP_BinaryMessages(t *testing.T) {
if err != nil {
return
}
- defer conn.Close()
+ defer func() {
+ if err := conn.Close(); err != nil {
+ t.Logf("close websocket connection: %v", err)
+ }
+ }()
for {
mt, msg, err := conn.ReadMessage()
@@ -161,9 +177,11 @@ func TestProxyHTTP_BinaryMessages(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(proxyURL, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
- defer clientConn.Close()
+ defer func() {
+ require.NoError(t, clientConn.Close())
+ }()
binaryData := []byte{0x00, 0x01, 0x02, 0xFF, 0xFE, 0xFD}
err = clientConn.WriteMessage(websocket.BinaryMessage, binaryData)
@@ -185,7 +203,9 @@ func TestProxyHTTP_HeadersForwarded(t *testing.T) {
if err != nil {
return
}
- conn.Close()
+ if err := conn.Close(); err != nil {
+ t.Logf("close websocket connection: %v", err)
+ }
}))
defer remoteServer.Close()
@@ -205,9 +225,11 @@ func TestProxyHTTP_HeadersForwarded(t *testing.T) {
clientConn, resp, err := websocket.DefaultDialer.Dial(proxyURL, nil)
require.NoError(t, err)
if resp != nil {
- resp.Body.Close()
+ require.NoError(t, resp.Body.Close())
}
- defer clientConn.Close()
+ defer func() {
+ require.NoError(t, clientConn.Close())
+ }()
select {
case receivedHeaders := <-headersCh:
diff --git a/backend/pkg/utils/notifications/messages.go b/backend/pkg/utils/notifications/messages.go
index 5fc5b3382..36cca4ca1 100644
--- a/backend/pkg/utils/notifications/messages.go
+++ b/backend/pkg/utils/notifications/messages.go
@@ -71,17 +71,17 @@ func BuildImageUpdateNotificationMessage(format MessageFormat, environmentName,
}
var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "🔔 Container Image Update Notification"))
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Image"), imageRef)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Status"), updateStatus)
+ message.WriteString(fmt.Sprintf("%s\n\n", formatNotificationTitleInternal(format, "🔔 Container Image Update Notification")))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Image"), imageRef))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Status"), updateStatus))
if updateInfo != nil {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Update Type"), updateInfo.UpdateType)
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Update Type"), updateInfo.UpdateType))
if updateInfo.CurrentDigest != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Current Digest"), formatNotificationCodeInternal(format, updateInfo.CurrentDigest))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Current Digest"), formatNotificationCodeInternal(format, updateInfo.CurrentDigest)))
}
if updateInfo.LatestDigest != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Latest Digest"), formatNotificationCodeInternal(format, updateInfo.LatestDigest))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Latest Digest"), formatNotificationCodeInternal(format, updateInfo.LatestDigest)))
}
}
@@ -95,17 +95,17 @@ func BuildContainerUpdateNotificationMessage(format MessageFormat, environmentNa
}
var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "✅ Container Successfully Updated"))
- fmt.Fprintf(&message, "Your container has been updated with the latest image version.\n\n")
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Container"), containerName)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Image"), imageRef)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Status"), status)
+ message.WriteString(fmt.Sprintf("%s\n\n", formatNotificationTitleInternal(format, "✅ Container Successfully Updated")))
+ message.WriteString("Your container has been updated with the latest image version.\n\n")
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Container"), containerName))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Image"), imageRef))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Status"), status))
if oldDigest != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Previous Version"), formatNotificationCodeInternal(format, oldDigest))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Previous Version"), formatNotificationCodeInternal(format, oldDigest)))
}
if newDigest != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Current Version"), formatNotificationCodeInternal(format, newDigest))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Current Version"), formatNotificationCodeInternal(format, newDigest)))
}
return message.String()
@@ -125,32 +125,32 @@ func BuildBatchImageUpdateNotificationMessage(format MessageFormat, environmentN
sort.Strings(imageRefs)
var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n%s\n", formatNotificationTitleInternal(format, title), description)
- fmt.Fprintf(&message, "%s %s\n\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
+ message.WriteString(fmt.Sprintf("%s\n\n%s\n", formatNotificationTitleInternal(format, title), description))
+ message.WriteString(fmt.Sprintf("%s %s\n\n", formatNotificationLabelInternal(format, "Environment"), environmentName))
for _, imageRef := range imageRefs {
update := updates[imageRef]
switch format {
case MessageFormatPlain:
- fmt.Fprintf(&message, "%s\n", imageRef)
- fmt.Fprintf(&message, "• Type: %s\n", update.UpdateType)
- fmt.Fprintf(&message, "• Current: %s\n", update.CurrentDigest)
- fmt.Fprintf(&message, "• Latest: %s\n\n", update.LatestDigest)
+ message.WriteString(fmt.Sprintf("%s\n", imageRef))
+ message.WriteString(fmt.Sprintf("• Type: %s\n", update.UpdateType))
+ message.WriteString(fmt.Sprintf("• Current: %s\n", update.CurrentDigest))
+ message.WriteString(fmt.Sprintf("• Latest: %s\n\n", update.LatestDigest))
case MessageFormatMarkdown:
- fmt.Fprintf(&message, "**%s**\n", imageRef)
- fmt.Fprintf(&message, "• **Type:** %s\n", update.UpdateType)
- fmt.Fprintf(&message, "• **Current:** %s\n", formatNotificationCodeInternal(format, update.CurrentDigest))
- fmt.Fprintf(&message, "• **Latest:** %s\n\n", formatNotificationCodeInternal(format, update.LatestDigest))
+ message.WriteString(fmt.Sprintf("**%s**\n", imageRef))
+ message.WriteString(fmt.Sprintf("• **Type:** %s\n", update.UpdateType))
+ message.WriteString(fmt.Sprintf("• **Current:** %s\n", formatNotificationCodeInternal(format, update.CurrentDigest)))
+ message.WriteString(fmt.Sprintf("• **Latest:** %s\n\n", formatNotificationCodeInternal(format, update.LatestDigest)))
case MessageFormatSlack:
- fmt.Fprintf(&message, "*%s*\n", imageRef)
- fmt.Fprintf(&message, "• *Type:* %s\n", update.UpdateType)
- fmt.Fprintf(&message, "• *Current:* %s\n", formatNotificationCodeInternal(format, update.CurrentDigest))
- fmt.Fprintf(&message, "• *Latest:* %s\n\n", formatNotificationCodeInternal(format, update.LatestDigest))
+ message.WriteString(fmt.Sprintf("*%s*\n", imageRef))
+ message.WriteString(fmt.Sprintf("• *Type:* %s\n", update.UpdateType))
+ message.WriteString(fmt.Sprintf("• *Current:* %s\n", formatNotificationCodeInternal(format, update.CurrentDigest)))
+ message.WriteString(fmt.Sprintf("• *Latest:* %s\n\n", formatNotificationCodeInternal(format, update.LatestDigest)))
case MessageFormatHTML:
- fmt.Fprintf(&message, "<b>%s</b>\n", imageRef)
- fmt.Fprintf(&message, "• <b>Type:</b> %s\n", update.UpdateType)
- fmt.Fprintf(&message, "• <b>Current:</b> %s\n", formatNotificationCodeInternal(format, update.CurrentDigest))
- fmt.Fprintf(&message, "• <b>Latest:</b> %s\n\n", formatNotificationCodeInternal(format, update.LatestDigest))
+ message.WriteString(fmt.Sprintf("<b>%s</b>\n", imageRef))
+ message.WriteString(fmt.Sprintf("• <b>Type:</b> %s\n", update.UpdateType))
+ message.WriteString(fmt.Sprintf("• <b>Current:</b> %s\n", formatNotificationCodeInternal(format, update.CurrentDigest)))
+ message.WriteString(fmt.Sprintf("• <b>Latest:</b> %s\n\n", formatNotificationCodeInternal(format, update.LatestDigest)))
}
}
@@ -159,23 +159,23 @@ func BuildBatchImageUpdateNotificationMessage(format MessageFormat, environmentN
func BuildVulnerabilitySummaryNotificationMessage(format MessageFormat, environmentName, summaryLabel, overview, fixableCount, severityBreakdown, sampleCVEs string) string {
var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "📊 Daily Vulnerability Summary"))
+ message.WriteString(fmt.Sprintf("%s\n\n", formatNotificationTitleInternal(format, "📊 Daily Vulnerability Summary")))
if strings.TrimSpace(summaryLabel) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Summary"), summaryLabel)
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Summary"), summaryLabel))
}
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName))
if strings.TrimSpace(overview) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Overview"), overview)
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Overview"), overview))
}
if strings.TrimSpace(fixableCount) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Fixable Vulnerabilities"), fixableCount)
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Fixable Vulnerabilities"), fixableCount))
}
if strings.TrimSpace(severityBreakdown) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Severity Breakdown"), severityBreakdown)
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Severity Breakdown"), severityBreakdown))
}
if strings.TrimSpace(sampleCVEs) != "" {
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Sample CVEs"), sampleCVEs)
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Sample CVEs"), sampleCVEs))
}
return message.String()
@@ -183,23 +183,23 @@ func BuildVulnerabilitySummaryNotificationMessage(format MessageFormat, environm
func BuildPruneReportNotificationMessage(format MessageFormat, environmentName string, result *system.PruneAllResult) string {
var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "🧹 System Prune Report"))
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
- fmt.Fprintf(&message, "%s %s\n\n", formatNotificationLabelInternal(format, "Total Space Reclaimed"), FormatBytes(result.SpaceReclaimed))
- fmt.Fprintf(&message, "%s\n", formatNotificationLabelInternal(format, "Breakdown"))
- fmt.Fprintf(&message, "- Containers: %s\n", FormatBytes(result.ContainerSpaceReclaimed))
- fmt.Fprintf(&message, "- Images: %s\n", FormatBytes(result.ImageSpaceReclaimed))
- fmt.Fprintf(&message, "- Volumes: %s\n", FormatBytes(result.VolumeSpaceReclaimed))
- fmt.Fprintf(&message, "- Build Cache: %s\n", FormatBytes(result.BuildCacheSpaceReclaimed))
+ message.WriteString(fmt.Sprintf("%s\n\n", formatNotificationTitleInternal(format, "🧹 System Prune Report")))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName))
+ message.WriteString(fmt.Sprintf("%s %s\n\n", formatNotificationLabelInternal(format, "Total Space Reclaimed"), FormatBytes(result.SpaceReclaimed)))
+ message.WriteString(fmt.Sprintf("%s\n", formatNotificationLabelInternal(format, "Breakdown")))
+ message.WriteString(fmt.Sprintf("- Containers: %s\n", FormatBytes(result.ContainerSpaceReclaimed)))
+ message.WriteString(fmt.Sprintf("- Images: %s\n", FormatBytes(result.ImageSpaceReclaimed)))
+ message.WriteString(fmt.Sprintf("- Volumes: %s\n", FormatBytes(result.VolumeSpaceReclaimed)))
+ message.WriteString(fmt.Sprintf("- Build Cache: %s\n", FormatBytes(result.BuildCacheSpaceReclaimed)))
return message.String()
}
func BuildAutoHealNotificationMessage(format MessageFormat, environmentName, containerName string) string {
var message strings.Builder
- fmt.Fprintf(&message, "%s\n\n", formatNotificationTitleInternal(format, "Auto Heal"))
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName)
- fmt.Fprintf(&message, "%s %s\n", formatNotificationLabelInternal(format, "Container"), containerName)
- fmt.Fprintf(&message, "%s Automatically restarted because it was unhealthy.\n", formatNotificationLabelInternal(format, "Status"))
+ message.WriteString(fmt.Sprintf("%s\n\n", formatNotificationTitleInternal(format, "Auto Heal")))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Environment"), environmentName))
+ message.WriteString(fmt.Sprintf("%s %s\n", formatNotificationLabelInternal(format, "Container"), containerName))
+ message.WriteString(fmt.Sprintf("%s Automatically restarted because it was unhealthy.\n", formatNotificationLabelInternal(format, "Status")))
return message.String()
}