find.go 8.22 KB
Newer Older
liming6's avatar
liming6 committed
1
2
3
4
package docker

import (
	"get-container/utils"
5
	"strconv"
liming6's avatar
liming6 committed
6
7
8
9
10
11
12
13
14

	"context"
	"errors"
	"fmt"
	"os"
	"regexp"
	"strings"
	"sync"
	"time"
15
16
17

	"github.com/moby/moby/api/types/container"
	"github.com/moby/moby/client"
liming6's avatar
liming6 committed
18
19
20
21
)

/**
有两种方法获取进程属于哪个容器
22
1. 通过查询pid命名空间,仅在没有指定--pid参数时有效
liming6's avatar
liming6 committed
23
2. 通过查询进程的cgroup
24
3. 使用docker top <container-id>匹配
liming6's avatar
liming6 committed
25
26
27
28
29
30
31
*/

type FindCIDMethod string

const (
	ByCgroup FindCIDMethod = "byCGroup"
	ByPidNS  FindCIDMethod = "byPidNS"
32
	ByTop    FindCIDMethod = "byTop"
liming6's avatar
liming6 committed
33
34
35
36
37
38
39
40
41
42
43
44
)

var (
	ReDocker                      = regexp.MustCompile(`^.*docker[-/]([0-9a-z]*)(?:|.*)`)
	ContainerInfo *ContainersInfo = nil
)

type ContainersInfo struct {
	lock        sync.RWMutex // 读写锁,防止对Info的并发写
	time        time.Time    // 记录写入Info的时间
	inspectInfo map[string]container.InspectResponse
	listInfo    map[string]container.Summary
45
46
47
48
	topInfo     map[string]container.TopResponse
}

type ContainerPsInfo struct {
49
	Pid  int32
50
51
	Ppid uint64
	Uid  string
52
	Cmd  string
53
54
}

55
func ParsePsInfo(topInfo map[string]container.TopResponse) (map[string][]ContainerPsInfo, error) {
56
57
58
	if topInfo == nil {
		return nil, errors.New("topInfo is nil")
	}
59
	result := make(map[string][]ContainerPsInfo)
60
	for cid, topResp := range topInfo {
61
62
		indexMap, t := make(map[string]int), 0
		result[cid] = make([]ContainerPsInfo, 0)
63
64
65
		for index, key := range topResp.Titles {
			switch strings.TrimSpace(strings.ToLower(key)) {
			case "pid":
66
				indexMap["pid"] = index
67
68
				t++
			case "ppid":
69
				indexMap["ppid"] = index
70
71
				t++
			case "uid":
72
				indexMap["uid"] = index
73
74
				t++
			case "cmd":
75
				indexMap["cmd"] = index
76
77
78
79
80
81
82
				t++
			default:
			}
			if t >= 4 {
				break
			}
		}
83
84
85
86
87
88
89
90
		for _, fields := range topResp.Processes {
			item := ContainerPsInfo{}
			if v, ok := indexMap["pid"]; ok {
				pid, err := strconv.ParseUint(fields[v], 10, 64)
				if err != nil {
					return nil, err
				}
				item.Pid = int32(pid)
91
			}
92
93
94
95
96
97
			if v, ok := indexMap["ppid"]; ok {
				ppid, err := strconv.ParseUint(fields[v], 10, 64)
				if err != nil {
					return nil, err
				}
				item.Ppid = ppid
98
			}
99
100
101
102
103
104
105
			if v, ok := indexMap["uid"]; ok {
				item.Uid = fields[v]
			}
			if v, ok := indexMap["cmd"]; ok {
				item.Cmd = fields[v]
			}
			result[cid] = append(result[cid], item)
106
107
108
		}
	}
	return result, nil
liming6's avatar
liming6 committed
109
110
111
112
113
}

