github.com/crowdsecurity/crowdsec@v1.6.1/pkg/hubtest/utils.go (about) 1 package hubtest 2 3 import ( 4 "fmt" 5 "net" 6 "os" 7 "path/filepath" 8 "time" 9 10 log "github.com/sirupsen/logrus" 11 ) 12 13 func IsAlive(target string) (bool, error) { 14 start := time.Now() 15 for { 16 conn, err := net.Dial("tcp", target) 17 if err == nil { 18 log.Debugf("'%s' is up after %s", target, time.Since(start)) 19 conn.Close() 20 return true, nil 21 } 22 time.Sleep(500 * time.Millisecond) 23 if time.Since(start) > 10*time.Second { 24 return false, fmt.Errorf("took more than 10s for %s to be available", target) 25 } 26 } 27 } 28 29 func Copy(src string, dst string) error { 30 content, err := os.ReadFile(src) 31 if err != nil { 32 return err 33 } 34 35 err = os.WriteFile(dst, content, 0o644) 36 if err != nil { 37 return err 38 } 39 40 return nil 41 } 42 43 // checkPathNotContained returns an error if 'subpath' is inside 'path' 44 func checkPathNotContained(path string, subpath string) error { 45 absPath, err := filepath.Abs(path) 46 if err != nil { 47 return err 48 } 49 50 absSubPath, err := filepath.Abs(subpath) 51 if err != nil { 52 return err 53 } 54 55 current := absSubPath 56 57 for { 58 if current == absPath { 59 return fmt.Errorf("cannot copy a folder onto itself") 60 } 61 62 up := filepath.Dir(current) 63 if current == up { 64 break 65 } 66 67 current = up 68 } 69 70 return nil 71 } 72 73 func CopyDir(src string, dest string) error { 74 err := checkPathNotContained(src, dest) 75 if err != nil { 76 return err 77 } 78 79 f, err := os.Open(src) 80 if err != nil { 81 return err 82 } 83 84 file, err := f.Stat() 85 if err != nil { 86 return err 87 } 88 89 if !file.IsDir() { 90 return fmt.Errorf("Source " + file.Name() + " is not a directory!") 91 } 92 93 err = os.MkdirAll(dest, 0755) 94 if err != nil { 95 return err 96 } 97 98 files, err := os.ReadDir(src) 99 if err != nil { 100 return err 101 } 102 103 for _, f := range files { 104 if f.IsDir() { 105 if err = CopyDir(filepath.Join(src, f.Name()), filepath.Join(dest, f.Name())); err != nil { 106 return err 107 } 108 } else { 109 if err = Copy(filepath.Join(src, f.Name()), filepath.Join(dest, f.Name())); err != nil { 110 return err 111 } 112 } 113 } 114 115 return nil 116 }