virtualmtime.go 2.4 KB

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