-
Notifications
You must be signed in to change notification settings - Fork 22
/
docker.go
870 lines (729 loc) · 28.4 KB
/
docker.go
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
package v1
import (
"context"
"net/http"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/IceWhaleTech/CasaOS-AppManagement/common"
"github.com/IceWhaleTech/CasaOS-AppManagement/model"
"github.com/IceWhaleTech/CasaOS-AppManagement/pkg/config"
"github.com/IceWhaleTech/CasaOS-AppManagement/service"
v1 "github.com/IceWhaleTech/CasaOS-AppManagement/service/v1"
modelCommon "github.com/IceWhaleTech/CasaOS-Common/model"
"github.com/IceWhaleTech/CasaOS-Common/utils/common_err"
"github.com/IceWhaleTech/CasaOS-Common/utils/file"
"github.com/IceWhaleTech/CasaOS-Common/utils/logger"
"github.com/IceWhaleTech/CasaOS-Common/utils/port"
"github.com/IceWhaleTech/CasaOS-Common/utils/ssh"
"github.com/IceWhaleTech/CasaOS-Common/utils/systemctl"
"github.com/docker/docker/api/types"
"github.com/docker/docker/errdefs"
"github.com/gin-gonic/gin"
"github.com/gorilla/websocket"
"github.com/samber/lo"
uuid "github.com/satori/go.uuid"
"go.uber.org/zap"
)
const (
dockerRootDirFilePath = "/var/lib/casaos/docker_root"
dockerDaemonConfigurationFilePath = "/etc/docker/daemon.json"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool { return true },
HandshakeTimeout: time.Duration(time.Second * 5),
}
// 打开docker的terminal
func DockerTerminal(c *gin.Context) {
col := c.DefaultQuery("cols", "100")
row := c.DefaultQuery("rows", "30")
conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
defer conn.Close()
container := c.Param("id")
hr, err := service.MyService.Docker().CreateContainerShellSession(container, row, col)
if err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
// 关闭I/O流
defer hr.Close()
// 退出进程
defer func() {
if _, err := hr.Conn.Write([]byte("exit\r")); err != nil {
logger.Error("error when trying `exit` to container", zap.Error(err))
}
}()
go func() {
ssh.WsWriterCopy(hr.Conn, conn)
}()
ssh.WsReaderCopy(conn, hr.Conn)
}
// @Summary 安装app(该接口需要post json数据)
// @Produce application/json
// @Accept application/json
// @Tags app
// @Param id path int true "id"
// @Param port formData int true "主端口"
// @Param tcp formData string false "tcp端口"
// @Param udp formData string false "udp端口"
// @Param env formData string false "环境变量"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/install [post]
func InstallApp(c *gin.Context) {
m := model.CustomizationPostData{}
if err := c.ShouldBind(&m); err != nil {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: err.Error()})
return
}
const CUSTOM = "custom"
var dockerImage string
var dockerImageVersion string
// check app name is exist
if len(m.Protocol) == 0 {
m.Protocol = "http"
}
m.ContainerName = strings.Replace(m.Label, " ", "_", -1)
if m.Origin != CUSTOM {
oldName := m.ContainerName
oldLabel := m.Label
for i := 0; true; i++ {
if i != 0 {
m.ContainerName = oldName + "-" + strconv.Itoa(i)
m.Label = oldLabel + "-" + strconv.Itoa(i)
}
if _, err := service.MyService.Docker().GetContainerByName(m.ContainerName); err != nil {
break
}
}
} else {
if _, err := service.MyService.Docker().GetContainerByName(m.ContainerName); err == nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.ERROR_APP_NAME_EXIST, Message: common_err.GetMsg(common_err.ERROR_APP_NAME_EXIST)})
return
}
}
// check port
if len(m.PortMap) > 0 && m.PortMap != "0" {
portMap, err := strconv.Atoi(m.PortMap)
if err != nil {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: err.Error()})
return
}
if !port.IsPortAvailable(portMap, "tcp") {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + m.PortMap})
return
}
}
imageArr := strings.Split(m.Image, ":")
if len(imageArr) == 2 {
dockerImage = imageArr[0]
dockerImageVersion = imageArr[1]
} else {
dockerImage = m.Image
dockerImageVersion = "latest"
}
m.Image = dockerImage + ":" + dockerImageVersion
for _, u := range m.Ports {
protocol := strings.ToLower(u.Protocol)
if !lo.Contains([]string{"tcp", "udp", "both"}, protocol) {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: "Protocol must be tcp or udp or both"})
return
}
protocols := strings.Replace(protocol, "both", "tcp,udp", -1)
for _, p := range strings.Split(protocols, ",") {
t, err := strconv.Atoi(u.CommendPort)
if err != nil {
logger.Info("host port is not number - will pick port number randomly", zap.String("port", u.CommendPort))
}
if !port.IsPortAvailable(t, p) {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: "Duplicate port:" + u.CommendPort})
return
}
}
}
if m.Origin == CUSTOM {
for _, device := range m.Devices {
if file.CheckNotExist(device.Path) {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.DEVICE_NOT_EXIST, Message: device.Path + "," + common_err.GetMsg(common_err.DEVICE_NOT_EXIST)})
return
}
}
} else {
dev := []model.PathMap{}
for _, device := range dev {
if !file.CheckNotExist(device.Path) {
dev = append(dev, device)
}
}
m.Devices = dev
}
id := uuid.NewV4().String()
m.CustomID = id
imageName := dockerImage + ":" + dockerImageVersion
ctx := common.WithProperties(context.Background(), PropertiesFromQueryParams(c))
eventProperties := common.PropertiesFromContext(ctx)
eventProperties[common.PropertyTypeAppName.Name] = m.Label
eventProperties[common.PropertyTypeAppIcon.Name] = m.Icon
eventProperties[common.PropertyTypeImageName.Name] = imageName
go func() {
go service.PublishEventWrapper(ctx, common.EventTypeAppInstallBegin, nil)
defer service.PublishEventWrapper(ctx, common.EventTypeAppInstallEnd, nil)
if err := pullAndInstall(ctx, imageName, &m); err != nil {
go service.PublishEventWrapper(ctx, common.EventTypeAppInstallError, map[string]string{
common.PropertyTypeMessage.Name: err.Error(),
})
}
}()
c.JSON(http.StatusOK, modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m.Label})
}
// @Summary 卸载app
// @Produce application/json
// @Accept multipart/form-data
// @Tags app
// @Param id path string true "容器id"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/uninstall/{id} [delete]
func UninstallApp(c *gin.Context) {
containerID := c.Param("id")
if len(containerID) == 0 {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: common_err.GetMsg(common_err.INVALID_PARAMS)})
return
}
j := make(map[string]bool)
if err := c.ShouldBind(&j); err != nil {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: err.Error()})
return
}
isDelete, ok := j["delete_config_folder"]
if !ok {
isDelete = false
}
ctx := common.WithProperties(context.Background(), PropertiesFromQueryParams(c))
container, err := service.MyService.Docker().DescribeContainer(ctx, containerID)
if err != nil {
if _, ok := err.(errdefs.ErrNotFound); ok {
c.JSON(http.StatusNotFound, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
}
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
eventProperties := common.PropertiesFromContext(ctx)
eventProperties[common.PropertyTypeAppName.Name] = v1.AppName(container)
eventProperties[common.PropertyTypeAppIcon.Name] = v1.AppIcon(container)
go func() {
go service.PublishEventWrapper(ctx, common.EventTypeAppUninstallBegin, nil)
defer service.PublishEventWrapper(ctx, common.EventTypeAppUninstallEnd, nil)
if err := uninstall(ctx, container, isDelete); err != nil {
go service.PublishEventWrapper(ctx, common.EventTypeAppUninstallError, map[string]string{
common.PropertyTypeMessage.Name: err.Error(),
})
}
}()
c.JSON(http.StatusOK, modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
}
// @Summary 修改app状态
// @Produce application/json
// @Accept multipart/form-data
// @Tags app
// @Param id path string true "appid"
// @Param state query string false "是否停止 start stop restart"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/state/{id} [put]
func ChangAppState(c *gin.Context) {
appID := c.Param("id")
if len(appID) == 0 {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: "id should not be empty"})
return
}
js := make(map[string]string)
if err := c.ShouldBind(&js); err != nil {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: err.Error()})
return
}
state, ok := js["state"]
if !ok || len(state) == 0 {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: "`state` should exist and it should not be empty"})
return
}
switch state {
case "start":
if err := service.MyService.Docker().StartContainer(appID); err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
case "restart":
if err := service.MyService.Docker().StopContainer(appID); err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
if err := service.MyService.Docker().StartContainer(appID); err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
case "stop":
if err := service.MyService.Docker().StopContainer(appID); err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
default:
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: "`state` should be start, stop or restart"})
}
info, err := service.MyService.Docker().GetContainer(appID)
if err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
c.JSON(http.StatusOK, modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: info.State})
}
// @Summary 查看容器日志
// @Produce application/json
// @Accept application/json
// @Tags app
// @Param id path string true "appid"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/logs/{id} [get]
func ContainerLog(c *gin.Context) {
appID := c.Param("id")
log, err := service.MyService.Docker().GetContainerLog(appID)
if err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
c.JSON(http.StatusOK, modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: string(log)})
}
// @Summary 获取容器状态
// @Produce application/json
// @Accept application/json
// @Tags app
// @Param id path string true "容器id"
// @Param type query string false "type=1"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/state/{id} [get]
func GetContainerState(c *gin.Context) {
id := c.Param("id")
// t := c.DefaultQuery("type", "0")
containerInfo, e := service.MyService.Docker().GetContainer(id)
if e != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: e.Error()})
return
}
data := make(map[string]interface{})
data["state"] = containerInfo.State
c.JSON(http.StatusOK, modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
}
// @Summary 更新设置
// @Produce application/json
// @Accept multipart/form-data
// @Tags app
// @Param id path string true "容器id"
// @Param shares formData string false "cpu权重"
// @Param mem formData string false "内存大小MB"
// @Param restart formData string false "重启策略"
// @Param label formData string false "应用名称"
// @Param position formData bool true "是否放到首页"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/update/{id}/setting [put]
func UpdateSetting(c *gin.Context) {
id := c.Param("id")
if len(id) == 0 {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: "id should not be empty"})
return
}
m := model.CustomizationPostData{}
if err := c.ShouldBind(&m); err != nil {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: err.Error()})
return
}
if err := service.MyService.Docker().StopContainer(id); err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
for _, u := range m.Ports {
protocol := strings.ToLower(u.Protocol)
if !lo.Contains([]string{"tcp", "udp", "both"}, protocol) {
c.JSON(http.StatusBadRequest, modelCommon.Result{Success: common_err.INVALID_PARAMS, Message: "protocol should be tcp, udp or both"})
return
}
}
if err := service.MyService.Docker().RenameContainer(id, id); err != nil {
logger.Error("rename container error: ", zap.Error(err))
}
containerID, err := service.MyService.Docker().CreateContainer(m, id)
if err != nil {
if err := service.MyService.Docker().RenameContainer(m.ContainerName, id); err != nil {
logger.Error("rename container error: ", zap.Error(err))
}
if err := service.MyService.Docker().StartContainer(id); err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
// step:启动容器
if err = service.MyService.Docker().StartContainer(containerID); err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
if err := service.MyService.Docker().RemoveContainer(id, true); err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()})
return
}
c.JSON(http.StatusOK, modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS)})
}
func GetDockerNetworks(c *gin.Context) {
networks := service.MyService.Docker().GetNetworkList()
list := []map[string]string{}
for _, network := range networks {
if network.Driver != "null" {
list = append(list, map[string]string{"name": network.Name, "driver": network.Driver, "id": network.ID})
}
}
c.JSON(http.StatusOK, modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list})
}
// @Produce application/json
// @Accept application/json
// @Tags app
// @Param id path string true "appid"
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/update/{id}/info [get]
func ContainerUpdateInfo(c *gin.Context) {
appID := c.Param("id")
ctx := common.WithProperties(context.Background(), PropertiesFromQueryParams(c))
info, err := service.MyService.Docker().DescribeContainer(ctx, appID)
if err != nil {
c.JSON(http.StatusInternalServerError, modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: err.Error()})
return
}
var port model.PortArray
for k, v := range info.HostConfig.PortBindings {
temp := model.PortMap{
CommendPort: v[0].HostPort,
ContainerPort: k.Port(),
Protocol: strings.ToLower(k.Proto()),
}
port = append(port, temp)
}
var envs model.EnvArray
showENV := info.Config.Labels["show_env"]
showENVList := strings.Split(showENV, ",")
showENVMap := make(map[string]string)
if len(showENVList) > 0 && showENVList[0] != "" {
for _, name := range showENVList {
showENVMap[name] = "1"
}
}
for _, v := range info.Config.Env {
env := strings.SplitN(v, "=", 2)
if len(showENVList) > 0 && info.Config.Labels["origin"] != "local" {
if _, ok := showENVMap[env[0]]; ok {
temp := model.Env{Name: env[0], Value: env[1]}
envs = append(envs, temp)
}
} else {
temp := model.Env{Name: env[0], Value: env[1]}
envs = append(envs, temp)
}
}
var vol model.PathArray
for i := 0; i < len(info.Mounts); i++ {
temp := model.PathMap{
Path: strings.ReplaceAll(info.Mounts[i].Source, "$AppID", info.Name),
ContainerPath: info.Mounts[i].Destination,
}
vol = append(vol, temp)
}
var driver model.PathArray
for _, v := range info.HostConfig.Resources.Devices {
temp := model.PathMap{
Path: v.PathOnHost,
ContainerPath: v.PathInContainer,
}
driver = append(driver, temp)
}
name := v1.AppName(info)
if len(name) == 0 {
name = strings.ReplaceAll(info.Name, "/", "")
}
var appStoreID uint
if appStoreIDStr, ok := info.Config.Labels[common.ContainerLabelV1AppStoreID]; ok {
_appStoreID, err := strconv.Atoi(appStoreIDStr)
if err != nil {
logger.Error("error when converting appStoreID from string to int", zap.Error(err), zap.String("appStoreIDStr", appStoreIDStr))
}
if _appStoreID > 0 {
appStoreID = uint(_appStoreID)
}
}
m := model.CustomizationPostData{
AppStoreID: appStoreID,
CapAdd: info.HostConfig.CapAdd,
Cmd: info.Config.Cmd,
ContainerName: strings.ReplaceAll(info.Name, "/", ""),
CPUShares: info.HostConfig.CPUShares,
CustomID: info.Config.Labels["custom_id"],
Description: info.Config.Labels["desc"],
Devices: driver,
EnableUPNP: false,
Envs: envs,
Host: info.Config.Labels["host"],
HostName: info.Config.Hostname,
Icon: v1.AppIcon(info),
Image: info.Config.Image,
Index: info.Config.Labels["index"],
Label: name,
Memory: info.HostConfig.Memory >> 20,
NetworkModel: string(info.HostConfig.NetworkMode),
Origin: info.Config.Labels["origin"],
PortMap: info.Config.Labels["web"],
Ports: port,
Position: false,
Privileged: info.HostConfig.Privileged,
Protocol: info.Config.Labels["protocol"],
Restart: info.HostConfig.RestartPolicy.Name,
Volumes: vol,
}
if len(m.Origin) == 0 {
m.Origin = "local"
}
if len(m.CustomID) == 0 {
m.CustomID = uuid.NewV4().String()
}
if m.Protocol == "" {
m.Protocol = "http"
}
c.JSON(http.StatusOK, modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: m})
}
// @Summary 我的应用列表
// @Produce application/json
// @Accept application/json
// @Tags app
// @Security ApiKeyAuth
// @Param index query int false "index"
// @Param size query int false "size"
// @Param position query bool false "是否是首页应用"
// @Success 200 {string} string "ok"
// @Router /app/my/list [get]
func MyAppList(c *gin.Context) {
name := c.Query("name")
image := c.Query("image")
state := c.Query("state")
casaOSApps, localApps := service.MyService.Docker().GetContainerAppList(&name, &image, &state)
data := make(map[string]interface{}, 2)
data["casaos_apps"] = casaOSApps
data["local_apps"] = localApps
c.JSON(common_err.SUCCESS, &modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
}
// @Summary my app hardware usage list
// @Produce application/json
// @Accept application/json
// @Tags app
// @Security ApiKeyAuth
// @Success 200 {string} string "ok"
// @Router /app/usage [get]
func AppUsageList(c *gin.Context) {
list := service.MyService.Docker().GetContainerStats()
c.JSON(common_err.SUCCESS, &modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: list})
// c.JSON(common_err.SUCCESS, &modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: nil})
}
func GetDockerDaemonConfiguration(c *gin.Context) {
// info, err := service.MyService.Docker().GetServerInfo()
// if err != nil {
// c.JSON(common_err.SERVICE_ERROR, &modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: common_err.GetMsg(common_err.SERVICE_ERROR), Data: err.Error()})
// return
// }
data := make(map[string]interface{})
if file.Exists(dockerRootDirFilePath) {
buf := file.ReadFullFile(dockerRootDirFilePath)
err := json.Unmarshal(buf, &data)
if err != nil {
c.JSON(common_err.CLIENT_ERROR, &modelCommon.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err})
return
}
}
c.JSON(common_err.SUCCESS, &modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: data})
}
func PutDockerDaemonConfiguration(c *gin.Context) {
request := make(map[string]interface{})
if err := c.BindJSON(&request); err != nil {
c.JSON(http.StatusBadRequest, &modelCommon.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: err})
return
}
value, ok := request["docker_root_dir"]
if !ok {
c.JSON(http.StatusBadRequest, &modelCommon.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.INVALID_PARAMS), Data: "`docker_root_dir` should not empty"})
return
}
dockerConfig := model.DockerDaemonConfigurationModel{}
if file.Exists(dockerDaemonConfigurationFilePath) {
byteResult := file.ReadFullFile(dockerDaemonConfigurationFilePath)
err := json.Unmarshal(byteResult, &dockerConfig)
if err != nil {
c.JSON(http.StatusInternalServerError, &modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to deserialize " + dockerDaemonConfigurationFilePath, Data: err})
return
}
}
dockerRootDir := value.(string)
if dockerRootDir == "/" {
dockerConfig.Root = "" // omitempty - empty string will not be serialized
} else {
if !file.Exists(dockerRootDir) {
c.JSON(http.StatusBadRequest, &modelCommon.Result{Success: common_err.CLIENT_ERROR, Message: common_err.GetMsg(common_err.DIR_NOT_EXISTS), Data: common_err.GetMsg(common_err.DIR_NOT_EXISTS)})
return
}
dockerConfig.Root = filepath.Join(dockerRootDir, "docker")
if err := file.IsNotExistMkDir(dockerConfig.Root); err != nil {
c.JSON(http.StatusInternalServerError, &modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to create " + dockerConfig.Root, Data: err})
return
}
}
buf, err := json.Marshal(request)
if err != nil {
c.JSON(http.StatusBadRequest, &modelCommon.Result{Success: common_err.CLIENT_ERROR, Message: "error when trying to serialize docker root json", Data: err})
return
}
if err := file.WriteToFullPath(buf, dockerRootDirFilePath, 0o644); err != nil {
c.JSON(http.StatusInternalServerError, &modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to write " + dockerRootDirFilePath, Data: err})
return
}
buf, err = json.Marshal(dockerConfig)
if err != nil {
c.JSON(http.StatusBadRequest, &modelCommon.Result{Success: common_err.CLIENT_ERROR, Message: "error when trying to serialize docker config", Data: dockerConfig})
return
}
if err := file.WriteToFullPath(buf, dockerDaemonConfigurationFilePath, 0o644); err != nil {
c.JSON(http.StatusInternalServerError, &modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to write to " + dockerDaemonConfigurationFilePath, Data: err})
return
}
if err := systemctl.ReloadDaemon(); err != nil {
c.JSON(http.StatusInternalServerError, &modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to reload systemd daemon"})
}
if err := systemctl.StopService("docker"); err != nil {
c.JSON(http.StatusInternalServerError, &modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to stop docker service"})
}
if err := systemctl.StartService("docker"); err != nil {
c.JSON(http.StatusInternalServerError, &modelCommon.Result{Success: common_err.SERVICE_ERROR, Message: "error when trying to start docker service"})
}
c.JSON(http.StatusOK, &modelCommon.Result{Success: common_err.SUCCESS, Message: common_err.GetMsg(common_err.SUCCESS), Data: request})
}
func pullAndInstall(ctx context.Context, imageName string, m *model.CustomizationPostData) error {
// step:下载镜像
if err := func() error {
go service.PublishEventWrapper(ctx, common.EventTypeImagePullBegin, nil)
defer service.PublishEventWrapper(ctx, common.EventTypeImagePullEnd, nil)
if err := service.MyService.Docker().PullImage(ctx, imageName); err != nil {
go service.PublishEventWrapper(ctx, common.EventTypeImagePullError, map[string]string{
common.PropertyTypeMessage.Name: err.Error(),
})
return err
}
for !service.MyService.Docker().IsExistImage(m.Image) {
time.Sleep(time.Second)
}
return nil
}(); err != nil {
return err
}
var containerID string
if err := func() error {
go service.PublishEventWrapper(ctx, common.EventTypeContainerCreateBegin, nil)
defer service.PublishEventWrapper(ctx, common.EventTypeContainerCreateEnd, nil)
_containerID, err := service.MyService.Docker().CreateContainer(*m, "")
if err != nil {
go service.PublishEventWrapper(ctx, common.EventTypeContainerCreateError, map[string]string{
common.PropertyTypeMessage.Name: err.Error(),
})
return err
}
containerID = _containerID
eventProperties := common.PropertiesFromContext(ctx)
eventProperties[common.PropertyTypeContainerID.Name] = containerID
return nil
}(); err != nil {
return err
}
// step:启动容器
if err := func() error {
go service.PublishEventWrapper(ctx, common.EventTypeContainerStartBegin, nil)
defer service.PublishEventWrapper(ctx, common.EventTypeContainerStartEnd, nil)
if err := service.MyService.Docker().StartContainer(m.ContainerName); err != nil {
go service.PublishEventWrapper(ctx, common.EventTypeContainerStartError, map[string]string{
common.PropertyTypeMessage.Name: err.Error(),
})
return err
}
return nil
}(); err != nil {
return err
}
config.CasaOSGlobalVariables.AppChange = true
return nil
}
func uninstall(ctx context.Context, container *types.ContainerJSON, isDelete bool) error {
// step:停止容器
if err := func() error {
go service.PublishEventWrapper(ctx, common.EventTypeContainerStopBegin, nil)
defer service.PublishEventWrapper(ctx, common.EventTypeContainerStopEnd, nil)
if err := service.MyService.Docker().StopContainer(container.ID); err != nil {
go service.PublishEventWrapper(ctx, common.EventTypeContainerStopError, map[string]string{
common.PropertyTypeMessage.Name: err.Error(),
})
return err
}
return nil
}(); err != nil {
return err
}
if err := func() error {
go service.PublishEventWrapper(ctx, common.EventTypeContainerRemoveBegin, nil)
defer service.PublishEventWrapper(ctx, common.EventTypeContainerRemoveEnd, nil)
if err := service.MyService.Docker().RemoveContainer(container.ID, false); err != nil {
go service.PublishEventWrapper(ctx, common.EventTypeContainerRemoveError, map[string]string{
common.PropertyTypeMessage.Name: err.Error(),
})
return err
}
return nil
}(); err != nil {
return err
}
if err := func() error {
go service.PublishEventWrapper(ctx, common.EventTypeImageRemoveBegin, nil)
defer service.PublishEventWrapper(ctx, common.EventTypeImageRemoveEnd, nil)
if err := service.MyService.Docker().RemoveImage(container.Config.Image); err != nil {
logger.Error("error when trying to remove docker image", zap.Error(err), zap.String("image", container.Config.Image))
go service.PublishEventWrapper(ctx, common.EventTypeImageRemoveError, map[string]string{
common.PropertyTypeMessage.Name: err.Error(),
})
}
return nil
}(); err != nil {
return err
}
if container.Config.Labels["origin"] != "custom" && isDelete {
// step: 删除文件夹
for _, v := range container.Mounts {
if strings.Contains(v.Source, container.Name) {
path := filepath.Join(strings.Split(v.Source, container.Name)[0], container.Name)
if err := file.RMDir(path); err != nil {
return err
}
}
}
}
config.CasaOSGlobalVariables.AppChange = true
return nil
}