File: overlay_item_linux_test.go

package info (click to toggle)
singularity-container 4.0.3%2Bds1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 21,672 kB
  • sloc: asm: 3,857; sh: 2,125; ansic: 1,677; awk: 414; makefile: 110; python: 99
file content (431 lines) | stat: -rw-r--r-- 13,034 bytes parent folder | download
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
// Copyright (c) 2019-2023, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.

package overlay

import (
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/sylabs/singularity/v4/internal/pkg/test/tool/dirs"
	"github.com/sylabs/singularity/v4/internal/pkg/test/tool/require"
	"github.com/sylabs/singularity/v4/internal/pkg/util/fs"
	"github.com/sylabs/singularity/v4/pkg/image"
	"github.com/sylabs/singularity/v4/pkg/util/fs/proc"
	"github.com/sylabs/singularity/v4/pkg/util/slice"
)

const (
	testFilePath       string = "file-for-testing"
	squashfsTestString string = "squashfs-test-string\n"
	extfsTestString    string = "extfs-test-string\n"
)

var (
	imgsPath        = filepath.Join("..", "..", "..", "..", "..", "test", "images")
	squashfsImgPath = filepath.Join(imgsPath, "squashfs-for-overlay.img")
	extfsImgPath    = filepath.Join(imgsPath, "extfs-for-overlay.img")
)

func mkTempDirOrFatal(t *testing.T) string {
	tmpDir, err := os.MkdirTemp(t.TempDir(), "testoverlayitem-")
	if err != nil {
		t.Fatalf("failed to create temporary dir: %s", err)
	}
	t.Cleanup(func() {
		if !t.Failed() {
			os.RemoveAll(tmpDir)
		}
	})

	return tmpDir
}

func mkTempOlDirOrFatal(t *testing.T) string {
	tmpOlDir := mkTempDirOrFatal(t)
	dirs.MkdirOrFatal(t, filepath.Join(tmpOlDir, "upper"), 0o777)
	dirs.MkdirOrFatal(t, filepath.Join(tmpOlDir, "lower"), 0o777)

	return tmpOlDir
}

func TestItemWritableField(t *testing.T) {
	tmpOlDir := mkTempOlDirOrFatal(t)
	rwOverlayStr := tmpOlDir
	roOverlayStr := tmpOlDir + ":ro"

	rwItem, err := NewItemFromString(rwOverlayStr)
	if err != nil {
		t.Fatalf("unexpected error while initializing rwItem from string %q: %s", rwOverlayStr, err)
	}
	roItem, err := NewItemFromString(roOverlayStr)
	if err != nil {
		t.Fatalf("unexpected error while initializing roItem from string %q: %s", roOverlayStr, err)
	}

	if rwItem.Readonly {
		t.Errorf("Readonly field of overlay.Item initialized with string %q should be false but is true", rwOverlayStr)
	}

	if !roItem.Readonly {
		t.Errorf("Readonly field of overlay.Item initialized with string %q should be true but is false", roOverlayStr)
	}
}

func TestItemMissing(t *testing.T) {
	const dir string = "/testoverlayitem-this_should_be_missing"
	rwOverlayStr := dir
	roOverlayStr := dir + ":ro"

	if _, err := NewItemFromString(rwOverlayStr); err == nil {
		t.Errorf("unexpected success: initializing overlay.Item with missing file/dir (%q) should have failed", rwOverlayStr)
	}
	if _, err := NewItemFromString(roOverlayStr); err == nil {
		t.Errorf("unexpected success: initializing overlay.Item with missing file/dir (%q) should have failed", roOverlayStr)
	}
}

func verifyAutoParentDir(t *testing.T, item *Item) {
	const autoParentDirStr string = "overlay-parent-"
	if parentDir, err := item.GetParentDir(); err != nil {
		t.Fatalf("unexpected error while calling Item.GetParentDir(): %s", err)
	} else if !strings.Contains(parentDir, autoParentDirStr) {
		t.Errorf("auto-generated parent dir %q does not contain expected identifier string %q", parentDir, autoParentDirStr)
	} else if !strings.HasPrefix(parentDir, "/tmp/") {
		t.Errorf("auto-generated parent dir %q is not in expected location", parentDir)
	}
}

