-
-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathws_handler.go
More file actions
1876 lines (1641 loc) · 56.2 KB
/
ws_handler.go
File metadata and controls
1876 lines (1641 loc) · 56.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package api
import (
"bytes"
"context"
"encoding/csv"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/config"
"github.com/getarcaneapp/arcane/backend/internal/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"
ws "github.com/getarcaneapp/arcane/backend/pkg/libarcane/ws"
httputil "github.com/getarcaneapp/arcane/backend/pkg/utils/httpx"
systemtypes "github.com/getarcaneapp/arcane/types/system"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/shirou/gopsutil/v4/cpu"
"github.com/shirou/gopsutil/v4/disk"
"github.com/shirou/gopsutil/v4/host"
"github.com/shirou/gopsutil/v4/mem"
)
const (
gpuCacheDuration = 30 * time.Second
cgroupCacheTTL = 30 * time.Second
)
// amdGPUSysfsPath is the base path for AMD GPU sysfs entries
const amdGPUSysfsPath = "/sys/class/drm"
// ============================================================================
// WebSocket Metrics
// ============================================================================
// WebSocketMetrics tracks active WebSocket connections and their counts.
type WebSocketMetrics struct {
projectLogsActive atomic.Int64
containerLogsActive atomic.Int64
containerStats atomic.Int64
containerExec atomic.Int64
systemStats atomic.Int64
serviceLogsActive atomic.Int64
seq atomic.Uint64
mu sync.RWMutex
connections map[string]systemtypes.WebSocketConnectionInfo
}
// NewWebSocketMetrics creates a new WebSocketMetrics instance.
func NewWebSocketMetrics() *WebSocketMetrics {
return &WebSocketMetrics{
connections: make(map[string]systemtypes.WebSocketConnectionInfo),
}
}
// Snapshot returns a point-in-time copy of the active connection counts.
func (m *WebSocketMetrics) Snapshot() systemtypes.WebSocketMetricsSnapshot {
return systemtypes.WebSocketMetricsSnapshot{
ProjectLogsActive: m.projectLogsActive.Load(),
ContainerLogsActive: m.containerLogsActive.Load(),
ContainerStats: m.containerStats.Load(),
ContainerExec: m.containerExec.Load(),
SystemStats: m.systemStats.Load(),
ServiceLogsActive: m.serviceLogsActive.Load(),
}
}
// Connections returns a snapshot of all tracked WebSocket connections.
func (m *WebSocketMetrics) Connections() []systemtypes.WebSocketConnectionInfo {
m.mu.RLock()
defer m.mu.RUnlock()
result := make([]systemtypes.WebSocketConnectionInfo, 0, len(m.connections))
for _, info := range m.connections {
result = append(result, info)
}
return result
}
// RegisterConnection adds a connection to the tracker and increments the
// appropriate kind counter. Returns the assigned connection ID.
func (m *WebSocketMetrics) RegisterConnection(info systemtypes.WebSocketConnectionInfo) string {
if info.ID == "" {
info.ID = "ws-" + strconv.FormatUint(m.seq.Add(1), 10)
}
if info.StartedAt.IsZero() {
info.StartedAt = time.Now().UTC()
}
m.mu.Lock()
m.connections[info.ID] = info
m.mu.Unlock()
m.applyDelta(info.Kind, 1)
return info.ID
}
// UnregisterConnection removes a connection from the tracker and decrements
// the appropriate kind counter.
func (m *WebSocketMetrics) UnregisterConnection(id string) {
if id == "" {
return
}
var info systemtypes.WebSocketConnectionInfo
m.mu.Lock()
if existing, ok := m.connections[id]; ok {
info = existing
delete(m.connections, id)
}
m.mu.Unlock()
if info.Kind != "" {
m.applyDelta(info.Kind, -1)
}
}
func (m *WebSocketMetrics) applyDelta(kind string, delta int64) {
switch kind {
case systemtypes.WSKindProjectLogs:
m.projectLogsActive.Add(delta)
case systemtypes.WSKindContainerLogs:
m.containerLogsActive.Add(delta)
case systemtypes.WSKindContainerStats:
m.containerStats.Add(delta)
case systemtypes.WSKindContainerExec:
m.containerExec.Add(delta)
case systemtypes.WSKindSystemStats:
m.systemStats.Add(delta)
case systemtypes.WSKindServiceLogs:
m.serviceLogsActive.Add(delta)
}
}
var defaultWebSocketMetrics = NewWebSocketMetrics()
// DefaultWebSocketMetrics returns the package-level WebSocketMetrics singleton.
func DefaultWebSocketMetrics() *WebSocketMetrics {
return defaultWebSocketMetrics
}
// ============================================================================
// WebSocket Handler
// ============================================================================
// WebSocketHandler consolidates all WebSocket and streaming endpoints.
// REST endpoints are handled by Huma handlers.
type WebSocketHandler struct {
projectService *services.ProjectService
containerService *services.ContainerService
swarmService *services.SwarmService
systemService *services.SystemService
wsUpgrader websocket.Upgrader
wsMetrics *WebSocketMetrics
activeConnections sync.Map
logStreamsMu sync.Mutex
logStreams map[string]*wsLogStream
cpuCache struct {
sync.RWMutex
value float64
timestamp time.Time
}
systemStaticInfo struct {
once sync.Once
cpuCount int
hostname string
}
systemStatsSampler struct {
stateMu sync.RWMutex
latest systemtypes.SystemStats
timestamp time.Time
lifecycleMu sync.Mutex
clients int
cancel context.CancelFunc
ready chan struct{}
running bool
}
cgroupCache struct {
sync.RWMutex
value *docker.CgroupLimits
detected bool
timestamp time.Time
}
diskUsagePathCache struct {
sync.RWMutex
value string
timestamp time.Time
}
gpuDetectionCache struct {
sync.RWMutex
detected bool
timestamp time.Time
gpuType string
toolPath string
}
detectionDone bool
detectionMutex sync.Mutex
gpuMonitoringEnabled bool
gpuType string
projectLogStreamer func(ctx context.Context, projectID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error
containerLogStreamer func(ctx context.Context, containerID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error
systemStatsCollector func(ctx context.Context) systemtypes.SystemStats
cpuUsageReader func(interval time.Duration) (float64, bool)
cgroupLimitsDetector func() (*docker.CgroupLimits, error)
}
type wsLogStream struct {
hub *ws.Hub
cancel context.CancelFunc
firstSubscriber chan struct{}
format string
key string
refs int
done bool
seq atomic.Uint64
}
func getContextUserIDInternal(c *gin.Context) string {
if val, ok := c.Get("userID"); ok {
if userID, ok := val.(string); ok {
return userID
}
}
return ""
}
func buildWSConnectionInfoInternal(c *gin.Context, kind, resourceID string) systemtypes.WebSocketConnectionInfo {
return systemtypes.WebSocketConnectionInfo{
Kind: kind,
EnvID: c.Param("id"),
ResourceID: resourceID,
ClientIP: c.ClientIP(),
UserID: getContextUserIDInternal(c),
UserAgent: c.GetHeader("User-Agent"),
}
}
func buildLogStreamKeyInternal(envID, kind, resourceID, format string, batched, follow bool, tail, since string, timestamps bool) string {
return strings.Join([]string{
envID,
kind,
resourceID,
format,
strconv.FormatBool(batched),
strconv.FormatBool(follow),
tail,
since,
strconv.FormatBool(timestamps),
}, "|")
}
func (h *WebSocketHandler) streamProjectLogsInternal(ctx context.Context, projectID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error {
if h.projectLogStreamer != nil {
return h.projectLogStreamer(ctx, projectID, logsChan, follow, tail, since, timestamps)
}
return h.projectService.StreamProjectLogs(ctx, projectID, logsChan, follow, tail, since, timestamps)
}
func (h *WebSocketHandler) streamContainerLogsInternal(ctx context.Context, containerID string, logsChan chan<- string, follow bool, tail, since string, timestamps bool) error {
if h.containerLogStreamer != nil {
return h.containerLogStreamer(ctx, containerID, logsChan, follow, tail, since, timestamps)
}
return h.containerService.StreamLogs(ctx, containerID, logsChan, follow, tail, since, timestamps)
}
func (h *WebSocketHandler) getOrCreateLogStreamInternal(key string, create func(onEmpty func(*wsLogStream)) *wsLogStream) *wsLogStream {
h.logStreamsMu.Lock()
defer h.logStreamsMu.Unlock()
if stream, ok := h.logStreams[key]; ok {
if !stream.done {
stream.refs++
return stream
}
}
stream := create(func(stream *wsLogStream) {
h.markLogStreamDoneInternal(key, stream)
})
stream.key = key
stream.refs = 1
h.logStreams[key] = stream
return stream
}
func takeLogStreamCancelInternal(stream *wsLogStream) context.CancelFunc {
cancel := stream.cancel
stream.cancel = nil
return cancel
}
func (h *WebSocketHandler) releaseLogStreamInternal(key string, stream *wsLogStream) {
var cancel context.CancelFunc
h.logStreamsMu.Lock()
if stream.refs > 0 {
stream.refs--
}
if stream.refs == 0 {
if current, ok := h.logStreams[key]; ok && current == stream {
delete(h.logStreams, key)
}
cancel = takeLogStreamCancelInternal(stream)
}
h.logStreamsMu.Unlock()
if cancel != nil {
cancel()
}
}
func (h *WebSocketHandler) markLogStreamDoneInternal(key string, stream *wsLogStream) {
var cancel context.CancelFunc
h.logStreamsMu.Lock()
stream.done = true
if stream.refs == 0 {
if current, ok := h.logStreams[key]; ok && current == stream {
delete(h.logStreams, key)
}
cancel = takeLogStreamCancelInternal(stream)
}
h.logStreamsMu.Unlock()
if cancel != nil {
cancel()
}
}
func NewWebSocketHandler(
group *gin.RouterGroup,
projectService *services.ProjectService,
containerService *services.ContainerService,
swarmService *services.SwarmService,
systemService *services.SystemService,
authMiddleware *middleware.AuthMiddleware,
cfg *config.Config,
) {
handler := &WebSocketHandler{
projectService: projectService,
containerService: containerService,
swarmService: swarmService,
systemService: systemService,
wsMetrics: defaultWebSocketMetrics,
logStreams: make(map[string]*wsLogStream),
gpuMonitoringEnabled: cfg.GPUMonitoringEnabled,
gpuType: cfg.GPUType,
wsUpgrader: websocket.Upgrader{
CheckOrigin: httputil.ValidateWebSocketOrigin(cfg.GetAppURL()),
ReadBufferSize: 32 * 1024,
WriteBufferSize: 32 * 1024,
EnableCompression: true,
},
}
wsGroup := group.Group("/environments/:id/ws")
wsGroup.Use(authMiddleware.WithAdminNotRequired().Add())
{
wsGroup.GET("/projects/:projectId/logs", handler.ProjectLogs)
wsGroup.GET("/containers/:containerId/logs", handler.ContainerLogs)
wsGroup.GET("/containers/:containerId/stats", handler.ContainerStats)
wsGroup.GET("/containers/:containerId/terminal", handler.ContainerExec)
wsGroup.GET("/swarm/services/:serviceId/logs", handler.ServiceLogs)
wsGroup.GET("/system/stats", handler.SystemStats)
}
}
// ============================================================================
// Project WebSocket/Streaming Endpoints
// ============================================================================
// ProjectLogs streams project logs over WebSocket.
//
// @Summary Get project logs via WebSocket
// @Description Stream project logs over WebSocket connection
// @Tags WebSocket
// @Param id path string true "Environment ID"
// @Param projectId path string true "Project ID"
// @Param follow query bool false "Follow log output" default(true)
// @Param tail query string false "Number of lines to show from the end" default(100)
// @Param since query string false "Show logs since timestamp"
// @Param timestamps query bool false "Show timestamps" default(false)
// @Param format query string false "Output format (text or json)" default(text)
// @Param batched query bool false "Batch log messages" default(false)
// @Router /api/environments/{id}/ws/projects/{projectId}/logs [get]
func (h *WebSocketHandler) ProjectLogs(c *gin.Context) {
projectID := c.Param("projectId")
if strings.TrimSpace(projectID) == "" {
c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ProjectIDRequiredError{}).Error()})
return
}
follow := c.DefaultQuery("follow", "true") == "true"
tail, _ := httputil.GetQueryParam(c, "tail", false)
if tail == "" {
tail = "100"
}
since, _ := httputil.GetQueryParam(c, "since", false)
timestamps := c.DefaultQuery("timestamps", "false") == "true"
format, _ := httputil.GetQueryParam(c, "format", false)
if format == "" {
format = "text"
}
batched := c.DefaultQuery("batched", "false") == "true"
conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
streamKey := buildLogStreamKeyInternal(c.Param("id"), systemtypes.WSKindProjectLogs, projectID, format, batched, follow, tail, since, timestamps)
stream := h.getOrCreateLogStreamInternal(streamKey, func(onEmpty func(*wsLogStream)) *wsLogStream {
return h.startProjectLogHub(streamKey, projectID, format, batched, follow, tail, since, timestamps, onEmpty)
})
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindProjectLogs, projectID))
// WebSocket connections use context.Background() because they are long-lived and should not
// be tied to the HTTP request context. Cleanup is handled via the hub's OnEmpty callback
// which triggers when all clients disconnect.
ws.ServeClientWithOnRemove(context.Background(), stream.hub, conn, func() {
h.wsMetrics.UnregisterConnection(connID)
h.releaseLogStreamInternal(streamKey, stream)
})
}
func newWSLogStreamInternal(key, format string) (*wsLogStream, context.Context) {
ls := &wsLogStream{
hub: ws.NewHub(1024),
firstSubscriber: make(chan struct{}),
format: format,
key: key,
}
ls.hub.SetOnFirstClient(func() {
close(ls.firstSubscriber)
})
ctx, cancel := context.WithCancel(context.Background()) //nolint:gosec // cancel is intentionally retained and invoked by the hub OnEmpty callback.
ls.cancel = cancel
go ls.hub.Run(ctx)
return ls, ctx
}
func (h *WebSocketHandler) startProjectLogSourceInternal(ctx context.Context, key, projectID, format string, follow bool, tail, since string, timestamps bool, ls *wsLogStream) <-chan string {
lines := make(chan string, 256)
go func() {
defer close(lines)
if !waitForLogStreamSubscriberInternal(ctx, ls.firstSubscriber) {
return
}
if err := h.streamProjectLogsInternal(ctx, projectID, lines, follow, tail, since, timestamps); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return
}
h.broadcastProjectLogStreamErrorInternal(projectID, format, err, ls)
h.markLogStreamDoneInternal(key, ls)
return
}
if ctx.Err() == nil {
h.markLogStreamDoneInternal(key, ls)
}
}()
return lines
}
func waitForLogStreamSubscriberInternal(ctx context.Context, firstSubscriber <-chan struct{}) bool {
for {
select {
case <-ctx.Done():
return false
case <-firstSubscriber:
return true
}
}
}
func (h *WebSocketHandler) broadcastProjectLogStreamErrorInternal(projectID, format string, err error, ls *wsLogStream) {
slog.Warn("project log stream failed", "projectID", projectID, "error", err)
if format == "json" {
msg := ws.LogMessage{
Seq: ls.seq.Add(1),
Level: "error",
Message: "Failed to stream project logs: " + err.Error(),
Service: "arcane",
Timestamp: ws.NowRFC3339(),
}
if b, marshalErr := json.Marshal(msg); marshalErr == nil {
ls.hub.Broadcast(b)
}
return
}
ls.hub.Broadcast([]byte("Failed to stream project logs: " + err.Error()))
}
func startProjectLogForwardersInternal(ctx context.Context, format string, batched bool, lines <-chan string, ls *wsLogStream) {
if format == "json" {
startProjectJSONForwarderInternal(ctx, batched, lines, ls)
return
}
startProjectTextForwarderInternal(ctx, lines, ls)
}
func startProjectJSONForwarderInternal(ctx context.Context, batched bool, lines <-chan string, ls *wsLogStream) {
msgs := make(chan ws.LogMessage, 256)
go func() {
defer close(msgs)
for line := range lines {
level, service, msg, ts := ws.NormalizeProjectLine(line)
seq := ls.seq.Add(1)
timestamp := ts
if timestamp == "" {
timestamp = ws.NowRFC3339()
}
msgs <- ws.LogMessage{
Seq: seq,
Level: level,
Message: msg,
Service: service,
Timestamp: timestamp,
}
}
}()
if batched {
go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
return
}
go ws.ForwardLogJSON(ctx, ls.hub, msgs)
}
func startProjectTextForwarderInternal(ctx context.Context, lines <-chan string, ls *wsLogStream) {
cleanChan := make(chan string, 256)
go func() {
defer close(cleanChan)
for line := range lines {
_, _, msg, _ := ws.NormalizeProjectLine(line)
cleanChan <- msg
}
}()
go ws.ForwardLines(ctx, ls.hub, cleanChan)
}
func (h *WebSocketHandler) startProjectLogHub(key, projectID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {
ls, ctx := newWSLogStreamInternal(key, format)
ls.hub.SetOnEmpty(func() {
if onEmptyHook != nil {
onEmptyHook(ls)
}
slog.Debug("client disconnected, cleaning up project log hub", "projectID", projectID)
})
lines := h.startProjectLogSourceInternal(ctx, key, projectID, format, follow, tail, since, timestamps, ls)
startProjectLogForwardersInternal(ctx, format, batched, lines, ls)
return ls
}
// ============================================================================
// Container WebSocket Endpoints
// ============================================================================
// ContainerLogs streams container logs over WebSocket.
//
// @Summary Get container logs via WebSocket
// @Description Stream container logs over WebSocket connection
// @Tags WebSocket
// @Param id path string true "Environment ID"
// @Param containerId path string true "Container ID"
// @Param follow query bool false "Follow log output" default(true)
// @Param tail query string false "Number of lines to show from the end" default(100)
// @Param since query string false "Show logs since timestamp"
// @Param timestamps query bool false "Show timestamps" default(false)
// @Param format query string false "Output format (text or json)" default(text)
// @Param batched query bool false "Batch log messages" default(false)
// @Router /api/environments/{id}/ws/containers/{containerId}/logs [get]
func (h *WebSocketHandler) ContainerLogs(c *gin.Context) {
containerID := c.Param("containerId")
if strings.TrimSpace(containerID) == "" {
c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
return
}
follow := c.DefaultQuery("follow", "true") == "true"
tail, _ := httputil.GetQueryParam(c, "tail", false)
if tail == "" {
tail = "100"
}
since, _ := httputil.GetQueryParam(c, "since", false)
timestamps := c.DefaultQuery("timestamps", "false") == "true"
format, _ := httputil.GetQueryParam(c, "format", false)
if format == "" {
format = "text"
}
batched := c.DefaultQuery("batched", "false") == "true"
conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
streamKey := buildLogStreamKeyInternal(c.Param("id"), systemtypes.WSKindContainerLogs, containerID, format, batched, follow, tail, since, timestamps)
stream := h.getOrCreateLogStreamInternal(streamKey, func(onEmpty func(*wsLogStream)) *wsLogStream {
return h.startContainerLogHub(streamKey, containerID, format, batched, follow, tail, since, timestamps, onEmpty)
})
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindContainerLogs, containerID))
// WebSocket connections use context.Background() because they are long-lived and should not
// be tied to the HTTP request context. Cleanup is handled via the hub's OnEmpty callback
// which triggers when all clients disconnect.
ws.ServeClientWithOnRemove(context.Background(), stream.hub, conn, func() {
h.wsMetrics.UnregisterConnection(connID)
h.releaseLogStreamInternal(streamKey, stream)
})
}
func (h *WebSocketHandler) startContainerLogHub(key, containerID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {
ls, ctx := newWSLogStreamInternal(key, format)
ls.hub.SetOnEmpty(func() {
if onEmptyHook != nil {
onEmptyHook(ls)
}
slog.Debug("client disconnected, cleaning up container log hub", "containerID", containerID)
})
lines := make(chan string, 256)
go func(ctx context.Context) {
defer close(lines)
if !waitForLogStreamSubscriberInternal(ctx, ls.firstSubscriber) {
return
}
if err := h.streamContainerLogsInternal(ctx, containerID, lines, follow, tail, since, timestamps); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return
}
h.broadcastContainerLogStreamErrorInternal(containerID, format, err, ls)
h.markLogStreamDoneInternal(key, ls)
return
}
if ctx.Err() == nil {
h.markLogStreamDoneInternal(key, ls)
}
}(ctx)
if format == "json" {
msgs := make(chan ws.LogMessage, 256)
go func() {
defer close(msgs)
for line := range lines {
level, msg, ts := ws.NormalizeContainerLine(line)
seq := ls.seq.Add(1)
timestamp := ts
if timestamp == "" {
timestamp = ws.NowRFC3339()
}
msgs <- ws.LogMessage{
Seq: seq,
Level: level,
Message: msg,
Timestamp: timestamp,
}
}
}()
if batched {
go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
} else {
go ws.ForwardLogJSON(ctx, ls.hub, msgs)
}
} else {
go ws.ForwardLines(ctx, ls.hub, lines)
}
return ls
}
func (h *WebSocketHandler) broadcastContainerLogStreamErrorInternal(containerID, format string, err error, ls *wsLogStream) {
slog.Warn("container log stream failed", "containerID", containerID, "error", err)
if format == "json" {
msg := ws.LogMessage{
Seq: ls.seq.Add(1),
Level: "error",
Message: "Failed to stream container logs: " + err.Error(),
Service: "arcane",
Timestamp: ws.NowRFC3339(),
}
if b, marshalErr := json.Marshal(msg); marshalErr == nil {
ls.hub.Broadcast(b)
}
return
}
ls.hub.Broadcast([]byte("Failed to stream container logs: " + err.Error()))
}
// ============================================================================
// Swarm Service WebSocket/Streaming Endpoints
// ============================================================================
// ServiceLogs streams swarm service logs over WebSocket.
//
// @Summary Get swarm service logs via WebSocket
// @Description Stream swarm service logs over WebSocket connection
// @Tags WebSocket
// @Param id path string true "Environment ID"
// @Param serviceId path string true "Service ID"
// @Param follow query bool false "Follow log output" default(true)
// @Param tail query string false "Number of lines to show from the end" default(100)
// @Param since query string false "Show logs since timestamp"
// @Param timestamps query bool false "Show timestamps" default(false)
// @Param format query string false "Output format (text or json)" default(text)
// @Param batched query bool false "Batch log messages" default(false)
// @Router /api/environments/{id}/ws/swarm/services/{serviceId}/logs [get]
func (h *WebSocketHandler) ServiceLogs(c *gin.Context) {
environmentID := c.Param("id")
serviceID := c.Param("serviceId")
if strings.TrimSpace(serviceID) == "" {
c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": "Service ID is required"})
return
}
follow := c.DefaultQuery("follow", "true") == "true"
tail, _ := httputil.GetQueryParam(c, "tail", false)
if tail == "" {
tail = "100"
}
since, _ := httputil.GetQueryParam(c, "since", false)
timestamps := c.DefaultQuery("timestamps", "false") == "true"
format, _ := httputil.GetQueryParam(c, "format", false)
if format == "" {
format = "text"
}
batched := c.DefaultQuery("batched", "false") == "true"
conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
streamKey := buildLogStreamKeyInternal(environmentID, systemtypes.WSKindServiceLogs, serviceID, format, batched, follow, tail, since, timestamps)
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindServiceLogs, serviceID))
stream := h.getOrCreateLogStreamInternal(streamKey, func(onEmpty func(*wsLogStream)) *wsLogStream {
return h.startServiceLogHub(streamKey, serviceID, format, batched, follow, tail, since, timestamps, onEmpty)
})
// WebSocket connections use context.Background() because they are long-lived and should not
// be tied to the HTTP request context. Cleanup is handled via the hub's OnEmpty callback
// which triggers when all clients disconnect.
ws.ServeClientWithOnRemove(context.Background(), stream.hub, conn, func() {
h.wsMetrics.UnregisterConnection(connID)
h.releaseLogStreamInternal(streamKey, stream)
})
}
func (h *WebSocketHandler) startServiceLogHub(key, serviceID, format string, batched, follow bool, tail, since string, timestamps bool, onEmptyHook func(*wsLogStream)) *wsLogStream {
ls, ctx := newWSLogStreamInternal(key, format)
ls.hub.SetOnEmpty(func() {
if onEmptyHook != nil {
onEmptyHook(ls)
}
slog.Debug("client disconnected, cleaning up service log hub", "serviceID", serviceID)
})
lines := make(chan string, 256)
go func() {
defer close(lines)
if !waitForLogStreamSubscriberInternal(ctx, ls.firstSubscriber) {
return
}
if err := h.swarmService.StreamServiceLogs(ctx, serviceID, lines, follow, tail, since, timestamps); err != nil {
if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {
return
}
h.broadcastServiceLogStreamErrorInternal(serviceID, format, err, ls)
h.markLogStreamDoneInternal(key, ls)
return
}
if ctx.Err() == nil {
h.markLogStreamDoneInternal(key, ls)
}
}()
if format == "json" {
msgs := make(chan ws.LogMessage, 256)
go func() {
defer close(msgs)
for line := range lines {
level, msg, ts := ws.NormalizeContainerLine(line)
seq := ls.seq.Add(1)
timestamp := ts
if timestamp == "" {
timestamp = ws.NowRFC3339()
}
msgs <- ws.LogMessage{
Seq: seq,
Level: level,
Message: msg,
Timestamp: timestamp,
}
}
}()
if batched {
go ws.ForwardLogJSONBatched(ctx, ls.hub, msgs, 50, 400*time.Millisecond)
} else {
go ws.ForwardLogJSON(ctx, ls.hub, msgs)
}
} else {
go ws.ForwardLines(ctx, ls.hub, lines)
}
return ls
}
func (h *WebSocketHandler) broadcastServiceLogStreamErrorInternal(serviceID, format string, err error, ls *wsLogStream) {
slog.Warn("service log stream failed", "serviceID", serviceID, "error", err)
if format == "json" {
msg := ws.LogMessage{
Seq: ls.seq.Add(1),
Level: "error",
Message: "Failed to stream service logs: " + err.Error(),
Service: "arcane",
Timestamp: ws.NowRFC3339(),
}
if b, marshalErr := json.Marshal(msg); marshalErr == nil {
ls.hub.Broadcast(b)
}
return
}
ls.hub.Broadcast([]byte("Failed to stream service logs: " + err.Error()))
}
// ContainerStats streams container stats over WebSocket.
//
// @Summary Get container stats via WebSocket
// @Description Stream container resource statistics over WebSocket connection
// @Tags WebSocket
// @Param id path string true "Environment ID"
// @Param containerId path string true "Container ID"
// @Router /api/environments/{id}/ws/containers/{containerId}/stats [get]
func (h *WebSocketHandler) ContainerStats(c *gin.Context) {
containerID := c.Param("containerId")
if strings.TrimSpace(containerID) == "" {
c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
return
}
conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindContainerStats, containerID))
hub := h.startContainerStatsHub(containerID, func() {
h.wsMetrics.UnregisterConnection(connID)
})
// WebSocket connections use context.Background() because they are long-lived and should not
// be tied to the HTTP request context. Cleanup is handled via the hub's OnEmpty callback
// which triggers when all clients disconnect.
ws.ServeClient(context.Background(), hub, conn)
}
func (h *WebSocketHandler) startContainerStatsHub(containerID string, onEmptyHook func()) *ws.Hub {
hub := ws.NewHub(64)
ctx, cancel := context.WithCancel(context.Background()) //nolint:gosec // cancel is intentionally retained and invoked by the hub OnEmpty callback.
hub.SetOnEmpty(func() {
if onEmptyHook != nil {
onEmptyHook()
}
slog.Debug("client disconnected, cleaning up container stats hub", "containerID", containerID)
cancel()
})
go hub.Run(ctx)
statsChan := make(chan any, 64)
go func(ctx context.Context) {
defer close(statsChan)
_ = h.containerService.StreamStats(ctx, containerID, statsChan)
}(ctx)
go func() {
for {
select {
case <-ctx.Done():
return
case stats, ok := <-statsChan:
if !ok {
return
}
if b, err := json.Marshal(stats); err == nil {
hub.Broadcast(b)
}
}
}
}()
return hub
}
// ContainerExec provides interactive terminal access to a container.
//
// @Summary Execute command in container via WebSocket
// @Description Interactive terminal access to a container over WebSocket
// @Tags WebSocket
// @Param id path string true "Environment ID"
// @Param containerId path string true "Container ID"
// @Param shell query string false "Shell to execute" default(/bin/sh)
// @Router /api/environments/{id}/ws/containers/{containerId}/terminal [get]
func (h *WebSocketHandler) ContainerExec(c *gin.Context) {
containerID := c.Param("containerId")
if strings.TrimSpace(containerID) == "" {
c.JSON(http.StatusBadRequest, gin.H{"success": false, "error": (&common.ContainerIDRequiredError{}).Error()})
return
}
shell := c.DefaultQuery("shell", "/bin/sh")
conn, err := h.wsUpgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
return
}
connID := h.wsMetrics.RegisterConnection(buildWSConnectionInfoInternal(c, systemtypes.WSKindContainerExec, containerID))
defer h.wsMetrics.UnregisterConnection(connID)
defer func() {
if err := conn.Close(); err != nil {
slog.Debug("Failed to close container exec websocket connection", "containerID", containerID, "error", err)
}
}()
ctx, cancel := context.WithCancel(c.Request.Context())
defer cancel()
h.runContainerExecInternal(ctx, cancel, conn, containerID, shell)
}
func (h *WebSocketHandler) runContainerExecInternal(ctx context.Context, cancel context.CancelFunc, conn *websocket.Conn, containerID, shell string) {
// Create exec instance
execID, err := h.containerService.CreateExec(ctx, containerID, []string{shell})
if err != nil {
h.writeExecErrorInternal(conn, &common.ExecCreationError{Err: err})
return
}
// Attach to exec
execSession, err := h.containerService.AttachExec(ctx, containerID, execID)
if err != nil {
h.writeExecErrorInternal(conn, &common.ExecAttachError{Err: err})
return
}
cleanup := h.execCleanupFuncInternal(ctx, execSession, execID, containerID)
defer cleanup()
h.watchExecContextInternal(ctx, execID, containerID, cleanup)
done := make(chan struct{})
go h.pipeExecOutputInternal(ctx, conn, execSession.Stdout(), execID, containerID, done)
go h.pipeExecInputInternal(ctx, cancel, conn, execSession.Stdin(), execID, containerID)
<-done
}
func (h *WebSocketHandler) writeExecErrorInternal(conn *websocket.Conn, err error) {
_ = conn.WriteMessage(websocket.TextMessage, []byte(err.Error()+"\r\n"))
}
func (h *WebSocketHandler) execCleanupFuncInternal(ctx context.Context, execSession *services.ExecSession, execID, containerID string) func() {
return func() {
slog.Debug("Cleaning up exec session", "execID", execID, "containerID", containerID, "contextErr", ctx.Err())
// Cleanup must proceed even if parent ctx is canceled.
cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 5*time.Second) //nolint:contextcheck
defer cleanupCancel()
if err := execSession.Close(cleanupCtx); err != nil { //nolint:contextcheck
slog.Warn("Failed to clean up exec session", "execID", execID, "error", err)