-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
326 lines (308 loc) · 8.98 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
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
package main
import (
"archive/tar"
"compress/gzip"
"encoding/json"
"fmt"
spec "github.com/opencontainers/runtime-spec/specs-go"
cp "github.com/otiai10/copy"
"github.com/shirou/gopsutil/v3/process"
log "github.com/sirupsen/logrus"
logrusSyslog "github.com/sirupsen/logrus/hooks/syslog"
"github.com/spf13/cobra"
"io"
"io/fs"
"log/syslog"
"os"
"path"
"path/filepath"
"strings"
)
const (
upperDirPrefix = "upperdir="
defaultLogLevel = "info"
)
var (
LogLevels = []string{"trace", "debug", "info", "warn", "warning", "error", "fatal", "panic"}
logLevel = defaultLogLevel
useSyslog = false
mountProgram = "/usr/bin/fuse-overlayfs"
)
func loadSpec(stateInput io.Reader) spec.Spec {
var state spec.State
err := json.NewDecoder(stateInput).Decode(&state)
if err != nil {
log.Fatalf("Failed to parse stdin with error %s", err)
}
configPath := path.Join(state.Bundle, "config.json")
jsonFile, err := os.Open(configPath)
defer jsonFile.Close()
if err != nil {
log.Fatalf("Failed to open OCI spec file %s with error %s", configPath, err)
}
var containerSpec spec.Spec
err = json.NewDecoder(jsonFile).Decode(&containerSpec)
if err != nil {
log.Fatalf("Failed to parse OCI spec JSON file %s with error %s", configPath, err)
}
return containerSpec
}
func archiveTarGzip(src string, archiveTo string, uid int, gid int) error {
// ref: https://golangdocs.com/tar-gzip-in-golang
// ref: https://github.com/containers/podman/blob/d09edd2820e25372c63e2a9d16a42b6d258b7f80/pkg/bindings/images/build.go#L633-L791
// ref: https://gist.github.com/mimoo/25fc9716e0f1353791f5908f94d6e726
archiveFile, err := os.OpenFile(archiveTo, os.O_CREATE|os.O_RDWR, os.FileMode(0644))
gzipWriter := gzip.NewWriter(archiveFile)
tarWriter := tar.NewWriter(gzipWriter)
defer archiveFile.Close()
defer gzipWriter.Close()
defer tarWriter.Close()
srcPath, err := filepath.Abs(src)
err = filepath.Walk(src, func(path string, fileInfo os.FileInfo, err error) error {
absPath, err := filepath.Abs(path)
if err != nil {
return err
}
header, err := tar.FileInfoHeader(fileInfo, fileInfo.Name())
if err != nil {
return err
}
separator := string(filepath.Separator)
if absPath == srcPath {
separator = ""
}
header.Name = "./" + filepath.ToSlash(strings.TrimPrefix(absPath, srcPath+separator))
if absPath != srcPath && fileInfo.IsDir() {
header.Name += "/"
}
if uid >= 0 {
header.Uid = uid
header.Uname = ""
}
if gid >= 0 {
header.Gid = gid
header.Gname = ""
}
if err := tarWriter.WriteHeader(header); err != nil {
return err
}
if !fileInfo.IsDir() && fileInfo.Mode()&fs.ModeDevice == 0 {
data, err := os.Open(path)
if err != nil {
return err
}
if _, err := io.Copy(tarWriter, data); err != nil {
return err
}
}
return nil
})
if err != nil {
return err
}
return nil
}
func archiveUpperDirs(containerSpec spec.Spec, mountPointArchives map[string]Archive) {
var fuseMountListed = false
var fuseMountOptions = map[string][]string{}
for _, mount := range containerSpec.Mounts {
archive, ok := mountPointArchives[mount.Destination]
if !ok {
log.Tracef("Cannot find mount point %s to archive, skip", mount.Destination)
continue
}
var mountOptions []string
if mount.Type == "overlay" {
// For root run, podman is going to use overlay directly and this will be an overlay mount
log.Debugf("Overlay mount found at %s with options %s", mount.Destination, mount.Options)
mountOptions = mount.Options
} else if mount.Type == "bind" {
if !fuseMountListed {
fuseMountOptions = listFuseMountOptions()
fuseMountListed = true
}
// For rootless run, podman is going to use fuse-overlayfs mount, and this will be a
// bind mount, so we need to find out the options from mounts.
mountOptions, ok = fuseMountOptions[mount.Source]
if !ok {
log.Fatalf("No fuse mount found for %s", mount.Destination)
continue
}
log.Debugf("Bind mount source fuse mount options %s found for %s", fuseMountOptions, mount.Destination)
} else {
log.Fatalf("Unexpected mount type %s at %s, only overlay supported", mount.Type, mount.Destination)
}
var upperDir = ""
for _, option := range mountOptions {
if strings.HasPrefix(option, upperDirPrefix) {
upperDir = option[len(upperDirPrefix):]
break
}
}
if upperDir == "" {
log.WithFields(log.Fields{"mount": mount}).Fatalf(
"Cannot find upperdir for archive %s in mount with mount options %s",
archive.Name,
mountOptions,
)
}
var method = archive.Method
if method == "" {
method = ArchiveMethodCopy
}
if method == ArchiveMethodCopy {
log.Infof("Copying upperdir from %s to %s for archive %s", upperDir, archive.ArchiveTo, archive.Name)
err := cp.Copy(upperDir, archive.ArchiveTo)
if err != nil {
log.Fatalf("Failed to copy from %s to %s for archive %s with error %s", upperDir, archive.ArchiveTo, archive.Name, err)
}
} else if method == ArchiveMethodTarGzip {
log.Infof("Archiving upperdir from %s to %s for archive %s", upperDir, archive.ArchiveTo, archive.Name)
err := archiveTarGzip(upperDir, archive.ArchiveTo, archive.TarUser, archive.TarGroup)
if err != nil {
log.Fatalf("Failed to archive tar.gz from %s to %s for archive %s with error %s", upperDir, archive.ArchiveTo, archive.Name, err)
}
} else {
log.Fatalf("Unknown archive method %s", method)
}
if archive.ArchiveSuccess != "" {
err := os.WriteFile(archive.ArchiveSuccess, []byte{}, 0644)
if err != nil {
log.Fatalf("Failed to write archive success file %s for archive %s with error %s", archive.ArchiveSuccess, archive.Name, err)
}
}
}
}
func listFuseMountOptions() map[string][]string {
log.Infof("Enumerate fuse mount processes with mount program %s ...", mountProgram)
mountOptions := map[string][]string{}
processes, err := process.Processes()
if err != nil {
log.Fatalf("Failed to fetch processes")
}
for _, proc := range processes {
exe, err := proc.Exe()
if err != nil {
log.Warnf("Cannot get exe of proc %d, skip", proc.Pid)
continue
}
if exe != mountProgram {
continue
}
cmd, err := proc.CmdlineSlice()
if err != nil {
log.Warnf("Cannot get cmd of proc %d, skip", proc.Pid)
continue
}
var lastOption string
var fuseMountOption string
var fuseMountPoint string
for _, arg := range cmd {
if strings.HasPrefix(arg, "-") {
lastOption = arg
continue
}
if lastOption == "-o" {
fuseMountOption = arg
} else if lastOption == "" {
fuseMountPoint = arg
}
lastOption = ""
}
if fuseMountOption == "" {
log.Warnf("Cannot find option argument of mount process %d, skip", proc.Pid)
continue
}
if fuseMountPoint == "" {
log.Warnf("Cannot find mount point argument of mount process %d, skip", proc.Pid)
continue
}
mountOptions[fuseMountPoint] = strings.Split(fuseMountOption, ",")
}
return mountOptions
}
func run() {
containerSpec := loadSpec(os.Stdin)
destArchives := parseArchives(containerSpec.Annotations)
archivesJson, err := json.Marshal(destArchives)
if err != nil {
log.Fatal(err)
}
log.Debugf("Parsed archives: %s", string(archivesJson))
archiveUpperDirs(containerSpec, destArchives)
log.Infof("Done")
}
func setupLogLevel() {
var found = false
for _, level := range LogLevels {
if level == strings.ToLower(logLevel) {
found = true
break
}
}
if !found {
fmt.Fprintf(os.Stderr, "Log Level %q is not supported, choose from: %s\n", logLevel, strings.Join(LogLevels, ", "))
os.Exit(1)
}
level, err := log.ParseLevel(logLevel)
if err != nil {
fmt.Fprint(os.Stderr, err.Error())
os.Exit(1)
}
log.SetLevel(level)
}
func initSyslog() {
if !useSyslog {
return
}
hook, err := logrusSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to enable syslog with error %s", err)
return
}
log.AddHook(hook)
}
func init() {
// Hooks are called before PersistentPreRunE(). These hooks affect global
// state and are executed after processing the command-line, but before
// actually running the command.
cobra.OnInitialize(initSyslog)
}
func main() {
var rootCmd = &cobra.Command{
Use: "archive_overlay [options]",
Short: "Invoked as a poststop OCI-hooks to archive upperdir of specific overlay mount",
Version: Version,
Run: func(cmd *cobra.Command, args []string) {
setupLogLevel()
log.Infof("Run archive_overlay %s", Version)
run()
},
}
pFlags := rootCmd.PersistentFlags()
logLevelFlagName := "log-level"
pFlags.StringVar(
&logLevel,
logLevelFlagName,
logLevel,
fmt.Sprintf("Log messages above specified level (%s)", strings.Join(LogLevels, ", ")),
)
syslogFlagName := "syslog"
pFlags.BoolVar(
&useSyslog,
syslogFlagName,
useSyslog,
fmt.Sprintf("Log messages to syslog"),
)
mountProgramFlagName := "mount-program"
pFlags.StringVar(
&mountProgram,
mountProgramFlagName,
mountProgram,
fmt.Sprintf("The paht to mount program used by the OCI runtime, used for looking up fuse mount options"),
)
err := rootCmd.Execute()
if err != nil {
log.Fatal(err)
}
}