func TestAutofillParentDir(t *testing.T) {
	tmpOlDir := mkTempOlDirOrFatal(t)
	rwOverlayStr := tmpOlDir
	roOverlayStr := tmpOlDir + ":ro"

	rwItem, err := NewItemFromString(rwOverlayStr)
	if err != nil {
		t.Fatalf("unexpected error while initializing rwItem from string %q: %s", rwOverlayStr, err)
	}
	roItem, err := NewItemFromString(roOverlayStr)
	if err != nil {
		t.Fatalf("unexpected error while initializing roItem from string %q: %s", roOverlayStr, err)
	}

	verifyAutoParentDir(t, rwItem)
	verifyAutoParentDir(t, roItem)
}

func verifyExplicitParentDir(t *testing.T, item *Item, dir string) {
	item.SetParentDir(dir)
	if parentDir, err := item.GetParentDir(); err != nil {
		t.Fatalf("unexpected error while calling Item.GetParentDir(): %s", err)
	} else if parentDir != dir {
		t.Errorf("item returned parent dir %q (expected: %q)", parentDir, dir)
	}
}

func TestExplicitParentDir(t *testing.T) {
	tmpOlDir := mkTempOlDirOrFatal(t)
	rwOverlayStr := tmpOlDir
	roOverlayStr := tmpOlDir + ":ro"

	rwItem, err := NewItemFromString(rwOverlayStr)
	if err != nil {
		t.Fatalf("unexpected error while initializing rwItem from string %q: %s", rwOverlayStr, err)
	}
	roItem, err := NewItemFromString(roOverlayStr)
	if err != nil {
		t.Fatalf("unexpected error while initializing roItem from string %q: %s", roOverlayStr, err)
	}

	verifyExplicitParentDir(t, rwItem, "/my-special-directory")
	verifyExplicitParentDir(t, roItem, "/my-other-special-directory")
}

func verifyDirExistsAndWritable(t *testing.T, dir string) {
	s, err := os.Stat(dir)
	if err != nil {
		if os.IsNotExist(err) {
			t.Errorf("expected directory %q not found", dir)
		} else {
			t.Fatalf("unexpected error while looking for directory %q: %s", dir, err)
		}
		return
	}

	if !s.IsDir() {
		t.Fatalf("expected %q to be a directory but it is not", dir)
		return
	}

	file, err := os.CreateTemp(dir, "attempt-to-write-a-file")
	if err != nil {
		t.Fatalf("could not create a file inside %q, which should have been writable: %s", dir, err)
	}
	path := file.Name()
	file.Close()
	if err := os.Remove(path); err != nil {
		t.Fatalf("unexpected error while trying to remove temporary file %q: %s", path, err)
	}
}

func TestUpperAndWorkCreation(t *testing.T) {
	tmpDir := mkTempDirOrFatal(t)

	item, err := NewItemFromString(tmpDir)
	if err != nil {
		t.Fatalf("unexpected error while initializing rwItem from string %q: %s", tmpDir, err)
	}

	if err := item.prepareWritableOverlay(); err != nil {
		t.Fatalf("unexpected error while calling prepareWritableOverlay(): %s", err)
	}

	verifyDirExistsAndWritable(t, tmpDir+"/upper")
	verifyDirExistsAndWritable(t, tmpDir+"/work")
}

