Debian Codegraph @

internal/proc/status.go

raw symbols SCIP
1 // Copyright 2018 psgo authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package proc
16
17 import (
18 "bufio"
19 "fmt"
20 "os"
21 "strconv"
22 "strings"
23 "sync"
24
25 "go.podman.io/storage/pkg/idtools"
26 )
27
28 // Status is a direct translation of a `/proc/[pid]/status`, which provides much
29 // of the information in /proc/[pid]/stat and /proc/[pid]/statm in a format
30 // that's easier for humans to parse.
31 type Status struct {
32 // Name: Command run by this process.
33 Name string
34 // Umask: Process umask, expressed in octal with a leading zero; see
35 // umask(2). (Since Linux 4.7.)
36 Umask string
37 // State: Current state of the process. One of "R (running)", "S
38 // (sleeping)", "D (disk sleep)", "T (stopped)", "T (tracing stop)", "Z
39 // (zombie)", or "X (dead)".
40 State string
41 // Tgid: Thread group ID (i.e., Process ID).
42 Tgid string
43 // Ngid: NUMA group ID (0 if none; since Linux 3.13).
44 Ngid string
45 // Pid: Thread ID (see gettid(2)).
46 Pid string
47 // PPid: PID of parent process.
48 PPid string
49 // TracerPid: PID of process tracing this process (0 if not being traced).
50 TracerPid string
51 // Uids: Real, effective, saved set, and filesystem.
52 Uids []string
53 // Gids: Real, effective, saved set, and filesystem.
54 Gids []string
55 // FDSize: Number of file descriptor slots currently allocated.
56 FdSize string
57 // Groups: Supplementary group list.
58 Groups []string
59 // NStgid : Thread group ID (i.e., PID) in each of the PID namespaces
60 // of which [pid] is a member. The leftmost entry shows the value
61 // with respect to the PID namespace of the reading process, followed
62 // by the value in successively nested inner namespaces. (Since Linux
63 // 4.1.)
64 NStgid string
65 // NSpid: Thread ID in each of the PID namespaces of which [pid] is a
66 // member. The fields are ordered as for NStgid. (Since Linux 4.1.)
67 NSpid []string
68 // NSpgid: Process group ID in each of the PID namespaces of which
69 // [pid] is a member. The fields are ordered as for NStgid. (Since
70 // Linux 4.1.)
71 NSpgid string
72 // NSsid: descendant namespace session ID hierarchy Session ID in
73 // each of the PID names- paces of which [pid] is a member. The fields
74 // are ordered as for NStgid. (Since Linux 4.1.)
75 NSsid string
76 // VMPeak: Peak virtual memory size.
77 VMPeak string
78 // VMSize: Virtual memory size.
79 VMSize string
80 // VMLck: Locked memory size (see mlock(3)).
81 VMLCK string
82 // VMPin: Pinned memory size (since Linux 3.2). These are pages
83 // that can't be moved because something needs to directly access
84 // physical memory.
85 VMPin string
86 // VMHWM: Peak resident set size ("high water mark").
87 VMHWM string
88 // VMRSS: Resident set size. Note that the value here is the sum of
89 // RssAnon, RssFile, and RssShmem.
90 VMRSS string
91 // RssAnon: Size of resident anonymous memory. (since Linux 4.5).
92 RssAnon string
93 // RssFile: Size of resident file mappings. (since Linux 4.5).
94 RssFile string
95 // RssShmem: Size of resident shared memory (includes System V
96 // shared memory, mappings from tmpfs(5), and shared anonymous
97 // mappings). (since Linux 4.5).
98 RssShmem string
99 // VMData: Size of data segment.
100 VMData string
101 // VMStk: Size of stack segment.
102 VMStk string
103 // VMExe: Size of text segment.
104 VMExe string
105 // VMLib: Shared library code size.
106 VMLib string
107 // VMPTE: Page table entries size (since Linux 2.6.10).
108 VMPTE string
109 // VMPMD: Size of second-level page tables (since Linux 4.0).
110 VMPMD string
111 // VMSwap: Swapped-out virtual memory size by anonymous private pages;
112 // shmem swap usage is not included (since Linux 2.6.34).
113 VMSwap string
114 // HugetlbPages: Size of hugetlb memory portions. (since Linux 4.4).
115 HugetlbPages string
116 // Threads: Number of threads in process containing this thread.
117 Threads string
118 // SigQ: This field contains two slash-separated numbers that relate to
119 // queued signals for the real user ID of this process. The first of
120 // these is the number of currently queued signals for this real
121 // user ID, and the second is the resource limit on the number of
122 // queued signals for this process (see the description of
123 // RLIMIT_SIGPENDING in getr- limit(2)).
124 SigQ string
125 // SigPnd: Number of signals pending for thread and for (see pthreads(7)).
126 SigPnd string
127 // ShdPnd: Number of signals pending for process as a whole (see
128 // signal(7)).
129 ShdPnd string
130 // SigBlk: Mask indicating signals being blocked (see signal(7)).
131 SigBlk string
132 // SigIgn: Mask indicating signals being ignored (see signal(7)).
133 SigIgn string
134 // SigCgt: Mask indicating signals being blocked caught (see signal(7)).
135 SigCgt string
136 // CapInh: Mask of capabilities enabled in inheritable sets (see
137 // capabilities(7)).
138 CapInh string
139 // CapPrm: Mask of capabilities enabled in permitted sets (see
140 // capabilities(7)).
141 CapPrm string
142 // CapEff: Mask of capabilities enabled in effective sets (see
143 // capabilities(7)).
144 CapEff string
145 // CapBnd: Capability Bounding set (since Linux 2.6.26, see
146 // capabilities(7)).
147 CapBnd string
148 // CapAmb: Ambient capability set (since Linux 4.3, see capabilities(7)).
149 CapAmb string
150 // NoNewPrivs: Value of the no_new_privs bit (since Linux 4.10, see
151 // prctl(2)).
152 NoNewPrivs string
153 // Seccomp: Seccomp mode of the process (since Linux 3.8, see
154 // seccomp(2)). 0 means SEC- COMP_MODE_DISABLED; 1 means
155 // SECCOMP_MODE_STRICT; 2 means SECCOMP_MODE_FILTER. This field is
156 // provided only if the kernel was built with the CONFIG_SECCOMP kernel
157 // configu- ration option enabled.
158 Seccomp string
159 // SeccompFilters: Amount of filters attached to the process.
160 // (since Linux 5.9)
161 SeccompFilters string
162 // Cpus_allowed: Mask of CPUs on which this process may run
163 // (since Linux 2.6.24, see cpuset(7)).
164 CpusAllowed string
165 // Cpus_allowed_list: Same as previous, but in "list format" (since
166 // Linux 2.6.26, see cpuset(7)).
167 CpusAllowedList string
168 // Mems_allowed: Mask of memory nodes allowed to this process
169 // (since Linux 2.6.24, see cpuset(7)).
170 MemsAllowed string
171 // Mems_allowed_list: Same as previous, but in "list format" (since
172 // Linux 2.6.26, see cpuset(7)).
173 MemsAllowedList string
174 // voluntaryCtxtSwitches: Number of voluntary context switches
175 // (since Linux 2.6.23).
176 VoluntaryCtxtSwitches string
177 // nonvoluntaryCtxtSwitches: Number of involuntary context switches
178 // (since Linux 2.6.23).
179 NonvoluntaryCtxtSwitches string
180 }
181
182 // readStatus returns the content of /proc/pid/status as a string slice.
183 func readStatus(pid string) ([]string, error) {
184 path := fmt.Sprintf("/proc/%s/status", pid)
185 f, err := os.Open(path)
186 if err != nil {
187 return nil, err
188 }
189 lines := []string{}
190 scanner := bufio.NewScanner(f)
191 for scanner.Scan() {
192 lines = append(lines, scanner.Text())
193 }
194 return lines, nil
195 }
196
197 // mapField maps a single string-typed ID field given the set of mappings. If
198 // no mapping exists, the overflow uid/gid is used.
199 func mapStatusField(field *string, mapping []idtools.IDMap, overflow string) {
200 hostId, err := strconv.Atoi(*field)
201 if err != nil {
202 *field = overflow
203 return
204 }
205 contId, err := idtools.RawToContainer(hostId, mapping)
206 if err != nil {
207 *field = overflow
208 return
209 }
210 *field = strconv.Itoa(contId)
211 }
212
213 var (
214 overflowOnce sync.Once
215 overflowUid = "65534"
216 overflowGid = "65534"
217 )
218
219 func overflowIds() (string, string) {
220 overflowOnce.Do(func() {
221 if uid, err := os.ReadFile("/proc/sys/kernel/overflowuid"); err == nil {
222 overflowUid = strings.TrimSpace(string(uid))
223 }
224 if gid, err := os.ReadFile("/proc/sys/kernel/overflowgid"); err == nil {
225 overflowGid = strings.TrimSpace(string(gid))
226 }
227 })
228 return overflowUid, overflowGid
229 }
230
231 // mapStatus takes a Status struct and remaps all of the relevant fields to
232 // match the user namespace of the target process.
233 func mapStatus(pid string, status *Status) (*Status, error) {
234 uidMap, err := ReadMappings(fmt.Sprintf("/proc/%s/uid_map", pid))
235 if err != nil {
236 return nil, err
237 }
238 gidMap, err := ReadMappings(fmt.Sprintf("/proc/%s/gid_map", pid))
239 if err != nil {
240 return nil, err
241 }
242 overflowUid, overflowGid := overflowIds()
243 for i := range status.Uids {
244 mapStatusField(&status.Uids[i], uidMap, overflowUid)
245 }
246 for i := range status.Gids {
247 mapStatusField(&status.Gids[i], gidMap, overflowGid)
248 }
249 for i := range status.Groups {
250 mapStatusField(&status.Groups[i], gidMap, overflowGid)
251 }
252 return status, nil
253 }
254
255 // ParseStatus parses the /proc/$pid/status file and returns a *Status.
256 func ParseStatus(pid string, mapUserNS bool) (*Status, error) {
257 lines, err := readStatus(pid)
258 if err != nil {
259 return nil, err
260 }
261 status, err := parseStatus(pid, lines)
262 if err != nil {
263 return nil, err
264 }
265 if mapUserNS {
266 status, err = mapStatus(pid, status)
267 if err != nil {
268 return nil, err
269 }
270 }
271 return status, nil
272 }
273
274 // parseStatus extracts data from lines and returns a *Status.
275 func parseStatus(pid string, lines []string) (*Status, error) {
276 s := Status{}
277 errUnexpectedInput := fmt.Errorf("unexpected input from /proc/%s/status", pid)
278 for _, line := range lines {
279 fields := strings.Fields(line)
280 if len(fields) < 2 {
281 continue
282 }
283
284 switch fields[0] {
285 case "Name:":
286 s.Name = fields[1]
287 case "Umask:":
288 s.Umask = fields[1]
289 case "State:":
290 s.State = fields[1]
291 case "Tgid:":
292 s.Tgid = fields[1]
293 case "Ngid:":
294 s.Ngid = fields[1]
295 case "Pid:":
296 s.Pid = fields[1]
297 case "PPid:":
298 s.PPid = fields[1]
299 case "TracerPid:":
300 s.TracerPid = fields[1]
301 case "Uid:":
302 if len(fields) != 5 {
303 return nil, fmt.Errorf(line+": %w", errUnexpectedInput)
304 }
305 s.Uids = []string{fields[1], fields[2], fields[3], fields[4]}
306 case "Gid:":
307 if len(fields) != 5 {
308 return nil, fmt.Errorf(line+": %w", errUnexpectedInput)
309 }
310 s.Gids = []string{fields[1], fields[2], fields[3], fields[4]}
311 case "FDSize:":
312 s.FdSize = fields[1]
313 case "Groups:":
314 s.Groups = fields[1:]
315 case "NStgid:":
316 s.NStgid = fields[1]
317 case "NSpid:":
318 s.NSpid = fields[1:]
319 case "NSpgid:":
320 s.NSpgid = fields[1]
321 case "NSsid:":
322 s.NSsid = fields[1]
323 case "VmPeak:":
324 s.VMPeak = fields[1]
325 case "VmSize:":
326 s.VMSize = fields[1]
327 case "VmLck:":
328 s.VMLCK = fields[1]
329 case "VmPin:":
330 s.VMPin = fields[1]
331 case "VmHWM:":
332 s.VMHWM = fields[1]
333 case "VmRSS:":
334 s.VMRSS = fields[1]
335 case "RssAnon:":
336 s.RssAnon = fields[1]
337 case "RssFile:":
338 s.RssFile = fields[1]
339 case "RssShmem:":
340 s.RssShmem = fields[1]
341 case "VmData:":
342 s.VMData = fields[1]
343 case "VmStk:":
344 s.VMStk = fields[1]
345 case "VmExe:":
346 s.VMExe = fields[1]
347 case "VmLib:":
348 s.VMLib = fields[1]
349 case "VmPTE:":
350 s.VMPTE = fields[1]
351 case "VmPMD:":
352 s.VMPMD = fields[1]
353 case "VmSwap:":
354 s.VMSwap = fields[1]
355 case "HugetlbPages:":
356 s.HugetlbPages = fields[1]
357 case "Threads:":
358 s.Threads = fields[1]
359 case "SigQ:":
360 s.SigQ = fields[1]
361 case "SigPnd:":
362 s.SigPnd = fields[1]
363 case "ShdPnd:":
364 s.ShdPnd = fields[1]
365 case "SigBlk:":
366 s.SigBlk = fields[1]
367 case "SigIgn:":
368 s.SigIgn = fields[1]
369 case "SigCgt:":
370 s.SigCgt = fields[1]
371 case "CapInh:":
372 s.CapInh = fields[1]
373 case "CapPrm:":
374 s.CapPrm = fields[1]
375 case "CapEff:":
376 s.CapEff = fields[1]
377 case "CapBnd:":
378 s.CapBnd = fields[1]
379 case "CapAmb:":
380 s.CapAmb = fields[1]
381 case "NoNewPrivs:":
382 s.NoNewPrivs = fields[1]
383 case "Seccomp:":
384 s.Seccomp = fields[1]
385 case "Seccomp_filters:":
386 s.SeccompFilters = fields[1]
387 case "Cpus_allowed:":
388 s.CpusAllowed = fields[1]
389 case "Cpus_allowed_list:":
390 s.CpusAllowedList = fields[1]
391 case "Mems_allowed:":
392 s.MemsAllowed = fields[1]
393 case "Mems_allowed_list:":
394 s.MemsAllowedList = fields[1]
395 case "voluntary_ctxt_switches:":
396 s.VoluntaryCtxtSwitches = fields[1]
397 case "nonvoluntary_ctxt_switches:":
398 s.NonvoluntaryCtxtSwitches = fields[1]
399 }
400 }
401
402 return &s, nil
403 }