volume_sync.go 6.9 KB

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