File: process.go

package info (click to toggle)
golang-github-containers-psgo 1.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 340 kB
  • sloc: makefile: 46; sh: 6
file content (235 lines) | stat: -rw-r--r-- 5,656 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
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
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
// Copyright 2018 psgo authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package process

import (
	"errors"
	"fmt"
	"os"
	"strconv"
	"time"

	"github.com/containers/psgo/internal/host"
	"github.com/containers/psgo/internal/proc"
	"github.com/opencontainers/runc/libcontainer/user"
)

// Process includes process-related from the /proc FS.
type Process struct {
	// PID is the process ID.
	Pid string
	// Stat contains data from /proc/$pid/stat.
	Stat proc.Stat
	// Status contains data from /proc/$pid/status.
	Status proc.Status
	// CmdLine contains data from /proc/$pid/cmdline.
	CmdLine []string
	// Label containers data from /proc/$pid/attr/current.
	Label string
	// PidNS contains data from /proc/$pid/ns/pid.
	PidNS string
	// Huser is the effective host user of a container process.
	Huser string
	// Hgroup is the effective host group of a container process.
	Hgroup string
}

// LookupGID returns the textual group ID, if it can be obtained, or the
// decimal representation otherwise.
func LookupGID(gid string) (string, error) {
	gidNum, err := strconv.Atoi(gid)
	if err != nil {
		return "", fmt.Errorf("error parsing group ID: %w", err)
	}
	g, err := user.LookupGid(gidNum)
	if err != nil {
		return gid, nil
	}
	return g.Name, nil
}

// LookupUID return the textual user ID, if it can be obtained, or the decimal
// representation otherwise.
func LookupUID(uid string) (string, error) {
	uidNum, err := strconv.Atoi(uid)
	if err != nil {
		return "", fmt.Errorf("error parsing user ID: %w", err)
	}
	u, err := user.LookupUid(uidNum)
	if err != nil {
		return uid, nil
	}
	return u.Name, nil
}

// New returns a new Process with the specified pid and parses the relevant
// data from /proc and /dev.
func New(pid string, joinUserNS bool) (*Process, error) {
	p := Process{Pid: pid}

	if err := p.parseStat(); err != nil {
		return nil, err
	}
	if err := p.parseStatus(joinUserNS); err != nil {
		return nil, err
	}
	if err := p.parseCmdLine(); err != nil {
		return nil, err
	}
	if err := p.parsePIDNamespace(); err != nil {
		// Ignore permission errors as those occur for some pids when
		// the caller has limited permissions.
		if !os.IsPermission(err) {
			return nil, err
		}
	}
	if err := p.parseLabel(); err != nil {
		return nil, err
	}

	return &p, nil
}

// FromPIDs creates a new Process for each pid.
func FromPIDs(pids []string, joinUserNS bool) ([]*Process, error) {
	processes := []*Process{}
	for _, pid := range pids {
		p, err := New(pid, joinUserNS)
		if err != nil {
			if errors.Is(err, os.ErrNotExist) {
				// proc parsing is racy
				// Let's ignore "does not exist" errors
				continue
			}
			return nil, err
		}
		processes = append(processes, p)
	}
	return processes, nil
}

// parseStat parses /proc/$pid/stat.
func (p *Process) parseStat() error {
	s, err := proc.ParseStat(p.Pid)
	if err != nil {
		return err
	}
	p.Stat = *s
	return nil
}

// parseStatus parses /proc/$pid/status.
func (p *Process) parseStatus(joinUserNS bool) error {
	s, err := proc.ParseStatus(p.Pid, joinUserNS)
	if err != nil {
		return err
	}
	p.Status = *s
	return nil
}

// parseCmdLine parses /proc/$pid/cmdline.
func (p *Process) parseCmdLine() error {
	s, err := proc.ParseCmdLine(p.Pid)
	if err != nil {
		return err
	}
	p.CmdLine = s
	return nil
}

// parsePIDNamespace sets the PID namespace.
func (p *Process) parsePIDNamespace() error {
	pidNS, err := proc.ParsePIDNamespace(p.Pid)
	if err != nil {
		return err
	}
	p.PidNS = pidNS
	return nil
}

// parseLabel parses the security label.
func (p *Process) parseLabel() error {
	label, err := proc.ParseAttrCurrent(p.Pid)
	if err != nil {
		return err
	}
	p.Label = label
	return nil
}

// SetHostData sets all host-related data fields.
func (p *Process) SetHostData() error {
	var err error

	p.Huser, err = LookupUID(p.Status.Uids[1])
	if err != nil {
		return err
	}

	p.Hgroup, err = LookupGID(p.Status.Gids[1])
	if err != nil {
		return err
	}

	return nil
}

// ElapsedTime returns the time.Duration since process p was created.
func (p *Process) ElapsedTime() (time.Duration, error) {
	startTime, err := p.StartTime()
	if err != nil {
		return 0, err
	}
	return time.Since(startTime), nil
}

// StarTime returns the time.Time when process p was started.
func (p *Process) StartTime() (time.Time, error) {
	sinceBoot, err := strconv.ParseInt(p.Stat.Starttime, 10, 64)
	if err != nil {
		return time.Time{}, err
	}
	clockTicks, err := host.ClockTicks()
	if err != nil {
		return time.Time{}, err
	}
	bootTime, err := host.BootTime()
	if err != nil {
		return time.Time{}, err
	}

	sinceBoot = sinceBoot / clockTicks
	return time.Unix(sinceBoot+bootTime, 0), nil
}

// CPUTime returns the cumulative CPU time of process p as a time.Duration.
func (p *Process) CPUTime() (time.Duration, error) {
	user, err := strconv.ParseInt(p.Stat.Utime, 10, 64)
	if err != nil {
		return 0, err
	}
	system, err := strconv.ParseInt(p.Stat.Stime, 10, 64)
	if err != nil {
		return 0, err
	}
	clockTicks, err := host.ClockTicks()
	if err != nil {
		return 0, err
	}
	secs := (user + system) / clockTicks
	cpu := time.Unix(secs, 0)
	return cpu.Sub(time.Unix(0, 0)), nil
}