staggered.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. package versioner
  5. import (
  6. "fmt"
  7. "github.com/syncthing/syncthing/osutil"
  8. "io/ioutil"
  9. "os"
  10. "path/filepath"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "sync"
  15. "time"
  16. )
  17. func init() {
  18. // Register the constructor for this type of versioner with the name "staggered"
  19. Factories["staggered"] = NewStaggered
  20. }
  21. type Interval struct {
  22. step int64
  23. end int64
  24. }
  25. // The type holds our configuration
  26. type Staggered struct {
  27. versionsPath string
  28. cleanInterval int64
  29. repoPath string
  30. interval [4]Interval
  31. mutex *sync.Mutex
  32. }
  33. // Check if file or dir
  34. func isFile(path string) bool {
  35. fileordir := path
  36. file, err := os.Open(fileordir)
  37. if err != nil {
  38. l.Infoln("versioner isFile:", err)
  39. return false
  40. }
  41. defer file.Close()
  42. fileInfo, err := file.Stat()
  43. if err != nil {
  44. l.Infoln("versioner isFile:", err)
  45. return false
  46. }
  47. return fileInfo.Mode().IsRegular()
  48. }
  49. // The constructor function takes a map of parameters and creates the type.
  50. func NewStaggered(repoID, repoPath string, params map[string]string) Versioner {
  51. maxAge, err := strconv.ParseInt(params["maxAge"], 10, 0)
  52. if err != nil {
  53. maxAge = 31536000 // Default: ~1 year
  54. }
  55. cleanInterval, err := strconv.ParseInt(params["cleanInterval"], 10, 0)
  56. if err != nil {
  57. cleanInterval = 3600 // Default: clean once per hour
  58. }
  59. // Use custom path if set, otherwise .stversions in repoPath
  60. var versionsDir string
  61. if params["versionsPath"] == "" {
  62. if debug {
  63. l.Debugln("using default dir .stversions")
  64. }
  65. versionsDir = filepath.Join(repoPath, ".stversions")
  66. } else {
  67. if debug {
  68. l.Debugln("using dir", params["versionsPath"])
  69. }
  70. versionsDir = params["versionsPath"]
  71. }
  72. var mutex sync.Mutex
  73. s := Staggered{
  74. versionsPath: versionsDir,
  75. cleanInterval: cleanInterval,
  76. repoPath: repoPath,
  77. interval: [4]Interval{
  78. Interval{30, 3600}, // first hour -> 30 sec between versions
  79. Interval{3600, 86400}, // next day -> 1 h between versions
  80. Interval{86400, 2592000}, // next 30 days -> 1 day between versions
  81. Interval{604800, maxAge}, // next year -> 1 week between versions
  82. },
  83. mutex: &mutex,
  84. }
  85. if debug {
  86. l.Debugf("instantiated %#v", s)
  87. }
  88. go func() {
  89. s.clean()
  90. for _ = range time.Tick(time.Duration(cleanInterval) * time.Second) {
  91. s.clean()
  92. }
  93. }()
  94. return s
  95. }
  96. func (v Staggered) clean() {
  97. if debug {
  98. l.Debugln("Versioner clean: Waiting for lock on", v.versionsPath)
  99. }
  100. v.mutex.Lock()
  101. defer v.mutex.Unlock()
  102. if debug {
  103. l.Debugln("Versioner clean: Cleaning", v.versionsPath)
  104. }
  105. _, err := os.Stat(v.versionsPath)
  106. if err != nil {
  107. if os.IsNotExist(err) {
  108. if debug {
  109. l.Debugln("creating versions dir", v.versionsPath)
  110. }
  111. os.MkdirAll(v.versionsPath, 0755)
  112. osutil.HideFile(v.versionsPath)
  113. } else {
  114. l.Warnln("Versioner: can't create versions dir",err)
  115. }
  116. }
  117. // Using keys of map as set
  118. clean_filelist := make(map[string]struct{})
  119. clean_emptyDirs := make(map[string]struct{})
  120. err = filepath.Walk(v.versionsPath, func(path string, f os.FileInfo, err error) error {
  121. switch mode := f.Mode(); {
  122. case mode.IsDir():
  123. files, _ := ioutil.ReadDir(path)
  124. if len(files) == 0 {
  125. clean_emptyDirs[path] = struct{}{}
  126. }
  127. case mode.IsRegular():
  128. extension := filepath.Ext(path)
  129. name := path[0 : len(path)-len(extension)]
  130. clean_filelist[name] = struct{}{}
  131. }
  132. return nil
  133. })
  134. if err != nil {
  135. l.Warnln("Versioner: error scanning versions dir",err)
  136. }
  137. for k, _ := range clean_filelist {
  138. versions, err := filepath.Glob(k + ".v[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]")
  139. if err != nil {
  140. l.Warnln("Versioner: error finding versions for", k, err)
  141. }
  142. sort.Strings(versions)
  143. expire(versions, v)
  144. }
  145. for k, _ := range clean_emptyDirs {
  146. if k == v.versionsPath {
  147. if debug {
  148. l.Debugln("Cleaner: versions dir is empty, don't delete", k)
  149. }
  150. continue
  151. }
  152. if debug {
  153. l.Debugln("Cleaner: deleting empty directory", k)
  154. }
  155. err = os.Remove(k)
  156. if err != nil {
  157. l.Warnln("Versioner: can't remove directory", k, err)
  158. }
  159. }
  160. if debug {
  161. l.Debugln("Cleaner: Finished cleaning", v.versionsPath)
  162. }
  163. }
  164. func expire(versions []string, v Staggered) {
  165. if debug {
  166. l.Debugln("Versioner: Expiring versions", versions)
  167. }
  168. now := time.Now().Unix()
  169. var prevAge int64
  170. firstFile := true
  171. for _, file := range versions {
  172. if isFile(file) {
  173. versiondate, err := strconv.ParseInt(strings.Replace(filepath.Ext(file), ".v", "", 1), 10, 0)
  174. if err != nil {
  175. l.Warnln("Versioner expire: file", file, "is invalid")
  176. continue
  177. }
  178. age := now - versiondate
  179. var usedInterval Interval
  180. for _, usedInterval = range v.interval { // Find the interval the file fits in
  181. if age < usedInterval.end {
  182. break
  183. }
  184. }
  185. if lastIntv := v.interval[len(v.interval)-1]; lastIntv.end != -1 && age > lastIntv.end {
  186. if debug {
  187. l.Debugln("Versioner: File over maximum age -> delete ", file)
  188. }
  189. err = os.Remove(file)
  190. if err != nil {
  191. l.Warnln("Versioner: can't remove file", file, err)
  192. }
  193. continue
  194. }
  195. if firstFile {
  196. prevAge = age
  197. firstFile = false
  198. continue
  199. }
  200. if prevAge-age < usedInterval.step {
  201. if debug {
  202. l.Debugln("too many files in step -> delete", file)
  203. }
  204. err = os.Remove(file)
  205. if err != nil {
  206. l.Warnln("Versioner: can't remove file", file, err)
  207. }
  208. continue
  209. }
  210. prevAge = age
  211. } else {
  212. l.Warnln("Versioner: folder", file, "is named like a file version")
  213. }
  214. }
  215. }
  216. // Move away the named file to a version archive. If this function returns
  217. // nil, the named file does not exist any more (has been archived).
  218. func (v Staggered) Archive(filePath string) error {
  219. if debug {
  220. l.Debugln("Waiting for lock on ", v.versionsPath)
  221. }
  222. v.mutex.Lock()
  223. defer v.mutex.Unlock()
  224. _, err := os.Stat(filePath)
  225. if err != nil {
  226. if os.IsNotExist(err) {
  227. if debug {
  228. l.Debugln("not archiving nonexistent file", filePath)
  229. }
  230. return nil
  231. } else {
  232. return err
  233. }
  234. }
  235. _, err = os.Stat(v.versionsPath)
  236. if err != nil {
  237. if os.IsNotExist(err) {
  238. if debug {
  239. l.Debugln("creating versions dir", v.versionsPath)
  240. }
  241. os.MkdirAll(v.versionsPath, 0755)
  242. osutil.HideFile(v.versionsPath)
  243. } else {
  244. return err
  245. }
  246. }
  247. if debug {
  248. l.Debugln("archiving", filePath)
  249. }
  250. file := filepath.Base(filePath)
  251. inRepoPath, err := filepath.Rel(v.repoPath, filepath.Dir(filePath))
  252. if err != nil {
  253. return err
  254. }
  255. dir := filepath.Join(v.versionsPath, inRepoPath)
  256. err = os.MkdirAll(dir, 0755)
  257. if err != nil && !os.IsExist(err) {
  258. return err
  259. }
  260. ver := file + ".v" + fmt.Sprintf("%010d", time.Now().Unix())
  261. dst := filepath.Join(dir, ver)
  262. if debug {
  263. l.Debugln("moving to", dst)
  264. }
  265. err = osutil.Rename(filePath, dst)
  266. if err != nil {
  267. return err
  268. }
  269. versions, err := filepath.Glob(filepath.Join(dir, file+".v[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]"))
  270. if err != nil {
  271. l.Warnln("Versioner: error finding versions for", file, err)
  272. return nil
  273. }
  274. sort.Strings(versions)
  275. expire(versions, v)
  276. return nil
  277. }