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.

271 lines
7.7 KiB

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