-
-
Notifications
You must be signed in to change notification settings - Fork 186
Expand file tree
/
Copy pathsystem.go
More file actions
556 lines (473 loc) · 16.5 KB
/
system.go
File metadata and controls
556 lines (473 loc) · 16.5 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
package handlers
import (
"context"
"errors"
"log/slog"
"net/http"
"strings"
"github.com/danielgtaylor/huma/v2"
"github.com/getarcaneapp/arcane/backend/internal/common"
"github.com/getarcaneapp/arcane/backend/internal/config"
humamw "github.com/getarcaneapp/arcane/backend/internal/huma/middleware"
"github.com/getarcaneapp/arcane/backend/internal/services"
docker "github.com/getarcaneapp/arcane/backend/pkg/dockerutil"
"github.com/getarcaneapp/arcane/types/base"
containertypes "github.com/getarcaneapp/arcane/types/container"
"github.com/getarcaneapp/arcane/types/dockerinfo"
"github.com/getarcaneapp/arcane/types/system"
dockersystem "github.com/moby/moby/api/types/system"
"github.com/moby/moby/client"
)
// SystemHandler handles system management endpoints.
type SystemHandler struct {
dockerService *services.DockerClientService
systemService *services.SystemService
upgradeService *services.SystemUpgradeService
cfg *config.Config
}
// --- Input/Output Types ---
type SystemHealthInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
type SystemHealthOutput struct {
Status int `status:"200"`
}
type GetDockerInfoInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
type GetDockerInfoOutput struct {
Body dockerinfo.Info
}
type PruneAllInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body system.PruneAllRequest `doc:"Prune options"`
}
type PruneAllOutput struct {
Body base.ApiResponse[system.PruneAllResult]
}
type StartAllContainersInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
type StartAllContainersOutput struct {
Body base.ApiResponse[containertypes.ActionResult]
}
type StartAllStoppedContainersInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
type StartAllStoppedContainersOutput struct {
Body base.ApiResponse[containertypes.ActionResult]
}
type StopAllContainersInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
type StopAllContainersOutput struct {
Body base.ApiResponse[containertypes.ActionResult]
}
type ConvertDockerRunInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
Body system.ConvertDockerRunRequest `doc:"Docker run command"`
}
type ConvertDockerRunOutput struct {
Body system.ConvertDockerRunResponse
}
type CheckUpgradeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
// UpgradeCheckResultData is the response for upgrade check.
type UpgradeCheckResultData struct {
CanUpgrade bool `json:"canUpgrade"`
Error bool `json:"error"`
Message string `json:"message"`
}
type CheckUpgradeOutput struct {
Body UpgradeCheckResultData
}
type TriggerUpgradeInput struct {
EnvironmentID string `path:"id" doc:"Environment ID"`
}
type TriggerUpgradeOutput struct {
Body base.ApiResponse[base.MessageResponse]
}
// RegisterSystem registers system management endpoints using Huma.
// Note: WebSocket endpoints (stats) remain in the Gin handler.
func RegisterSystem(api huma.API, dockerService *services.DockerClientService, systemService *services.SystemService, upgradeService *services.SystemUpgradeService, cfg *config.Config) {
h := &SystemHandler{
dockerService: dockerService,
systemService: systemService,
upgradeService: upgradeService,
cfg: cfg,
}
huma.Register(api, huma.Operation{
OperationID: "system-health",
Method: http.MethodHead,
Path: "/environments/{id}/system/health",
Summary: "Check system health",
Description: "Check if the Docker daemon is responsive",
Tags: []string{"System"},
DefaultStatus: http.StatusOK,
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.Health)
huma.Register(api, huma.Operation{
OperationID: "get-docker-info",
Method: http.MethodGet,
Path: "/environments/{id}/system/docker/info",
Summary: "Get Docker info",
Description: "Get Docker daemon version and system information",
Tags: []string{"System"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.GetDockerInfo)
huma.Register(api, huma.Operation{
OperationID: "prune-all",
Method: http.MethodPost,
Path: "/environments/{id}/system/prune",
Summary: "Prune Docker resources",
Description: "Remove unused Docker resources (containers, images, volumes, networks)",
Tags: []string{"System"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.PruneAll)
huma.Register(api, huma.Operation{
OperationID: "start-all-containers",
Method: http.MethodPost,
Path: "/environments/{id}/system/containers/start-all",
Summary: "Start all containers",
Description: "Start all Docker containers",
Tags: []string{"System"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.StartAllContainers)
huma.Register(api, huma.Operation{
OperationID: "start-all-stopped-containers",
Method: http.MethodPost,
Path: "/environments/{id}/system/containers/start-stopped",
Summary: "Start all stopped containers",
Description: "Start all stopped Docker containers",
Tags: []string{"System"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.StartAllStoppedContainers)
huma.Register(api, huma.Operation{
OperationID: "stop-all-containers",
Method: http.MethodPost,
Path: "/environments/{id}/system/containers/stop-all",
Summary: "Stop all containers",
Description: "Stop all running Docker containers",
Tags: []string{"System"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.StopAllContainers)
huma.Register(api, huma.Operation{
OperationID: "convert-docker-run",
Method: http.MethodPost,
Path: "/environments/{id}/system/convert",
Summary: "Convert docker run command",
Description: "Convert a docker run command to docker-compose format",
Tags: []string{"System"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.ConvertDockerRun)
huma.Register(api, huma.Operation{
OperationID: "check-upgrade",
Method: http.MethodGet,
Path: "/environments/{id}/system/upgrade/check",
Summary: "Check for system upgrade",
Description: "Check if a system upgrade is available",
Tags: []string{"System"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.CheckUpgradeAvailable)
huma.Register(api, huma.Operation{
OperationID: "trigger-upgrade",
Method: http.MethodPost,
Path: "/environments/{id}/system/upgrade",
Summary: "Trigger system upgrade",
Description: "Trigger a system upgrade",
DefaultStatus: http.StatusAccepted,
Tags: []string{"System"},
Security: []map[string][]string{
{"BearerAuth": {}},
{"ApiKeyAuth": {}},
},
}, h.TriggerUpgrade)
}
// Health checks if the Docker daemon is responsive.
func (h *SystemHandler) Health(ctx context.Context, input *SystemHealthInput) (*SystemHealthOutput, error) {
if h.dockerService == nil {
return nil, huma.Error503ServiceUnavailable("docker service not available")
}
dockerClient, err := h.dockerService.GetClient(ctx)
if err != nil {
return nil, huma.Error503ServiceUnavailable((&common.DockerConnectionError{Err: err}).Error())
}
_, err = dockerClient.Ping(ctx, client.PingOptions{})
if err != nil {
return nil, huma.Error503ServiceUnavailable((&common.DockerPingError{Err: err}).Error())
}
return &SystemHealthOutput{}, nil
}
// GetDockerInfo returns Docker daemon version and system information.
func (h *SystemHandler) GetDockerInfo(ctx context.Context, input *GetDockerInfoInput) (*GetDockerInfoOutput, error) {
if h.dockerService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
dockerClient, err := h.dockerService.GetClient(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.DockerConnectionError{Err: err}).Error())
}
version, err := dockerClient.ServerVersion(ctx, client.ServerVersionOptions{})
if err != nil {
return nil, huma.Error500InternalServerError((&common.DockerVersionError{Err: err}).Error())
}
infoResult, err := dockerClient.Info(ctx, client.InfoOptions{})
if err != nil {
return nil, huma.Error500InternalServerError((&common.DockerInfoError{Err: err}).Error())
}
info := infoResult.Info
cpuCount := info.NCPU
memTotal := info.MemTotal
// Apply cgroup limits only when running outside Docker (e.g. in LXC).
// In Docker, --cpus/--memory are artificial operator constraints that
// should not cap the host totals shown in the dashboard. The Docker
// daemon's NCPU/MemTotal already reflect the real host. In LXC the
// daemon may report the physical machine's full capacity while the
// LXC guest has a smaller cgroup budget — apply those limits so the
// dashboard shows what Arcane's host actually has available.
if !docker.IsDockerContainer() {
if cgroupLimits, err := docker.DetectCgroupLimits(); err == nil {
if limit := cgroupLimits.MemoryLimit; limit > 0 {
limitInt := int64(limit)
if memTotal == 0 || limitInt < memTotal {
memTotal = limitInt
}
}
if cgroupLimits.CPUCount > 0 && (cpuCount == 0 || cgroupLimits.CPUCount < cpuCount) {
cpuCount = cgroupLimits.CPUCount
}
}
}
info.NCPU = cpuCount
info.MemTotal = memTotal
gitCommit, goVersion, buildTime := extractVersionDetailsFromComponents(version.Components)
return &GetDockerInfoOutput{
Body: dockerinfo.Info{
Success: true,
APIVersion: version.APIVersion,
GitCommit: gitCommit,
GoVersion: goVersion,
Os: version.Os,
Arch: version.Arch,
BuildTime: buildTime,
Info: info,
},
}, nil
}
func extractVersionDetailsFromComponents(components []dockersystem.ComponentVersion) (gitCommit, goVersion, buildTime string) {
for _, component := range components {
if component.Details == nil {
continue
}
for key, value := range component.Details {
switch strings.ToLower(key) {
case "gitcommit":
if gitCommit == "" {
gitCommit = value
}
case "goversion":
if goVersion == "" {
goVersion = value
}
case "buildtime":
if buildTime == "" {
buildTime = value
}
}
}
}
return gitCommit, goVersion, buildTime
}
// PruneAll removes unused Docker resources.
func (h *SystemHandler) PruneAll(ctx context.Context, input *PruneAllInput) (*PruneAllOutput, error) {
if h.systemService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
if err := checkAdmin(ctx); err != nil {
return nil, err
}
slog.InfoContext(ctx, "System prune operation initiated",
"containers", input.Body.Containers,
"images", input.Body.Images,
"volumes", input.Body.Volumes,
"networks", input.Body.Networks,
"build_cache", input.Body.BuildCache)
result, err := h.systemService.PruneAll(ctx, input.Body)
if err != nil {
slog.ErrorContext(ctx, "System prune operation failed", "error", err)
return nil, huma.Error500InternalServerError((&common.SystemPruneError{Err: err}).Error())
}
slog.InfoContext(ctx, "System prune operation completed successfully",
"containers_pruned", len(result.ContainersPruned),
"images_deleted", len(result.ImagesDeleted),
"volumes_deleted", len(result.VolumesDeleted),
"networks_deleted", len(result.NetworksDeleted),
"space_reclaimed", result.SpaceReclaimed)
return &PruneAllOutput{
Body: base.ApiResponse[system.PruneAllResult]{
Success: true,
Data: *result,
},
}, nil
}
// StartAllContainers starts all Docker containers.
func (h *SystemHandler) StartAllContainers(ctx context.Context, input *StartAllContainersInput) (*StartAllContainersOutput, error) {
if h.systemService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
if err := checkAdmin(ctx); err != nil {
return nil, err
}
result, err := h.systemService.StartAllContainers(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStartAllError{Err: err}).Error())
}
return &StartAllContainersOutput{
Body: base.ApiResponse[containertypes.ActionResult]{
Success: true,
Data: *result,
},
}, nil
}
// StartAllStoppedContainers starts all stopped Docker containers.
func (h *SystemHandler) StartAllStoppedContainers(ctx context.Context, input *StartAllStoppedContainersInput) (*StartAllStoppedContainersOutput, error) {
if h.systemService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
if err := checkAdmin(ctx); err != nil {
return nil, err
}
result, err := h.systemService.StartAllStoppedContainers(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStartStoppedError{Err: err}).Error())
}
return &StartAllStoppedContainersOutput{
Body: base.ApiResponse[containertypes.ActionResult]{
Success: true,
Data: *result,
},
}, nil
}
// StopAllContainers stops all running Docker containers.
func (h *SystemHandler) StopAllContainers(ctx context.Context, input *StopAllContainersInput) (*StopAllContainersOutput, error) {
if h.systemService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
if err := checkAdmin(ctx); err != nil {
return nil, err
}
result, err := h.systemService.StopAllContainers(ctx)
if err != nil {
return nil, huma.Error500InternalServerError((&common.ContainerStopAllError{Err: err}).Error())
}
return &StopAllContainersOutput{
Body: base.ApiResponse[containertypes.ActionResult]{
Success: true,
Data: *result,
},
}, nil
}
// ConvertDockerRun converts a docker run command to docker-compose format.
func (h *SystemHandler) ConvertDockerRun(ctx context.Context, input *ConvertDockerRunInput) (*ConvertDockerRunOutput, error) {
if h.systemService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
parsed, err := h.systemService.ParseDockerRunCommand(input.Body.DockerRunCommand)
if err != nil {
return nil, huma.Error400BadRequest((&common.DockerRunParseError{Err: err}).Error())
}
dockerCompose, envVars, serviceName, err := h.systemService.ConvertToDockerCompose(parsed)
if err != nil {
return nil, huma.Error500InternalServerError((&common.DockerComposeConversionError{Err: err}).Error())
}
return &ConvertDockerRunOutput{
Body: system.ConvertDockerRunResponse{
Success: true,
DockerCompose: dockerCompose,
EnvVars: envVars,
ServiceName: serviceName,
},
}, nil
}
// CheckUpgradeAvailable checks if a system upgrade is available.
func (h *SystemHandler) CheckUpgradeAvailable(ctx context.Context, input *CheckUpgradeInput) (*CheckUpgradeOutput, error) {
if h.upgradeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
if err := checkAdmin(ctx); err != nil {
return nil, err
}
canUpgrade, err := h.upgradeService.CanUpgrade(ctx)
if err != nil {
slog.Debug("System upgrade check failed", "error", err)
return &CheckUpgradeOutput{
Body: UpgradeCheckResultData{
CanUpgrade: false,
Error: true,
Message: (&common.UpgradeCheckError{Err: err}).Error(),
},
}, nil
}
return &CheckUpgradeOutput{
Body: UpgradeCheckResultData{
CanUpgrade: canUpgrade,
Error: false,
Message: "System can be upgraded",
},
}, nil
}
// TriggerUpgrade triggers a system upgrade.
func (h *SystemHandler) TriggerUpgrade(ctx context.Context, input *TriggerUpgradeInput) (*TriggerUpgradeOutput, error) {
if h.upgradeService == nil {
return nil, huma.Error500InternalServerError("service not available")
}
if err := checkAdmin(ctx); err != nil {
return nil, err
}
user, exists := humamw.GetCurrentUserFromContext(ctx)
if !exists {
return nil, huma.Error401Unauthorized((&common.NotAuthenticatedError{}).Error())
}
slog.Info("System upgrade triggered", "user", user.Username, "userId", user.ID)
err := h.upgradeService.TriggerUpgradeViaCLI(ctx, *user)
if err != nil {
slog.Error("System upgrade failed", "error", err, "user", user.Username)
if errors.Is(err, services.ErrUpgradeInProgress) {
return nil, huma.Error409Conflict((&common.UpgradeTriggerError{Err: err}).Error())
}
return nil, huma.Error500InternalServerError((&common.UpgradeTriggerError{Err: err}).Error())
}
return &TriggerUpgradeOutput{
Body: base.ApiResponse[base.MessageResponse]{
Success: true,
Data: base.MessageResponse{
Message: "Upgrade initiated successfully. A new container is being created and will replace this one shortly.",
},
},
}, nil
}