func (info *ContainersInfo) Update() error {
	info.lock.Lock()
	defer info.lock.Unlock()
114
	i, s, t, err := getContainerInfo()
liming6's avatar
liming6 committed
115
116
117
118
119
	if err != nil {
		return err
	}
	info.inspectInfo = i
	info.listInfo = s
120
	info.topInfo = t
liming6's avatar
liming6 committed
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
	info.time = time.Now()
	return nil
}

func (info *ContainersInfo) Get() (map[string]container.InspectResponse, sync.Locker) {
	rl := info.lock.RLocker()
	rl.Lock()
	return info.inspectInfo, rl
}

func init() {
	_ = initContainerInfo()
}

func initContainerInfo() error {
136
	inspect, lists, tops, err := getContainerInfo()
liming6's avatar
liming6 committed
137
138
139
140
141
142
143
144
	if err != nil {
		return err
	}
	ContainerInfo = &ContainersInfo{
		lock:        sync.RWMutex{},
		time:        time.Now(),
		inspectInfo: inspect,
		listInfo:    lists,
145
		topInfo:     tops,
liming6's avatar
liming6 committed
146
147
148
149
	}
	return nil
}

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
// GetProcessIdInDocker 获取所用容器的进程信息
func (info *ContainersInfo) GetProcessIdInDocker(update bool) (map[int32]bool, error) {
	result := make(map[int32]bool)
	if update {
		err := info.Update()
		if err != nil {
			return result, err
		}
	}
	rl := info.lock.RLocker()
	rl.Lock()
	i, err := ParsePsInfo(info.topInfo)
	rl.Unlock()
	rl = nil
	if err != nil {
		return result, err
	}
	for _, v := range i {
		for _, k := range v {
			result[k.Pid] = true
		}
	}
	return result, nil
}

liming6's avatar
liming6 committed
175
176
177
178
179
180
181
182
183
184
185
186
187
// FindContainerIdByPid 根据pid获取该进程属于哪个docker容器,返回容器id,如果为nil,表示找不到容器id
func FindContainerIdByPid(pid uint64, method FindCIDMethod) (*string, error) {
	switch method {
	case ByPidNS:
		return findContainerIdByNS(pid)
	case ByCgroup:
		return findContainerIdByCgroup(pid)
	default:
		return nil, fmt.Errorf("unknown method: %s", method)
	}
}

func FindContainerIdByPidBatch(pids []uint64, method FindCIDMethod) (map[uint64]string, error) {
188
	if len(pids) == 0 {
liming6's avatar
liming6 committed
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
		return nil, nil
	}
	switch method {
	case ByPidNS:
		return findContainerIdByNSBatch(pids)
	case ByCgroup:
		return findContainerIdByCgroupBatch(pids)
	default:
		return nil, fmt.Errorf("unknown method: %s", method)
	}
}

// findContainerIdByPidCgroup 通过cgroup查询docker容器id
func findContainerIdByCgroup(pid uint64) (*string, error) {
	content, err := os.ReadFile(fmt.Sprintf("/proc/%d/cgroup", pid))
	if err != nil {
		return nil, err
	}
	contentStr := strings.Trim(string(content), "\n")
	if len(contentStr) == 0 {
		return nil, errors.New("process's cgroup not found")
	}
	lines := strings.Split(contentStr, "\n")
	var target string
	if len(lines) > 1 {
		// 如果有多行,解析有pids的行
		for _, line := range lines {
			if strings.Contains(line, "pids") {
				target = strings.TrimSpace(line)
				break
			}
		}
		if target == "" {
			return nil, errors.New("process's cgroup not found pids line")
		}
	} else {
		// 如果是单行,直接解析
		target = strings.TrimSpace(lines[0])
	}
	target = strings.TrimSpace(target)
	if !strings.Contains(target, "docker") {
		return nil, errors.New("process's cgroup is not create by docker")
	}
	if ReDocker.MatchString(target) {
		fields := ReDocker.FindStringSubmatch(target)
		if len(fields) < 2 {
			return nil, errors.New("process's cgroup is not create by docker")
		}
		cid := fields[1]
		return &cid, nil
	} else {
		return nil, errors.New("process's cgroup is not create by docker")
	}
}

