| 1 | |
| 2 | |
| 3 | package containerenv |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | |
| 14 | systemd "github.com/coreos/go-systemd/v22/dbus" |
| 15 | "github.com/godbus/dbus/v5" |
| 16 | ) |
| 17 | |
| 18 | func userSystemd(ctx context.Context) (*systemd.Conn, error) { |
| 19 | return systemd.NewConnection(func() (*dbus.Conn, error) { |
| 20 | connection, err := dbus.Dial("unix:path=/run/user/"+strconv.Itoa(os.Getuid())+"/bus", dbus.WithContext(ctx)) |
| 21 | if err != nil { |
| 22 | return nil, err |
| 23 | } |
| 24 | if err = connection.Auth([]dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}); err == nil { |
| 25 | err = connection.Hello() |
| 26 | } |
| 27 | if err != nil { |
| 28 | connection.Close() |
| 29 | return nil, err |
| 30 | } |
| 31 | return connection, nil |
| 32 | }) |
| 33 | } |
| 34 | |
| 35 | |
| 36 | |
| 37 | |
| 38 | func (r *Runtime) ensureResourceSlice(ctx context.Context) error { |
| 39 | connection, err := userSystemd(ctx) |
| 40 | if err != nil { |
| 41 | return fmt.Errorf("无法连接宿主用户 systemd 以设置容器资源上限: %w", err) |
| 42 | } |
| 43 | defer connection.Close() |
| 44 | properties := []systemd.Property{ |
| 45 | systemd.PropDescription("Cage container " + r.identity), |
| 46 | {Name: "MemoryMax", Value: dbus.MakeVariant(uint64(r.config.MemoryBytes))}, |
| 47 | {Name: "CPUQuotaPerSecUSec", Value: dbus.MakeVariant(uint64(r.config.CPUs) * 1000000)}, |
| 48 | {Name: "TasksMax", Value: dbus.MakeVariant(uint64(PIDLimit))}, |
| 49 | } |
| 50 | |
| 51 | |
| 52 | |
| 53 | result := make(chan string, 1) |
| 54 | _, err = connection.StartTransientUnitContext(ctx, r.resourceSlice(), "fail", properties, result) |
| 55 | if err != nil { |
| 56 | var busError dbus.Error |
| 57 | if !errors.As(err, &busError) || busError.Name != "org.freedesktop.systemd1.UnitExists" { |
| 58 | return err |
| 59 | } |
| 60 | current, err := connection.GetUnitPropertiesContext(ctx, r.resourceSlice()) |
| 61 | if err != nil { |
| 62 | return err |
| 63 | } |
| 64 | if current["Description"] != "Cage container "+r.identity { |
| 65 | return errors.New("容器资源 slice 名称已被其他单元占用") |
| 66 | } |
| 67 | if err := connection.SetUnitPropertiesContext(ctx, r.resourceSlice(), true, properties[1:]...); err != nil { |
| 68 | return err |
| 69 | } |
| 70 | if _, err := connection.StartUnitContext(ctx, r.resourceSlice(), "replace", result); err != nil { |
| 71 | return err |
| 72 | } |
| 73 | } |
| 74 | select { |
| 75 | case state := <-result: |
| 76 | if state != "done" { |
| 77 | return fmt.Errorf("容器资源 slice 启动失败: %s", state) |
| 78 | } |
| 79 | case <-ctx.Done(): |
| 80 | return ctx.Err() |
| 81 | } |
| 82 | _, err = r.readParentLimits(ctx, connection, "") |
| 83 | return err |
| 84 | } |
| 85 | |
| 86 | func (r *Runtime) readParentLimits(ctx context.Context, connection *systemd.Conn, containerID string) (resourceEvidence, error) { |
| 87 | parent, err := connection.GetAllPropertiesContext(ctx, r.resourceSlice()) |
| 88 | if err != nil { |
| 89 | return resourceEvidence{}, err |
| 90 | } |
| 91 | if parent["Description"] != "Cage container "+r.identity || parent["ActiveState"] != "active" { |
| 92 | return resourceEvidence{}, errors.New("容器的宿主资源边界未运行") |
| 93 | } |
| 94 | parentPath, ok := parent["ControlGroup"].(string) |
| 95 | if !ok || !strings.HasPrefix(parentPath, "/") || filepath.Clean(parentPath) != parentPath || filepath.Base(parentPath) != r.resourceSlice() { |
| 96 | return resourceEvidence{}, errors.New("宿主资源 cgroup 路径无效") |
| 97 | } |
| 98 | if containerID != "" { |
| 99 | prefix := "docker-" |
| 100 | if r.config.Engine == "podman" { |
| 101 | prefix = "libpod-" |
| 102 | } |
| 103 | scope, err := connection.GetAllPropertiesContext(ctx, prefix+containerID+".scope") |
| 104 | if err != nil { |
| 105 | return resourceEvidence{}, err |
| 106 | } |
| 107 | path, ok := scope["ControlGroup"].(string) |
| 108 | if !ok || !strings.HasPrefix(path, parentPath+"/") || scope["ActiveState"] != "active" { |
| 109 | return resourceEvidence{}, errors.New("实际容器未处于 Cage 的宿主资源边界内") |
| 110 | } |
| 111 | } |
| 112 | root := filepath.Join("/sys/fs/cgroup", parentPath) |
| 113 | var evidence strings.Builder |
| 114 | for _, file := range []string{"memory.max", "cpu.max", "pids.max"} { |
| 115 | data, err := os.ReadFile(filepath.Join(root, file)) |
| 116 | if err != nil { |
| 117 | return resourceEvidence{}, err |
| 118 | } |
| 119 | evidence.WriteString(strings.TrimSpace(string(data))) |
| 120 | evidence.WriteByte('\n') |
| 121 | } |
| 122 | mounts, err := os.ReadFile("/proc/self/mountinfo") |
| 123 | if err != nil { |
| 124 | return resourceEvidence{}, err |
| 125 | } |
| 126 | evidence.Write(mounts) |
| 127 | return parseResourceEvidence(evidence.String(), r.config) |
| 128 | } |
| 129 | |
| 130 | func (r *Runtime) verifyHostResources(ctx context.Context, containerID string) (resourceEvidence, error) { |
| 131 | connection, err := userSystemd(ctx) |
| 132 | if err != nil { |
| 133 | return resourceEvidence{}, err |
| 134 | } |
| 135 | defer connection.Close() |
| 136 | return r.readParentLimits(ctx, connection, containerID) |
| 137 | } |