virtualmtime.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // Copyright (C) 2015 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. package db
  7. import (
  8. "fmt"
  9. "time"
  10. )
  11. // This type encapsulates a repository of mtimes for platforms where file mtimes
  12. // can't be set to arbitrary values. For this to work, we need to store both
  13. // the mtime we tried to set (the "actual" mtime) as well as the mtime the file
  14. // has when we're done touching it (the "disk" mtime) so that we can tell if it
  15. // was changed. So in GetMtime(), it's not sufficient that the record exists --
  16. // the argument must also equal the "disk" mtime in the record, otherwise it's
  17. // been touched locally and the "disk" mtime is actually correct.
  18. type VirtualMtimeRepo struct {
  19. ns *NamespacedKV
  20. }
  21. func NewVirtualMtimeRepo(ldb *Instance, folder string) *VirtualMtimeRepo {
  22. prefix := string(KeyTypeVirtualMtime) + folder
  23. return &VirtualMtimeRepo{
  24. ns: NewNamespacedKV(ldb, prefix),
  25. }
  26. }
  27. func (r *VirtualMtimeRepo) UpdateMtime(path string, diskMtime, actualMtime time.Time) {
  28. l.Debugf("virtual mtime: storing values for path:%s disk:%v actual:%v", path, diskMtime, actualMtime)
  29. diskBytes, _ := diskMtime.MarshalBinary()
  30. actualBytes, _ := actualMtime.MarshalBinary()
  31. data := append(diskBytes, actualBytes...)
  32. r.ns.PutBytes(path, data)
  33. }
  34. func (r *VirtualMtimeRepo) GetMtime(path string, diskMtime time.Time) time.Time {
  35. data, exists := r.ns.Bytes(path)
  36. if !exists {
  37. // Absence of debug print is significant enough in itself here
  38. return diskMtime
  39. }
  40. var mtime time.Time
  41. if err := mtime.UnmarshalBinary(data[:len(data)/2]); err != nil {
  42. panic(fmt.Sprintf("Can't unmarshal stored mtime at path %s: %v", path, err))
  43. }
  44. if mtime.Equal(diskMtime) {
  45. if err := mtime.UnmarshalBinary(data[len(data)/2:]); err != nil {
  46. panic(fmt.Sprintf("Can't unmarshal stored mtime at path %s: %v", path, err))
  47. }
  48. l.Debugf("virtual mtime: return %v instead of %v for path: %s", mtime, diskMtime, path)
  49. return mtime
  50. }
  51. l.Debugf("virtual mtime: record exists, but mismatch inDisk: %v dbDisk: %v for path: %s", diskMtime, mtime, path)
  52. return diskMtime
  53. }
  54. func (r *VirtualMtimeRepo) DeleteMtime(path string) {
  55. r.ns.Delete(path)
  56. }
  57. func (r *VirtualMtimeRepo) Drop() {
  58. r.ns.Reset()
  59. }