filechunk_manifest.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package filer
  2. import (
  3. "bytes"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/util/mem"
  6. "github.com/chrislusf/seaweedfs/weed/wdclient"
  7. "io"
  8. "math"
  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 := mem.Allocate(int(chunk.Size))
  69. defer mem.Free(data)
  70. _, err := fetchChunk(data, lookupFileIdFn, chunk.GetFileIdString(), chunk.CipherKey, chunk.IsCompressed)
  71. if err != nil {
  72. return nil, fmt.Errorf("fail to read manifest %s: %v", chunk.GetFileIdString(), err)
  73. }
  74. m := &filer_pb.FileChunkManifest{}
  75. if err := proto.Unmarshal(data, m); err != nil {
  76. return nil, fmt.Errorf("fail to unmarshal manifest %s: %v", chunk.GetFileIdString(), err)
  77. }
  78. // recursive
  79. filer_pb.AfterEntryDeserialization(m.Chunks)
  80. return m.Chunks, nil
  81. }
  82. // TODO fetch from cache for weed mount?
  83. func fetchChunk(data []byte, lookupFileIdFn wdclient.LookupFileIdFunctionType, fileId string, cipherKey []byte, isGzipped bool) (int, error) {
  84. urlStrings, err := lookupFileIdFn(fileId)
  85. if err != nil {
  86. glog.Errorf("operation LookupFileId %s failed, err: %v", fileId, err)
  87. return 0, err
  88. }
  89. return retriedFetchChunkData(data, urlStrings, cipherKey, isGzipped, true, 0)
  90. }
  91. func retriedFetchChunkData(buffer []byte, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64) (n int, err error) {
  92. var shouldRetry bool
  93. for waitTime := time.Second; waitTime < util.RetryWaitTime; waitTime += waitTime / 2 {
  94. for _, urlString := range urlStrings {
  95. n = 0
  96. if strings.Contains(urlString, "%") {
  97. urlString = url.PathEscape(urlString)
  98. }
  99. shouldRetry, err = util.ReadUrlAsStream(urlString+"?readDeleted=true", cipherKey, isGzipped, isFullChunk, offset, len(buffer), func(data []byte) {
  100. if n < len(buffer) {
  101. x := copy(buffer[n:], data)
  102. n += x
  103. }
  104. })
  105. if !shouldRetry {
  106. break
  107. }
  108. if err != nil {
  109. glog.V(0).Infof("read %s failed, err: %v", urlString, err)
  110. } else {
  111. break
  112. }
  113. }
  114. if err != nil && shouldRetry {
  115. glog.V(0).Infof("retry reading in %v", waitTime)
  116. time.Sleep(waitTime)
  117. } else {
  118. break
  119. }
  120. }
  121. return n, err
  122. }
  123. func retriedStreamFetchChunkData(writer io.Writer, urlStrings []string, cipherKey []byte, isGzipped bool, isFullChunk bool, offset int64, size int) (err error) {
  124. var shouldRetry bool
  125. var totalWritten int
  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)