forked from GoogleCloudPlatform/gcsfuse
/
setup.go
455 lines (388 loc) · 11.9 KB
/
setup.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
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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
// Copyright 2023 Google Inc. All Rights Reserved.
//
// 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 setup
import (
"flag"
"fmt"
"log"
"math/rand"
"os"
"os/exec"
"path"
"runtime/debug"
"strings"
"syscall"
"testing"
"time"
"github.com/Tulsishah/gcsfuse-tulsishah7/tools/integration_tests/util/operations"
"github.com/Tulsishah/gcsfuse-tulsishah7/tools/util"
)
var testBucket = flag.String("testbucket", "", "The GCS bucket used for the test.")
var mountedDirectory = flag.String("mountedDirectory", "", "The GCSFuse mounted directory used for the test.")
var integrationTest = flag.Bool("integrationTest", false, "Run tests only when the flag value is true.")
var testInstalledPackage = flag.Bool("testInstalledPackage", false, "[Optional] Run tests on the package pre-installed on the host machine. By default, integration tests build a new package to run the tests.")
var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano()))
const (
BufferSize = 100
FilePermission_0600 = 0600
DirPermission_0755 = 0755
Charset = "abcdefghijklmnopqrstuvwxyz0123456789"
)
var (
binFile string
logFile string
testDir string
mntDir string
sbinFile string
onlyDirMounted string
dynamicBucketMounted string
)
// Run the shell script to prepare the testData in the specified bucket.
// First argument will be name of scipt script
func RunScriptForTestData(args ...string) {
cmd := exec.Command("/bin/bash", args...)
out, err := cmd.Output()
if err != nil {
log.Printf("Error: %s", out)
panic(err)
}
}
func TestBucket() string {
return *testBucket
}
func TestInstalledPackage() bool {
return *testInstalledPackage
}
func MountedDirectory() string {
return *mountedDirectory
}
func SetLogFile(logFileValue string) {
logFile = logFileValue
}
func LogFile() string {
return logFile
}
func SetBinFile(binFileValue string) {
binFile = binFileValue
}
func BinFile() string {
return binFile
}
func SbinFile() string {
return sbinFile
}
func SetTestDir(testDirValue string) {
testDir = testDirValue
}
func TestDir() string {
return testDir
}
func SetMntDir(mntDirValue string) {
mntDir = mntDirValue
}
func MntDir() string {
return mntDir
}
// OnlyDirMounted returns the name of the directory mounted in case of only dir mount.
func OnlyDirMounted() string {
return onlyDirMounted
}
// SetOnlyDirMounted sets the name of the directory mounted in case of only dir mount.
func SetOnlyDirMounted(onlyDirValue string) {
onlyDirMounted = onlyDirValue
}
// DynamicBucketMounted returns the name of the bucket in case of dynamic mount.
func DynamicBucketMounted() string {
return dynamicBucketMounted
}
// SetDynamicBucketMounted sets the name of the bucket in case of dynamic mount.
func SetDynamicBucketMounted(dynamicBucketValue string) {
dynamicBucketMounted = dynamicBucketValue
}
func CompareFileContents(t *testing.T, fileName string, fileContent string) {
content, err := os.ReadFile(fileName)
if err != nil {
t.Errorf("Read: %v", err)
}
if got := string(content); got != fileContent {
t.Errorf("File content doesn't match. Expected: %q, Actual: %q", fileContent, got)
}
}
func CreateTempFile() string {
// A temporary file is created and some lines are added
// to it for testing purposes.
fileName := path.Join(mntDir, "tmpFile")
file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC|syscall.O_DIRECT, FilePermission_0600)
if err != nil {
LogAndExit(fmt.Sprintf("Error in the opening the file %v", err))
}
defer operations.CloseFile(file)
_, err = file.WriteString("line 1\nline 2\n")
if err != nil {
LogAndExit(fmt.Sprintf("Temporary file at %v", err))
}
return fileName
}
func SetUpTestDir() error {
var err error
testDir, err = os.MkdirTemp("", "gcsfuse_readwrite_test_")
if err != nil {
return fmt.Errorf("TempDir: %w\n", err)
}
if !TestInstalledPackage() {
err = util.BuildGcsfuse(testDir)
if err != nil {
return fmt.Errorf("BuildGcsfuse(%q): %w\n", TestDir(), err)
}
binFile = path.Join(TestDir(), "bin/gcsfuse")
sbinFile = path.Join(TestDir(), "sbin/mount.gcsfuse")
// mount.gcsfuse will find gcsfuse executable in mentioned locations.
// https://github.com/GoogleCloudPlatform/gcsfuse/blob/master/tools/mount_gcsfuse/find.go#L59
// Copying the executable to /usr/local/bin
err := operations.CopyDirWithRootPermission(binFile, "/usr/local/bin")
if err != nil {
log.Printf("Error in copying bin file:%v", err)
}
} else {
// when testInstalledPackage flag is set, gcsfuse is preinstalled on the
// machine. Hence, here we are overwriting binFile to gcsfuse.
binFile = "gcsfuse"
sbinFile = "mount.gcsfuse"
}
logFile = path.Join(TestDir(), "gcsfuse.log")
mntDir = path.Join(TestDir(), "mnt")
err = os.Mkdir(mntDir, 0755)
if err != nil {
return fmt.Errorf("Mkdir(%q): %v\n", MntDir(), err)
}
return nil
}
// Removing bin file after testing.
func RemoveBinFileCopiedForTesting() {
if !TestInstalledPackage() {
cmd := exec.Command("sudo", "rm", "/usr/local/bin/gcsfuse")
err := cmd.Run()
if err != nil {
log.Printf("Error in removing file:%v", err)
}
}
}
func UnMount() error {
fusermount, err := exec.LookPath("fusermount")
if err != nil {
return fmt.Errorf("cannot find fusermount: %w", err)
}
cmd := exec.Command(fusermount, "-uz", mntDir)
if _, err := cmd.CombinedOutput(); err != nil {
return fmt.Errorf("fusermount error: %w", err)
}
return nil
}
func ExecuteTest(m *testing.M) (successCode int) {
successCode = m.Run()
return successCode
}
func GenerateRandomString(length int) string {
b := make([]byte, length)
for i := range b {
b[i] = Charset[seededRand.Intn(len(Charset))]
}
return string(b)
}
func UnMountBucket() {
err := UnMount()
if err != nil {
LogAndExit(fmt.Sprintf("Error in unmounting bucket: %v", err))
}
}
func SaveLogFileInCaseOfFailure(successCode int) {
if successCode != 0 {
// Logfile name will be failed-integration-test-log-xxxxx
failedlogsFileName := "failed-integration-test-logs-" + GenerateRandomString(5)
log.Printf("log file is available on kokoro artifacts with file name: %s", failedlogsFileName)
logFileInKokoroArtifact := path.Join(os.Getenv("KOKORO_ARTIFACTS_DIR"), failedlogsFileName)
err := operations.CopyFile(logFile, logFileInKokoroArtifact)
if err != nil {
log.Fatalf("Error in coping logfile in kokoro artifact: %v", err)
}
}
}
func UnMountAndThrowErrorInFailure(flags []string, successCode int) {
UnMountBucket()
if successCode != 0 {
// Print flag on which test fails
f := strings.Join(flags, " ")
log.Print("Test Fails on " + f)
SaveLogFileInCaseOfFailure(successCode)
}
}
func ExecuteTestForFlagsSet(flags []string, m *testing.M) (successCode int) {
successCode = ExecuteTest(m)
UnMountAndThrowErrorInFailure(flags, successCode)
return
}
func ParseSetUpFlags() {
flag.Parse()
if !*integrationTest {
log.Print("Pass --integrationTest flag to run the tests.")
os.Exit(0)
}
}
func IgnoreTestIfIntegrationTestFlagIsSet(t *testing.T) {
flag.Parse()
if *integrationTest {
t.SkipNow()
}
}
func ExitWithFailureIfBothTestBucketAndMountedDirectoryFlagsAreNotSet() {
ParseSetUpFlags()
if *testBucket == "" && *mountedDirectory == "" {
log.Print("--testbucket or --mountedDirectory must be specified")
os.Exit(1)
}
}
func RunTestsForMountedDirectoryFlag(m *testing.M) {
// Execute tests for the mounted directory.
if *mountedDirectory != "" {
mntDir = *mountedDirectory
successCode := ExecuteTest(m)
os.Exit(successCode)
}
}
func SetUpTestDirForTestBucketFlag() {
if TestBucket() == "" {
log.Fatal("Not running TestBucket tests as --testBucket flag is not set.")
}
if err := SetUpTestDir(); err != nil {
log.Printf("setUpTestDir: %v\n", err)
os.Exit(1)
}
}
func SetUpLogDirForTestDirTests(logDirName string) (logDir string) {
logDir = path.Join(TestDir(), logDirName)
err := os.Mkdir(logDir, DirPermission_0755)
if err != nil {
log.Printf("os.Mkdir %s: %v\n", logDir, err)
os.Exit(1)
}
return
}
func ValidateLogDirForMountedDirTests(logDirName string) (logDir string) {
if *mountedDirectory == "" {
return ""
}
logDir = path.Join(os.TempDir(), logDirName)
_, err := os.Stat(logDir)
if err != nil {
log.Printf("validateLogDirForMountedDirTests %s: %v\n", logDir, err)
os.Exit(1)
}
return
}
func LogAndExit(s string) {
log.Print(s)
log.Print(string(debug.Stack()))
os.Exit(1)
}
// CleanUpDir cleans up the content in given directory.
func CleanUpDir(directoryPath string) {
dir, err := os.ReadDir(directoryPath)
if err != nil {
log.Printf("Error in reading directory: %v", err)
}
for _, d := range dir {
err := os.RemoveAll(path.Join([]string{directoryPath, d.Name()}...))
if err != nil {
log.Printf("Error in removing directory: %v", err)
}
}
}
// CleanMntDir cleans the mounted directory.
func CleanMntDir() {
CleanUpDir(mntDir)
}
// SetupTestDirectory creates a testDirectory in the mounted directory and cleans up
// any content present in it.
func SetupTestDirectory(testDirName string) string {
testDirPath := path.Join(MntDir(), testDirName)
err := os.Mkdir(testDirPath, DirPermission_0755)
if err != nil && !strings.Contains(err.Error(), "file exists") {
log.Printf("Error while setting up directory %s for testing: %v", testDirPath, err)
}
CleanUpDir(testDirPath)
return testDirPath
}
// CleanupDirectoryOnGCS cleans up the object/directory path passed in parameter.
func CleanupDirectoryOnGCS(directoryPathOnGCS string) {
_, err := operations.ExecuteGsutilCommandf("rm -rf gs://%s", directoryPathOnGCS)
if err != nil {
log.Printf("Error while cleaning up directory %s from GCS: %v",
directoryPathOnGCS, err)
}
}
func AreBothMountedDirectoryAndTestBucketFlagsSet() bool {
if MountedDirectory() != "" && TestBucket() != "" {
return true
}
log.Print("Not running mounted directory tests as both --mountedDirectory and --testBucket flags are not set.")
return false
}
func separateBucketAndObjectName(bucket, object string) (string, string) {
bucketAndObjectPath := strings.SplitN(bucket, "/", 2)
bucket = bucketAndObjectPath[0]
object = path.Join(bucketAndObjectPath[1], object)
return bucket, object
}
func GetBucketAndObjectBasedOnTypeOfMount(object string) (string, string) {
bucket := TestBucket()
if strings.Contains(TestBucket(), "/") {
// This case arises when we run tests on mounted directory and pass
// bucket/directory in testbucket flag.
bucket, object = separateBucketAndObjectName(bucket, object)
}
if dynamicBucketMounted != "" {
bucket = dynamicBucketMounted
}
if OnlyDirMounted() != "" {
var suffix string
if strings.HasSuffix(object, "/") {
suffix = "/"
}
object = path.Join(OnlyDirMounted(), object) + suffix
}
return bucket, object
}
func MountGCSFuseWithGivenMountFunc(flags []string, mountFunc func([]string) error) {
if *mountedDirectory == "" {
// Mount GCSFuse only when tests are not running on mounted directory.
if err := mountFunc(flags); err != nil {
LogAndExit(fmt.Sprintf("Failed to mount GCSFuse: %v", err))
}
}
}
func UnmountGCSFuseAndDeleteLogFile(rootDir string) {
SetMntDir(rootDir)
if *mountedDirectory == "" {
// Unmount GCSFuse only when tests are not running on mounted directory.
err := UnMount()
if err != nil {
LogAndExit(fmt.Sprintf("Error in unmounting bucket: %v", err))
}
// delete log file created
err = os.Remove(LogFile())
if err != nil {
LogAndExit(fmt.Sprintf("Error in deleting log file: %v", err))
}
}
}