reloader.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. // ReloadLogDescription returns a description to be used for logging
  42. // events related to the Reloader.
  43. ReloadLogDescription() 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. type ReloadableFile struct {
  58. sync.RWMutex
  59. filename string
  60. loadFileContent bool
  61. hasLoaded 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. //
  72. // The returned ReloadableFile contains a sync.RWMutex and must not be copied
  73. // after first use.
  74. func NewReloadableFile(
  75. filename string,
  76. loadFileContent bool,
  77. reloadAction func([]byte, time.Time) error) ReloadableFile {
  78. return ReloadableFile{
  79. filename: filename,
  80. loadFileContent: loadFileContent,
  81. reloadAction: reloadAction,
  82. }
  83. }
  84. // WillReload indicates whether the ReloadableFile is capable
  85. // of reloading.
  86. func (reloadable *ReloadableFile) WillReload() bool {
  87. return reloadable.filename != ""
  88. }
  89. var crc64table = crc64.MakeTable(crc64.ISO)
  90. // Reload checks if the underlying file has changed and, when changed, invokes
  91. // the reloadAction callback which should reload the in-memory data structures.
  92. //
  93. // In some case (e.g., traffic rules and OSL), there are penalties associated
  94. // with proceeding with reload, so care is taken to not invoke the reload action
  95. // unless the contents have changed.
  96. //
  97. // The file content is loaded and a checksum is taken to determine whether it
  98. // has changed. Neither file size (may not change when content changes) nor
  99. // modified date (may change when identical file is repaved) is a sufficient
  100. // indicator.
  101. //
  102. // All data structure readers should be blocked by the ReloadableFile mutex.
  103. //
  104. // Reload must not be called from multiple concurrent goroutines.
  105. func (reloadable *ReloadableFile) Reload() (bool, error) {
  106. if !reloadable.WillReload() {
  107. return false, nil
  108. }
  109. // Check whether the file has changed _before_ blocking readers
  110. reloadable.RLock()
  111. filename := reloadable.filename
  112. hasLoaded := reloadable.hasLoaded
  113. previousChecksum := reloadable.checksum
  114. reloadable.RUnlock()
  115. // Record the file modification time _before_ loading, as reload actions will
  116. // assume that the content is at least as fresh as the modification time.
  117. fileInfo, err := os.Stat(filename)
  118. if err != nil {
  119. return false, errors.Trace(err)
  120. }
  121. fileModTime := fileInfo.ModTime()
  122. file, err := os.Open(filename)
  123. if err != nil {
  124. return false, errors.Trace(err)
  125. }
  126. defer file.Close()
  127. hash := crc64.New(crc64table)
  128. _, err = io.Copy(hash, file)
  129. if err != nil {
  130. return false, errors.Trace(err)
  131. }
  132. checksum := hash.Sum64()
  133. if hasLoaded && checksum == previousChecksum {
  134. return false, nil
  135. }
  136. // It's possible for the file content to revert to its previous value
  137. // between the checksum operation and subsequent content load. We accept
  138. // the false positive in this unlikely case.
  139. var content []byte
  140. if reloadable.loadFileContent {
  141. _, err = file.Seek(0, 0)
  142. if err != nil {
  143. return false, errors.Trace(err)
  144. }
  145. content, err = ioutil.ReadAll(file)
  146. if err != nil {
  147. return false, errors.Trace(err)
  148. }
  149. }
  150. // Don't keep file open during reloadAction call.
  151. file.Close()
  152. // ...now block readers and reload
  153. reloadable.Lock()
  154. defer reloadable.Unlock()
  155. if reloadable.reloadAction != nil {
  156. err := reloadable.reloadAction(content, fileModTime)
  157. if err != nil {
  158. return false, errors.Trace(err)
  159. }
  160. }
  161. reloadable.hasLoaded = true
  162. reloadable.checksum = checksum
  163. return true, nil
  164. }
  165. func (reloadable *ReloadableFile) ReloadLogDescription() string {
  166. return reloadable.filename
  167. }