func findContainerIdByCgroupBatch(pids []uint64) (map[uint64]string, error) {
	results := make(map[uint64]string)
	for _, pid := range pids {
		str, err := findContainerIdByCgroup(pid)
		if err != nil {
			return nil, err
		}
		s := *str
		results[pid] = s
	}
	return results, nil
}

// findContainerIdByNS 通过pid命名空间查询docker容器id
func findContainerIdByNS(pid uint64) (*string, error) {
	ns, err := utils.GetPidNS(pid)
	if err != nil {
		return nil, err
	}
	if ContainerInfo == nil {
		innerErr := initContainerInfo()
		if innerErr != nil {
			return nil, innerErr
		}
	} else {
		if innerErr := ContainerInfo.Update(); innerErr != nil {
			return nil, innerErr
		}
	}
	info, lock := ContainerInfo.Get()
	defer lock.Unlock()
	for k, v := range info {
		containerNs, innerErr := utils.GetPidNS(uint64(v.State.Pid))
		if innerErr != nil {
			continue
		}
		if containerNs == ns {
			cid := k
			return &cid, nil
		}
	}
	return nil, nil
}

func findContainerIdByNSBatch(pids []uint64) (map[uint64]string, error) {
	if ContainerInfo == nil {
		innerErr := initContainerInfo()
		if innerErr != nil {
			return nil, innerErr
		}
	} else {
		if innerErr := ContainerInfo.Update(); innerErr != nil {
			return nil, innerErr
		}
	}
	info, lock := ContainerInfo.Get()
	defer lock.Unlock()
	results := make(map[uint64]string)
	ns2cid := make(map[uint64]string)
	for k, v := range info {
		containerNs, innerErr := utils.GetPidNS(uint64(v.State.Pid))
		if innerErr != nil {
			return nil, innerErr
		}
		ns2cid[containerNs] = k
	}
	for _, pid := range pids {
		ns, err := utils.GetPidNS(pid)
		if err != nil {
			continue
		}
		if cid, ok := ns2cid[ns]; ok {
			results[pid] = cid
		}
	}
	return results, nil
}

// getContainerInfo 获取所有正在运行的docker容器的详细信息
323
func getContainerInfo() (map[string]container.InspectResponse, map[string]container.Summary, map[string]container.TopResponse, error) {
liming6's avatar
liming6 committed
324
325
	cli, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
	if err != nil {
326
		return nil, nil, nil, err
liming6's avatar
liming6 committed
327
328
329
330
331
332
	}
	defer func() {
		_ = cli.Close()
	}()
	containerSum, err := cli.ContainerList(context.Background(), client.ContainerListOptions{All: false})
	if err != nil {
333
		return nil, nil, nil, err
liming6's avatar
liming6 committed
334
335
336
	}
	inspects := make(map[string]container.InspectResponse)
	lists := make(map[string]container.Summary)
337
	tops := make(map[string]container.TopResponse)
liming6's avatar
liming6 committed
338
339
340
	for _, c := range containerSum {
		inspect, innerErr := cli.ContainerInspect(context.Background(), c.ID)
		if innerErr != nil {
341
			return nil, nil, nil, innerErr
liming6's avatar
liming6 committed
342
343
344
		}
		inspects[c.ID] = inspect
		lists[c.ID] = c
345
346
347
348
349
		topInfo, innerErr := cli.ContainerTop(context.Background(), c.ID, nil)
		if innerErr != nil {
			return nil, nil, nil, innerErr
		}
		tops[c.ID] = topInfo
liming6's avatar
liming6 committed
350
	}
351
	return inspects, lists, tops, nil
liming6's avatar
liming6 committed
352
}