You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

215 lines
7.0 KiB

  1. package storage
  2. import (
  3. "fmt"
  4. "io"
  5. "io/ioutil"
  6. "net/url"
  7. "os"
  8. "sort"
  9. "strconv"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. "github.com/chrislusf/seaweedfs/weed/operation"
  12. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  13. . "github.com/chrislusf/seaweedfs/weed/storage/types"
  14. "github.com/chrislusf/seaweedfs/weed/util"
  15. )
  16. // The volume sync with a master volume via 2 steps:
  17. // 1. The slave checks master side to find subscription checkpoint
  18. // to setup the replication.
  19. // 2. The slave receives the updates from master
  20. /*
  21. Assume the slave volume needs to follow the master volume.
  22. The master volume could be compacted, and could be many files ahead of
  23. slave volume.
  24. Step 1:
  25. The slave volume will ask the master volume for a snapshot
  26. of (existing file entries, last offset, number of compacted times).
  27. For each entry x in master existing file entries:
  28. if x does not exist locally:
  29. add x locally
  30. For each entry y in local slave existing file entries:
  31. if y does not exist on master:
  32. delete y locally
  33. Step 2:
  34. After this, use the last offset and number of compacted times to request
  35. the master volume to send a new file, and keep looping. If the number of
  36. compacted times is changed, go back to step 1 (very likely this can be
  37. optimized more later).
  38. */
  39. func (v *Volume) Synchronize(volumeServer string) (err error) {
  40. var lastCompactRevision uint16 = 0
  41. var compactRevision uint16 = 0
  42. var masterMap *needle.CompactMap
  43. for i := 0; i < 3; i++ {
  44. if masterMap, _, compactRevision, err = fetchVolumeFileEntries(volumeServer, v.Id); err != nil {
  45. return fmt.Errorf("Failed to sync volume %d entries with %s: %v", v.Id, volumeServer, err)
  46. }
  47. if lastCompactRevision != compactRevision && lastCompactRevision != 0 {
  48. if err = v.Compact(0); err != nil {
  49. return fmt.Errorf("Compact Volume before synchronizing %v", err)
  50. }
  51. if err = v.commitCompact(); err != nil {
  52. return fmt.Errorf("Commit Compact before synchronizing %v", err)
  53. }
  54. }
  55. lastCompactRevision = compactRevision
  56. if err = v.trySynchronizing(volumeServer, masterMap, compactRevision); err == nil {
  57. return
  58. }
  59. }
  60. return
  61. }
  62. type ByOffset []needle.NeedleValue
  63. func (a ByOffset) Len() int { return len(a) }
  64. func (a ByOffset) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  65. func (a ByOffset) Less(i, j int) bool { return a[i].Offset < a[j].Offset }
  66. // trySynchronizing sync with remote volume server incrementally by
  67. // make up the local and remote delta.
  68. func (v *Volume) trySynchronizing(volumeServer string, masterMap *needle.CompactMap, compactRevision uint16) error {
  69. slaveIdxFile, err := os.Open(v.nm.IndexFileName())
  70. if err != nil {
  71. return fmt.Errorf("Open volume %d index file: %v", v.Id, err)
  72. }
  73. defer slaveIdxFile.Close()
  74. slaveMap, err := LoadBtreeNeedleMap(slaveIdxFile)
  75. if err != nil {
  76. return fmt.Errorf("Load volume %d index file: %v", v.Id, err)
  77. }
  78. var delta []needle.NeedleValue
  79. if err := masterMap.Visit(func(needleValue needle.NeedleValue) error {
  80. if needleValue.Key == NeedleIdEmpty {
  81. return nil
  82. }
  83. if _, ok := slaveMap.Get(needleValue.Key); ok {
  84. return nil // skip intersection
  85. }
  86. delta = append(delta, needleValue)
  87. return nil
  88. }); err != nil {
  89. return fmt.Errorf("Add master entry: %v", err)
  90. }
  91. if err := slaveMap.m.Visit(func(needleValue needle.NeedleValue) error {
  92. if needleValue.Key == NeedleIdEmpty {
  93. return nil
  94. }
  95. if _, ok := masterMap.Get(needleValue.Key); ok {
  96. return nil // skip intersection
  97. }
  98. needleValue.Size = 0
  99. delta = append(delta, needleValue)
  100. return nil
  101. }); err != nil {
  102. return fmt.Errorf("Remove local entry: %v", err)
  103. }
  104. // simulate to same ordering of remote .dat file needle entries
  105. sort.Sort(ByOffset(delta))
  106. // make up the delta
  107. fetchCount := 0
  108. volumeDataContentHandlerUrl := "http://" + volumeServer + "/admin/sync/data"
  109. for _, needleValue := range delta {
  110. if needleValue.Size == 0 {
  111. // remove file entry from local
  112. v.removeNeedle(needleValue.Key)
  113. continue
  114. }
  115. // add master file entry to local data file
  116. if err := v.fetchNeedle(volumeDataContentHandlerUrl, needleValue, compactRevision); err != nil {
  117. glog.V(0).Infof("Fetch needle %v from %s: %v", needleValue, volumeServer, err)
  118. return err
  119. }
  120. fetchCount++
  121. }
  122. glog.V(1).Infof("Fetched %d needles from %s", fetchCount, volumeServer)
  123. return nil
  124. }
  125. func fetchVolumeFileEntries(volumeServer string, vid VolumeId) (m *needle.CompactMap, lastOffset uint64, compactRevision uint16, err error) {
  126. m = needle.NewCompactMap()
  127. syncStatus, err := operation.GetVolumeSyncStatus(volumeServer, vid.String())
  128. if err != nil {
  129. return m, 0, 0, err
  130. }
  131. total := 0
  132. err = operation.GetVolumeIdxEntries(volumeServer, vid.String(), func(key NeedleId, offset Offset, size uint32) {
  133. // println("remote key", key, "offset", offset*NeedlePaddingSize, "size", size)
  134. if offset > 0 && size != TombstoneFileSize {
  135. m.Set(NeedleId(key), offset, size)
  136. } else {
  137. m.Delete(NeedleId(key))
  138. }
  139. total++
  140. })
  141. glog.V(2).Infof("server %s volume %d, entries %d, last offset %d, revision %d", volumeServer, vid, total, syncStatus.TailOffset, syncStatus.CompactRevision)
  142. return m, syncStatus.TailOffset, syncStatus.CompactRevision, err
  143. }
  144. func (v *Volume) GetVolumeSyncStatus() operation.SyncVolumeResponse {
  145. var syncStatus = operation.SyncVolumeResponse{}
  146. if stat, err := v.dataFile.Stat(); err == nil {
  147. syncStatus.TailOffset = uint64(stat.Size())
  148. }
  149. syncStatus.IdxFileSize = v.nm.IndexFileSize()
  150. syncStatus.CompactRevision = v.SuperBlock.CompactRevision
  151. syncStatus.Ttl = v.SuperBlock.Ttl.String()
  152. syncStatus.Replication = v.SuperBlock.ReplicaPlacement.String()
  153. return syncStatus
  154. }
  155. func (v *Volume) IndexFileContent() ([]byte, error) {
  156. return v.nm.IndexFileContent()
  157. }
  158. // removeNeedle removes one needle by needle key
  159. func (v *Volume) removeNeedle(key NeedleId) {
  160. n := new(Needle)
  161. n.Id = key
  162. v.deleteNeedle(n)
  163. }
  164. // fetchNeedle fetches a remote volume needle by vid, id, offset
  165. // The compact revision is checked first in case the remote volume
  166. // is compacted and the offset is invalid any more.
  167. func (v *Volume) fetchNeedle(volumeDataContentHandlerUrl string,
  168. needleValue needle.NeedleValue, compactRevision uint16) error {
  169. // add master file entry to local data file
  170. values := make(url.Values)
  171. values.Add("revision", strconv.Itoa(int(compactRevision)))
  172. values.Add("volume", v.Id.String())
  173. values.Add("id", needleValue.Key.String())
  174. values.Add("offset", strconv.FormatUint(uint64(needleValue.Offset), 10))
  175. values.Add("size", strconv.FormatUint(uint64(needleValue.Size), 10))
  176. glog.V(4).Infof("Fetch %+v", needleValue)
  177. return util.GetUrlStream(volumeDataContentHandlerUrl, values, func(r io.Reader) error {
  178. b, err := ioutil.ReadAll(r)
  179. if err != nil {
  180. return fmt.Errorf("Reading from %s error: %v", volumeDataContentHandlerUrl, err)
  181. }
  182. offset, err := v.AppendBlob(b)
  183. if err != nil {
  184. return fmt.Errorf("Appending volume %d error: %v", v.Id, err)
  185. }
  186. // println("add key", needleValue.Key, "offset", offset, "size", needleValue.Size)
  187. v.nm.Put(needleValue.Key, Offset(offset/NeedlePaddingSize), needleValue.Size)
  188. return nil
  189. })
  190. }