util.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // +build integration
  7. package integration
  8. import (
  9. "crypto/md5"
  10. cr "crypto/rand"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "log"
  15. "math/rand"
  16. "os"
  17. "path/filepath"
  18. "runtime"
  19. "sort"
  20. "strings"
  21. "testing"
  22. "time"
  23. "unicode"
  24. "github.com/syncthing/syncthing/lib/osutil"
  25. "github.com/syncthing/syncthing/lib/rc"
  26. "github.com/syncthing/syncthing/lib/symlinks"
  27. )
  28. func init() {
  29. rand.Seed(42)
  30. }
  31. const (
  32. id1 = "I6KAH76-66SLLLB-5PFXSOA-UFJCDZC-YAOMLEK-CP2GB32-BV5RQST-3PSROAU"
  33. id2 = "MRIW7OK-NETT3M4-N6SBWME-N25O76W-YJKVXPH-FUMQJ3S-P57B74J-GBITBAC"
  34. id3 = "373HSRP-QLPNLIE-JYKZVQF-P4PKZ63-R2ZE6K3-YD442U2-JHBGBQG-WWXAHAU"
  35. apiKey = "abc123"
  36. )
  37. func generateFiles(dir string, files, maxexp int, srcname string) error {
  38. fd, err := os.Open(srcname)
  39. if err != nil {
  40. return err
  41. }
  42. for i := 0; i < files; i++ {
  43. n := randomName()
  44. if rand.Float64() < 0.05 {
  45. // Some files and directories are dotfiles
  46. n = "." + n
  47. }
  48. p0 := filepath.Join(dir, string(n[0]), n[0:2])
  49. err = os.MkdirAll(p0, 0755)
  50. if err != nil {
  51. log.Fatal(err)
  52. }
  53. p1 := filepath.Join(p0, n)
  54. s := int64(1 << uint(rand.Intn(maxexp)))
  55. a := int64(128 * 1024)
  56. if a > s {
  57. a = s
  58. }
  59. s += rand.Int63n(a)
  60. if err := generateOneFile(fd, p1, s); err != nil {
  61. return err
  62. }
  63. }
  64. return nil
  65. }
  66. func generateOneFile(fd io.ReadSeeker, p1 string, s int64) error {
  67. src := io.LimitReader(&inifiteReader{fd}, int64(s))
  68. dst, err := os.Create(p1)
  69. if err != nil {
  70. return err
  71. }
  72. _, err = io.Copy(dst, src)
  73. if err != nil {
  74. return err
  75. }
  76. err = dst.Close()
  77. if err != nil {
  78. return err
  79. }
  80. _ = os.Chmod(p1, os.FileMode(rand.Intn(0777)|0400))
  81. t := time.Now().Add(-time.Duration(rand.Intn(30*86400)) * time.Second)
  82. err = os.Chtimes(p1, t, t)
  83. if err != nil {
  84. return err
  85. }
  86. return nil
  87. }
  88. func alterFiles(dir string) error {
  89. err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
  90. if os.IsNotExist(err) {
  91. // Something we deleted. Never mind.
  92. return nil
  93. }
  94. info, err = os.Stat(path)
  95. if err != nil {
  96. // Something we deleted while walking. Ignore.
  97. return nil
  98. }
  99. if strings.HasPrefix(filepath.Base(path), "test-") {
  100. return nil
  101. }
  102. switch filepath.Base(path) {
  103. case ".stfolder":
  104. return nil
  105. case ".stversions":
  106. return nil
  107. }
  108. // File structure is base/x/xy/xyz12345...
  109. // comps == 1: base (don't touch)
  110. // comps == 2: base/x (must be dir)
  111. // comps == 3: base/x/xy (must be dir)
  112. // comps > 3: base/x/xy/xyz12345... (can be dir or file)
  113. comps := len(strings.Split(path, string(os.PathSeparator)))
  114. r := rand.Intn(10)
  115. switch {
  116. case r == 0 && comps > 2:
  117. // Delete every tenth file or directory, except top levels
  118. return removeAll(path)
  119. case r == 1 && info.Mode().IsRegular():
  120. if info.Mode()&0200 != 0200 {
  121. // Not owner writable. Fix.
  122. if err = os.Chmod(path, 0644); err != nil {
  123. return err
  124. }
  125. }
  126. // Overwrite a random kilobyte of every tenth file
  127. fd, err := os.OpenFile(path, os.O_RDWR, 0644)
  128. if err != nil {
  129. return err
  130. }
  131. if info.Size() > 1024 {
  132. _, err = fd.Seek(rand.Int63n(info.Size()), os.SEEK_SET)
  133. if err != nil {
  134. return err
  135. }
  136. }
  137. _, err = io.Copy(fd, io.LimitReader(cr.Reader, 1024))
  138. if err != nil {
  139. return err
  140. }
  141. return fd.Close()
  142. // Change capitalization
  143. case r == 2 && comps > 3 && rand.Float64() < 0.2:
  144. if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
  145. // Syncthing is currently broken for case-only renames on case-
  146. // insensitive platforms.
  147. // https://github.com/syncthing/syncthing/issues/1787
  148. return nil
  149. }
  150. base := []rune(filepath.Base(path))
  151. for i, r := range base {
  152. if rand.Float64() < 0.5 {
  153. base[i] = unicode.ToLower(r)
  154. } else {
  155. base[i] = unicode.ToUpper(r)
  156. }
  157. }
  158. newPath := filepath.Join(filepath.Dir(path), string(base))
  159. if newPath != path {
  160. return osutil.TryRename(path, newPath)
  161. }
  162. /*
  163. This doesn't in fact work. Sometimes it appears to. We need to get this sorted...
  164. // Switch between files and directories
  165. case r == 3 && comps > 3 && rand.Float64() < 0.2:
  166. if !info.Mode().IsRegular() {
  167. err = removeAll(path)
  168. if err != nil {
  169. return err
  170. }
  171. d1 := []byte("I used to be a dir: " + path)
  172. err := ioutil.WriteFile(path, d1, 0644)
  173. if err != nil {
  174. return err
  175. }
  176. } else {
  177. err := osutil.Remove(path)
  178. if err != nil {
  179. return err
  180. }
  181. err = os.MkdirAll(path, 0755)
  182. if err != nil {
  183. return err
  184. }
  185. generateFiles(path, 10, 20, "../LICENSE")
  186. }
  187. return err
  188. */
  189. /*
  190. This fails. Bug?
  191. // Rename the file, while potentially moving it up in the directory hierarchy
  192. case r == 4 && comps > 2 && (info.Mode().IsRegular() || rand.Float64() < 0.2):
  193. rpath := filepath.Dir(path)
  194. if rand.Float64() < 0.2 {
  195. for move := rand.Intn(comps - 1); move > 0; move-- {
  196. rpath = filepath.Join(rpath, "..")
  197. }
  198. }
  199. return osutil.TryRename(path, filepath.Join(rpath, randomName()))
  200. */
  201. }
  202. return nil
  203. })
  204. if err != nil {
  205. return err
  206. }
  207. return generateFiles(dir, 25, 20, "../LICENSE")
  208. }
  209. func ReadRand(bs []byte) (int, error) {
  210. var r uint32
  211. for i := range bs {
  212. if i%4 == 0 {
  213. r = uint32(rand.Int63())
  214. }
  215. bs[i] = byte(r >> uint((i%4)*8))
  216. }
  217. return len(bs), nil
  218. }
  219. func randomName() string {
  220. var b [16]byte
  221. ReadRand(b[:])
  222. return fmt.Sprintf("%x", b[:])
  223. }
  224. type inifiteReader struct {
  225. rd io.ReadSeeker
  226. }
  227. func (i *inifiteReader) Read(bs []byte) (int, error) {
  228. n, err := i.rd.Read(bs)
  229. if err == io.EOF {
  230. err = nil
  231. i.rd.Seek(0, 0)
  232. }
  233. return n, err
  234. }
  235. // rm -rf
  236. func removeAll(dirs ...string) error {
  237. for _, dir := range dirs {
  238. files, err := osutil.Glob(dir)
  239. if err != nil {
  240. return err
  241. }
  242. for _, file := range files {
  243. // Set any non-writeable files and dirs to writeable. This is necessary for os.RemoveAll to work on Windows.
  244. filepath.Walk(file, func(path string, info os.FileInfo, err error) error {
  245. if err != nil {
  246. return err
  247. }
  248. if info.Mode()&0700 != 0700 {
  249. os.Chmod(path, 0777)
  250. }
  251. return nil
  252. })
  253. os.RemoveAll(file)
  254. }
  255. }
  256. return nil
  257. }
  258. // Compare a number of directories. Returns nil if the contents are identical,
  259. // otherwise an error describing the first found difference.
  260. func compareDirectories(dirs ...string) error {
  261. chans := make([]chan fileInfo, len(dirs))
  262. for i := range chans {
  263. chans[i] = make(chan fileInfo)
  264. }
  265. errcs := make([]chan error, len(dirs))
  266. abort := make(chan struct{})
  267. for i := range dirs {
  268. errcs[i] = startWalker(dirs[i], chans[i], abort)
  269. }
  270. res := make([]fileInfo, len(dirs))
  271. for {
  272. numDone := 0
  273. for i := range chans {
  274. fi, ok := <-chans[i]
  275. if !ok {
  276. err, hasError := <-errcs[i]
  277. if hasError {
  278. close(abort)
  279. return err
  280. }
  281. numDone++
  282. }
  283. res[i] = fi
  284. }
  285. for i := 1; i < len(res); i++ {
  286. if res[i] != res[0] {
  287. close(abort)
  288. return fmt.Errorf("Mismatch; %#v (%s) != %#v (%s)", res[i], dirs[i], res[0], dirs[0])
  289. }
  290. }
  291. if numDone == len(dirs) {
  292. return nil
  293. }
  294. }
  295. }
  296. func directoryContents(dir string) ([]fileInfo, error) {
  297. res := make(chan fileInfo)
  298. errc := startWalker(dir, res, nil)
  299. var files []fileInfo
  300. for f := range res {
  301. files = append(files, f)
  302. }
  303. return files, <-errc
  304. }
  305. func mergeDirectoryContents(c ...[]fileInfo) []fileInfo {
  306. m := make(map[string]fileInfo)
  307. for _, l := range c {
  308. for _, f := range l {
  309. if cur, ok := m[f.name]; !ok || cur.mod < f.mod {
  310. m[f.name] = f
  311. }
  312. }
  313. }
  314. res := make([]fileInfo, len(m))
  315. i := 0
  316. for _, f := range m {
  317. res[i] = f
  318. i++
  319. }
  320. sort.Sort(fileInfoList(res))
  321. return res
  322. }
  323. func compareDirectoryContents(actual, expected []fileInfo) error {
  324. if len(actual) != len(expected) {
  325. return fmt.Errorf("len(actual) = %d; len(expected) = %d", len(actual), len(expected))
  326. }
  327. for i := range actual {
  328. if actual[i] != expected[i] {
  329. return fmt.Errorf("Mismatch; actual %#v != expected %#v", actual[i], expected[i])
  330. }
  331. }
  332. return nil
  333. }
  334. type fileInfo struct {
  335. name string
  336. mode os.FileMode
  337. mod int64
  338. hash [16]byte
  339. size int64
  340. }
  341. func (f fileInfo) String() string {
  342. return fmt.Sprintf("%s %04o %d %x", f.name, f.mode, f.mod, f.hash)
  343. }
  344. type fileInfoList []fileInfo
  345. func (l fileInfoList) Len() int {
  346. return len(l)
  347. }
  348. func (l fileInfoList) Less(a, b int) bool {
  349. return l[a].name < l[b].name
  350. }
  351. func (l fileInfoList) Swap(a, b int) {
  352. l[a], l[b] = l[b], l[a]
  353. }
  354. func startWalker(dir string, res chan<- fileInfo, abort <-chan struct{}) chan error {
  355. walker := func(path string, info os.FileInfo, err error) error {
  356. if err != nil {
  357. return err
  358. }
  359. rn, _ := filepath.Rel(dir, path)
  360. if rn == "." || rn == ".stfolder" {
  361. return nil
  362. }
  363. if rn == ".stversions" {
  364. return filepath.SkipDir
  365. }
  366. var f fileInfo
  367. if info.Mode()&os.ModeSymlink != 0 {
  368. f = fileInfo{
  369. name: rn,
  370. mode: os.ModeSymlink,
  371. }
  372. tgt, _, err := symlinks.Read(path)
  373. if err != nil {
  374. return err
  375. }
  376. h := md5.New()
  377. h.Write([]byte(tgt))
  378. hash := h.Sum(nil)
  379. copy(f.hash[:], hash)
  380. } else if info.IsDir() {
  381. f = fileInfo{
  382. name: rn,
  383. mode: info.Mode(),
  384. // hash and modtime zero for directories
  385. }
  386. } else {
  387. f = fileInfo{
  388. name: rn,
  389. mode: info.Mode(),
  390. mod: info.ModTime().Unix(),
  391. size: info.Size(),
  392. }
  393. sum, err := md5file(path)
  394. if err != nil {
  395. return err
  396. }
  397. f.hash = sum
  398. }
  399. select {
  400. case res <- f:
  401. return nil
  402. case <-abort:
  403. return errors.New("abort")
  404. }
  405. }
  406. errc := make(chan error)
  407. go func() {
  408. err := filepath.Walk(dir, walker)
  409. close(res)
  410. if err != nil {
  411. errc <- err
  412. }
  413. close(errc)
  414. }()
  415. return errc
  416. }
  417. func md5file(fname string) (hash [16]byte, err error) {
  418. f, err := os.Open(fname)
  419. if err != nil {
  420. return
  421. }
  422. defer f.Close()
  423. h := md5.New()
  424. io.Copy(h, f)
  425. hb := h.Sum(nil)
  426. copy(hash[:], hb)
  427. return
  428. }
  429. func isTimeout(err error) bool {
  430. if err == nil {
  431. return false
  432. }
  433. return strings.Contains(err.Error(), "use of closed network connection") ||
  434. strings.Contains(err.Error(), "request canceled while waiting")
  435. }
  436. func getTestName() string {
  437. callers := make([]uintptr, 100)
  438. runtime.Callers(1, callers)
  439. for i, caller := range callers {
  440. f := runtime.FuncForPC(caller)
  441. if f != nil {
  442. if f.Name() == "testing.tRunner" {
  443. testf := runtime.FuncForPC(callers[i-1])
  444. if testf != nil {
  445. path := strings.Split(testf.Name(), ".")
  446. return path[len(path)-1]
  447. }
  448. }
  449. }
  450. }
  451. return time.Now().String()
  452. }
  453. func checkedStop(t *testing.T, p *rc.Process) {
  454. if _, err := p.Stop(); err != nil {
  455. t.Fatal(err)
  456. }
  457. }
  458. func startInstance(t *testing.T, i int) *rc.Process {
  459. log.Printf("Starting instance %d...", i)
  460. addr := fmt.Sprintf("127.0.0.1:%d", 8080+i)
  461. log := fmt.Sprintf("logs/%s-%d-%d.out", getTestName(), i, time.Now().Unix()%86400)
  462. p := rc.NewProcess(addr)
  463. p.LogTo(log)
  464. if err := p.Start("../bin/syncthing", "-home", fmt.Sprintf("h%d", i), "-no-browser"); err != nil {
  465. t.Fatal(err)
  466. }
  467. p.AwaitStartup()
  468. return p
  469. }