reloader.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. /*
  2. * Copyright (c) 2016, Psiphon Inc.
  3. * All rights reserved.
  4. *
  5. * This program is free software: you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation, either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. *
  18. */
  19. package common
  20. import (
  21. "hash/crc64"
  22. "io"
  23. "io/ioutil"
  24. "os"
  25. "sync"
  26. "time"
  27. )
  28. // Reloader represents a read-only, in-memory reloadable data object. For example,
  29. // a JSON data file that is loaded into memory and accessed for read-only lookups;
  30. // and from time to time may be reloaded from the same file, updating the memory
  31. // copy.
  32. type Reloader interface {
  33. // Reload reloads the data object. Reload returns a flag indicating if the
  34. // reloadable target has changed and reloaded or remains unchanged. By
  35. // convention, when reloading fails the Reloader should revert to its previous
  36. // in-memory state.
  37. Reload() (bool, error)
  38. // WillReload indicates if the data object is capable of reloading.
  39. WillReload() bool
  40. // LogDescription returns a description to be used for logging
  41. // events related to the Reloader.
  42. LogDescription() string
  43. }
  44. // ReloadableFile is a file-backed Reloader. This type is intended to be embedded
  45. // in other types that add the actual reloadable data structures.
  46. //
  47. // ReloadableFile has a multi-reader mutex for synchronization. Its Reload() function
  48. // will obtain a write lock before reloading the data structures. The actual reloading
  49. // action is to be provided via the reloadAction callback, which receives the content
  50. // of reloaded files, along with file modification time, and must process the new data
  51. // (for example, unmarshall the contents into data structures). All read access to the
  52. // data structures should be guarded by RLocks on the ReloadableFile mutex.
  53. //
  54. // reloadAction must ensure that data structures revert to their previous state when
  55. // a reload fails.
  56. //
  57. type ReloadableFile struct {
  58. sync.RWMutex
  59. filename string
  60. loadFileContent bool
  61. checksum uint64
  62. reloadAction func([]byte, time.Time) error
  63. }
  64. // NewReloadableFile initializes a new ReloadableFile.
  65. //
  66. // When loadFileContent is true, the file content is loaded and passed to
  67. // reloadAction; otherwise, reloadAction receives a nil argument and is
  68. // responsible for loading the file. The latter option allows for cases where
  69. // the file contents must be streamed, memory mapped, etc.
  70. func NewReloadableFile(
  71. filename string,
  72. loadFileContent bool,
  73. reloadAction func([]byte, time.Time) error) ReloadableFile {
  74. return ReloadableFile{
  75. filename: filename,
  76. loadFileContent: loadFileContent,
  77. reloadAction: reloadAction,
  78. }
  79. }
  80. // WillReload indicates whether the ReloadableFile is capable
  81. // of reloading.
  82. func (reloadable *ReloadableFile) WillReload() bool {
  83. return reloadable.filename != ""
  84. }
  85. var crc64table = crc64.MakeTable(crc64.ISO)
  86. // Reload checks if the underlying file has changed and, when changed, invokes
  87. // the reloadAction callback which should reload the in-memory data structures.
  88. //
  89. // In some case (e.g., traffic rules and OSL), there are penalties associated
  90. // with proceeding with reload, so care is taken to not invoke the reload action
  91. // unless the contents have changed.
  92. //
  93. // The file content is loaded and a checksum is taken to determine whether it
  94. // has changed. Neither file size (may not change when content changes) nor
  95. // modified date (may change when identical file is repaved) is a sufficient
  96. // indicator.
  97. //
  98. // All data structure readers should be blocked by the ReloadableFile mutex.
  99. //
  100. // Reload must not be called from multiple concurrent goroutines.
  101. func (reloadable *ReloadableFile) Reload() (bool, error) {
  102. if !reloadable.WillReload() {
  103. return false, nil
  104. }
  105. // Check whether the file has changed _before_ blocking readers
  106. reloadable.RLock()
  107. filename := reloadable.filename
  108. previousChecksum := reloadable.checksum
  109. reloadable.RUnlock()
  110. // Record the file modification time _before_ loading, as reload actions will
  111. // assume that the content is at least as fresh as the modification time.
  112. fileInfo, err := os.Stat(filename)
  113. if err != nil {
  114. return false, ContextError(err)
  115. }
  116. fileModTime := fileInfo.ModTime()
  117. file, err := os.Open(filename)
  118. if err != nil {
  119. return false, ContextError(err)
  120. }
  121. defer file.Close()
  122. hash := crc64.New(crc64table)
  123. _, err = io.Copy(hash, file)
  124. if err != nil {
  125. return false, ContextError(err)
  126. }
  127. checksum := hash.Sum64()
  128. if checksum == previousChecksum {
  129. return false, nil
  130. }
  131. // It's possible for the file content to revert to its previous value
  132. // between the checksum operation and subsequent content load. We accept
  133. // the false positive in this unlikely case.
  134. var content []byte
  135. if reloadable.loadFileContent {
  136. _, err = file.Seek(0, 0)
  137. if err != nil {
  138. return false, ContextError(err)
  139. }
  140. content, err = ioutil.ReadAll(file)
  141. if err != nil {
  142. return false, ContextError(err)
  143. }
  144. }
  145. // Don't keep file open during reloadAction call.
  146. file.Close()
  147. // ...now block readers and reload
  148. reloadable.Lock()
  149. defer reloadable.Unlock()
  150. err = reloadable.reloadAction(content, fileModTime)
  151. if err != nil {
  152. return false, ContextError(err)
  153. }
  154. reloadable.checksum = checksum
  155. return true, nil
  156. }
  157. func (reloadable *ReloadableFile) LogDescription() string {
  158. return reloadable.filename
  159. }