/
util.go
278 lines (248 loc) · 6.85 KB
/
util.go
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
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
//
// Copyright © 2016-2017 Ikey Doherty <ikey@solus-project.com>
//
// 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 builder
import (
"crypto/sha256"
"encoding/hex"
"fmt"
log "github.com/Sirupsen/logrus"
"github.com/solus-project/libosdev/commands"
"github.com/solus-project/libosdev/disk"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"syscall"
"time"
)
var (
// ChrootEnvironment is the env used by ChrootExec calls
ChrootEnvironment []string
)
func init() {
ChrootEnvironment = nil
}
// PidNotifier provides a simple way to set the PID on a blocking process
type PidNotifier interface {
SetActivePID(int)
}
// ActivateRoot will do the hard work of actually bring up the overlayfs
// system to allow manipulation of the roots for builds, etc.
func (p *Package) ActivateRoot(overlay *Overlay) error {
log.Debug("Configuring overlay storage")
// Now mount the overlayfs
if err := overlay.Mount(); err != nil {
return err
}
// Add build user
if p.Type == PackageTypeYpkg {
if err := AddBuildUser(overlay.MountPoint); err != nil {
return err
}
}
log.Debug("Bringing up virtual filesystems")
if err := overlay.MountVFS(); err != nil {
return err
}
return nil
}
// DeactivateRoot will tear down the previously activated root
func (p *Package) DeactivateRoot(overlay *Overlay) {
MurderDeathKill(overlay.MountPoint)
mountMan := disk.GetMountManager()
commands.SetStdin(nil)
overlay.Unmount()
log.Debug("Requesting unmount of all remaining mountpoints")
mountMan.UnmountAll()
}
// MurderDeathKill will find all processes with a root matching the given root
// and set about killing them, to assist in clean closing.
func MurderDeathKill(root string) error {
path, err := filepath.EvalSymlinks(root)
if err != nil {
return err
}
var files []os.FileInfo
if files, err = ioutil.ReadDir("/proc"); err != nil {
return err
}
for _, f := range files {
fpath := filepath.Join("/proc", f.Name(), "cwd")
spath, err := filepath.EvalSymlinks(fpath)
if err != nil {
continue
}
if spath != path {
continue
}
spid := f.Name()
var pid int
if pid, err = strconv.Atoi(spid); err != nil {
log.WithFields(log.Fields{
"pid": spid,
"error": err,
}).Error("POSIX Weeps - broken pid identifier")
return err
}
log.WithFields(log.Fields{
"pid": pid,
}).Debug("Killing child process in chroot")
if err := syscall.Kill(pid, syscall.SIGTERM); err != nil {
log.WithFields(log.Fields{
"pid": pid,
}).Error("Error terminating process, attempting force kill")
time.Sleep(400 * time.Millisecond)
if err := syscall.Kill(pid, syscall.SIGKILL); err != nil {
log.WithFields(log.Fields{
"pid": pid,
}).Error("Error killing (-9) process")
}
}
}
return nil
}
// TouchFile will create the file if it doesn't exist, enabling use of bind
// mounts.
func TouchFile(path string) error {
w, err := os.OpenFile(path, os.O_RDONLY|os.O_CREATE, 00644)
if err != nil {
return err
}
defer w.Close()
return nil
}
// SaneEnvironment will generate a clean environment for the chroot'd
// processes to use
func SaneEnvironment(username, home string) []string {
environment := []string{
"PATH=/usr/bin:/usr/sbin:/bin/:/sbin",
"LANG=en_US.utf8",
"LC_ALL=en_US.utf8",
fmt.Sprintf("HOME=%s", home),
fmt.Sprintf("USER=%s", username),
fmt.Sprintf("USERNAME=%s", username),
}
// Consider an option to even filter these out
permitted := []string{
"http_proxy",
"https_proxy",
"no_proxy",
"ftp_proxy",
"TERM",
}
if !DisableColors {
permitted = append(permitted, "TERM")
}
for _, p := range permitted {
env := os.Getenv(p)
if env == "" {
p = strings.ToUpper(p)
env = os.Getenv(p)
}
if env == "" {
continue
}
environment = append(environment,
fmt.Sprintf("%s=%s", p, env))
}
if DisableColors {
environment = append(environment, "TERM=dumb")
}
return environment
}
// ChrootExec is a simple wrapper to return a correctly set up chroot command,
// so that we can store the PID, for long running tasks
func ChrootExec(notif PidNotifier, dir, command string) error {
args := []string{dir, "/bin/sh", "-c", command}
c := exec.Command("chroot", args...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Stdin = nil
c.Env = ChrootEnvironment
c.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
if err := c.Start(); err != nil {
return err
}
notif.SetActivePID(c.Process.Pid)
return c.Wait()
}
// ChrootExecStdin is almost identical to ChrootExec, except it permits a stdin
// to be associated with the command
func ChrootExecStdin(notif PidNotifier, dir, command string) error {
args := []string{dir, "/bin/sh", "-c", command}
c := exec.Command("chroot", args...)
c.Stdout = os.Stdout
c.Stderr = os.Stderr
c.Stdin = os.Stdin
c.Env = ChrootEnvironment
if err := c.Start(); err != nil {
return err
}
notif.SetActivePID(c.Process.Pid)
return c.Wait()
}
// AddBuildUser will attempt to add the solbuild user & group if they've not
// previously been added
// Note this should be changed when Solus goes fully stateless for /etc/passwd
func AddBuildUser(rootfs string) error {
pwd, err := NewPasswd(filepath.Join(rootfs, "etc"))
if err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Unable to discover chroot users")
return err
}
// User already exists
if _, ok := pwd.Users[BuildUser]; ok {
return nil
}
log.WithFields(log.Fields{
"username": BuildUser,
"uid": BuildUserID,
"gid": BuildUserGID,
"home": BuildUserHome,
"shell": BuildUserShell,
"gecos": BuildUserGecos,
}).Debug("Adding build user to system")
// Add the build group
if err := commands.AddGroup(rootfs, BuildUser, BuildUserGID); err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Failed to add build group to system")
return err
}
if err := commands.AddUser(rootfs, BuildUser, BuildUserGecos, BuildUserHome, BuildUserShell, BuildUserID, BuildUserGID); err != nil {
log.WithFields(log.Fields{
"error": err,
}).Error("Failed to add build user to system")
return err
}
return nil
}
// FileSha256sum is a quick wrapper to grab the sha256sum for the given file
func FileSha256sum(path string) (string, error) {
mfile, err := MapFile(path)
if err != nil {
return "", err
}
defer mfile.Close()
h := sha256.New()
// Pump from memory into hash for zero-copy sha1sum
h.Write(mfile.Data)
return hex.EncodeToString(h.Sum(nil)), nil
}