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.

251 lines
7.2 KiB

5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package filer
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/wdclient"
  6. "io"
  7. "math"
  8. "math/rand"
  9. "net/url"
  10. "strings"
  11. "time"
  12. "github.com/golang/protobuf/proto"
  13. "github.com/chrislusf/seaweedfs/weed/glog"
  14. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. )
  17. const (
  18. ManifestBatch = 10000
  19. )
  20. func HasChunkManifest(chunks []*filer_pb.FileChunk) bool {
  21. for _, chunk := range chunks {
  22. if chunk.IsChunkManifest {
  23. return true
  24. }
  25. }
  26. return false
  27. }
  28. func SeparateManifestChunks(chunks []*filer_pb.FileChunk) (manifestChunks, nonManifestChunks []*filer_pb.FileChunk) {
  29. for _, c := range chunks {
  30. if c.IsChunkManifest {
  31. manifestChunks = append(manifestChunks, c)
  32. } else {
  33. nonManifestChunks = append(nonManifestChunks, c)
  34. }
  35. }
  36. return
  37. }
  38. func ResolveChunkManifest(lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, startOffset, stopOffset int64) (dataChunks, manifestChunks []*filer_pb.FileChunk, manifestResolveErr error) {
  39. // TODO maybe parallel this
  40. for _, chunk := range chunks {
  41. if max(chunk.Offset, startOffset) >= min(chunk.Offset+int64(chunk.Size), stopOffset) {
  42. continue
  43. }
  44. if !chunk.IsChunkManifest {
  45. dataChunks = append(dataChunks, chunk)
  46. continue
  47. }
  48. resolvedChunks, err := ResolveOneChunkManifest(lookupFileIdFn, chunk)
  49. if err != nil {
  50. return chunks, nil, err
  51. }
  52. manifestChunks = append(manifestChunks, chunk)
  53. // recursive
  54. dchunks, mchunks, subErr := ResolveChunkManifest(lookupFileIdFn, resolvedChunks, startOffset, stopOffset)
  55. if subErr != nil {
  56. return chunks, nil, subErr
  57. }
  58. dataChunks = append(dataChunks, dchunks...)
  59. manifestChunks = append(manifestChunks, mchunks...)
  60. }
  61. return
  62. }
  63. func ResolveOneChunkManifest(lookupFileIdFn wdclient.LookupFileIdFunctionType, chunk *filer_pb.FileChunk) (dataChunks []*filer_pb.FileChunk, manifestResolveErr error) {
  64. if !chunk.IsChunkManifest {
  65. return
  66. }
  67. // IsChunkManifest
  68. data, err := fetchChunk(lookupFileIdFn, chunk.GetFileIdString(), chunk.CipherKey, chunk.IsCompressed)
  69. if err != nil {
  70. return nil, fmt.Errorf("fail to read manifest %s: %v", chunk.GetFileIdString(), err)
  71. }
  72. m := &filer_pb.FileChunkManifest{}
  73. if err := proto.Unmarshal(data, m); err != nil {
  74. return nil, fmt.Errorf("fail to unmarshal manifest %s: %v", chunk.GetFileIdString(), err)
  75. }
  76. // recursive
  77. filer_pb.AfterEntryDeserialization(m.Chunks)
  78. return m.Chunks, nil
  79. }
  80. // TODO fetch from cache for weed mount?
  81. func fetchChunk(lookupFileIdFn wdclient.LookupFileIdFunctionType, fileId string, cipherKey []byte, isGzipped bool) ([]byte, error) {
  82. urlStrings, err := lookupFileIdFn(fileId)
  83. if err != nil {
  84. glog.Errorf("operation LookupFileId %s failed, err: %v", fileId, err)
  85. return nil, err
  86. }
  87. return retriedFetchChunkData(urlStrings, cipherKey, isGzipped, true, 0, 0)
  88. }
  89. func retriedFetchChunkData(urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, size int) ([]byte, error) {
  90. var err error
  91. var shouldRetry bool
  92. receivedData := make([]byte, 0, size)
  93. for waitTime := time.Second; waitTime < util.RetryWaitTime; waitTime += waitTime / 2 {
  94. for _, urlString := range urlStrings {
  95. receivedData = receivedData[:0]
  96. if strings.Contains(urlString, "%") {
  97. urlString = url.PathEscape(urlString)
  98. }
  99. shouldRetry, err = util.ReadUrlAsStream(urlString+"?readDeleted=true", cipherKey, isGzipped, isFullChunk, offset, size, func(data []byte) {
  100. receivedData = append(receivedData, data...)
  101. })
  102. if !shouldRetry {
  103. break
  104. }
  105. if err != nil {
  106. glog.V(0).Infof("read %s failed, err: %v", urlString, err)
  107. } else {
  108. break
  109. }
  110. }
  111. if err != nil && shouldRetry {
  112. glog.V(0).Infof("retry reading in %v", waitTime)
  113. time.Sleep(waitTime)
  114. } else {
  115. break
  116. }
  117. }
  118. return receivedData, err
  119. }
  120. func retriedStreamFetchChunkData(writer io.Writer, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, size int) (err error) {
  121. var shouldRetry bool
  122. var totalWritten int
  123. rand.Shuffle(len(urlStrings), func(i, j int) {
  124. urlStrings[i], urlStrings[j] = urlStrings[j], urlStrings[i]
  125. })
  126. for waitTime := time.Second; waitTime < util.RetryWaitTime; waitTime += waitTime / 2 {
  127. for _, urlString := range urlStrings {
  128. var localProcesed int
  129. shouldRetry, err = util.ReadUrlAsStream(urlString+"?readDeleted=true", cipherKey, isGzipped, isFullChunk, offset, size, func(data []byte) {
  130. if totalWritten > localProcesed {
  131. toBeSkipped := totalWritten - localProcesed
  132. if len(data) <= toBeSkipped {
  133. localProcesed += len(data)
  134. return // skip if already processed
  135. }
  136. data = data[toBeSkipped:]
  137. localProcesed += toBeSkipped
  138. }
  139. writer.Write(data)
  140. localProcesed += len(data)
  141. totalWritten += len(data)
  142. })
  143. if !shouldRetry {
  144. break
  145. }
  146. if err != nil {
  147. glog.V(0).Infof("read %s failed, err: %v", urlString, err)
  148. } else {
  149. break
  150. }
  151. }
  152. if err != nil && shouldRetry {
  153. glog.V(0).Infof("retry reading in %v", waitTime)
  154. time.Sleep(waitTime)
  155. } else {
  156. break
  157. }
  158. }
  159. return err
  160. }
  161. func MaybeManifestize(saveFunc SaveDataAsChunkFunctionType, inputChunks []*filer_pb.FileChunk) (chunks []*filer_pb.FileChunk, err error) {
  162. return doMaybeManifestize(saveFunc, inputChunks, ManifestBatch, mergeIntoManifest)
  163. }
  164. func doMaybeManifestize(saveFunc SaveDataAsChunkFunctionType, inputChunks []*filer_pb.FileChunk, mergeFactor int, mergefn func(saveFunc SaveDataAsChunkFunctionType, dataChunks []*filer_pb.FileChunk) (manifestChunk *filer_pb.FileChunk, err error)) (chunks []*filer_pb.FileChunk, err error) {
  165. var dataChunks []*filer_pb.FileChunk
  166. for _, chunk := range inputChunks {
  167. if !chunk.IsChunkManifest {
  168. dataChunks = append(dataChunks, chunk)
  169. } else {
  170. chunks = append(chunks, chunk)
  171. }
  172. }
  173. remaining := len(dataChunks)
  174. for i := 0; i+mergeFactor <= len(dataChunks); i += mergeFactor {
  175. chunk, err := mergefn(saveFunc, dataChunks[i:i+mergeFactor])
  176. if err != nil {
  177. return dataChunks, err
  178. }
  179. chunks = append(chunks, chunk)
  180. remaining -= mergeFactor
  181. }
  182. // remaining
  183. for i := len(dataChunks) - remaining; i < len(dataChunks); i++ {
  184. chunks = append(chunks, dataChunks[i])
  185. }
  186. return
  187. }
  188. func mergeIntoManifest(saveFunc SaveDataAsChunkFunctionType, dataChunks []*filer_pb.FileChunk) (manifestChunk *filer_pb.FileChunk, err error) {
  189. filer_pb.BeforeEntrySerialization(dataChunks)
  190. // create and serialize the manifest
  191. data, serErr := proto.Marshal(&filer_pb.FileChunkManifest{
  192. Chunks: dataChunks,
  193. })
  194. if serErr != nil {
  195. return nil, fmt.Errorf("serializing manifest: %v", serErr)
  196. }
  197. minOffset, maxOffset := int64(math.MaxInt64), int64(math.MinInt64)
  198. for _, chunk := range dataChunks {
  199. if minOffset > int64(chunk.Offset) {
  200. minOffset = chunk.Offset
  201. }
  202. if maxOffset < int64(chunk.Size)+chunk.Offset {
  203. maxOffset = int64(chunk.Size) + chunk.Offset
  204. }
  205. }
  206. manifestChunk, _, _, err = saveFunc(bytes.NewReader(data), "", 0)
  207. if err != nil {
  208. return nil, err
  209. }
  210. manifestChunk.IsChunkManifest = true
  211. manifestChunk.Offset = minOffset
  212. manifestChunk.Size = uint64(maxOffset - minOffset)
  213. return
  214. }
  215. type SaveDataAsChunkFunctionType func(reader io.Reader, name string, offset int64) (chunk *filer_pb.FileChunk, collection, replication string, err error)