2022-10-08 18:32:02 +08:00
|
|
|
package service
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2023-03-23 16:24:36 +08:00
|
|
|
"errors"
|
2022-10-11 14:20:51 +08:00
|
|
|
"fmt"
|
2023-03-28 19:02:11 +08:00
|
|
|
"io"
|
2023-03-09 18:42:17 +08:00
|
|
|
"os/exec"
|
2022-12-06 18:24:26 +08:00
|
|
|
"sort"
|
2022-10-12 18:55:47 +08:00
|
|
|
"strconv"
|
2022-10-08 18:32:02 +08:00
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
|
2022-10-18 18:39:45 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/app/dto"
|
2023-03-13 23:49:31 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/buserr"
|
2022-10-18 18:39:45 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/constant"
|
2022-12-28 18:35:53 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/global"
|
2023-03-13 23:49:31 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/utils/common"
|
2022-10-18 18:39:45 +08:00
|
|
|
"github.com/1Panel-dev/1Panel/backend/utils/docker"
|
2022-10-08 18:32:02 +08:00
|
|
|
"github.com/docker/docker/api/types"
|
2022-10-12 18:55:47 +08:00
|
|
|
"github.com/docker/docker/api/types/container"
|
2022-10-11 14:20:51 +08:00
|
|
|
"github.com/docker/docker/api/types/filters"
|
|
|
|
"github.com/docker/docker/api/types/network"
|
2023-03-28 19:02:11 +08:00
|
|
|
"github.com/docker/docker/client"
|
2022-10-12 18:55:47 +08:00
|
|
|
"github.com/docker/go-connections/nat"
|
|
|
|
v1 "github.com/opencontainers/image-spec/specs-go/v1"
|
2022-10-08 18:32:02 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
type ContainerService struct{}
|
|
|
|
|
|
|
|
type IContainerService interface {
|
|
|
|
Page(req dto.PageContainer) (int64, interface{}, error)
|
2023-02-07 18:48:32 +08:00
|
|
|
PageNetwork(req dto.SearchWithPage) (int64, interface{}, error)
|
|
|
|
PageVolume(req dto.SearchWithPage) (int64, interface{}, error)
|
2022-10-12 18:55:47 +08:00
|
|
|
ListVolume() ([]dto.Options, error)
|
2023-02-07 18:48:32 +08:00
|
|
|
PageCompose(req dto.SearchWithPage) (int64, interface{}, error)
|
2023-03-20 18:16:26 +08:00
|
|
|
CreateCompose(req dto.ComposeCreate) (string, error)
|
2022-10-17 16:04:39 +08:00
|
|
|
ComposeOperation(req dto.ComposeOperation) error
|
2022-10-12 18:55:47 +08:00
|
|
|
ContainerCreate(req dto.ContainerCreate) error
|
2022-10-08 18:32:02 +08:00
|
|
|
ContainerOperation(req dto.ContainerOperation) error
|
|
|
|
ContainerLogs(param dto.ContainerLog) (string, error)
|
2022-10-13 18:24:24 +08:00
|
|
|
ContainerStats(id string) (*dto.ContainterStats, error)
|
2022-10-11 19:47:16 +08:00
|
|
|
Inspect(req dto.InspectReq) (string, error)
|
2022-10-11 14:20:51 +08:00
|
|
|
DeleteNetwork(req dto.BatchDelete) error
|
|
|
|
CreateNetwork(req dto.NetworkCreat) error
|
|
|
|
DeleteVolume(req dto.BatchDelete) error
|
|
|
|
CreateVolume(req dto.VolumeCreat) error
|
2023-03-28 18:00:06 +08:00
|
|
|
TestCompose(req dto.ComposeCreate) (bool, error)
|
|
|
|
ComposeUpdate(req dto.ComposeUpdate) error
|
2022-10-08 18:32:02 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewIContainerService() IContainerService {
|
|
|
|
return &ContainerService{}
|
|
|
|
}
|
2022-10-11 14:20:51 +08:00
|
|
|
|
2022-10-08 18:32:02 +08:00
|
|
|
func (u *ContainerService) Page(req dto.PageContainer) (int64, interface{}, error) {
|
|
|
|
var (
|
|
|
|
records []types.Container
|
|
|
|
list []types.Container
|
|
|
|
backDatas []dto.ContainerInfo
|
|
|
|
)
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
2022-10-17 16:04:39 +08:00
|
|
|
options := types.ContainerListOptions{All: true}
|
|
|
|
if len(req.Filters) != 0 {
|
|
|
|
options.Filters = filters.NewArgs()
|
|
|
|
options.Filters.Add("label", req.Filters)
|
|
|
|
}
|
|
|
|
list, err = client.ContainerList(context.Background(), options)
|
2022-10-08 18:32:02 +08:00
|
|
|
if err != nil {
|
|
|
|
return 0, nil, err
|
|
|
|
}
|
2023-02-07 18:48:32 +08:00
|
|
|
if len(req.Name) != 0 {
|
|
|
|
lenth, count := len(list), 0
|
|
|
|
for count < lenth {
|
|
|
|
if !strings.Contains(list[count].Names[0][1:], req.Name) {
|
|
|
|
list = append(list[:count], list[(count+1):]...)
|
|
|
|
lenth--
|
|
|
|
} else {
|
|
|
|
count++
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-12-06 18:24:26 +08:00
|
|
|
sort.Slice(list, func(i, j int) bool {
|
|
|
|
return list[i].Created > list[j].Created
|
|
|
|
})
|
2022-10-08 18:32:02 +08: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]
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, container := range records {
|
2023-02-17 17:59:45 +08:00
|
|
|
IsFromCompose := false
|
|
|
|
if _, ok := container.Labels[composeProjectLabel]; ok {
|
|
|
|
IsFromCompose = true
|
|
|
|
}
|
2023-03-15 16:48:26 +08:00
|
|
|
IsFromApp := false
|
|
|
|
if created, ok := container.Labels[composeCreatedBy]; ok && created == "Apps" {
|
|
|
|
IsFromApp = true
|
|
|
|
}
|
2022-10-08 18:32:02 +08:00
|
|
|
backDatas = append(backDatas, dto.ContainerInfo{
|
2023-02-17 17:59:45 +08:00
|
|
|
ContainerID: container.ID,
|
|
|
|
CreateTime: time.Unix(container.Created, 0).Format("2006-01-02 15:04:05"),
|
|
|
|
Name: container.Names[0][1:],
|
|
|
|
ImageId: strings.Split(container.ImageID, ":")[1],
|
|
|
|
ImageName: container.Image,
|
|
|
|
State: container.State,
|
|
|
|
RunTime: container.Status,
|
2023-03-15 16:48:26 +08:00
|
|
|
IsFromApp: IsFromApp,
|
2023-02-17 17:59:45 +08:00
|
|
|
IsFromCompose: IsFromCompose,
|
2022-10-08 18:32:02 +08:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
return int64(total), backDatas, nil
|
|
|
|
}
|
|
|
|
|
2022-10-11 19:47:16 +08:00
|
|
|
func (u *ContainerService) Inspect(req dto.InspectReq) (string, error) {
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
var inspectInfo interface{}
|
|
|
|
switch req.Type {
|
|
|
|
case "container":
|
|
|
|
inspectInfo, err = client.ContainerInspect(context.Background(), req.ID)
|
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2022-10-12 18:55:47 +08:00
|
|
|
func (u *ContainerService) ContainerCreate(req dto.ContainerCreate) error {
|
2023-03-13 23:49:31 +08:00
|
|
|
if len(req.ExposedPorts) != 0 {
|
|
|
|
for _, port := range req.ExposedPorts {
|
|
|
|
if common.ScanPort(port.HostPort) {
|
|
|
|
return buserr.WithDetail(constant.ErrPortInUsed, port.HostPort, nil)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-10-12 18:55:47 +08:00
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
config := &container.Config{
|
2023-03-28 17:50:11 +08:00
|
|
|
Image: req.Image,
|
|
|
|
Cmd: req.Cmd,
|
|
|
|
Env: req.Env,
|
|
|
|
Labels: stringsToMap(req.Labels),
|
|
|
|
Tty: true,
|
|
|
|
OpenStdin: true,
|
2022-10-12 18:55:47 +08:00
|
|
|
}
|
|
|
|
hostConf := &container.HostConfig{
|
|
|
|
AutoRemove: req.AutoRemove,
|
|
|
|
PublishAllPorts: req.PublishAllPorts,
|
|
|
|
RestartPolicy: container.RestartPolicy{Name: req.RestartPolicy},
|
|
|
|
}
|
|
|
|
if req.RestartPolicy == "on-failure" {
|
|
|
|
hostConf.RestartPolicy.MaximumRetryCount = 5
|
|
|
|
}
|
|
|
|
if req.NanoCPUs != 0 {
|
|
|
|
hostConf.NanoCPUs = req.NanoCPUs * 1000000000
|
|
|
|
}
|
|
|
|
if req.Memory != 0 {
|
|
|
|
hostConf.Memory = req.Memory
|
|
|
|
}
|
|
|
|
if len(req.ExposedPorts) != 0 {
|
|
|
|
hostConf.PortBindings = make(nat.PortMap)
|
|
|
|
for _, port := range req.ExposedPorts {
|
|
|
|
bindItem := nat.PortBinding{HostPort: strconv.Itoa(port.HostPort)}
|
|
|
|
hostConf.PortBindings[nat.Port(fmt.Sprintf("%d/tcp", port.ContainerPort))] = []nat.PortBinding{bindItem}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if len(req.Volumes) != 0 {
|
|
|
|
config.Volumes = make(map[string]struct{})
|
|
|
|
for _, volume := range req.Volumes {
|
|
|
|
config.Volumes[volume.ContainerDir] = struct{}{}
|
|
|
|
hostConf.Binds = append(hostConf.Binds, fmt.Sprintf("%s:%s:%s", volume.SourceDir, volume.ContainerDir, volume.Mode))
|
|
|
|
}
|
|
|
|
}
|
2022-12-28 18:35:53 +08:00
|
|
|
|
|
|
|
global.LOG.Infof("new container info %s has been made, now start to create", req.Name)
|
2023-03-28 19:02:11 +08:00
|
|
|
|
|
|
|
ctx := context.Background()
|
|
|
|
if err := pullImages(ctx, client, req.Image); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
container, err := client.ContainerCreate(ctx, config, hostConf, &network.NetworkingConfig{}, &v1.Platform{}, req.Name)
|
2022-10-12 18:55:47 +08:00
|
|
|
if err != nil {
|
2023-03-28 19:02:11 +08:00
|
|
|
_ = client.ContainerRemove(ctx, req.Name, types.ContainerRemoveOptions{RemoveVolumes: true, Force: true})
|
2022-10-12 18:55:47 +08:00
|
|
|
return err
|
|
|
|
}
|
2023-01-06 18:53:25 +08: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)
|
2023-03-28 19:02:11 +08:00
|
|
|
if err := client.ContainerStart(ctx, container.ID, types.ContainerStartOptions{}); err != nil {
|
|
|
|
_ = client.ContainerRemove(ctx, req.Name, types.ContainerRemoveOptions{RemoveVolumes: true, Force: true})
|
2022-10-12 18:55:47 +08:00
|
|
|
return fmt.Errorf("create successful but start failed, err: %v", err)
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2022-10-08 18:32:02 +08:00
|
|
|
func (u *ContainerService) ContainerOperation(req dto.ContainerOperation) error {
|
|
|
|
var err error
|
|
|
|
ctx := context.Background()
|
2022-10-13 18:24:24 +08:00
|
|
|
client, err := docker.NewDockerClient()
|
2022-10-08 18:32:02 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-12-28 18:35:53 +08:00
|
|
|
global.LOG.Infof("start container %s operation %s", req.Name, req.Operation)
|
2022-10-08 18:32:02 +08:00
|
|
|
switch req.Operation {
|
|
|
|
case constant.ContainerOpStart:
|
2022-12-13 18:54:28 +08:00
|
|
|
err = client.ContainerStart(ctx, req.Name, types.ContainerStartOptions{})
|
2022-10-08 18:32:02 +08:00
|
|
|
case constant.ContainerOpStop:
|
2023-03-28 10:52:17 +08:00
|
|
|
err = client.ContainerStop(ctx, req.Name, container.StopOptions{})
|
2022-10-08 18:32:02 +08:00
|
|
|
case constant.ContainerOpRestart:
|
2023-03-28 10:52:17 +08:00
|
|
|
err = client.ContainerRestart(ctx, req.Name, container.StopOptions{})
|
2022-10-08 18:32:02 +08:00
|
|
|
case constant.ContainerOpKill:
|
2022-12-13 18:54:28 +08:00
|
|
|
err = client.ContainerKill(ctx, req.Name, "SIGKILL")
|
2022-10-08 18:32:02 +08:00
|
|
|
case constant.ContainerOpPause:
|
2022-12-13 18:54:28 +08:00
|
|
|
err = client.ContainerPause(ctx, req.Name)
|
2022-10-08 18:32:02 +08:00
|
|
|
case constant.ContainerOpUnpause:
|
2022-12-13 18:54:28 +08:00
|
|
|
err = client.ContainerUnpause(ctx, req.Name)
|
2022-10-08 18:32:02 +08:00
|
|
|
case constant.ContainerOpRename:
|
2022-12-13 18:54:28 +08:00
|
|
|
err = client.ContainerRename(ctx, req.Name, req.NewName)
|
2022-10-08 18:32:02 +08:00
|
|
|
case constant.ContainerOpRemove:
|
2022-12-13 18:54:28 +08:00
|
|
|
err = client.ContainerRemove(ctx, req.Name, types.ContainerRemoveOptions{RemoveVolumes: true, Force: true})
|
2022-10-08 18:32:02 +08:00
|
|
|
}
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (u *ContainerService) ContainerLogs(req dto.ContainerLog) (string, error) {
|
2023-03-09 18:42:17 +08:00
|
|
|
cmd := exec.Command("docker", "logs", req.ContainerID)
|
2022-10-08 18:32:02 +08:00
|
|
|
if req.Mode != "all" {
|
2023-03-09 18:42:17 +08:00
|
|
|
cmd = exec.Command("docker", "logs", req.ContainerID, "--since", req.Mode)
|
2022-10-08 18:32:02 +08:00
|
|
|
}
|
2023-03-09 18:42:17 +08:00
|
|
|
stdout, err := cmd.CombinedOutput()
|
|
|
|
if err != nil {
|
2023-03-23 16:24:36 +08:00
|
|
|
return "", errors.New(string(stdout))
|
2022-10-08 18:32:02 +08:00
|
|
|
}
|
2023-03-09 18:42:17 +08:00
|
|
|
return string(stdout), nil
|
2022-10-08 18:32:02 +08:00
|
|
|
}
|
2022-10-11 14:20:51 +08:00
|
|
|
|
2022-10-13 18:24:24 +08:00
|
|
|
func (u *ContainerService) ContainerStats(id string) (*dto.ContainterStats, error) {
|
|
|
|
client, err := docker.NewDockerClient()
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
res, err := client.ContainerStats(context.TODO(), id, false)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
defer res.Body.Close()
|
|
|
|
|
2023-04-07 11:30:10 +08:00
|
|
|
body, err := io.ReadAll(res.Body)
|
2022-10-13 18:24:24 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var stats *types.StatsJSON
|
|
|
|
if err := json.Unmarshal(body, &stats); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
var data dto.ContainterStats
|
|
|
|
previousCPU := stats.PreCPUStats.CPUUsage.TotalUsage
|
|
|
|
previousSystem := stats.PreCPUStats.SystemUsage
|
|
|
|
data.CPUPercent = calculateCPUPercentUnix(previousCPU, previousSystem, stats)
|
|
|
|
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.Memory = data.Memory - data.Cache
|
|
|
|
data.NetworkRX, data.NetworkTX = calculateNetwork(stats.Networks)
|
|
|
|
data.ShotTime = stats.Read
|
|
|
|
return &data, nil
|
|
|
|
}
|
|
|
|
|
2022-10-11 14:20:51 +08:00
|
|
|
func stringsToMap(list []string) map[string]string {
|
|
|
|
var lableMap = make(map[string]string)
|
|
|
|
for _, label := range list {
|
|
|
|
sps := strings.Split(label, "=")
|
|
|
|
if len(sps) > 1 {
|
|
|
|
lableMap[sps[0]] = sps[1]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return lableMap
|
|
|
|
}
|
2022-10-13 18:24:24 +08:00
|
|
|
func calculateCPUPercentUnix(previousCPU, previousSystem uint64, v *types.StatsJSON) float64 {
|
|
|
|
var (
|
|
|
|
cpuPercent = 0.0
|
|
|
|
cpuDelta = float64(v.CPUStats.CPUUsage.TotalUsage) - float64(previousCPU)
|
|
|
|
systemDelta = float64(v.CPUStats.SystemUsage) - float64(previousSystem)
|
|
|
|
)
|
|
|
|
|
|
|
|
if systemDelta > 0.0 && cpuDelta > 0.0 {
|
|
|
|
cpuPercent = (cpuDelta / systemDelta) * float64(len(v.CPUStats.CPUUsage.PercpuUsage)) * 100.0
|
|
|
|
}
|
|
|
|
return cpuPercent
|
|
|
|
}
|
|
|
|
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 19:02:11 +08:00
|
|
|
|
|
|
|
func pullImages(ctx context.Context, client *client.Client, image string) error {
|
|
|
|
out, err := client.ImagePull(ctx, image, types.ImagePullOptions{})
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer out.Close()
|
2023-04-07 11:30:10 +08:00
|
|
|
_, err = io.Copy(io.Discard, out)
|
2023-03-28 19:02:11 +08:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|