-
Notifications
You must be signed in to change notification settings - Fork 757
/
main.go
254 lines (230 loc) · 8.54 KB
/
main.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
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"runtime"
"runtime/pprof"
"strings"
"syscall"
"github.com/containers/buildah"
"github.com/containers/buildah/define"
"github.com/containers/buildah/pkg/cli"
"github.com/containers/buildah/pkg/parse"
"github.com/containers/common/pkg/config"
"github.com/containers/storage"
"github.com/containers/storage/pkg/unshare"
ispecs "github.com/opencontainers/image-spec/specs-go"
rspecs "github.com/opencontainers/runtime-spec/specs-go"
"github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
type globalFlags struct {
Debug bool
LogLevel string
Root string
RunRoot string
StorageDriver string
RegistriesConf string
RegistriesConfDir string
DefaultMountsFile string
StorageOpts []string
UserNSUID []string
UserNSGID []string
CPUProfile string
cpuProfileFile *os.File
MemoryProfile string
UserShortNameAliasConfPath string
CgroupManager string
}
var rootCmd = &cobra.Command{
Use: "buildah",
Long: "A tool that facilitates building OCI images",
RunE: func(cmd *cobra.Command, args []string) error {
return cmd.Help()
},
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
return before(cmd)
},
PersistentPostRunE: func(cmd *cobra.Command, args []string) error {
return after(cmd)
},
SilenceUsage: true,
SilenceErrors: true,
}
var (
globalFlagResults globalFlags
exitCode int
defaultContainerConfig *config.Config
)
func init() {
var (
defaultStoreDriverOptions []string
)
storageOptions, err := storage.DefaultStoreOptions()
if err != nil {
logrus.Errorf(err.Error())
os.Exit(1)
}
if len(storageOptions.GraphDriverOptions) > 0 {
optionSlice := storageOptions.GraphDriverOptions[:]
defaultStoreDriverOptions = optionSlice
}
defaultContainerConfig, err = config.Default()
if err != nil {
logrus.Errorf(err.Error())
os.Exit(1)
}
defaultContainerConfig.CheckCgroupsAndAdjustConfig()
cobra.OnInitialize(initConfig)
// Disable the implicit `completion` command in cobra.
rootCmd.CompletionOptions.DisableDefaultCmd = true
//rootCmd.TraverseChildren = true
rootCmd.Version = fmt.Sprintf("%s (image-spec %s, runtime-spec %s)", define.Version, ispecs.Version, rspecs.Version)
rootCmd.PersistentFlags().BoolVar(&globalFlagResults.Debug, "debug", false, "print debugging information")
// TODO Need to allow for environment variable
rootCmd.PersistentFlags().StringVar(&globalFlagResults.RegistriesConf, "registries-conf", "", "path to registries.conf file (not usually used)")
rootCmd.PersistentFlags().StringVar(&globalFlagResults.RegistriesConfDir, "registries-conf-dir", "", "path to registries.conf.d directory (not usually used)")
rootCmd.PersistentFlags().StringVar(&globalFlagResults.UserShortNameAliasConfPath, "short-name-alias-conf", "", "path to short name alias cache file (not usually used)")
rootCmd.PersistentFlags().StringVar(&globalFlagResults.Root, "root", storageOptions.GraphRoot, "storage root dir")
rootCmd.PersistentFlags().StringVar(&globalFlagResults.RunRoot, "runroot", storageOptions.RunRoot, "storage state dir")
rootCmd.PersistentFlags().StringVar(&globalFlagResults.CgroupManager, "cgroup-manager", defaultContainerConfig.Engine.CgroupManager, "cgroup manager")
rootCmd.PersistentFlags().StringVar(&globalFlagResults.StorageDriver, "storage-driver", storageOptions.GraphDriverName, "storage-driver")
rootCmd.PersistentFlags().StringSliceVar(&globalFlagResults.StorageOpts, "storage-opt", defaultStoreDriverOptions, "storage driver option")
rootCmd.PersistentFlags().StringSliceVar(&globalFlagResults.UserNSUID, "userns-uid-map", []string{}, "default `ctrID:hostID:length` UID mapping to use")
rootCmd.PersistentFlags().StringSliceVar(&globalFlagResults.UserNSGID, "userns-gid-map", []string{}, "default `ctrID:hostID:length` GID mapping to use")
rootCmd.PersistentFlags().StringVar(&globalFlagResults.DefaultMountsFile, "default-mounts-file", "", "path to default mounts file")
rootCmd.PersistentFlags().StringVar(&globalFlagResults.LogLevel, logLevel, "warn", `the log level to be used, one of "trace", "debug", "info", "warn", "error", "fatal", or "panic"`)
rootCmd.PersistentFlags().StringVar(&globalFlagResults.CPUProfile, "cpu-profile", "", "`file` to write CPU profile")
rootCmd.PersistentFlags().StringVar(&globalFlagResults.MemoryProfile, "memory-profile", "", "`file` to write memory profile")
if err := rootCmd.PersistentFlags().MarkHidden("cpu-profile"); err != nil {
logrus.Fatalf("unable to mark cpu-profile flag as hidden: %v", err)
}
if err := rootCmd.PersistentFlags().MarkHidden("debug"); err != nil {
logrus.Fatalf("unable to mark debug flag as hidden: %v", err)
}
if err := rootCmd.PersistentFlags().MarkHidden("default-mounts-file"); err != nil {
logrus.Fatalf("unable to mark default-mounts-file flag as hidden: %v", err)
}
if err := rootCmd.PersistentFlags().MarkHidden("memory-profile"); err != nil {
logrus.Fatalf("unable to mark memory-profile flag as hidden: %v", err)
}
}
func initConfig() {
// TODO Cobra allows us to do extra stuff here at init
// time if we ever want to take advantage.
}
const logLevel = "log-level"
func before(cmd *cobra.Command) error {
strLvl, err := cmd.Flags().GetString(logLevel)
if err != nil {
return err
}
logrusLvl, err := logrus.ParseLevel(strLvl)
if err != nil {
return fmt.Errorf("unable to parse log level: %w", err)
}
logrus.SetLevel(logrusLvl)
if globalFlagResults.Debug {
logrus.SetLevel(logrus.DebugLevel)
}
switch cmd.Use {
case "", "help", "version", "mount":
return nil
}
debugCapabilities()
unshare.MaybeReexecUsingUserNamespace(false)
if globalFlagResults.CPUProfile != "" {
globalFlagResults.cpuProfileFile, err = os.Create(globalFlagResults.CPUProfile)
if err != nil {
logrus.Fatalf("could not create CPU profile %s: %v", globalFlagResults.CPUProfile, err)
}
if err = pprof.StartCPUProfile(globalFlagResults.cpuProfileFile); err != nil {
logrus.Fatalf("error starting CPU profiling: %v", err)
}
}
defaultContainerConfig, err := config.Default()
if err != nil {
return err
}
for _, env := range defaultContainerConfig.Engine.Env.Get() {
splitEnv := strings.SplitN(env, "=", 2)
if len(splitEnv) != 2 {
return fmt.Errorf("invalid environment variable %q from containers.conf, valid configuration is KEY=value pair", env)
}
// skip if the env is already defined
if _, ok := os.LookupEnv(splitEnv[0]); ok {
logrus.Debugf("environment variable %q is already defined, skip the settings from containers.conf", splitEnv[0])
continue
}
if err := os.Setenv(splitEnv[0], splitEnv[1]); err != nil {
return err
}
}
return nil
}
func shutdownStore(cmd *cobra.Command) error {
if needToShutdownStore {
store, err := getStore(cmd)
if err != nil {
return err
}
logrus.Debugf("shutting down the store")
needToShutdownStore = false
if _, err = store.Shutdown(false); err != nil {
if errors.Is(err, storage.ErrLayerUsedByContainer) {
logrus.Infof("failed to shutdown storage: %q", err)
} else {
logrus.Warnf("failed to shutdown storage: %q", err)
}
}
}
return nil
}
func after(cmd *cobra.Command) error {
if err := shutdownStore(cmd); err != nil {
return err
}
if globalFlagResults.CPUProfile != "" {
pprof.StopCPUProfile()
globalFlagResults.cpuProfileFile.Close()
}
if globalFlagResults.MemoryProfile != "" {
memoryProfileFile, err := os.Create(globalFlagResults.MemoryProfile)
if err != nil {
logrus.Fatalf("could not create memory profile %s: %v", globalFlagResults.MemoryProfile, err)
}
defer memoryProfileFile.Close()
runtime.GC()
if err := pprof.Lookup("heap").WriteTo(memoryProfileFile, 1); err != nil {
logrus.Fatalf("could not write memory profile %s: %v", globalFlagResults.MemoryProfile, err)
}
}
return nil
}
func main() {
if buildah.InitReexec() {
return
}
// Hard code TMPDIR functions to use $TMPDIR or /var/tmp
os.Setenv("TMPDIR", parse.GetTempDir())
if err := rootCmd.Execute(); err != nil {
if logrus.IsLevelEnabled(logrus.TraceLevel) {
fmt.Fprintf(os.Stderr, "Error: %+v\n", err)
} else {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
}
exitCode = cli.ExecErrorCodeGeneric
var ee *exec.ExitError
if errors.As(err, &ee) {
if w, ok := ee.Sys().(syscall.WaitStatus); ok {
exitCode = w.ExitStatus()
}
}
if err := shutdownStore(rootCmd); err != nil {
logrus.Warnf("failed to shutdown storage: %q", err)
}
}
os.Exit(exitCode)
}