2022-10-08 10:32:02 +00:00
|
|
|
package service
|
|
|
|
|
|
|
|
import (
|
2024-06-25 10:17:15 +00:00
|
|
|
"bufio"
|
2022-10-08 10:32:02 +00:00
|
|
|
"context"
|
2023-12-14 04:02:11 +00:00
|
|
|
"encoding/base64"
|
2022-10-08 10:32:02 +00:00
|
|
|
"encoding/json"
|
2022-10-11 06:20:51 +00:00
|
|
|
"fmt"
|
2023-03-28 11:02:11 +00:00
|
|
|
"io"
|
2024-06-25 10:17:15 +00:00
|
|
|
"net/http"
|
|
|
|
"net/url"
|
2023-05-23 07:43:51 +00:00
|
|
|
"os"
|
2023-03-09 10:42:17 +00:00
|
|
|
"os/exec"
|
2023-07-12 06:33:19 +00:00
|
|
|
"path/filepath"
|
2022-12-06 10:24:26 +00:00
|
|
|
"sort"
|
2022-10-12 10:55:47 +00:00
|
|
|
"strconv"
|
2022-10-08 10:32:02 +00:00
|
|
|
"strings"
|
2023-04-25 14:06:17 +00:00
|
|
|
"sync"
|
2023-11-08 06:29:30 +00:00
|
|
|
"syscall"
|
2022-10-08 10:32:02 +00:00
|
|
|
"time"
|
2024-01-26 08:07:37 +00:00
|
|
|
"unicode/utf8"
|
2022-10-08 10:32:02 +00:00
|
|
|
|
2024-06-26 06:28:49 +00:00
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
|
2024-02-29 03:08:18 +00:00
|
|
|
"github.com/pkg/errors"
|
|
|
|
|
2022-10-18 10:39:45 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/app/dto"
|
2023-03-13 15:49:31 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/buserr"
|
2022-10-18 10:39:45 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/constant"
|
2022-12-28 10:35:53 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
2023-07-17 08:34:29 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/utils/cmd"
|
2023-03-13 15:49:31 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/utils/common"
|
2022-10-18 10:39:45 +00:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/utils/docker"
|
2022-10-08 10:32:02 +00:00
|
|
|
"github.com/docker/docker/api/types"
|
2022-10-12 10:55:47 +00:00
|
|
|
"github.com/docker/docker/api/types/container"
|
2022-10-11 06:20:51 +00:00
|
|
|
"github.com/docker/docker/api/types/filters"
|
2024-05-22 10:32:47 +00:00
|
|
|
"github.com/docker/docker/api/types/image"
|
2024-04-02 09:14:45 +00:00
|
|
|
"github.com/docker/docker/api/types/mount"
|
2022-10-11 06:20:51 +00:00
|
|
|
"github.com/docker/docker/api/types/network"
|
2023-12-14 04:02:11 +00:00
|
|
|
"github.com/docker/docker/api/types/registry"
|
2023-03-28 11:02:11 +00:00
|
|
|
"github.com/docker/docker/client"
|
2022-10-12 10:55:47 +00:00
|
|
|
"github.com/docker/go-connections/nat"
|
2023-06-13 15:04:12 +00:00
|
|
|
"github.com/gorilla/websocket"
|
2022-10-12 10:55:47 +00:00
|
|
|
v1 "github.com/opencontainers/image-spec/specs-go/v1"
|
2023-06-15 12:44:13 +00:00
|
|
|
"github.com/shirou/gopsutil/v3/cpu"
|
|
|
|
"github.com/shirou/gopsutil/v3/mem"
|
2022-10-08 10:32:02 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type ContainerService struct{}
|
|
|
|
|
|
|
|
type IContainerService interface {
|
|
|
|
Page(req dto.PageContainer) (int64, interface{}, error)
|
2023-06-28 06:30:11 +00:00
|
|
|
List() ([]string, error)
|
2023-02-07 10:48:32 +00:00
|
|
|
PageNetwork(req dto.SearchWithPage) (int64, interface{}, error)
|
2023-07-07 15:17:05 +00:00
|
|
|
ListNetwork() ([]dto.Options, error)
|
2023-02-07 10:48:32 +00:00
|
|
|
PageVolume(req dto.SearchWithPage) (int64, interface{}, error)
|
2022-10-12 10:55:47 +00:00
|
|
|
ListVolume() ([]dto.Options, error)
|
2023-02-07 10:48:32 +00:00
|
|
|
PageCompose(req dto.SearchWithPage) (int64, interface{}, error)
|
2023-03-20 10:16:26 +00:00
|
|
|
CreateCompose(req dto.ComposeCreate) (string, error)
|
2022-10-17 08:04:39 +00:00
|
|
|
ComposeOperation(req dto.ComposeOperation) error
|
2023-06-15 03:00:11 +00:00
|
|
|
ContainerCreate(req dto.ContainerOperate) error
|
|
|
|
ContainerUpdate(req dto.ContainerOperate) error
|
2023-06-16 09:54:11 +00:00
|
|
|
ContainerUpgrade(req dto.ContainerUpgrade) error
|
2023-06-15 03:00:11 +00:00
|
|
|
ContainerInfo(req dto.OperationWithName) (*dto.ContainerOperate, error)
|
2023-07-06 10:04:22 +00:00
|
|
|
ContainerListStats() ([]dto.ContainerListStats, error)
|
2023-10-07 06:30:46 +00:00
|
|
|
LoadResourceLimit() (*dto.ResourceLimit, error)
|
2023-10-26 10:20:16 +00:00
|
|
|
ContainerRename(req dto.ContainerRename) error
|
2024-06-14 08:18:39 +00:00
|
|
|
ContainerCommit(req dto.ContainerCommit) error
|
2023-05-23 07:43:51 +00:00
|
|
|
ContainerLogClean(req dto.OperationWithName) error
|
2022-10-08 10:32:02 +00:00
|
|
|
ContainerOperation(req dto.ContainerOperation) error
|
2023-11-08 06:29:30 +00:00
|
|
|
ContainerLogs(wsConn *websocket.Conn, containerType, container, since, tail string, follow bool) error
|
2024-06-25 10:17:15 +00:00
|
|
|
DownloadContainerLogs(containerType, container, since, tail string, c *gin.Context) error
|
2023-07-06 10:04:22 +00:00
|
|
|
ContainerStats(id string) (*dto.ContainerStats, error)
|
2022-10-11 11:47:16 +00:00
|
|
|
Inspect(req dto.InspectReq) (string, error)
|
2022-10-11 06:20:51 +00:00
|
|
|
DeleteNetwork(req dto.BatchDelete) error
|
2023-05-30 07:30:57 +00:00
|
|
|
CreateNetwork(req dto.NetworkCreate) error
|
2022-10-11 06:20:51 +00:00
|
|
|
DeleteVolume(req dto.BatchDelete) error
|
2023-05-30 07:30:57 +00:00
|
|
|
CreateVolume(req dto.VolumeCreate) error
|
2023-03-28 10:00:06 +00:00
|
|
|
TestCompose(req dto.ComposeCreate) (bool, error)
|
|
|
|
ComposeUpdate(req dto.ComposeUpdate) error
|
2023-05-23 11:00:06 +00:00
|
|
|
Prune(req dto.ContainerPrune) (dto.ContainerPruneReport, error)
|
2023-08-02 08:47:30 +00:00
|
|
|
|
2023-08-09 03:18:12 +00:00
|
|
|
LoadContainerLogs(req dto.OperationWithNameAndType) string
|
2022-10-08 10:32:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewIContainerService() IContainerService {
|
|
|
|
return &ContainerService{}
|
|
|
|
}
|
2022-10-11 06:20:51 +00:00
|
|
|
|
2022-10-08 10:32:02 +00:00
|
|
|
func (u *ContainerService) Page(req dto.PageContainer) (int64, interface{}, error) {
|
|
|
|
var (
|
2023-06-29 10:40:12 +00:00
|
|
|
records []types.Container
|
|
|
|
list []types.Container
|
2022-10-08 10:32:02 +00:00
|
|
|
)
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2024-04-08 09:54:07 +00:00
|
|
|
options := container.ListOptions{
|
|
|
|
All: true,
|
|
|
|
}
|
2022-10-17 08:04:39 +00:00
|
|
|
if len(req.Filters) != 0 {
|
|
|
|
options.Filters = filters.NewArgs()
|
|
|
|
options.Filters.Add("label", req.Filters)
|
|
|
|
}
|
2023-12-28 03:44:11 +00:00
|
|
|
containers, err := client.ContainerList(context.Background(), options)
|
2022-10-08 10:32:02 +00:00
|
|
|
if err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
2023-12-28 03:44:11 +00:00
|
|
|
if req.ExcludeAppStore {
|
|
|
|
for _, item := range containers {
|
|
|
|
if created, ok := item.Labels[composeCreatedBy]; ok && created == "Apps" {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
list = append(list, item)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
list = containers
|
|
|
|
}
|
|
|
|
|
2023-02-07 10:48:32 +00:00
|
|
|
if len(req.Name) != 0 {
|
2023-05-30 07:30:57 +00:00
|
|
|
length, count := len(list), 0
|
|
|
|
for count < length {
|
2023-02-07 10:48:32 +00:00
|
|
|
if !strings.Contains(list[count].Names[0][1:], req.Name) {
|
|
|
|
list = append(list[:count], list[(count+1):]...)
|
2023-05-30 07:30:57 +00:00
|
|
|
length--
|
2023-02-07 10:48:32 +00:00
|
|
|
} else {
|
|
|
|
count++
|
2023-10-18 02:14:26 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if req.State != "all" {
|
|
|
|
length, count := len(list), 0
|
|
|
|
for count < length {
|
|
|
|
if list[count].State != req.State {
|
|
|
|
list = append(list[:count], list[(count+1):]...)
|
|
|
|
length--
|
|
|
|
} else {
|
|
|
|
count++
|
2023-02-07 10:48:32 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2023-06-29 10:40:12 +00:00
|
|
|
switch req.OrderBy {
|
|
|
|
case "name":
|
|
|
|
sort.Slice(list, func(i, j int) bool {
|
|
|
|
if req.Order == constant.OrderAsc {
|
|
|
|
return list[i].Names[0][1:] < list[j].Names[0][1:]
|
|
|
|
}
|
|
|
|
return list[i].Names[0][1:] > list[j].Names[0][1:]
|
|
|
|
})
|
|
|
|
case "state":
|
|
|
|
sort.Slice(list, func(i, j int) bool {
|
|
|
|
if req.Order == constant.OrderAsc {
|
|
|
|
return list[i].State < list[j].State
|
|
|
|
}
|
|
|
|
return list[i].State > list[j].State
|
|
|
|
})
|
|
|
|
default:
|
|
|
|
sort.Slice(list, func(i, j int) bool {
|
|
|
|
if req.Order == constant.OrderAsc {
|
|
|
|
return list[i].Created < list[j].Created
|
|
|
|
}
|
|
|
|
return list[i].Created > list[j].Created
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2022-10-08 10:32:02 +00:00
|
|
|
total, start, end := len(list), (req.Page-1)*req.PageSize, req.Page*req.PageSize
|
|
|
|
if start > total {
|
|
|
|
records = make([]types.Container, 0)
|
|
|
|
} else {
|
|
|
|
if end >= total {
|
|
|
|
end = total
|
|
|
|
}
|
|
|
|
records = list[start:end]
|
|
|
|
}
|
|
|
|
|
2023-06-29 10:40:12 +00:00
|
|
|
backDatas := make([]dto.ContainerInfo, len(records))
|
|
|
|
for i := 0; i < len(records); i++ {
|
2023-07-06 10:04:22 +00:00
|
|
|
item := records[i]
|
|
|
|
IsFromCompose := false
|
|
|
|
if _, ok := item.Labels[composeProjectLabel]; ok {
|
|
|
|
IsFromCompose = true
|
|
|
|
}
|
|
|
|
IsFromApp := false
|
|
|
|
if created, ok := item.Labels[composeCreatedBy]; ok && created == "Apps" {
|
|
|
|
IsFromApp = true
|
|
|
|
}
|
2023-04-25 14:06:17 +00:00
|
|
|
|
2023-12-11 06:06:06 +00:00
|
|
|
ports := loadContainerPort(item.Ports)
|
2023-12-27 14:38:10 +00:00
|
|
|
info := dto.ContainerInfo{
|
2023-07-06 10:04:22 +00:00
|
|
|
ContainerID: item.ID,
|
2024-06-28 06:04:08 +00:00
|
|
|
CreateTime: time.Unix(item.Created, 0).Format(constant.DateTimeLayout),
|
2023-07-06 10:04:22 +00:00
|
|
|
Name: item.Names[0][1:],
|
|
|
|
ImageId: strings.Split(item.ImageID, ":")[1],
|
|
|
|
ImageName: item.Image,
|
|
|
|
State: item.State,
|
|
|
|
RunTime: item.Status,
|
|
|
|
Ports: ports,
|
|
|
|
IsFromApp: IsFromApp,
|
|
|
|
IsFromCompose: IsFromCompose,
|
|
|
|
}
|
2023-12-27 14:38:10 +00:00
|
|
|
install, _ := appInstallRepo.GetFirst(appInstallRepo.WithContainerName(info.Name))
|
|
|
|
if install.ID > 0 {
|
|
|
|
info.AppInstallName = install.Name
|
|
|
|
info.AppName = install.App.Name
|
|
|
|
websites, _ := websiteRepo.GetBy(websiteRepo.WithAppInstallId(install.ID))
|
|
|
|
for _, website := range websites {
|
|
|
|
info.Websites = append(info.Websites, website.PrimaryDomain)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
backDatas[i] = info
|
2023-09-04 07:51:10 +00:00
|
|
|
if item.NetworkSettings != nil && len(item.NetworkSettings.Networks) > 0 {
|
|
|
|
networks := make([]string, 0, len(item.NetworkSettings.Networks))
|
|
|
|
for key := range item.NetworkSettings.Networks {
|
2023-09-04 14:24:14 +00:00
|
|
|
networks = append(networks, item.NetworkSettings.Networks[key].IPAddress)
|
2023-09-04 07:51:10 +00:00
|
|
|
}
|
|
|
|
sort.Strings(networks)
|
|
|
|
backDatas[i].Network = networks
|
|
|
|
}
|
2023-04-25 14:06:17 +00:00
|
|
|
}
|
2022-10-08 10:32:02 +00:00
|
|
|
|
|
|
|
return int64(total), backDatas, nil
|
|
|
|
}
|
|
|
|
|
2023-06-28 06:30:11 +00:00
|
|
|
func (u *ContainerService) List() ([]string, error) {
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2024-04-08 09:54:07 +00:00
|
|
|
containers, err := client.ContainerList(context.Background(), container.ListOptions{All: true})
|
2023-06-28 06:30:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var datas []string
|
|
|
|
for _, container := range containers {
|
|
|
|
for _, name := range container.Names {
|
|
|
|
if len(name) != 0 {
|
2023-08-02 08:47:30 +00:00
|
|
|
datas = append(datas, strings.TrimPrefix(name, "/"))
|
2023-06-28 06:30:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return datas, nil
|
|
|
|
}
|
|
|
|
|
2023-07-06 10:04:22 +00:00
|
|
|
func (u *ContainerService) ContainerListStats() ([]dto.ContainerListStats, error) {
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2024-04-08 09:54:07 +00:00
|
|
|
list, err := client.ContainerList(context.Background(), container.ListOptions{All: true})
|
2023-07-06 10:04:22 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var datas []dto.ContainerListStats
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
wg.Add(len(list))
|
|
|
|
for i := 0; i < len(list); i++ {
|
|
|
|
go func(item types.Container) {
|
2023-09-21 09:34:22 +00:00
|
|
|
datas = append(datas, loadCpuAndMem(client, item.ID))
|
2023-07-06 10:04:22 +00:00
|
|
|
wg.Done()
|
|
|
|
}(list[i])
|
|
|
|
}
|
|
|
|
wg.Wait()
|
|
|
|
return datas, nil
|
|
|
|
}
|
|
|
|
|
2022-10-11 11:47:16 +00:00
|
|
|
func (u *ContainerService) Inspect(req dto.InspectReq) (string, error) {
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2022-10-11 11:47:16 +00:00
|
|
|
var inspectInfo interface{}
|
|
|
|
switch req.Type {
|
|
|
|
case "container":
|
|
|
|
inspectInfo, err = client.ContainerInspect(context.Background(), req.ID)
|
2023-09-21 09:20:20 +00:00
|
|
|
case "image":
|
|
|
|
inspectInfo, _, err = client.ImageInspectWithRaw(context.Background(), req.ID)
|
2022-10-11 11:47:16 +00:00
|
|
|
case "network":
|
|
|
|
inspectInfo, err = client.NetworkInspect(context.TODO(), req.ID, types.NetworkInspectOptions{})
|
|
|
|
case "volume":
|
|
|
|
inspectInfo, err = client.VolumeInspect(context.TODO(), req.ID)
|
|
|
|
}
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
bytes, err := json.Marshal(inspectInfo)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return string(bytes), nil
|
|
|
|
}
|
|
|
|
|
2023-05-23 11:00:06 +00:00
|
|
|
func (u *ContainerService) Prune(req dto.ContainerPrune) (dto.ContainerPruneReport, error) {
|
|
|
|
report := dto.ContainerPruneReport{}
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return report, err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2023-05-23 11:00:06 +00:00
|
|
|
pruneFilters := filters.NewArgs()
|
|
|
|
if req.WithTagAll {
|
|
|
|
pruneFilters.Add("dangling", "false")
|
|
|
|
if req.PruneType != "image" {
|
|
|
|
pruneFilters.Add("until", "24h")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
switch req.PruneType {
|
|
|
|
case "container":
|
|
|
|
rep, err := client.ContainersPrune(context.Background(), pruneFilters)
|
|
|
|
if err != nil {
|
|
|
|
return report, err
|
|
|
|
}
|
|
|
|
report.DeletedNumber = len(rep.ContainersDeleted)
|
|
|
|
report.SpaceReclaimed = int(rep.SpaceReclaimed)
|
|
|
|
case "image":
|
|
|
|
rep, err := client.ImagesPrune(context.Background(), pruneFilters)
|
|
|
|
if err != nil {
|
|
|
|
return report, err
|
|
|
|
}
|
|
|
|
report.DeletedNumber = len(rep.ImagesDeleted)
|
|
|
|
report.SpaceReclaimed = int(rep.SpaceReclaimed)
|
|
|
|
case "network":
|
|
|
|
rep, err := client.NetworksPrune(context.Background(), pruneFilters)
|
|
|
|
if err != nil {
|
|
|
|
return report, err
|
|
|
|
}
|
|
|
|
report.DeletedNumber = len(rep.NetworksDeleted)
|
|
|
|
case "volume":
|
2024-05-13 03:32:29 +00:00
|
|
|
versions, err := client.ServerVersion(context.Background())
|
|
|
|
if err != nil {
|
|
|
|
return report, err
|
|
|
|
}
|
|
|
|
if common.ComparePanelVersion(versions.APIVersion, "1.42") {
|
|
|
|
pruneFilters.Add("all", "true")
|
|
|
|
}
|
2023-05-23 11:00:06 +00:00
|
|
|
rep, err := client.VolumesPrune(context.Background(), pruneFilters)
|
|
|
|
if err != nil {
|
|
|
|
return report, err
|
|
|
|
}
|
|
|
|
report.DeletedNumber = len(rep.VolumesDeleted)
|
|
|
|
report.SpaceReclaimed = int(rep.SpaceReclaimed)
|
2024-05-11 09:50:24 +00:00
|
|
|
case "buildcache":
|
2024-05-17 06:02:37 +00:00
|
|
|
opts := types.BuildCachePruneOptions{}
|
|
|
|
opts.All = true
|
|
|
|
rep, err := client.BuildCachePrune(context.Background(), opts)
|
2024-05-11 09:50:24 +00:00
|
|
|
if err != nil {
|
|
|
|
return report, err
|
|
|
|
}
|
|
|
|
report.DeletedNumber = len(rep.CachesDeleted)
|
|
|
|
report.SpaceReclaimed = int(rep.SpaceReclaimed)
|
2023-05-23 11:00:06 +00:00
|
|
|
}
|
|
|
|
return report, nil
|
|
|
|
}
|
|
|
|
|
2023-10-07 06:30:46 +00:00
|
|
|
func (u *ContainerService) LoadResourceLimit() (*dto.ResourceLimit, error) {
|
2023-07-05 10:16:19 +00:00
|
|
|
cpuCounts, err := cpu.Counts(true)
|
2023-06-15 12:44:13 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("load cpu limit failed, err: %v", err)
|
|
|
|
}
|
|
|
|
memoryInfo, err := mem.VirtualMemory()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("load memory limit failed, err: %v", err)
|
|
|
|
}
|
|
|
|
|
|
|
|
data := dto.ResourceLimit{
|
|
|
|
CPU: cpuCounts,
|
2024-03-04 03:29:04 +00:00
|
|
|
Memory: memoryInfo.Total,
|
2023-06-15 12:44:13 +00:00
|
|
|
}
|
|
|
|
return &data, nil
|
|
|
|
}
|
|
|
|
|
2023-06-15 03:00:11 +00:00
|
|
|
func (u *ContainerService) ContainerCreate(req dto.ContainerOperate) error {
|
|
|
|
client, err := docker.NewDockerClient()
|
2023-04-28 14:46:20 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
2023-03-13 15:49:31 +00:00
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2023-07-05 08:48:25 +00:00
|
|
|
ctx := context.Background()
|
|
|
|
newContainer, _ := client.ContainerInspect(ctx, req.Name)
|
2023-07-05 09:40:19 +00:00
|
|
|
if newContainer.ContainerJSONBase != nil {
|
2023-07-05 08:48:25 +00:00
|
|
|
return buserr.New(constant.ErrContainerName)
|
|
|
|
}
|
2023-06-15 03:00:11 +00:00
|
|
|
|
2023-07-10 14:45:08 +00:00
|
|
|
if !checkImageExist(client, req.Image) || req.ForcePull {
|
2023-06-15 03:00:11 +00:00
|
|
|
if err := pullImages(ctx, client, req.Image); err != nil {
|
2023-07-10 14:45:08 +00:00
|
|
|
if !req.ForcePull {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
global.LOG.Errorf("force pull image %s failed, err: %v", req.Image, err)
|
2023-06-15 03:00:11 +00:00
|
|
|
}
|
2023-04-28 14:46:20 +00:00
|
|
|
}
|
2023-10-23 06:05:15 +00:00
|
|
|
imageInfo, _, err := client.ImageInspectWithRaw(ctx, req.Image)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if len(req.Entrypoint) == 0 {
|
|
|
|
req.Entrypoint = imageInfo.Config.Entrypoint
|
|
|
|
}
|
2023-10-23 07:25:17 +00:00
|
|
|
if len(req.Cmd) == 0 {
|
|
|
|
req.Cmd = imageInfo.Config.Cmd
|
|
|
|
}
|
2023-10-23 06:05:15 +00:00
|
|
|
config, hostConf, networkConf, err := loadConfigInfo(true, req, nil)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
global.LOG.Infof("new container info %s has been made, now start to create", req.Name)
|
2024-04-08 09:54:07 +00:00
|
|
|
con, err := client.ContainerCreate(ctx, config, hostConf, networkConf, &v1.Platform{}, req.Name)
|
2023-06-15 03:00:11 +00:00
|
|
|
if err != nil {
|
2024-04-08 09:54:07 +00:00
|
|
|
_ = client.ContainerRemove(ctx, req.Name, container.RemoveOptions{RemoveVolumes: true, Force: true})
|
2023-06-15 03:00:11 +00:00
|
|
|
return err
|
2022-10-12 10:55:47 +00:00
|
|
|
}
|
2023-06-15 03:00:11 +00:00
|
|
|
global.LOG.Infof("create container %s successful! now check if the container is started and delete the container information if it is not.", req.Name)
|
2024-04-08 09:54:07 +00:00
|
|
|
if err := client.ContainerStart(ctx, con.ID, container.StartOptions{}); err != nil {
|
|
|
|
_ = client.ContainerRemove(ctx, req.Name, container.RemoveOptions{RemoveVolumes: true, Force: true})
|
2023-06-15 03:00:11 +00:00
|
|
|
return fmt.Errorf("create successful but start failed, err: %v", err)
|
2022-10-12 10:55:47 +00:00
|
|
|
}
|
2023-06-15 03:00:11 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (u *ContainerService) ContainerInfo(req dto.OperationWithName) (*dto.ContainerOperate, error) {
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2022-10-12 10:55:47 +00:00
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2023-06-15 03:00:11 +00:00
|
|
|
ctx := context.Background()
|
|
|
|
oldContainer, err := client.ContainerInspect(ctx, req.Name)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
2022-10-12 10:55:47 +00:00
|
|
|
}
|
2023-06-15 03:00:11 +00:00
|
|
|
|
|
|
|
var data dto.ContainerOperate
|
2023-07-05 08:48:25 +00:00
|
|
|
data.ContainerID = oldContainer.ID
|
2023-06-15 03:00:11 +00:00
|
|
|
data.Name = strings.ReplaceAll(oldContainer.Name, "/", "")
|
|
|
|
data.Image = oldContainer.Config.Image
|
2023-07-07 15:17:05 +00:00
|
|
|
if oldContainer.NetworkSettings != nil {
|
|
|
|
for network := range oldContainer.NetworkSettings.Networks {
|
|
|
|
data.Network = network
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2024-04-13 11:56:07 +00:00
|
|
|
|
2024-08-26 08:07:13 +00:00
|
|
|
data.ExposedPorts, _ = loadContainerPortForInfo(req.Name, client)
|
2024-04-13 11:56:07 +00:00
|
|
|
networkSettings := oldContainer.NetworkSettings
|
|
|
|
bridgeNetworkSettings := networkSettings.Networks[data.Network]
|
2024-04-15 07:12:10 +00:00
|
|
|
if bridgeNetworkSettings.IPAMConfig != nil {
|
|
|
|
ipv4Address := bridgeNetworkSettings.IPAMConfig.IPv4Address
|
|
|
|
data.Ipv4 = ipv4Address
|
|
|
|
ipv6Address := bridgeNetworkSettings.IPAMConfig.IPv6Address
|
|
|
|
data.Ipv6 = ipv6Address
|
|
|
|
} else {
|
|
|
|
data.Ipv4 = bridgeNetworkSettings.IPAddress
|
|
|
|
}
|
2024-04-13 11:56:07 +00:00
|
|
|
|
2023-06-15 03:00:11 +00:00
|
|
|
data.Cmd = oldContainer.Config.Cmd
|
2023-10-07 06:30:46 +00:00
|
|
|
data.OpenStdin = oldContainer.Config.OpenStdin
|
|
|
|
data.Tty = oldContainer.Config.Tty
|
2023-09-07 08:24:10 +00:00
|
|
|
data.Entrypoint = oldContainer.Config.Entrypoint
|
2023-06-15 03:00:11 +00:00
|
|
|
data.Env = oldContainer.Config.Env
|
2023-06-16 09:54:11 +00:00
|
|
|
data.CPUShares = oldContainer.HostConfig.CPUShares
|
2023-06-15 03:00:11 +00:00
|
|
|
for key, val := range oldContainer.Config.Labels {
|
|
|
|
data.Labels = append(data.Labels, fmt.Sprintf("%s=%s", key, val))
|
2023-06-14 15:26:13 +00:00
|
|
|
}
|
2024-08-26 08:07:13 +00:00
|
|
|
|
2023-06-15 03:00:11 +00:00
|
|
|
data.AutoRemove = oldContainer.HostConfig.AutoRemove
|
2023-12-12 07:22:09 +00:00
|
|
|
data.Privileged = oldContainer.HostConfig.Privileged
|
2023-06-15 03:00:11 +00:00
|
|
|
data.PublishAllPorts = oldContainer.HostConfig.PublishAllPorts
|
2024-02-06 08:36:13 +00:00
|
|
|
data.RestartPolicy = string(oldContainer.HostConfig.RestartPolicy.Name)
|
2023-06-15 03:00:11 +00:00
|
|
|
if oldContainer.HostConfig.NanoCPUs != 0 {
|
2023-07-10 06:45:08 +00:00
|
|
|
data.NanoCPUs = float64(oldContainer.HostConfig.NanoCPUs) / 1000000000
|
2022-10-12 10:55:47 +00:00
|
|
|
}
|
2023-06-15 03:00:11 +00:00
|
|
|
if oldContainer.HostConfig.Memory != 0 {
|
2023-07-10 06:45:08 +00:00
|
|
|
data.Memory = float64(oldContainer.HostConfig.Memory) / 1024 / 1024
|
2023-06-15 03:00:11 +00:00
|
|
|
}
|
2024-04-02 09:14:45 +00:00
|
|
|
data.Volumes = loadVolumeBinds(oldContainer.Mounts)
|
2022-12-28 10:35:53 +00:00
|
|
|
|
2023-06-15 03:00:11 +00:00
|
|
|
return &data, nil
|
|
|
|
}
|
2023-03-28 11:02:11 +00:00
|
|
|
|
2023-06-15 03:00:11 +00:00
|
|
|
func (u *ContainerService) ContainerUpdate(req dto.ContainerOperate) error {
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2023-03-28 11:02:11 +00:00
|
|
|
ctx := context.Background()
|
2023-07-05 08:48:25 +00:00
|
|
|
newContainer, _ := client.ContainerInspect(ctx, req.Name)
|
2023-07-05 09:40:19 +00:00
|
|
|
if newContainer.ContainerJSONBase != nil && newContainer.ID != req.ContainerID {
|
2023-07-05 08:48:25 +00:00
|
|
|
return buserr.New(constant.ErrContainerName)
|
|
|
|
}
|
|
|
|
|
|
|
|
oldContainer, err := client.ContainerInspect(ctx, req.ContainerID)
|
2023-06-15 03:00:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-07-10 14:45:08 +00:00
|
|
|
if !checkImageExist(client, req.Image) || req.ForcePull {
|
2023-04-17 08:08:28 +00:00
|
|
|
if err := pullImages(ctx, client, req.Image); err != nil {
|
2023-07-10 14:45:08 +00:00
|
|
|
if !req.ForcePull {
|
|
|
|
return err
|
|
|
|
}
|
2023-12-12 07:22:09 +00:00
|
|
|
return fmt.Errorf("pull image %s failed, err: %v", req.Image, err)
|
2023-04-17 08:08:28 +00:00
|
|
|
}
|
2023-03-28 11:02:11 +00:00
|
|
|
}
|
2023-07-12 06:33:19 +00:00
|
|
|
|
2024-04-08 09:54:07 +00:00
|
|
|
if err := client.ContainerRemove(ctx, req.ContainerID, container.RemoveOptions{Force: true}); err != nil {
|
2023-07-12 06:33:19 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-10-12 03:50:31 +00:00
|
|
|
config, hostConf, networkConf, err := loadConfigInfo(false, req, &oldContainer)
|
|
|
|
if err != nil {
|
2023-07-27 05:58:13 +00:00
|
|
|
reCreateAfterUpdate(req.Name, client, oldContainer.Config, oldContainer.HostConfig, oldContainer.NetworkSettings)
|
2023-06-15 03:00:11 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
global.LOG.Infof("new container info %s has been update, now start to recreate", req.Name)
|
2024-04-08 09:54:07 +00:00
|
|
|
con, err := client.ContainerCreate(ctx, config, hostConf, networkConf, &v1.Platform{}, req.Name)
|
2022-10-12 10:55:47 +00:00
|
|
|
if err != nil {
|
2023-07-27 05:58:13 +00:00
|
|
|
reCreateAfterUpdate(req.Name, client, oldContainer.Config, oldContainer.HostConfig, oldContainer.NetworkSettings)
|
2023-10-07 06:30:46 +00:00
|
|
|
return fmt.Errorf("update container failed, err: %v", err)
|
2022-10-12 10:55:47 +00:00
|
|
|
}
|
2023-06-15 03:00:11 +00:00
|
|
|
global.LOG.Infof("update container %s successful! now check if the container is started.", req.Name)
|
2024-04-08 09:54:07 +00:00
|
|
|
if err := client.ContainerStart(ctx, con.ID, container.StartOptions{}); err != nil {
|
2023-06-15 03:00:11 +00:00
|
|
|
return fmt.Errorf("update successful but start failed, err: %v", err)
|
2022-10-12 10:55:47 +00:00
|
|
|
}
|
2023-06-15 03:00:11 +00:00
|
|
|
|
2022-10-12 10:55:47 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-06-16 09:54:11 +00:00
|
|
|
func (u *ContainerService) ContainerUpgrade(req dto.ContainerUpgrade) error {
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2023-06-16 09:54:11 +00:00
|
|
|
ctx := context.Background()
|
|
|
|
oldContainer, err := client.ContainerInspect(ctx, req.Name)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-07-10 14:45:08 +00:00
|
|
|
if !checkImageExist(client, req.Image) || req.ForcePull {
|
2023-06-16 09:54:11 +00:00
|
|
|
if err := pullImages(ctx, client, req.Image); err != nil {
|
2023-07-10 14:45:08 +00:00
|
|
|
if !req.ForcePull {
|
|
|
|
return err
|
|
|
|
}
|
2023-12-12 07:22:09 +00:00
|
|
|
return fmt.Errorf("pull image %s failed, err: %v", req.Image, err)
|
2023-06-16 09:54:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
config := oldContainer.Config
|
|
|
|
config.Image = req.Image
|
|
|
|
hostConf := oldContainer.HostConfig
|
2023-07-07 15:17:05 +00:00
|
|
|
var networkConf network.NetworkingConfig
|
|
|
|
if oldContainer.NetworkSettings != nil {
|
|
|
|
for networkKey := range oldContainer.NetworkSettings.Networks {
|
|
|
|
networkConf.EndpointsConfig = map[string]*network.EndpointSettings{networkKey: {}}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
2024-04-08 09:54:07 +00:00
|
|
|
if err := client.ContainerRemove(ctx, req.Name, container.RemoveOptions{Force: true}); err != nil {
|
2023-06-16 09:54:11 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
global.LOG.Infof("new container info %s has been update, now start to recreate", req.Name)
|
2024-04-08 09:54:07 +00:00
|
|
|
con, err := client.ContainerCreate(ctx, config, hostConf, &networkConf, &v1.Platform{}, req.Name)
|
2023-06-16 09:54:11 +00:00
|
|
|
if err != nil {
|
2023-07-27 05:58:13 +00:00
|
|
|
reCreateAfterUpdate(req.Name, client, oldContainer.Config, oldContainer.HostConfig, oldContainer.NetworkSettings)
|
2023-10-07 06:30:46 +00:00
|
|
|
return fmt.Errorf("upgrade container failed, err: %v", err)
|
2023-06-16 09:54:11 +00:00
|
|
|
}
|
2023-07-27 05:58:13 +00:00
|
|
|
global.LOG.Infof("upgrade container %s successful! now check if the container is started.", req.Name)
|
2024-04-08 09:54:07 +00:00
|
|
|
if err := client.ContainerStart(ctx, con.ID, container.StartOptions{}); err != nil {
|
2023-07-27 05:58:13 +00:00
|
|
|
return fmt.Errorf("upgrade successful but start failed, err: %v", err)
|
2023-06-16 09:54:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-10-26 10:20:16 +00:00
|
|
|
func (u *ContainerService) ContainerRename(req dto.ContainerRename) error {
|
|
|
|
ctx := context.Background()
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2023-10-26 10:20:16 +00:00
|
|
|
|
|
|
|
newContainer, _ := client.ContainerInspect(ctx, req.NewName)
|
|
|
|
if newContainer.ContainerJSONBase != nil {
|
|
|
|
return buserr.New(constant.ErrContainerName)
|
|
|
|
}
|
|
|
|
return client.ContainerRename(ctx, req.Name, req.NewName)
|
|
|
|
}
|
|
|
|
|
2024-06-14 08:18:39 +00:00
|
|
|
func (u *ContainerService) ContainerCommit(req dto.ContainerCommit) error {
|
|
|
|
ctx := context.Background()
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer client.Close()
|
|
|
|
options := container.CommitOptions{
|
|
|
|
Reference: req.NewImageName,
|
|
|
|
Comment: req.Comment,
|
|
|
|
Author: req.Author,
|
|
|
|
Changes: nil,
|
|
|
|
Pause: req.Pause,
|
|
|
|
Config: nil,
|
|
|
|
}
|
|
|
|
_, err = client.ContainerCommit(ctx, req.ContainerId, options)
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("failed to commit container, err: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-10-08 10:32:02 +00:00
|
|
|
func (u *ContainerService) ContainerOperation(req dto.ContainerOperation) error {
|
|
|
|
var err error
|
|
|
|
ctx := context.Background()
|
2022-10-13 10:24:24 +00:00
|
|
|
client, err := docker.NewDockerClient()
|
2022-10-08 10:32:02 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2023-10-26 10:20:16 +00:00
|
|
|
for _, item := range req.Names {
|
|
|
|
global.LOG.Infof("start container %s operation %s", item, req.Operation)
|
|
|
|
switch req.Operation {
|
|
|
|
case constant.ContainerOpStart:
|
2024-04-08 09:54:07 +00:00
|
|
|
err = client.ContainerStart(ctx, item, container.StartOptions{})
|
2023-10-26 10:20:16 +00:00
|
|
|
case constant.ContainerOpStop:
|
|
|
|
err = client.ContainerStop(ctx, item, container.StopOptions{})
|
|
|
|
case constant.ContainerOpRestart:
|
|
|
|
err = client.ContainerRestart(ctx, item, container.StopOptions{})
|
|
|
|
case constant.ContainerOpKill:
|
|
|
|
err = client.ContainerKill(ctx, item, "SIGKILL")
|
|
|
|
case constant.ContainerOpPause:
|
|
|
|
err = client.ContainerPause(ctx, item)
|
|
|
|
case constant.ContainerOpUnpause:
|
|
|
|
err = client.ContainerUnpause(ctx, item)
|
|
|
|
case constant.ContainerOpRemove:
|
2024-04-08 09:54:07 +00:00
|
|
|
err = client.ContainerRemove(ctx, item, container.RemoveOptions{RemoveVolumes: true, Force: true})
|
2023-07-05 08:48:25 +00:00
|
|
|
}
|
2022-10-08 10:32:02 +00:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2023-05-23 07:43:51 +00:00
|
|
|
func (u *ContainerService) ContainerLogClean(req dto.OperationWithName) error {
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2023-08-21 09:00:12 +00:00
|
|
|
ctx := context.Background()
|
|
|
|
containerItem, err := client.ContainerInspect(ctx, req.Name)
|
2023-05-23 07:43:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-08-21 09:00:12 +00:00
|
|
|
if err := client.ContainerStop(ctx, containerItem.ID, container.StopOptions{}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
file, err := os.OpenFile(containerItem.LogPath, os.O_RDWR|os.O_CREATE, 0666)
|
2023-05-23 07:43:51 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
if err = file.Truncate(0); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
_, _ = file.Seek(0, 0)
|
2023-07-12 06:33:19 +00:00
|
|
|
|
2023-08-21 09:00:12 +00:00
|
|
|
files, _ := filepath.Glob(fmt.Sprintf("%s.*", containerItem.LogPath))
|
2023-07-12 06:33:19 +00:00
|
|
|
for _, file := range files {
|
|
|
|
_ = os.Remove(file)
|
|
|
|
}
|
2023-08-21 09:00:12 +00:00
|
|
|
|
2024-04-08 09:54:07 +00:00
|
|
|
if err := client.ContainerStart(ctx, containerItem.ID, container.StartOptions{}); err != nil {
|
2023-08-21 09:00:12 +00:00
|
|
|
return err
|
|
|
|
}
|
2023-05-23 07:43:51 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-11-08 06:29:30 +00:00
|
|
|
func (u *ContainerService) ContainerLogs(wsConn *websocket.Conn, containerType, container, since, tail string, follow bool) error {
|
|
|
|
defer func() { wsConn.Close() }()
|
2023-07-17 08:34:29 +00:00
|
|
|
if cmd.CheckIllegal(container, since, tail) {
|
|
|
|
return buserr.New(constant.ErrCmdIllegal)
|
|
|
|
}
|
2024-04-10 14:18:08 +00:00
|
|
|
commandName := "docker"
|
|
|
|
commandArg := []string{"logs", container}
|
2023-11-08 06:29:30 +00:00
|
|
|
if containerType == "compose" {
|
2024-04-10 14:18:08 +00:00
|
|
|
commandName = "docker-compose"
|
|
|
|
commandArg = []string{"-f", container, "logs"}
|
2023-11-08 06:29:30 +00:00
|
|
|
}
|
2023-06-13 15:04:12 +00:00
|
|
|
if tail != "0" {
|
2024-04-10 14:18:08 +00:00
|
|
|
commandArg = append(commandArg, "--tail")
|
|
|
|
commandArg = append(commandArg, tail)
|
2022-10-08 10:32:02 +00:00
|
|
|
}
|
2023-06-13 15:04:12 +00:00
|
|
|
if since != "all" {
|
2024-04-10 14:18:08 +00:00
|
|
|
commandArg = append(commandArg, "--since")
|
|
|
|
commandArg = append(commandArg, since)
|
2023-06-13 15:04:12 +00:00
|
|
|
}
|
|
|
|
if follow {
|
2024-04-10 14:18:08 +00:00
|
|
|
commandArg = append(commandArg, "-f")
|
2023-06-13 15:04:12 +00:00
|
|
|
}
|
2023-11-08 06:29:30 +00:00
|
|
|
if !follow {
|
2024-04-10 14:18:08 +00:00
|
|
|
cmd := exec.Command(commandName, commandArg...)
|
2024-04-17 08:52:07 +00:00
|
|
|
cmd.Stderr = cmd.Stdout
|
2023-11-08 06:29:30 +00:00
|
|
|
stdout, _ := cmd.CombinedOutput()
|
2024-01-26 08:07:37 +00:00
|
|
|
if !utf8.Valid(stdout) {
|
|
|
|
return errors.New("invalid utf8")
|
|
|
|
}
|
2023-11-08 06:29:30 +00:00
|
|
|
if err := wsConn.WriteMessage(websocket.TextMessage, stdout); err != nil {
|
|
|
|
global.LOG.Errorf("send message with log to ws failed, err: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2024-04-10 14:18:08 +00:00
|
|
|
cmd := exec.Command(commandName, commandArg...)
|
2023-06-13 15:04:12 +00:00
|
|
|
stdout, err := cmd.StdoutPipe()
|
2023-03-09 10:42:17 +00:00
|
|
|
if err != nil {
|
2024-04-10 14:18:08 +00:00
|
|
|
_ = cmd.Process.Signal(syscall.SIGTERM)
|
2023-06-13 15:04:12 +00:00
|
|
|
return err
|
|
|
|
}
|
2024-04-17 08:52:07 +00:00
|
|
|
cmd.Stderr = cmd.Stdout
|
2023-06-13 15:04:12 +00:00
|
|
|
if err := cmd.Start(); err != nil {
|
2024-04-10 14:18:08 +00:00
|
|
|
_ = cmd.Process.Signal(syscall.SIGTERM)
|
2023-06-13 15:04:12 +00:00
|
|
|
return err
|
|
|
|
}
|
2024-04-10 14:18:08 +00:00
|
|
|
exitCh := make(chan struct{})
|
|
|
|
go func() {
|
|
|
|
_, wsData, _ := wsConn.ReadMessage()
|
|
|
|
if string(wsData) == "close conn" {
|
|
|
|
_ = cmd.Process.Signal(syscall.SIGTERM)
|
|
|
|
exitCh <- struct{}{}
|
|
|
|
}
|
2023-11-08 06:29:30 +00:00
|
|
|
}()
|
2024-04-10 14:18:08 +00:00
|
|
|
|
|
|
|
go func() {
|
|
|
|
buffer := make([]byte, 1024)
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-exitCh:
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
n, err := stdout.Read(buffer)
|
|
|
|
if err != nil {
|
|
|
|
if err == io.EOF {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
global.LOG.Errorf("read bytes from log failed, err: %v", err)
|
2024-04-19 07:18:10 +00:00
|
|
|
return
|
2024-04-10 14:18:08 +00:00
|
|
|
}
|
|
|
|
if !utf8.Valid(buffer[:n]) {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if err = wsConn.WriteMessage(websocket.TextMessage, buffer[:n]); err != nil {
|
|
|
|
global.LOG.Errorf("send message with log to ws failed, err: %v", err)
|
|
|
|
return
|
2023-11-08 06:29:30 +00:00
|
|
|
}
|
2023-06-13 15:04:12 +00:00
|
|
|
}
|
|
|
|
}
|
2024-04-10 14:18:08 +00:00
|
|
|
}()
|
|
|
|
_ = cmd.Wait()
|
|
|
|
return nil
|
2022-10-08 10:32:02 +00:00
|
|
|
}
|
2022-10-11 06:20:51 +00:00
|
|
|
|
2024-06-25 10:17:15 +00:00
|
|
|
func (u *ContainerService) DownloadContainerLogs(containerType, container, since, tail string, c *gin.Context) error {
|
|
|
|
if cmd.CheckIllegal(container, since, tail) {
|
|
|
|
return buserr.New(constant.ErrCmdIllegal)
|
|
|
|
}
|
|
|
|
commandName := "docker"
|
|
|
|
commandArg := []string{"logs", container}
|
|
|
|
if containerType == "compose" {
|
|
|
|
commandName = "docker-compose"
|
|
|
|
commandArg = []string{"-f", container, "logs"}
|
|
|
|
}
|
|
|
|
if tail != "0" {
|
|
|
|
commandArg = append(commandArg, "--tail")
|
|
|
|
commandArg = append(commandArg, tail)
|
|
|
|
}
|
|
|
|
if since != "all" {
|
|
|
|
commandArg = append(commandArg, "--since")
|
|
|
|
commandArg = append(commandArg, since)
|
|
|
|
}
|
|
|
|
|
|
|
|
cmd := exec.Command(commandName, commandArg...)
|
|
|
|
stdout, err := cmd.StdoutPipe()
|
|
|
|
if err != nil {
|
|
|
|
_ = cmd.Process.Signal(syscall.SIGTERM)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
cmd.Stderr = cmd.Stdout
|
|
|
|
if err := cmd.Start(); err != nil {
|
|
|
|
_ = cmd.Process.Signal(syscall.SIGTERM)
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
tempFile, err := os.CreateTemp("", "cmd_output_*.txt")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer tempFile.Close()
|
|
|
|
defer func() {
|
|
|
|
if err := os.Remove(tempFile.Name()); err != nil {
|
|
|
|
global.LOG.Errorf("os.Remove() failed: %v", err)
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
errCh := make(chan error)
|
|
|
|
go func() {
|
|
|
|
scanner := bufio.NewScanner(stdout)
|
|
|
|
for scanner.Scan() {
|
|
|
|
line := scanner.Text()
|
|
|
|
if _, err := tempFile.WriteString(line + "\n"); err != nil {
|
|
|
|
errCh <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
|
|
|
errCh <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
errCh <- nil
|
|
|
|
}()
|
|
|
|
select {
|
|
|
|
case err := <-errCh:
|
|
|
|
if err != nil {
|
|
|
|
global.LOG.Errorf("Error: %v", err)
|
|
|
|
}
|
|
|
|
case <-time.After(3 * time.Second):
|
|
|
|
global.LOG.Errorf("Timeout reached")
|
|
|
|
}
|
|
|
|
info, _ := tempFile.Stat()
|
|
|
|
|
|
|
|
c.Header("Content-Length", strconv.FormatInt(info.Size(), 10))
|
|
|
|
c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url.PathEscape(info.Name()))
|
|
|
|
http.ServeContent(c.Writer, c.Request, info.Name(), info.ModTime(), tempFile)
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2023-07-06 10:04:22 +00:00
|
|
|
func (u *ContainerService) ContainerStats(id string) (*dto.ContainerStats, error) {
|
2022-10-13 10:24:24 +00:00
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer client.Close()
|
2022-10-13 10:24:24 +00:00
|
|
|
res, err := client.ContainerStats(context.TODO(), id, false)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
2023-04-07 03:30:10 +00:00
|
|
|
body, err := io.ReadAll(res.Body)
|
2022-10-13 10:24:24 +00:00
|
|
|
if err != nil {
|
2023-04-25 14:06:17 +00:00
|
|
|
res.Body.Close()
|
2022-10-13 10:24:24 +00:00
|
|
|
return nil, err
|
|
|
|
}
|
2023-04-25 14:06:17 +00:00
|
|
|
res.Body.Close()
|
2022-10-13 10:24:24 +00:00
|
|
|
var stats *types.StatsJSON
|
|
|
|
if err := json.Unmarshal(body, &stats); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2023-07-06 10:04:22 +00:00
|
|
|
var data dto.ContainerStats
|
2023-04-25 14:06:17 +00:00
|
|
|
data.CPUPercent = calculateCPUPercentUnix(stats)
|
2022-10-13 10:24:24 +00:00
|
|
|
data.IORead, data.IOWrite = calculateBlockIO(stats.BlkioStats)
|
|
|
|
data.Memory = float64(stats.MemoryStats.Usage) / 1024 / 1024
|
|
|
|
if cache, ok := stats.MemoryStats.Stats["cache"]; ok {
|
|
|
|
data.Cache = float64(cache) / 1024 / 1024
|
|
|
|
}
|
|
|
|
data.NetworkRX, data.NetworkTX = calculateNetwork(stats.Networks)
|
|
|
|
data.ShotTime = stats.Read
|
|
|
|
return &data, nil
|
|
|
|
}
|
|
|
|
|
2023-08-09 03:18:12 +00:00
|
|
|
func (u *ContainerService) LoadContainerLogs(req dto.OperationWithNameAndType) string {
|
2023-08-02 08:47:30 +00:00
|
|
|
filePath := ""
|
2023-11-23 03:00:08 +00:00
|
|
|
if req.Type == "compose-detail" {
|
|
|
|
cli, err := docker.NewDockerClient()
|
2023-08-02 08:47:30 +00:00
|
|
|
if err != nil {
|
2023-08-09 03:18:12 +00:00
|
|
|
return ""
|
2023-08-02 08:47:30 +00:00
|
|
|
}
|
2024-04-25 08:45:12 +00:00
|
|
|
defer cli.Close()
|
2024-04-08 09:54:07 +00:00
|
|
|
options := container.ListOptions{All: true}
|
2023-08-02 08:47:30 +00:00
|
|
|
options.Filters = filters.NewArgs()
|
|
|
|
options.Filters.Add("label", fmt.Sprintf("%s=%s", composeProjectLabel, req.Name))
|
2023-11-23 03:00:08 +00:00
|
|
|
containers, err := cli.ContainerList(context.Background(), options)
|
2023-08-02 08:47:30 +00:00
|
|
|
if err != nil {
|
2023-08-09 03:18:12 +00:00
|
|
|
return ""
|
2023-08-02 08:47:30 +00:00
|
|
|
}
|
|
|
|
for _, container := range containers {
|
|
|
|
config := container.Labels[composeConfigLabel]
|
|
|
|
workdir := container.Labels[composeWorkdirLabel]
|
|
|
|
if len(config) != 0 && len(workdir) != 0 && strings.Contains(config, workdir) {
|
|
|
|
filePath = config
|
|
|
|
break
|
|
|
|
} else {
|
|
|
|
filePath = workdir
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if _, err := os.Stat(filePath); err != nil {
|
2023-08-09 03:18:12 +00:00
|
|
|
return ""
|
2023-08-02 08:47:30 +00:00
|
|
|
}
|
|
|
|
content, err := os.ReadFile(filePath)
|
|
|
|
if err != nil {
|
2023-08-09 03:18:12 +00:00
|
|
|
return ""
|
2023-08-02 08:47:30 +00:00
|
|
|
}
|
2023-08-09 03:18:12 +00:00
|
|
|
return string(content)
|
2023-08-02 08:47:30 +00:00
|
|
|
}
|
|
|
|
|
2022-10-11 06:20:51 +00:00
|
|
|
func stringsToMap(list []string) map[string]string {
|
2023-10-07 06:30:46 +00:00
|
|
|
var labelMap = make(map[string]string)
|
2022-10-11 06:20:51 +00:00
|
|
|
for _, label := range list {
|
2023-04-26 09:26:12 +00:00
|
|
|
if strings.Contains(label, "=") {
|
|
|
|
sps := strings.SplitN(label, "=", 2)
|
2023-10-07 06:30:46 +00:00
|
|
|
labelMap[sps[0]] = sps[1]
|
2022-10-11 06:20:51 +00:00
|
|
|
}
|
|
|
|
}
|
2023-10-07 06:30:46 +00:00
|
|
|
return labelMap
|
2022-10-11 06:20:51 +00:00
|
|
|
}
|
2023-04-25 14:06:17 +00:00
|
|
|
|
|
|
|
func calculateCPUPercentUnix(stats *types.StatsJSON) float64 {
|
|
|
|
cpuPercent := 0.0
|
|
|
|
cpuDelta := float64(stats.CPUStats.CPUUsage.TotalUsage) - float64(stats.PreCPUStats.CPUUsage.TotalUsage)
|
|
|
|
systemDelta := float64(stats.CPUStats.SystemUsage) - float64(stats.PreCPUStats.SystemUsage)
|
2022-10-13 10:24:24 +00:00
|
|
|
|
|
|
|
if systemDelta > 0.0 && cpuDelta > 0.0 {
|
2023-05-10 06:48:15 +00:00
|
|
|
cpuPercent = (cpuDelta / systemDelta) * 100.0
|
|
|
|
if len(stats.CPUStats.CPUUsage.PercpuUsage) != 0 {
|
|
|
|
cpuPercent = cpuPercent * float64(len(stats.CPUStats.CPUUsage.PercpuUsage))
|
|
|
|
}
|
2022-10-13 10:24:24 +00:00
|
|
|
}
|
|
|
|
return cpuPercent
|
|
|
|
}
|
2023-04-25 14:06:17 +00:00
|
|
|
func calculateMemPercentUnix(memStats types.MemoryStats) float64 {
|
|
|
|
memPercent := 0.0
|
2024-02-29 03:08:18 +00:00
|
|
|
memUsage := float64(memStats.Usage)
|
2023-04-25 14:06:17 +00:00
|
|
|
memLimit := float64(memStats.Limit)
|
|
|
|
if memUsage > 0.0 && memLimit > 0.0 {
|
|
|
|
memPercent = (memUsage / memLimit) * 100.0
|
|
|
|
}
|
|
|
|
return memPercent
|
|
|
|
}
|
2022-10-13 10:24:24 +00:00
|
|
|
func calculateBlockIO(blkio types.BlkioStats) (blkRead float64, blkWrite float64) {
|
|
|
|
for _, bioEntry := range blkio.IoServiceBytesRecursive {
|
|
|
|
switch strings.ToLower(bioEntry.Op) {
|
|
|
|
case "read":
|
|
|
|
blkRead = (blkRead + float64(bioEntry.Value)) / 1024 / 1024
|
|
|
|
case "write":
|
|
|
|
blkWrite = (blkWrite + float64(bioEntry.Value)) / 1024 / 1024
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
func calculateNetwork(network map[string]types.NetworkStats) (float64, float64) {
|
|
|
|
var rx, tx float64
|
|
|
|
|
|
|
|
for _, v := range network {
|
|
|
|
rx += float64(v.RxBytes) / 1024
|
|
|
|
tx += float64(v.TxBytes) / 1024
|
|
|
|
}
|
|
|
|
return rx, tx
|
|
|
|
}
|
2023-03-28 11:02:11 +00:00
|
|
|
|
2024-05-22 10:32:47 +00:00
|
|
|
func checkImageExist(client *client.Client, imageItem string) bool {
|
|
|
|
images, err := client.ImageList(context.Background(), image.ListOptions{})
|
2023-04-17 08:08:28 +00:00
|
|
|
if err != nil {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, img := range images {
|
|
|
|
for _, tag := range img.RepoTags {
|
2024-05-22 10:32:47 +00:00
|
|
|
if tag == imageItem || tag == imageItem+":latest" {
|
2023-04-17 08:08:28 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2024-06-26 06:28:49 +00:00
|
|
|
func pullImages(ctx context.Context, client *client.Client, imageName string) error {
|
|
|
|
options := image.PullOptions{}
|
2023-12-14 04:02:11 +00:00
|
|
|
repos, _ := imageRepoRepo.List()
|
|
|
|
if len(repos) != 0 {
|
|
|
|
for _, repo := range repos {
|
2024-06-26 06:28:49 +00:00
|
|
|
if strings.HasPrefix(imageName, repo.DownloadUrl) && repo.Auth {
|
2023-12-14 04:02:11 +00:00
|
|
|
authConfig := registry.AuthConfig{
|
|
|
|
Username: repo.Username,
|
|
|
|
Password: repo.Password,
|
|
|
|
}
|
|
|
|
encodedJSON, err := json.Marshal(authConfig)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
authStr := base64.URLEncoding.EncodeToString(encodedJSON)
|
|
|
|
options.RegistryAuth = authStr
|
|
|
|
}
|
|
|
|
}
|
2024-06-26 06:28:49 +00:00
|
|
|
} else {
|
|
|
|
hasAuth, authStr := loadAuthInfo(imageName)
|
|
|
|
if hasAuth {
|
|
|
|
options.RegistryAuth = authStr
|
|
|
|
}
|
2023-12-14 04:02:11 +00:00
|
|
|
}
|
2024-06-26 06:28:49 +00:00
|
|
|
out, err := client.ImagePull(ctx, imageName, options)
|
2023-03-28 11:02:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer out.Close()
|
2023-04-07 03:30:10 +00:00
|
|
|
_, err = io.Copy(io.Discard, out)
|
2023-03-28 11:02:11 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2023-04-25 14:06:17 +00:00
|
|
|
|
2023-09-21 09:34:22 +00:00
|
|
|
func loadCpuAndMem(client *client.Client, container string) dto.ContainerListStats {
|
|
|
|
data := dto.ContainerListStats{
|
|
|
|
ContainerID: container,
|
|
|
|
}
|
2023-04-25 14:06:17 +00:00
|
|
|
res, err := client.ContainerStats(context.Background(), container, false)
|
|
|
|
if err != nil {
|
2023-09-21 09:34:22 +00:00
|
|
|
return data
|
2023-04-25 14:06:17 +00:00
|
|
|
}
|
|
|
|
|
2024-04-25 08:45:12 +00:00
|
|
|
defer res.Body.Close()
|
2023-04-25 14:06:17 +00:00
|
|
|
body, err := io.ReadAll(res.Body)
|
|
|
|
if err != nil {
|
2023-09-21 09:34:22 +00:00
|
|
|
return data
|
2023-04-25 14:06:17 +00:00
|
|
|
}
|
|
|
|
var stats *types.StatsJSON
|
|
|
|
if err := json.Unmarshal(body, &stats); err != nil {
|
2023-09-21 09:34:22 +00:00
|
|
|
return data
|
2023-04-25 14:06:17 +00:00
|
|
|
}
|
|
|
|
|
2023-09-21 09:34:22 +00:00
|
|
|
data.CPUTotalUsage = stats.CPUStats.CPUUsage.TotalUsage - stats.PreCPUStats.CPUUsage.TotalUsage
|
|
|
|
data.SystemUsage = stats.CPUStats.SystemUsage - stats.PreCPUStats.SystemUsage
|
|
|
|
data.CPUPercent = calculateCPUPercentUnix(stats)
|
|
|
|
data.PercpuUsage = len(stats.CPUStats.CPUUsage.PercpuUsage)
|
|
|
|
|
2023-10-07 06:30:46 +00:00
|
|
|
data.MemoryCache = stats.MemoryStats.Stats["cache"]
|
2023-09-21 09:34:22 +00:00
|
|
|
data.MemoryUsage = stats.MemoryStats.Usage
|
|
|
|
data.MemoryLimit = stats.MemoryStats.Limit
|
2024-02-29 03:08:18 +00:00
|
|
|
|
2023-09-21 09:34:22 +00:00
|
|
|
data.MemoryPercent = calculateMemPercentUnix(stats.MemoryStats)
|
|
|
|
return data
|
2023-04-25 14:06:17 +00:00
|
|
|
}
|
2023-04-28 14:46:20 +00:00
|
|
|
|
|
|
|
func checkPortStats(ports []dto.PortHelper) (nat.PortMap, error) {
|
|
|
|
portMap := make(nat.PortMap)
|
|
|
|
if len(ports) == 0 {
|
|
|
|
return portMap, nil
|
|
|
|
}
|
|
|
|
for _, port := range ports {
|
2023-05-05 03:17:28 +00:00
|
|
|
if strings.Contains(port.ContainerPort, "-") {
|
|
|
|
if !strings.Contains(port.HostPort, "-") {
|
2023-04-28 14:46:20 +00:00
|
|
|
return portMap, buserr.New(constant.ErrPortRules)
|
|
|
|
}
|
|
|
|
hostStart, _ := strconv.Atoi(strings.Split(port.HostPort, "-")[0])
|
|
|
|
hostEnd, _ := strconv.Atoi(strings.Split(port.HostPort, "-")[1])
|
|
|
|
containerStart, _ := strconv.Atoi(strings.Split(port.ContainerPort, "-")[0])
|
|
|
|
containerEnd, _ := strconv.Atoi(strings.Split(port.ContainerPort, "-")[1])
|
|
|
|
if (hostEnd-hostStart) <= 0 || (containerEnd-containerStart) <= 0 {
|
|
|
|
return portMap, buserr.New(constant.ErrPortRules)
|
|
|
|
}
|
|
|
|
if (containerEnd - containerStart) != (hostEnd - hostStart) {
|
|
|
|
return portMap, buserr.New(constant.ErrPortRules)
|
|
|
|
}
|
|
|
|
for i := 0; i <= hostEnd-hostStart; i++ {
|
|
|
|
bindItem := nat.PortBinding{HostPort: strconv.Itoa(hostStart + i), HostIP: port.HostIP}
|
|
|
|
portMap[nat.Port(fmt.Sprintf("%d/%s", containerStart+i, port.Protocol))] = []nat.PortBinding{bindItem}
|
|
|
|
}
|
|
|
|
for i := hostStart; i <= hostEnd; i++ {
|
|
|
|
if common.ScanPort(i) {
|
|
|
|
return portMap, buserr.WithDetail(constant.ErrPortInUsed, i, nil)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2023-05-05 03:17:28 +00:00
|
|
|
portItem := 0
|
|
|
|
if strings.Contains(port.HostPort, "-") {
|
|
|
|
portItem, _ = strconv.Atoi(strings.Split(port.HostPort, "-")[0])
|
|
|
|
} else {
|
|
|
|
portItem, _ = strconv.Atoi(port.HostPort)
|
|
|
|
}
|
2023-04-28 14:46:20 +00:00
|
|
|
if common.ScanPort(portItem) {
|
|
|
|
return portMap, buserr.WithDetail(constant.ErrPortInUsed, portItem, nil)
|
|
|
|
}
|
|
|
|
bindItem := nat.PortBinding{HostPort: strconv.Itoa(portItem), HostIP: port.HostIP}
|
|
|
|
portMap[nat.Port(fmt.Sprintf("%s/%s", port.ContainerPort, port.Protocol))] = []nat.PortBinding{bindItem}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return portMap, nil
|
|
|
|
}
|
2023-06-15 03:00:11 +00:00
|
|
|
|
2023-10-12 03:50:31 +00:00
|
|
|
func loadConfigInfo(isCreate bool, req dto.ContainerOperate, oldContainer *types.ContainerJSON) (*container.Config, *container.HostConfig, *network.NetworkingConfig, error) {
|
|
|
|
var config container.Config
|
|
|
|
var hostConf container.HostConfig
|
|
|
|
if !isCreate {
|
|
|
|
config = *oldContainer.Config
|
|
|
|
hostConf = *oldContainer.HostConfig
|
|
|
|
}
|
|
|
|
var networkConf network.NetworkingConfig
|
|
|
|
|
2023-06-15 03:00:11 +00:00
|
|
|
portMap, err := checkPortStats(req.ExposedPorts)
|
|
|
|
if err != nil {
|
2023-10-12 03:50:31 +00:00
|
|
|
return nil, nil, nil, err
|
2023-06-15 03:00:11 +00:00
|
|
|
}
|
2023-10-07 06:30:46 +00:00
|
|
|
exposed := make(nat.PortSet)
|
2023-06-15 03:00:11 +00:00
|
|
|
for port := range portMap {
|
2023-10-07 06:30:46 +00:00
|
|
|
exposed[port] = struct{}{}
|
2023-06-15 03:00:11 +00:00
|
|
|
}
|
|
|
|
config.Image = req.Image
|
|
|
|
config.Cmd = req.Cmd
|
2023-09-07 08:24:10 +00:00
|
|
|
config.Entrypoint = req.Entrypoint
|
2023-06-15 03:00:11 +00:00
|
|
|
config.Env = req.Env
|
|
|
|
config.Labels = stringsToMap(req.Labels)
|
2023-10-07 06:30:46 +00:00
|
|
|
config.ExposedPorts = exposed
|
|
|
|
config.OpenStdin = req.OpenStdin
|
|
|
|
config.Tty = req.Tty
|
2023-06-15 03:00:11 +00:00
|
|
|
|
2023-07-27 05:58:13 +00:00
|
|
|
if len(req.Network) != 0 {
|
2023-10-17 09:56:25 +00:00
|
|
|
switch req.Network {
|
|
|
|
case "host", "none", "bridge":
|
|
|
|
hostConf.NetworkMode = container.NetworkMode(req.Network)
|
|
|
|
}
|
2024-04-13 11:56:07 +00:00
|
|
|
if req.Ipv4 != "" || req.Ipv6 != "" {
|
|
|
|
networkConf.EndpointsConfig = map[string]*network.EndpointSettings{
|
|
|
|
req.Network: {
|
|
|
|
IPAMConfig: &network.EndpointIPAMConfig{
|
|
|
|
IPv4Address: req.Ipv4,
|
|
|
|
IPv6Address: req.Ipv6,
|
|
|
|
},
|
|
|
|
}}
|
|
|
|
} else {
|
|
|
|
networkConf.EndpointsConfig = map[string]*network.EndpointSettings{req.Network: {}}
|
|
|
|
}
|
2023-07-27 05:58:13 +00:00
|
|
|
} else {
|
2024-04-13 11:56:07 +00:00
|
|
|
if req.Ipv4 != "" || req.Ipv6 != "" {
|
2024-06-28 06:04:08 +00:00
|
|
|
return nil, nil, nil, fmt.Errorf("please set up the network")
|
2024-04-13 11:56:07 +00:00
|
|
|
}
|
2023-10-12 03:50:31 +00:00
|
|
|
networkConf = network.NetworkingConfig{}
|
2023-07-27 05:58:13 +00:00
|
|
|
}
|
2023-07-07 15:17:05 +00:00
|
|
|
|
2023-11-22 05:58:08 +00:00
|
|
|
hostConf.Privileged = req.Privileged
|
2023-06-15 03:00:11 +00:00
|
|
|
hostConf.AutoRemove = req.AutoRemove
|
2023-06-16 09:54:11 +00:00
|
|
|
hostConf.CPUShares = req.CPUShares
|
2023-06-15 03:00:11 +00:00
|
|
|
hostConf.PublishAllPorts = req.PublishAllPorts
|
2024-02-06 08:36:13 +00:00
|
|
|
hostConf.RestartPolicy = container.RestartPolicy{Name: container.RestartPolicyMode(req.RestartPolicy)}
|
2023-06-15 03:00:11 +00:00
|
|
|
if req.RestartPolicy == "on-failure" {
|
|
|
|
hostConf.RestartPolicy.MaximumRetryCount = 5
|
|
|
|
}
|
2023-07-10 06:45:08 +00:00
|
|
|
hostConf.NanoCPUs = int64(req.NanoCPUs * 1000000000)
|
|
|
|
hostConf.Memory = int64(req.Memory * 1024 * 1024)
|
2023-10-20 06:16:45 +00:00
|
|
|
hostConf.MemorySwap = 0
|
2023-07-10 06:45:08 +00:00
|
|
|
hostConf.PortBindings = portMap
|
2023-06-15 03:00:11 +00:00
|
|
|
hostConf.Binds = []string{}
|
2024-04-02 09:14:45 +00:00
|
|
|
hostConf.Mounts = []mount.Mount{}
|
2023-07-10 06:45:08 +00:00
|
|
|
config.Volumes = make(map[string]struct{})
|
|
|
|
for _, volume := range req.Volumes {
|
2024-04-02 09:14:45 +00:00
|
|
|
if volume.Type == "volume" {
|
|
|
|
hostConf.Mounts = append(hostConf.Mounts, mount.Mount{
|
|
|
|
Type: mount.Type(volume.Type),
|
|
|
|
Source: volume.SourceDir,
|
|
|
|
Target: volume.ContainerDir,
|
|
|
|
})
|
|
|
|
config.Volumes[volume.ContainerDir] = struct{}{}
|
|
|
|
} else {
|
|
|
|
hostConf.Binds = append(hostConf.Binds, fmt.Sprintf("%s:%s:%s", volume.SourceDir, volume.ContainerDir, volume.Mode))
|
|
|
|
}
|
2023-06-15 03:00:11 +00:00
|
|
|
}
|
2023-10-12 03:50:31 +00:00
|
|
|
return &config, &hostConf, &networkConf, nil
|
2023-06-15 03:00:11 +00:00
|
|
|
}
|
2023-07-27 05:58:13 +00:00
|
|
|
|
|
|
|
func reCreateAfterUpdate(name string, client *client.Client, config *container.Config, hostConf *container.HostConfig, networkConf *types.NetworkSettings) {
|
|
|
|
ctx := context.Background()
|
|
|
|
|
|
|
|
var oldNetworkConf network.NetworkingConfig
|
|
|
|
if networkConf != nil {
|
|
|
|
for networkKey := range networkConf.Networks {
|
|
|
|
oldNetworkConf.EndpointsConfig = map[string]*network.EndpointSettings{networkKey: {}}
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
oldContainer, err := client.ContainerCreate(ctx, config, hostConf, &oldNetworkConf, &v1.Platform{}, name)
|
|
|
|
if err != nil {
|
|
|
|
global.LOG.Errorf("recreate after container update failed, err: %v", err)
|
|
|
|
return
|
|
|
|
}
|
2024-04-08 09:54:07 +00:00
|
|
|
if err := client.ContainerStart(ctx, oldContainer.ID, container.StartOptions{}); err != nil {
|
2023-07-27 05:58:13 +00:00
|
|
|
global.LOG.Errorf("restart after container update failed, err: %v", err)
|
|
|
|
}
|
2024-08-26 08:07:13 +00:00
|
|
|
global.LOG.Info("recreate after container update successful")
|
2023-07-27 05:58:13 +00:00
|
|
|
}
|
2023-07-28 10:26:02 +00:00
|
|
|
|
2024-04-02 09:14:45 +00:00
|
|
|
func loadVolumeBinds(binds []types.MountPoint) []dto.VolumeHelper {
|
2023-07-28 10:26:02 +00:00
|
|
|
var datas []dto.VolumeHelper
|
|
|
|
for _, bind := range binds {
|
|
|
|
var volumeItem dto.VolumeHelper
|
2024-04-02 09:14:45 +00:00
|
|
|
volumeItem.Type = string(bind.Type)
|
|
|
|
if bind.Type == "volume" {
|
|
|
|
volumeItem.SourceDir = bind.Name
|
|
|
|
} else {
|
|
|
|
volumeItem.SourceDir = bind.Source
|
2023-07-28 10:26:02 +00:00
|
|
|
}
|
2024-04-02 09:14:45 +00:00
|
|
|
volumeItem.ContainerDir = bind.Destination
|
|
|
|
volumeItem.Mode = "ro"
|
|
|
|
if bind.RW {
|
2023-07-28 10:26:02 +00:00
|
|
|
volumeItem.Mode = "rw"
|
|
|
|
}
|
|
|
|
datas = append(datas, volumeItem)
|
|
|
|
}
|
|
|
|
return datas
|
|
|
|
}
|
2023-09-05 09:32:15 +00:00
|
|
|
|
2023-12-11 06:06:06 +00:00
|
|
|
func loadContainerPort(ports []types.Port) []string {
|
|
|
|
var (
|
|
|
|
ipv4Ports []types.Port
|
|
|
|
ipv6Ports []types.Port
|
|
|
|
)
|
|
|
|
for _, port := range ports {
|
|
|
|
if strings.Contains(port.IP, ":") {
|
|
|
|
ipv6Ports = append(ipv6Ports, port)
|
|
|
|
} else {
|
|
|
|
ipv4Ports = append(ipv4Ports, port)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
list1 := simplifyPort(ipv4Ports)
|
|
|
|
list2 := simplifyPort(ipv6Ports)
|
|
|
|
return append(list1, list2...)
|
|
|
|
}
|
2023-09-05 09:32:15 +00:00
|
|
|
func simplifyPort(ports []types.Port) []string {
|
|
|
|
var datas []string
|
|
|
|
if len(ports) == 0 {
|
|
|
|
return datas
|
|
|
|
}
|
|
|
|
if len(ports) == 1 {
|
2023-10-08 09:04:18 +00:00
|
|
|
ip := ""
|
|
|
|
if len(ports[0].IP) != 0 {
|
|
|
|
ip = ports[0].IP + ":"
|
|
|
|
}
|
|
|
|
itemPortStr := fmt.Sprintf("%s%v/%s", ip, ports[0].PrivatePort, ports[0].Type)
|
2023-09-05 09:32:15 +00:00
|
|
|
if ports[0].PublicPort != 0 {
|
2023-10-08 09:04:18 +00:00
|
|
|
itemPortStr = fmt.Sprintf("%s%v->%v/%s", ip, ports[0].PublicPort, ports[0].PrivatePort, ports[0].Type)
|
2023-09-05 09:32:15 +00:00
|
|
|
}
|
|
|
|
datas = append(datas, itemPortStr)
|
|
|
|
return datas
|
|
|
|
}
|
|
|
|
|
|
|
|
sort.Slice(ports, func(i, j int) bool {
|
|
|
|
return ports[i].PrivatePort < ports[j].PrivatePort
|
|
|
|
})
|
|
|
|
start := ports[0]
|
|
|
|
|
|
|
|
for i := 1; i < len(ports); i++ {
|
|
|
|
if ports[i].PrivatePort != ports[i-1].PrivatePort+1 || ports[i].IP != ports[i-1].IP || ports[i].PublicPort != ports[i-1].PublicPort+1 || ports[i].Type != ports[i-1].Type {
|
|
|
|
if ports[i-1].PrivatePort == start.PrivatePort {
|
|
|
|
itemPortStr := fmt.Sprintf("%s:%v/%s", start.IP, start.PrivatePort, start.Type)
|
|
|
|
if start.PublicPort != 0 {
|
|
|
|
itemPortStr = fmt.Sprintf("%s:%v->%v/%s", start.IP, start.PublicPort, start.PrivatePort, start.Type)
|
|
|
|
}
|
2023-12-13 02:30:09 +00:00
|
|
|
if len(start.IP) == 0 {
|
|
|
|
itemPortStr = strings.TrimPrefix(itemPortStr, ":")
|
|
|
|
}
|
|
|
|
datas = append(datas, itemPortStr)
|
2023-09-05 09:32:15 +00:00
|
|
|
} else {
|
|
|
|
itemPortStr := fmt.Sprintf("%s:%v-%v/%s", start.IP, start.PrivatePort, ports[i-1].PrivatePort, start.Type)
|
|
|
|
if start.PublicPort != 0 {
|
|
|
|
itemPortStr = fmt.Sprintf("%s:%v-%v->%v-%v/%s", start.IP, start.PublicPort, ports[i-1].PublicPort, start.PrivatePort, ports[i-1].PrivatePort, start.Type)
|
|
|
|
}
|
2023-12-13 02:30:09 +00:00
|
|
|
if len(start.IP) == 0 {
|
|
|
|
itemPortStr = strings.TrimPrefix(itemPortStr, ":")
|
|
|
|
}
|
|
|
|
datas = append(datas, itemPortStr)
|
2023-09-05 09:32:15 +00:00
|
|
|
}
|
|
|
|
start = ports[i]
|
2023-10-31 10:03:51 +00:00
|
|
|
}
|
|
|
|
if i == len(ports)-1 {
|
2023-09-05 09:32:15 +00:00
|
|
|
if ports[i].PrivatePort == start.PrivatePort {
|
|
|
|
itemPortStr := fmt.Sprintf("%s:%v/%s", start.IP, start.PrivatePort, start.Type)
|
|
|
|
if start.PublicPort != 0 {
|
|
|
|
itemPortStr = fmt.Sprintf("%s:%v->%v/%s", start.IP, start.PublicPort, start.PrivatePort, start.Type)
|
|
|
|
}
|
2023-12-13 02:30:09 +00:00
|
|
|
if len(start.IP) == 0 {
|
|
|
|
itemPortStr = strings.TrimPrefix(itemPortStr, ":")
|
|
|
|
}
|
|
|
|
datas = append(datas, itemPortStr)
|
2023-09-05 09:32:15 +00:00
|
|
|
} else {
|
|
|
|
itemPortStr := fmt.Sprintf("%s:%v-%v/%s", start.IP, start.PrivatePort, ports[i].PrivatePort, start.Type)
|
|
|
|
if start.PublicPort != 0 {
|
|
|
|
itemPortStr = fmt.Sprintf("%s:%v-%v->%v-%v/%s", start.IP, start.PublicPort, ports[i].PublicPort, start.PrivatePort, ports[i].PrivatePort, start.Type)
|
|
|
|
}
|
2023-12-13 02:30:09 +00:00
|
|
|
if len(start.IP) == 0 {
|
|
|
|
itemPortStr = strings.TrimPrefix(itemPortStr, ":")
|
|
|
|
}
|
|
|
|
datas = append(datas, itemPortStr)
|
2023-09-05 09:32:15 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return datas
|
|
|
|
}
|
2024-08-26 08:07:13 +00:00
|
|
|
|
|
|
|
func loadContainerPortForInfo(id string, client *client.Client) ([]dto.PortHelper, error) {
|
|
|
|
var exposedPorts []dto.PortHelper
|
|
|
|
containers, err := client.ContainerList(context.Background(), container.ListOptions{})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
samePortMap := make(map[string]dto.PortHelper)
|
|
|
|
for _, container := range containers {
|
|
|
|
if container.ID == id {
|
|
|
|
ports := loadContainerPort(container.Ports)
|
|
|
|
var itemPort dto.PortHelper
|
|
|
|
for _, item := range ports {
|
|
|
|
itemStr := strings.Split(item, "->")
|
|
|
|
if len(itemStr) < 2 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
lastIndex := strings.LastIndex(itemStr[0], ":")
|
|
|
|
if lastIndex == -1 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
itemContainer := strings.Split(itemStr[1], "/")
|
|
|
|
if len(itemContainer) != 2 {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
itemPort.HostIP = itemStr[0][0:lastIndex]
|
|
|
|
itemPort.HostPort = itemStr[0][lastIndex+1:]
|
|
|
|
itemPort.ContainerPort = itemContainer[0]
|
|
|
|
itemPort.Protocol = itemContainer[1]
|
|
|
|
keyItem := fmt.Sprintf("%s->%s/%s", itemPort.HostPort, itemPort.ContainerPort, itemPort.Protocol)
|
|
|
|
if val, ok := samePortMap[keyItem]; ok {
|
|
|
|
val.HostIP = ""
|
|
|
|
samePortMap[keyItem] = val
|
|
|
|
} else {
|
|
|
|
samePortMap[keyItem] = itemPort
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
for _, val := range samePortMap {
|
|
|
|
exposedPorts = append(exposedPorts, val)
|
|
|
|
}
|
|
|
|
return exposedPorts, nil
|
|
|
|
}
|