fakefs.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  1. // Copyright (C) 2018 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 https://mozilla.org/MPL/2.0/.
  6. package fs
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "hash/fnv"
  12. "io"
  13. "math/rand"
  14. "net/url"
  15. "os"
  16. "os/user"
  17. "path/filepath"
  18. "strconv"
  19. "strings"
  20. "sync"
  21. "testing"
  22. "time"
  23. "github.com/syncthing/syncthing/lib/protocol"
  24. )
  25. const FilesystemTypeFake FilesystemType = "fake"
  26. func init() {
  27. RegisterFilesystemType(FilesystemTypeFake, func(root string, opts ...Option) (Filesystem, error) {
  28. return newFakeFilesystem(root, opts...), nil
  29. })
  30. }
  31. // see readShortAt()
  32. const randomBlockShift = 14 // 128k
  33. // fakeFS is a fake filesystem for testing and benchmarking. It has the
  34. // following properties:
  35. //
  36. // - File metadata is kept in RAM. Specifically, we remember which files and
  37. // directories exist, their dates, permissions and sizes. Symlinks are
  38. // not supported.
  39. //
  40. // - File contents are generated pseudorandomly with just the file name as
  41. // seed. Writes are discarded, other than having the effect of increasing
  42. // the file size. If you only write data that you've read from a file with
  43. // the same name on a different fakeFS, you'll never know the difference...
  44. //
  45. // - We totally ignore permissions - pretend you are root.
  46. //
  47. // - The root path can contain URL query-style parameters that pre populate
  48. // the filesystem at creation with a certain amount of random data:
  49. //
  50. // files=n to generate n random files (default 0)
  51. // maxsize=n to generate files up to a total of n MiB (default 0)
  52. // sizeavg=n to set the average size of random files, in bytes (default 1<<20)
  53. // seed=n to set the initial random seed (default 0)
  54. // insens=b "true" makes filesystem case-insensitive Windows- or OSX-style (default false)
  55. // latency=d to set the amount of time each "disk" operation takes, where d is time.ParseDuration format
  56. // content=true to save actual file contents instead of generating pseudorandomly; n.b. memory usage
  57. // nostfolder=true skip the creation of .stfolder
  58. // timeprecisionsecond=true Modification times are stored with only second precision
  59. //
  60. // - Two fakeFS:s pointing at the same root path see the same files.
  61. type fakeFS struct {
  62. counters fakeFSCounters
  63. uri string
  64. mut sync.Mutex
  65. root *fakeEntry
  66. insens bool
  67. withContent bool
  68. timePrecisionSecond bool
  69. latency time.Duration
  70. userCache *userCache
  71. groupCache *groupCache
  72. }
  73. type fakeFSCounters struct {
  74. Chmod int64
  75. Lchown int64
  76. Chtimes int64
  77. Create int64
  78. DirNames int64
  79. Lstat int64
  80. Mkdir int64
  81. MkdirAll int64
  82. Open int64
  83. OpenFile int64
  84. ReadSymlink int64
  85. Remove int64
  86. RemoveAll int64
  87. Rename int64
  88. }
  89. var (
  90. fakeFSMut sync.Mutex
  91. fakeFSCache = make(map[string]*fakeFS)
  92. )
  93. func newFakeFilesystem(rootURI string, _ ...Option) *fakeFS {
  94. fakeFSMut.Lock()
  95. defer fakeFSMut.Unlock()
  96. var params url.Values
  97. uri, err := url.Parse(rootURI)
  98. if err == nil {
  99. params = uri.Query()
  100. }
  101. if fs, ok := fakeFSCache[rootURI]; ok {
  102. // Already have an fs at this path
  103. return fs
  104. }
  105. fs := &fakeFS{
  106. uri: "fake://" + rootURI,
  107. root: &fakeEntry{
  108. name: "/",
  109. entryType: fakeEntryTypeDir,
  110. mode: 0o700,
  111. mtime: time.Now(),
  112. children: make(map[string]*fakeEntry),
  113. },
  114. userCache: newValueCache(time.Hour, user.LookupId),
  115. groupCache: newValueCache(time.Hour, user.LookupGroupId),
  116. }
  117. files, _ := strconv.Atoi(params.Get("files"))
  118. maxsize, _ := strconv.Atoi(params.Get("maxsize"))
  119. sizeavg, _ := strconv.Atoi(params.Get("sizeavg"))
  120. seed, _ := strconv.Atoi(params.Get("seed"))
  121. fs.insens = params.Get("insens") == "true"
  122. fs.withContent = params.Get("content") == "true"
  123. nostfolder := params.Get("nostfolder") == "true"
  124. fs.timePrecisionSecond = params.Get("timeprecisionsecond") == "true"
  125. if sizeavg == 0 {
  126. sizeavg = 1 << 20
  127. }
  128. if files > 0 || maxsize > 0 {
  129. // Generate initial data according to specs. Operations in here
  130. // *look* like file I/O, but they are not. Do not worry that they
  131. // might fail.
  132. rng := rand.New(rand.NewSource(int64(seed)))
  133. var createdFiles int
  134. var writtenData int64
  135. for (files == 0 || createdFiles < files) && (maxsize == 0 || writtenData>>20 < int64(maxsize)) {
  136. dir := filepath.Join(fmt.Sprintf("%02x", rng.Intn(255)), fmt.Sprintf("%02x", rng.Intn(255)))
  137. file := fmt.Sprintf("%016x", rng.Int63())
  138. fs.MkdirAll(dir, 0o755)
  139. fd, _ := fs.Create(filepath.Join(dir, file))
  140. createdFiles++
  141. fsize := int64(sizeavg/2 + rng.Intn(sizeavg))
  142. fd.Truncate(fsize)
  143. writtenData += fsize
  144. ftime := time.Unix(1000000000+rng.Int63n(10*365*86400), 0)
  145. fs.Chtimes(filepath.Join(dir, file), ftime, ftime)
  146. }
  147. }
  148. if !nostfolder {
  149. // Also create a default folder marker for good measure
  150. fs.Mkdir(".stfolder", 0o700)
  151. }
  152. // We only set the latency after doing the operations required to create
  153. // the filesystem initially.
  154. fs.latency, _ = time.ParseDuration(params.Get("latency"))
  155. fakeFSCache[rootURI] = fs
  156. return fs
  157. }
  158. type fakeEntryType int
  159. const (
  160. fakeEntryTypeFile fakeEntryType = iota
  161. fakeEntryTypeDir
  162. fakeEntryTypeSymlink
  163. )
  164. // fakeEntry is an entry (file or directory) in the fake filesystem
  165. type fakeEntry struct {
  166. name string
  167. entryType fakeEntryType
  168. dest string // for symlinks
  169. size int64
  170. mode FileMode
  171. uid int
  172. gid int
  173. mtime time.Time
  174. children map[string]*fakeEntry
  175. content []byte
  176. }
  177. func (fs *fakeFS) entryForName(name string) *fakeEntry {
  178. if fs.insens {
  179. name = UnicodeLowercaseNormalized(name)
  180. }
  181. name = filepath.ToSlash(name)
  182. if name == "." || name == "/" {
  183. return fs.root
  184. }
  185. name = strings.Trim(name, "/")
  186. comps := strings.Split(name, "/")
  187. entry := fs.root
  188. for i, comp := range comps {
  189. if entry.entryType != fakeEntryTypeDir {
  190. return nil
  191. }
  192. var ok bool
  193. entry, ok = entry.children[comp]
  194. if !ok {
  195. return nil
  196. }
  197. if i < len(comps)-1 && entry.entryType == fakeEntryTypeSymlink {
  198. // only absolute link targets are supported, and we assume
  199. // lookup is Lstat-kind so we only resolve symlinks when they
  200. // are not the last path component.
  201. return fs.entryForName(entry.dest)
  202. }
  203. }
  204. return entry
  205. }
  206. func (fs *fakeFS) Chmod(name string, mode FileMode) error {
  207. fs.mut.Lock()
  208. defer fs.mut.Unlock()
  209. fs.counters.Chmod++
  210. time.Sleep(fs.latency)
  211. entry := fs.entryForName(name)
  212. if entry == nil {
  213. return os.ErrNotExist
  214. }
  215. entry.mode = mode
  216. return nil
  217. }
  218. func (fs *fakeFS) Lchown(name, uid, gid string) error {
  219. fs.mut.Lock()
  220. defer fs.mut.Unlock()
  221. fs.counters.Lchown++
  222. time.Sleep(fs.latency)
  223. entry := fs.entryForName(name)
  224. if entry == nil {
  225. return os.ErrNotExist
  226. }
  227. entry.uid, _ = strconv.Atoi(uid)
  228. entry.gid, _ = strconv.Atoi(gid)
  229. return nil
  230. }
  231. func (fs *fakeFS) Chtimes(name string, _ time.Time, mtime time.Time) error {
  232. fs.mut.Lock()
  233. defer fs.mut.Unlock()
  234. fs.counters.Chtimes++
  235. time.Sleep(fs.latency)
  236. entry := fs.entryForName(name)
  237. if entry == nil {
  238. return os.ErrNotExist
  239. }
  240. if fs.timePrecisionSecond {
  241. mtime = mtime.Truncate(time.Second)
  242. }
  243. entry.mtime = mtime
  244. return nil
  245. }
  246. func (fs *fakeFS) create(name string) (*fakeEntry, error) {
  247. fs.mut.Lock()
  248. defer fs.mut.Unlock()
  249. fs.counters.Create++
  250. time.Sleep(fs.latency)
  251. if entry := fs.entryForName(name); entry != nil {
  252. if entry.entryType == fakeEntryTypeDir {
  253. return nil, os.ErrExist
  254. } else if entry.entryType == fakeEntryTypeSymlink {
  255. return nil, errors.New("following symlink not supported")
  256. }
  257. entry.size = 0
  258. entry.mtime = time.Now()
  259. entry.mode = 0o666
  260. entry.content = nil
  261. if fs.withContent {
  262. entry.content = make([]byte, 0)
  263. }
  264. return entry, nil
  265. }
  266. dir := filepath.Dir(name)
  267. base := filepath.Base(name)
  268. entry := fs.entryForName(dir)
  269. if entry == nil {
  270. return nil, os.ErrNotExist
  271. }
  272. new := &fakeEntry{
  273. name: base,
  274. mode: 0o666,
  275. mtime: time.Now(),
  276. }
  277. if fs.insens {
  278. base = UnicodeLowercaseNormalized(base)
  279. }
  280. if fs.withContent {
  281. new.content = make([]byte, 0)
  282. }
  283. entry.children[base] = new
  284. return new, nil
  285. }
  286. func (fs *fakeFS) Create(name string) (File, error) {
  287. entry, err := fs.create(name)
  288. if err != nil {
  289. return nil, err
  290. }
  291. if fs.insens {
  292. return &fakeFile{fakeEntry: entry, presentedName: filepath.Base(name), mut: &fs.mut}, nil
  293. }
  294. return &fakeFile{fakeEntry: entry, mut: &fs.mut}, nil
  295. }
  296. func (fs *fakeFS) CreateSymlink(target, name string) error {
  297. entry, err := fs.create(name)
  298. if err != nil {
  299. return err
  300. }
  301. entry.entryType = fakeEntryTypeSymlink
  302. entry.dest = target
  303. return nil
  304. }
  305. func (fs *fakeFS) DirNames(name string) ([]string, error) {
  306. fs.mut.Lock()
  307. defer fs.mut.Unlock()
  308. fs.counters.DirNames++
  309. time.Sleep(fs.latency)
  310. entry := fs.entryForName(name)
  311. if entry == nil {
  312. return nil, os.ErrNotExist
  313. }
  314. names := make([]string, 0, len(entry.children))
  315. for _, child := range entry.children {
  316. names = append(names, child.name)
  317. }
  318. return names, nil
  319. }
  320. func (fs *fakeFS) Lstat(name string) (FileInfo, error) {
  321. fs.mut.Lock()
  322. defer fs.mut.Unlock()
  323. fs.counters.Lstat++
  324. time.Sleep(fs.latency)
  325. entry := fs.entryForName(name)
  326. if entry == nil {
  327. return nil, os.ErrNotExist
  328. }
  329. info := &fakeFileInfo{*entry}
  330. if fs.insens {
  331. info.name = filepath.Base(name)
  332. }
  333. return info, nil
  334. }
  335. func (fs *fakeFS) Mkdir(name string, perm FileMode) error {
  336. fs.mut.Lock()
  337. defer fs.mut.Unlock()
  338. fs.counters.Mkdir++
  339. time.Sleep(fs.latency)
  340. dir := filepath.Dir(name)
  341. base := filepath.Base(name)
  342. entry := fs.entryForName(dir)
  343. key := base
  344. if entry == nil {
  345. return os.ErrNotExist
  346. }
  347. if entry.entryType != fakeEntryTypeDir {
  348. return os.ErrExist
  349. }
  350. if fs.insens {
  351. key = UnicodeLowercaseNormalized(key)
  352. }
  353. if _, ok := entry.children[key]; ok {
  354. return os.ErrExist
  355. }
  356. entry.children[key] = &fakeEntry{
  357. name: base,
  358. entryType: fakeEntryTypeDir,
  359. mode: perm,
  360. mtime: time.Now(),
  361. children: make(map[string]*fakeEntry),
  362. }
  363. return nil
  364. }
  365. func (fs *fakeFS) MkdirAll(name string, perm FileMode) error {
  366. fs.mut.Lock()
  367. defer fs.mut.Unlock()
  368. fs.counters.MkdirAll++
  369. time.Sleep(fs.latency)
  370. name = filepath.ToSlash(name)
  371. name = strings.Trim(name, "/")
  372. comps := strings.Split(name, "/")
  373. entry := fs.root
  374. for _, comp := range comps {
  375. key := comp
  376. if fs.insens {
  377. key = UnicodeLowercaseNormalized(key)
  378. }
  379. next, ok := entry.children[key]
  380. if !ok {
  381. new := &fakeEntry{
  382. name: comp,
  383. entryType: fakeEntryTypeDir,
  384. mode: perm,
  385. mtime: time.Now(),
  386. children: make(map[string]*fakeEntry),
  387. }
  388. entry.children[key] = new
  389. next = new
  390. } else if next.entryType != fakeEntryTypeDir {
  391. return errors.New("not a directory")
  392. }
  393. entry = next
  394. }
  395. return nil
  396. }
  397. func (fs *fakeFS) Open(name string) (File, error) {
  398. fs.mut.Lock()
  399. defer fs.mut.Unlock()
  400. fs.counters.Open++
  401. time.Sleep(fs.latency)
  402. entry := fs.entryForName(name)
  403. if entry == nil || entry.entryType != fakeEntryTypeFile {
  404. return nil, os.ErrNotExist
  405. }
  406. if fs.insens {
  407. return &fakeFile{fakeEntry: entry, presentedName: filepath.Base(name), mut: &fs.mut}, nil
  408. }
  409. return &fakeFile{fakeEntry: entry, mut: &fs.mut}, nil
  410. }
  411. func (fs *fakeFS) OpenFile(name string, flags int, mode FileMode) (File, error) {
  412. if flags&os.O_CREATE == 0 {
  413. return fs.Open(name)
  414. }
  415. fs.mut.Lock()
  416. defer fs.mut.Unlock()
  417. fs.counters.OpenFile++
  418. time.Sleep(fs.latency)
  419. dir := filepath.Dir(name)
  420. base := filepath.Base(name)
  421. entry := fs.entryForName(dir)
  422. key := base
  423. if entry == nil {
  424. return nil, os.ErrNotExist
  425. } else if entry.entryType != fakeEntryTypeDir {
  426. return nil, errors.New("not a directory")
  427. }
  428. if fs.insens {
  429. key = UnicodeLowercaseNormalized(key)
  430. }
  431. if flags&os.O_EXCL != 0 {
  432. if _, ok := entry.children[key]; ok {
  433. return nil, os.ErrExist
  434. }
  435. }
  436. newEntry := &fakeEntry{
  437. name: base,
  438. mode: mode,
  439. mtime: time.Now(),
  440. }
  441. if fs.withContent {
  442. newEntry.content = make([]byte, 0)
  443. }
  444. entry.children[key] = newEntry
  445. return &fakeFile{fakeEntry: newEntry, mut: &fs.mut}, nil
  446. }
  447. func (fs *fakeFS) ReadSymlink(name string) (string, error) {
  448. fs.mut.Lock()
  449. defer fs.mut.Unlock()
  450. fs.counters.ReadSymlink++
  451. time.Sleep(fs.latency)
  452. entry := fs.entryForName(name)
  453. if entry == nil {
  454. return "", os.ErrNotExist
  455. } else if entry.entryType != fakeEntryTypeSymlink {
  456. return "", errors.New("not a symlink")
  457. }
  458. return entry.dest, nil
  459. }
  460. func (fs *fakeFS) Remove(name string) error {
  461. fs.mut.Lock()
  462. defer fs.mut.Unlock()
  463. fs.counters.Remove++
  464. time.Sleep(fs.latency)
  465. if fs.insens {
  466. name = UnicodeLowercaseNormalized(name)
  467. }
  468. entry := fs.entryForName(name)
  469. if entry == nil {
  470. return os.ErrNotExist
  471. }
  472. if len(entry.children) != 0 {
  473. return errors.New("not empty")
  474. }
  475. entry = fs.entryForName(filepath.Dir(name))
  476. delete(entry.children, filepath.Base(name))
  477. return nil
  478. }
  479. func (fs *fakeFS) RemoveAll(name string) error {
  480. fs.mut.Lock()
  481. defer fs.mut.Unlock()
  482. fs.counters.RemoveAll++
  483. time.Sleep(fs.latency)
  484. if fs.insens {
  485. name = UnicodeLowercaseNormalized(name)
  486. }
  487. entry := fs.entryForName(filepath.Dir(name))
  488. if entry == nil {
  489. return nil // all tested real systems exhibit this behaviour
  490. }
  491. // RemoveAll is easy when the file system uses garbage collection under
  492. // the hood... We even get the correct semantics for open fd:s for free.
  493. delete(entry.children, filepath.Base(name))
  494. return nil
  495. }
  496. func (fs *fakeFS) Rename(oldname, newname string) error {
  497. fs.mut.Lock()
  498. defer fs.mut.Unlock()
  499. fs.counters.Rename++
  500. time.Sleep(fs.latency)
  501. oldKey := filepath.Base(oldname)
  502. newKey := filepath.Base(newname)
  503. if fs.insens {
  504. oldKey = UnicodeLowercaseNormalized(oldKey)
  505. newKey = UnicodeLowercaseNormalized(newKey)
  506. }
  507. p0 := fs.entryForName(filepath.Dir(oldname))
  508. if p0 == nil {
  509. return os.ErrNotExist
  510. }
  511. entry := p0.children[oldKey]
  512. if entry == nil {
  513. return os.ErrNotExist
  514. }
  515. p1 := fs.entryForName(filepath.Dir(newname))
  516. if p1 == nil {
  517. return os.ErrNotExist
  518. }
  519. dst, ok := p1.children[newKey]
  520. if ok {
  521. if fs.insens && newKey == oldKey {
  522. // case-only in-place rename
  523. entry.name = filepath.Base(newname)
  524. return nil
  525. }
  526. if dst.entryType == fakeEntryTypeDir {
  527. return errors.New("is a directory")
  528. }
  529. }
  530. p1.children[newKey] = entry
  531. entry.name = filepath.Base(newname)
  532. delete(p0.children, oldKey)
  533. return nil
  534. }
  535. func (fs *fakeFS) Stat(name string) (FileInfo, error) {
  536. return fs.Lstat(name)
  537. }
  538. func (*fakeFS) SymlinksSupported() bool {
  539. return false
  540. }
  541. func (*fakeFS) Walk(_ string, _ WalkFunc) error {
  542. return errors.New("not implemented")
  543. }
  544. func (*fakeFS) Watch(_ string, _ Matcher, _ context.Context, _ bool) (<-chan Event, <-chan error, error) {
  545. return nil, nil, ErrWatchNotSupported
  546. }
  547. func (*fakeFS) Hide(_ string) error {
  548. return nil
  549. }
  550. func (*fakeFS) Unhide(_ string) error {
  551. return nil
  552. }
  553. func (*fakeFS) GetXattr(_ string, _ XattrFilter) ([]protocol.Xattr, error) {
  554. return nil, nil
  555. }
  556. func (*fakeFS) SetXattr(_ string, _ []protocol.Xattr, _ XattrFilter) error {
  557. return nil
  558. }
  559. // A basic glob-impelementation that should be able to handle
  560. // simple test cases.
  561. func (fs *fakeFS) Glob(pattern string) ([]string, error) {
  562. dir := filepath.Dir(pattern)
  563. file := filepath.Base(pattern)
  564. if _, err := fs.Lstat(dir); err != nil {
  565. return nil, errPathInvalid
  566. }
  567. var matches []string
  568. names, err := fs.DirNames(dir)
  569. if err != nil {
  570. return nil, err
  571. }
  572. for _, n := range names {
  573. matched, err := filepath.Match(file, n)
  574. if err != nil {
  575. return nil, err
  576. }
  577. if matched {
  578. matches = append(matches, filepath.Join(dir, n))
  579. }
  580. }
  581. return matches, err
  582. }
  583. func (*fakeFS) Roots() ([]string, error) {
  584. return []string{"/"}, nil
  585. }
  586. func (*fakeFS) Usage(_ string) (Usage, error) {
  587. return Usage{}, errors.New("not implemented")
  588. }
  589. func (*fakeFS) Type() FilesystemType {
  590. return FilesystemTypeFake
  591. }
  592. func (fs *fakeFS) URI() string {
  593. return fs.uri
  594. }
  595. func (*fakeFS) Options() []Option {
  596. return nil
  597. }
  598. func (fs *fakeFS) SameFile(fi1, fi2 FileInfo) bool {
  599. // BUG: real systems base file sameness on path, inodes, etc
  600. // we try our best, but FileInfo just doesn't have enough data
  601. // so there be false positives, especially on Windows
  602. // where ModTime is not that precise
  603. var ok bool
  604. if fs.insens {
  605. ok = UnicodeLowercaseNormalized(fi1.Name()) == UnicodeLowercaseNormalized(fi2.Name())
  606. } else {
  607. ok = fi1.Name() == fi2.Name()
  608. }
  609. return ok && fi1.ModTime().Equal(fi2.ModTime()) && fi1.Mode() == fi2.Mode() && fi1.IsDir() == fi2.IsDir() && fi1.IsRegular() == fi2.IsRegular() && fi1.IsSymlink() == fi2.IsSymlink() && fi1.Owner() == fi2.Owner() && fi1.Group() == fi2.Group()
  610. }
  611. func (fs *fakeFS) PlatformData(name string, scanOwnership, scanXattrs bool, xattrFilter XattrFilter) (protocol.PlatformData, error) {
  612. return unixPlatformData(fs, name, fs.userCache, fs.groupCache, scanOwnership, scanXattrs, xattrFilter)
  613. }
  614. func (*fakeFS) underlying() (Filesystem, bool) {
  615. return nil, false
  616. }
  617. func (*fakeFS) wrapperType() filesystemWrapperType {
  618. return filesystemWrapperTypeNone
  619. }
  620. func (fs *fakeFS) resetCounters() {
  621. fs.mut.Lock()
  622. fs.counters = fakeFSCounters{}
  623. fs.mut.Unlock()
  624. }
  625. func (fs *fakeFS) reportMetricsPerOp(b *testing.B) {
  626. fs.reportMetricsPer(b, 1, "op")
  627. }
  628. func (fs *fakeFS) reportMetricsPer(b *testing.B, divisor float64, unit string) {
  629. fs.mut.Lock()
  630. defer fs.mut.Unlock()
  631. b.ReportMetric(float64(fs.counters.Lstat)/divisor/float64(b.N), "Lstat/"+unit)
  632. b.ReportMetric(float64(fs.counters.DirNames)/divisor/float64(b.N), "DirNames/"+unit)
  633. }
  634. // fakeFile is the representation of an open file. We don't care if it's
  635. // opened for reading or writing, it's all good.
  636. type fakeFile struct {
  637. *fakeEntry
  638. mut *sync.Mutex
  639. rng io.Reader
  640. seed int64
  641. offset int64
  642. seedOffs int64
  643. presentedName string // present (i.e. != "") on insensitive fs only
  644. }
  645. func (*fakeFile) Close() error {
  646. return nil
  647. }
  648. func (f *fakeFile) Read(p []byte) (int, error) {
  649. f.mut.Lock()
  650. defer f.mut.Unlock()
  651. return f.readShortAt(p, f.offset)
  652. }
  653. func (f *fakeFile) ReadAt(p []byte, offs int64) (int, error) {
  654. f.mut.Lock()
  655. defer f.mut.Unlock()
  656. // ReadAt is spec:ed to always read a full block unless EOF or failure,
  657. // so we must loop. It's also not supposed to affect the seek position,
  658. // but that would make things annoying or inefficient in terms of
  659. // generating the appropriate RNG etc so I ignore that. In practice we
  660. // currently don't depend on that aspect of it...
  661. var read int
  662. for {
  663. n, err := f.readShortAt(p[read:], offs+int64(read))
  664. read += n
  665. if err != nil {
  666. return read, err
  667. }
  668. if read == len(p) {
  669. return read, nil
  670. }
  671. }
  672. }
  673. func (f *fakeFile) readShortAt(p []byte, offs int64) (int, error) {
  674. // Here be a certain amount of magic... We want to return pseudorandom,
  675. // predictable data so that a read from the same offset in the same file
  676. // always returns the same data. But the RNG is a stream, and reads can
  677. // be random.
  678. //
  679. // We split the file into "blocks" numbered by "seedNo", where each
  680. // block becomes an instantiation of the RNG, seeded with the hash of
  681. // the file number plus the seedNo (block number). We keep the RNG
  682. // around in the hope that the next read will be sequential to this one
  683. // and we can continue reading from the same RNG.
  684. //
  685. // When that's not the case we create a new RNG for the block we are in,
  686. // read as many bytes from it as necessary to get to the right offset,
  687. // and then serve the read from there. We limit the length of the read
  688. // to the end of the block, as another RNG needs to be created to serve
  689. // the next block.
  690. //
  691. // The size of the blocks are a matter of taste... Larger blocks give
  692. // better performance for sequential reads, but worse for random reads
  693. // as we often need to generate and throw away a lot of data at the
  694. // start of the block to serve a given read. 128 KiB blocks fit
  695. // reasonably well with the type of IO Syncthing tends to do.
  696. if f.entryType == fakeEntryTypeDir {
  697. return 0, errors.New("is a directory")
  698. }
  699. if offs >= f.size {
  700. return 0, io.EOF
  701. }
  702. if f.content != nil {
  703. n := copy(p, f.content[int(offs):])
  704. f.offset = offs + int64(n)
  705. return n, nil
  706. }
  707. // Lazily calculate our main seed, a simple 64 bit FNV hash our file
  708. // name.
  709. if f.seed == 0 {
  710. hf := fnv.New64()
  711. hf.Write([]byte(f.name))
  712. f.seed = int64(hf.Sum64())
  713. }
  714. // Check whether the read is a continuation of an RNG we already have or
  715. // we need to set up a new one.
  716. seedNo := offs >> randomBlockShift
  717. minOffs := seedNo << randomBlockShift
  718. nextBlockOffs := (seedNo + 1) << randomBlockShift
  719. if f.rng == nil || f.offset != offs || seedNo != f.seedOffs {
  720. // This is not a straight read continuing from a previous one
  721. f.rng = rand.New(rand.NewSource(f.seed + seedNo))
  722. // If the read is not at the start of the block, discard data
  723. // accordingly.
  724. diff := offs - minOffs
  725. if diff > 0 {
  726. lr := io.LimitReader(f.rng, diff)
  727. io.Copy(io.Discard, lr)
  728. }
  729. f.offset = offs
  730. f.seedOffs = seedNo
  731. }
  732. size := len(p)
  733. // Don't read past the end of the file
  734. if offs+int64(size) > f.size {
  735. size = int(f.size - offs)
  736. }
  737. // Don't read across the block boundary
  738. if offs+int64(size) > nextBlockOffs {
  739. size = int(nextBlockOffs - offs)
  740. }
  741. f.offset += int64(size)
  742. return f.rng.Read(p[:size])
  743. }
  744. func (f *fakeFile) Seek(offset int64, whence int) (int64, error) {
  745. f.mut.Lock()
  746. defer f.mut.Unlock()
  747. if f.entryType == fakeEntryTypeDir {
  748. return 0, errors.New("is a directory")
  749. }
  750. f.rng = nil
  751. switch whence {
  752. case io.SeekCurrent:
  753. f.offset += offset
  754. case io.SeekEnd:
  755. f.offset = f.size - offset
  756. case io.SeekStart:
  757. f.offset = offset
  758. }
  759. if f.offset < 0 {
  760. f.offset = 0
  761. return f.offset, errors.New("seek before start")
  762. }
  763. if f.offset > f.size {
  764. f.offset = f.size
  765. return f.offset, io.EOF
  766. }
  767. return f.offset, nil
  768. }
  769. func (f *fakeFile) Write(p []byte) (int, error) {
  770. f.mut.Lock()
  771. offs := f.offset
  772. f.mut.Unlock()
  773. return f.WriteAt(p, offs)
  774. }
  775. func (f *fakeFile) WriteAt(p []byte, off int64) (int, error) {
  776. f.mut.Lock()
  777. defer f.mut.Unlock()
  778. if f.entryType == fakeEntryTypeDir {
  779. return 0, errors.New("is a directory")
  780. }
  781. if f.content != nil {
  782. if len(f.content) < int(off)+len(p) {
  783. newc := make([]byte, int(off)+len(p))
  784. copy(newc, f.content)
  785. f.content = newc
  786. }
  787. copy(f.content[int(off):], p)
  788. }
  789. f.rng = nil
  790. f.offset = off + int64(len(p))
  791. if f.offset > f.size {
  792. f.size = f.offset
  793. }
  794. return len(p), nil
  795. }
  796. func (f *fakeFile) Name() string {
  797. if f.presentedName != "" {
  798. return f.presentedName
  799. }
  800. f.mut.Lock()
  801. defer f.mut.Unlock()
  802. return f.name
  803. }
  804. func (f *fakeFile) Truncate(size int64) error {
  805. f.mut.Lock()
  806. defer f.mut.Unlock()
  807. if f.content != nil {
  808. if int64(cap(f.content)) < size {
  809. c := make([]byte, size)
  810. copy(c[:len(f.content)], f.content)
  811. f.content = c
  812. } else {
  813. f.content = f.content[:int(size)]
  814. }
  815. }
  816. f.rng = nil
  817. f.size = size
  818. if f.offset > size {
  819. f.offset = size
  820. }
  821. return nil
  822. }
  823. func (f *fakeFile) Stat() (FileInfo, error) {
  824. f.mut.Lock()
  825. info := &fakeFileInfo{*f.fakeEntry}
  826. f.mut.Unlock()
  827. if f.presentedName != "" {
  828. info.name = f.presentedName
  829. }
  830. return info, nil
  831. }
  832. func (*fakeFile) Sync() error {
  833. return nil
  834. }
  835. // fakeFileInfo is the stat result.
  836. type fakeFileInfo struct {
  837. fakeEntry // intentionally a copy of the struct
  838. }
  839. func (f *fakeFileInfo) Name() string {
  840. return f.name
  841. }
  842. func (f *fakeFileInfo) Mode() FileMode {
  843. return f.mode
  844. }
  845. func (f *fakeFileInfo) Size() int64 {
  846. return f.size
  847. }
  848. func (f *fakeFileInfo) ModTime() time.Time {
  849. return f.mtime
  850. }
  851. func (f *fakeFileInfo) IsDir() bool {
  852. return f.entryType == fakeEntryTypeDir
  853. }
  854. func (f *fakeFileInfo) IsRegular() bool {
  855. return f.entryType == fakeEntryTypeFile
  856. }
  857. func (f *fakeFileInfo) IsSymlink() bool {
  858. return f.entryType == fakeEntryTypeSymlink
  859. }
  860. func (f *fakeFileInfo) Owner() int {
  861. return f.uid
  862. }
  863. func (f *fakeFileInfo) Group() int {
  864. return f.gid
  865. }
  866. func (*fakeFileInfo) Sys() interface{} {
  867. return nil
  868. }
  869. func (*fakeFileInfo) InodeChangeTime() time.Time {
  870. return time.Time{}
  871. }