forked from containers/toolbox
/
root.go
393 lines (306 loc) · 9.57 KB
/
root.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
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
/*
* Copyright © 2019 – 2021 Red Hat Inc.
*
* 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 cmd
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"strings"
"syscall"
"github.com/containers/toolbox/pkg/podman"
"github.com/containers/toolbox/pkg/utils"
"github.com/containers/toolbox/pkg/version"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
var (
cgroupsVersion int
currentUser *user.User
executable string
executableBase string
rootCmd = &cobra.Command{
Use: "toolbox",
Short: "Tool for containerized command line environments on Linux",
PersistentPreRunE: preRun,
RunE: rootRun,
Version: version.GetVersion(),
}
rootFlags struct {
assumeYes bool
logLevel string
logPodman bool
verbose int
}
workingDirectory string
)
func Execute() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
os.Exit(0)
}
func init() {
if err := setUpGlobals(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
os.Exit(1)
}
persistentFlags := rootCmd.PersistentFlags()
persistentFlags.BoolVarP(&rootFlags.assumeYes,
"assumeyes",
"y",
false,
"Automatically answer yes for all questions")
persistentFlags.StringVar(&rootFlags.logLevel,
"log-level",
"error",
"Log messages at the specified level: trace, debug, info, warn, error, fatal or panic")
persistentFlags.BoolVar(&rootFlags.logPodman,
"log-podman",
false,
"Show the log output of Podman. The log level is handled by the log-level option")
persistentFlags.CountVarP(&rootFlags.verbose, "verbose", "v", "Set log-level to 'debug'")
rootCmd.SetHelpFunc(rootHelp)
usageTemplate := fmt.Sprintf("Run '%s --help' for usage.", executableBase)
rootCmd.SetUsageTemplate(usageTemplate)
}
func preRun(cmd *cobra.Command, args []string) error {
cmd.Root().SilenceUsage = true
if err := setUpLoggers(); err != nil {
return err
}
logrus.Debugf("Running as real user ID %s", currentUser.Uid)
logrus.Debugf("Resolved absolute path to the executable as %s", executable)
if !utils.IsInsideContainer() {
logrus.Debugf("Running on a cgroups v%d host", cgroupsVersion)
if currentUser.Uid != "0" {
logrus.Debugf("Checking if /etc/subgid and /etc/subuid have entries for user %s",
currentUser.Username)
if _, err := validateSubIDFile("/etc/subuid"); err != nil {
return newSubIDFileError()
}
if _, err := validateSubIDFile("/etc/subgid"); err != nil {
return newSubIDFileError()
}
}
}
toolboxPath := os.Getenv("TOOLBOX_PATH")
if toolboxPath == "" {
if utils.IsInsideContainer() {
if err := preRunIsCoreOSBug(); err != nil {
return err
}
return errors.New("TOOLBOX_PATH not set")
}
os.Setenv("TOOLBOX_PATH", executable)
toolboxPath = os.Getenv("TOOLBOX_PATH")
}
logrus.Debugf("TOOLBOX_PATH is %s", toolboxPath)
if err := migrate(); err != nil {
return err
}
if err := utils.SetUpConfiguration(); err != nil {
return err
}
return nil
}
func rootHelp(cmd *cobra.Command, args []string) {
if utils.IsInsideContainer() {
if !utils.IsInsideToolboxContainer() {
fmt.Fprintf(os.Stderr, "Error: this is not a toolbox container\n")
return
}
if _, err := utils.ForwardToHost(); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
return
}
return
}
manual := "toolbox"
for _, arg := range args {
if !strings.HasPrefix(arg, "-") {
manual = manual + "-" + arg
break
}
}
if err := showManual(manual); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err)
return
}
}
func rootRun(cmd *cobra.Command, args []string) error {
return rootRunImpl(cmd, args)
}
func migrate() error {
logrus.Debug("Migrating to newer Podman")
if utils.IsInsideContainer() {
return nil
}
configDir, err := os.UserConfigDir()
if err != nil {
logrus.Debugf("Migrating to newer Podman: failed to get the user config directory: %s", err)
return errors.New("failed to get the user config directory")
}
toolboxConfigDir := configDir + "/toolbox"
stampPath := toolboxConfigDir + "/podman-system-migrate"
logrus.Debugf("Toolbox config directory is %s", toolboxConfigDir)
podmanVersion, err := podman.GetVersion()
if err != nil {
logrus.Debugf("Migrating to newer Podman: failed to get the Podman version: %s", err)
return errors.New("failed to get the Podman version")
}
logrus.Debugf("Current Podman version is %s", podmanVersion)
err = os.MkdirAll(toolboxConfigDir, 0775)
if err != nil {
logrus.Debugf("Migrating to newer Podman: failed to create configuration directory %s: %s",
toolboxConfigDir,
err)
return errors.New("failed to create configuration directory")
}
toolboxRuntimeDirectory, err := utils.GetRuntimeDirectory(currentUser)
if err != nil {
return err
}
migrateLock := toolboxRuntimeDirectory + "/migrate.lock"
migrateLockFile, err := os.Create(migrateLock)
if err != nil {
logrus.Debugf("Migrating to newer Podman: failed to create migration lock file %s: %s", migrateLock, err)
return errors.New("failed to create migration lock file")
}
defer migrateLockFile.Close()
migrateLockFD := migrateLockFile.Fd()
migrateLockFDInt := int(migrateLockFD)
if err := syscall.Flock(migrateLockFDInt, syscall.LOCK_EX); err != nil {
logrus.Debugf("Migrating to newer Podman: failed to acquire migration lock on %s: %s", migrateLock, err)
return errors.New("failed to acquire migration lock")
}
stampBytes, err := ioutil.ReadFile(stampPath)
if err != nil {
if !os.IsNotExist(err) {
logrus.Debugf("Migrating to newer Podman: failed to read migration stamp file %s: %s", stampPath, err)
return errors.New("failed to read migration stamp file")
}
} else {
stampString := string(stampBytes)
podmanVersionOld := strings.TrimSpace(stampString)
if podmanVersionOld != "" {
logrus.Debugf("Old Podman version is %s", podmanVersionOld)
if podmanVersion == podmanVersionOld {
logrus.Debugf("Migration not needed: Podman version %s is unchanged",
podmanVersion)
return nil
}
if !podman.CheckVersion(podmanVersionOld) {
logrus.Debugf("Migration not needed: Podman version %s is old", podmanVersion)
return nil
}
}
}
if err = podman.SystemMigrate(""); err != nil {
logrus.Debugf("Migrating to newer Podman: failed to migrate containers: %s", err)
return errors.New("failed to migrate containers")
}
logrus.Debugf("Migration to Podman version %s was ok", podmanVersion)
logrus.Debugf("Updating Podman version in %s", stampPath)
podmanVersionBytes := []byte(podmanVersion + "\n")
err = ioutil.WriteFile(stampPath, podmanVersionBytes, 0664)
if err != nil {
logrus.Debugf("Migrating to newer Podman: failed to update Podman version in migration stamp file %s: %s",
stampPath,
err)
return errors.New("failed to update Podman version in migration stamp file")
}
return nil
}
func newSubIDFileError() error {
var builder strings.Builder
fmt.Fprintf(&builder, "/etc/subgid and /etc/subuid don't have entries for user %s\n", currentUser.Username)
fmt.Fprintf(&builder, "See the podman(1), subgid(5), subuid(5) and usermod(8) manuals for more\n")
fmt.Fprintf(&builder, "information.")
errMsg := builder.String()
return errors.New(errMsg)
}
func setUpGlobals() error {
var err error
if !utils.IsInsideContainer() {
cgroupsVersion, err = utils.GetCgroupsVersion()
if err != nil {
return fmt.Errorf("failed to get the cgroups version: %w", err)
}
}
currentUser, err = user.Current()
if err != nil {
return fmt.Errorf("failed to get the current user: %w", err)
}
executable, err = os.Executable()
if err != nil {
return fmt.Errorf("failed to get the path to the executable: %w", err)
}
executable, err = filepath.EvalSymlinks(executable)
if err != nil {
return fmt.Errorf("failed to resolve absolute path to the executable: %w", err)
}
executableBase = filepath.Base(executable)
workingDirectory, err = os.Getwd()
if err != nil {
return fmt.Errorf("failed to get the working directory: %w", err)
}
return nil
}
func setUpLoggers() error {
logrus.SetOutput(os.Stderr)
logrus.SetFormatter(&logrus.TextFormatter{
DisableTimestamp: true,
})
if rootFlags.verbose > 0 {
rootFlags.logLevel = "debug"
}
logLevel, err := logrus.ParseLevel(rootFlags.logLevel)
if err != nil {
return fmt.Errorf("failed to parse log-level: %w", err)
}
logrus.SetLevel(logLevel)
if rootFlags.verbose > 1 {
rootFlags.logPodman = true
}
if rootFlags.logPodman {
podman.SetLogLevel(logLevel)
}
return nil
}
func validateSubIDFile(path string) (bool, error) {
logrus.Debugf("Validating sub-ID file %s", path)
file, err := os.Open(path)
if err != nil {
logrus.Debugf("Validating sub-ID file: failed to open %s: %s", path, err)
return false, fmt.Errorf("failed to open %s", path)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
prefixes := []string{currentUser.Username + ":", currentUser.Uid + ":"}
for scanner.Scan() {
line := scanner.Text()
for _, prefix := range prefixes {
if strings.HasPrefix(line, prefix) {
return true, nil
}
}
}
return false, fmt.Errorf("failed to find an entry for user %s in %s", currentUser.Username, path)
}