func TestDirMounts(t *testing.T) {
	tests := []struct {
		name            string
		olStr           string
		allowSetUID     bool
		allowDev        bool
		expectMountOpts []string
	}{
		{
			name:            "RO",
			olStr:           mkTempOlDirOrFatal(t) + ":ro",
			allowSetUID:     false,
			allowDev:        false,
			expectMountOpts: []string{"ro", "nosuid", "nodev"},
		},
		{
			name:            "RW",
			olStr:           mkTempOlDirOrFatal(t),
			allowSetUID:     false,
			allowDev:        false,
			expectMountOpts: []string{"rw", "nosuid", "nodev"},
		},
		{
			name:            "AllowSetuid",
			olStr:           mkTempOlDirOrFatal(t),
			allowSetUID:     true,
			allowDev:        false,
			expectMountOpts: []string{"rw", "nodev"},
		},
		{
			name:            "AllowDev",
			olStr:           mkTempOlDirOrFatal(t),
			allowSetUID:     false,
			allowDev:        true,
			expectMountOpts: []string{"rw", "nosuid"},
		},
		{
			name:            "AllowSetuidDev",
			olStr:           mkTempOlDirOrFatal(t),
			allowSetUID:     true,
			allowDev:        true,
			expectMountOpts: []string{"rw"},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			item, err := NewItemFromString(tt.olStr)
			if err != nil {
				t.Fatalf("unexpected error while initializing overlay item from string %q: %s", tt.olStr, err)
			}

			item.SetAllowSetuid(tt.allowSetUID)
			item.SetAllowDev(tt.allowDev)

			if err := item.Mount(); err != nil {
				t.Fatalf("while trying to mount dir %q: %s", tt.olStr, err)
			}

			checkMountOpts(t, item.StagingDir, tt.expectMountOpts)

			if err := item.Unmount(); err != nil {
				t.Errorf("while trying to unmount dir %q: %s", tt.olStr, err)
			}
		})
	}
}

func TestImageRO(t *testing.T) {
	require.Command(t, "fusermount")

	tests := []struct {
		name            string
		fusebin         string
		olStr           string
		typeCode        int
		typeStr         string
		allowSetUID     bool
		allowDev        bool
		expectStr       string
		expectMountOpts []string
	}{
		{
			name:            "squashfs",
			fusebin:         "squashfuse",
			olStr:           squashfsImgPath,
			typeCode:        image.SQUASHFS,
			typeStr:         "squashfs",
			expectStr:       squashfsTestString,
			expectMountOpts: []string{"ro", "nosuid", "nodev"},
		},
		{
			name:      "extfs",
			fusebin:   "fuse2fs",
			olStr:     extfsImgPath + ":ro",
			typeCode:  image.EXT3,
			typeStr:   "extfs",
			expectStr: extfsTestString,
			// NOTE - fuse2fs mount shows a "rw" mount option even when mounted "ro".
			// However, it does actually restrict read-only.
			expectMountOpts: []string{"rw", "nosuid", "nodev"},
		},
		{
			name:            "AllowSetuid",
			fusebin:         "squashfuse",
			olStr:           squashfsImgPath,
			typeCode:        image.SQUASHFS,
			typeStr:         "squashfs",
			allowSetUID:     true,
			allowDev:        false,
			expectStr:       squashfsTestString,
			expectMountOpts: []string{"ro", "nodev"},
		},
		{
			name:            "AllowDev",
			fusebin:         "squashfuse",
			olStr:           squashfsImgPath,
			typeCode:        image.SQUASHFS,
			typeStr:         "squashfs",
			allowSetUID:     false,
			allowDev:        true,
			expectStr:       squashfsTestString,
			expectMountOpts: []string{"ro", "nosuid"},
		},
		{
			name:            "AllowSetuidDev",
			fusebin:         "squashfuse",
			olStr:           squashfsImgPath,
			typeCode:        image.SQUASHFS,
			typeStr:         "squashfs",
			allowSetUID:     true,
			allowDev:        true,
			expectStr:       squashfsTestString,
			expectMountOpts: []string{"ro"},
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			require.Command(t, tt.fusebin)

			item, err := NewItemFromString(tt.olStr)
			if err != nil {
				t.Fatalf("unexpected error while initializing overlay item from string %q: %s", tt.olStr, err)
			}
			item.SetAllowSetuid(tt.allowSetUID)
			item.SetAllowDev(tt.allowDev)

			if item.Type != tt.typeCode {
				t.Errorf("item.Type is %v (should be %v)", item.Type, tt.typeCode)
			}

			if err := item.Mount(); err != nil {
				t.Fatalf("unable to mount image for reading: %s", err)
			}
			t.Cleanup(func() {
				item.Unmount()
			})

			testFileStagedPath := filepath.Join(item.GetMountDir(), testFilePath)
			checkForStringInOverlay(t, tt.typeStr, testFileStagedPath, tt.expectStr)
			checkMountOpts(t, item.StagingDir, tt.expectMountOpts)
		})
	}
}

