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.

262 lines
7.3 KiB

5 years ago
5 years ago
5 years ago
5 years ago
4 years ago
4 years ago
3 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. "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. dchunks, mchunks, subErr := ResolveChunkManifest(lookupFileIdFn, resolvedChunks, startOffset, stopOffset)
  60. if subErr != nil {
  61. return chunks, nil, subErr
  62. }
  63. dataChunks = append(dataChunks, dchunks...)
  64. manifestChunks = append(manifestChunks, mchunks...)
  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 retriedFetchChunkData(buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64) (n int, err error) {
  102. var shouldRetry bool
  103. for waitTime := time.Second; waitTime < util.RetryWaitTime; waitTime += waitTime / 2 {
  104. for _, urlString := range urlStrings {
  105. n = 0
  106. if strings.Contains(urlString, "%") {
  107. urlString = url.PathEscape(urlString)
  108. }
  109. shouldRetry, err = util.ReadUrlAsStream(urlString+"?readDeleted=true", cipherKey, isGzipped, isFullChunk, offset, len(buffer), func(data []byte) {
  110. if n < len(buffer) {
  111. x := copy(buffer[n:], data)
  112. n += x
  113. }
  114. })
  115. if !shouldRetry {
  116. break
  117. }
  118. if err != nil {
  119. glog.V(0).Infof("read %s failed, err: %v", urlString, err)
  120. } else {
  121. break
  122. }
  123. }
  124. if err != nil && shouldRetry {
  125. glog.V(0).Infof("retry reading in %v", waitTime)
  126. time.Sleep(waitTime)
  127. } else {
  128. break
  129. }
  130. }
  131. return n, err
  132. }
  133. func retriedStreamFetchChunkData(writer io.Writer, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, size int) (err error) {
  134. var shouldRetry bool
  135. var totalWritten int
  136. for waitTime := time.Second; waitTime < util.RetryWaitTime; waitTime += waitTime / 2 {
  137. for _, urlString := range urlStrings {
  138. var localProcesed int
  139. shouldRetry, err = util.ReadUrlAsStream(urlString+"?readDeleted=true", cipherKey, isGzipped, isFullChunk, offset, size, func(data []byte) {
  140. if totalWritten > localProcesed {
  141. toBeSkipped := totalWritten - localProcesed
  142. if len(data) <= toBeSkipped {
  143. localProcesed += len(data)
  144. return // skip if already processed
  145. }
  146. data = data[toBeSkipped:]
  147. localProcesed += toBeSkipped
  148. }
  149. writer.Write(data)
  150. localProcesed += len(data)
  151. totalWritten += len(data)
  152. })
  153. if !shouldRetry {
  154. break
  155. }
  156. if err != nil {
  157. glog.V(0).Infof("read %s failed, err: %v", urlString, err)
  158. } else {
  159. break
  160. }
  161. }
  162. if err != nil && shouldRetry {
  163. glog.V(0).Infof("retry reading in %v", waitTime)
  164. time.Sleep(waitTime)
  165. } else {
  166. break
  167. }
  168. }
  169. return err
  170. }
  171. func MaybeManifestize(saveFunc SaveDataAsChunkFunctionType, inputChunks []*filer_pb.FileChunk) (chunks []*filer_pb.FileChunk, err error) {
  172. return doMaybeManifestize(saveFunc, inputChunks, ManifestBatch, mergeIntoManifest)
  173. }
  174. 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) {
  175. var dataChunks []*filer_pb.FileChunk
  176. for _, chunk := range inputChunks {
  177. if !chunk.IsChunkManifest {
  178. dataChunks = append(dataChunks, chunk)
  179. } else {
  180. chunks = append(chunks, chunk)
  181. }
  182. }
  183. remaining := len(dataChunks)
  184. for i := 0; i+mergeFactor <= len(dataChunks); i += mergeFactor {
  185. chunk, err := mergefn(saveFunc, dataChunks[i:i+mergeFactor])
  186. if err != nil {
  187. return dataChunks, err
  188. }
  189. chunks = append(chunks, chunk)
  190. remaining -= mergeFactor
  191. }
  192. // remaining
  193. for i := len(dataChunks) - remaining; i < len(dataChunks); i++ {
  194. chunks = append(chunks, dataChunks[i])
  195. }
  196. return
  197. }
  198. func mergeIntoManifest(saveFunc SaveDataAsChunkFunctionType, dataChunks []*filer_pb.FileChunk) (manifestChunk *filer_pb.FileChunk, err error) {
  199. filer_pb.BeforeEntrySerialization(dataChunks)
  200. // create and serialize the manifest
  201. data, serErr := proto.Marshal(&filer_pb.FileChunkManifest{
  202. Chunks: dataChunks,
  203. })
  204. if serErr != nil {
  205. return nil, fmt.Errorf("serializing manifest: %v", serErr)
  206. }
  207. minOffset, maxOffset := int64(math.MaxInt64), int64(math.MinInt64)
  208. for _, chunk := range dataChunks {
  209. if minOffset > int64(chunk.Offset) {
  210. minOffset = chunk.Offset
  211. }
  212. if maxOffset < int64(chunk.Size)+chunk.Offset {
  213. maxOffset = int64(chunk.Size) + chunk.Offset
  214. }
  215. }
  216. manifestChunk, _, _, err = saveFunc(bytes.NewReader(data), "", 0)
  217. if err != nil {
  218. return nil, err
  219. }
  220. manifestChunk.IsChunkManifest = true
  221. manifestChunk.Offset = minOffset
  222. manifestChunk.Size = uint64(maxOffset - minOffset)
  223. return
  224. }
  225. type SaveDataAsChunkFunctionType func(reader io.Reader, name string, offset int64) (chunk *filer_pb.FileChunk, collection, replication string, err error)