reloader.go 5.7 KB

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