func TestExtfsRW(t *testing.T) {
	require.Command(t, "fuse2fs")
	require.Command(t, "fuse-overlayfs")
	require.Command(t, "fusermount")
	tmpDir := mkTempDirOrFatal(t)

	// Create a copy of the extfs test image to be used for testing writable
	// extfs image overlays
	writableExtfsImgPath := filepath.Join(tmpDir, "writable-extfs.img")
	err := fs.CopyFile(extfsImgPath, writableExtfsImgPath, 0o755)
	if err != nil {
		t.Fatalf("could not copy %q to %q: %s", extfsImgPath, writableExtfsImgPath, err)
	}

	item, err := NewItemFromString(writableExtfsImgPath)
	if err != nil {
		t.Fatalf("failed to mount extfs image at %q: %s", writableExtfsImgPath, err)
	}

	if item.Type != image.EXT3 {
		t.Errorf("item.Type is %v (should be %v)", item.Type, image.EXT3)
	}

	if err := item.Mount(); err != nil {
		t.Fatalf("unable to mount extfs image for reading & writing: %s", err)
	}
	t.Cleanup(func() {
		item.Unmount()
	})

	testFileStagedPath := filepath.Join(item.GetMountDir(), testFilePath)
	checkForStringInOverlay(t, "extfs", testFileStagedPath, extfsTestString)
	otherTestFileStagedPath := item.GetMountDir() + "_other"
	otherExtfsTestString := "another string"
	err = os.WriteFile(otherTestFileStagedPath, []byte(otherExtfsTestString), 0o755)
	if err != nil {
		t.Errorf("could not write to file %q in extfs image %q: %s", otherTestFileStagedPath, writableExtfsImgPath, err)
	}
	checkForStringInOverlay(t, "extfs", otherTestFileStagedPath, otherExtfsTestString)
	checkMountOpts(t, item.StagingDir, []string{"rw", "nosuid", "nodev", "relatime"})
}

func checkForStringInOverlay(t *testing.T, typeStr, stagedPath, expectStr string) {
	data, err := os.ReadFile(stagedPath)
	if err != nil {
		t.Fatalf("error while trying to read from file %q: %s", stagedPath, err)
	}
	foundStr := string(data)
	if foundStr != expectStr {
		t.Errorf("incorrect file contents in %s img: expected %q, but found: %q", typeStr, expectStr, foundStr)
	}
}

func checkMountOpts(t *testing.T, mountPoint string, wantOpts []string) {
	entries, err := proc.GetMountInfoEntry("/proc/self/mountinfo")
	if err != nil {
		t.Fatal(err)
	}

	for _, e := range entries {
		if e.Point != mountPoint {
			continue
		}

		// Drop "relatime" as it may or may not be a default depending on distro, and is of no practical relevance to us.
		haveOpts := slice.Subtract(e.Options, []string{"relatime"})

		if len(slice.Subtract(haveOpts, wantOpts)) != 0 {
			t.Errorf("Mount %q has options %q, expected %q", mountPoint, e.Options, wantOpts)
		}
		return
	}

	t.Errorf("Mount %q not found", mountPoint)
}