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.

217 lines
4.7 KiB

9 years ago
9 years ago
  1. package operation
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "sort"
  9. "sync"
  10. "github.com/chrislusf/seaweedfs/go/glog"
  11. "github.com/chrislusf/seaweedfs/go/util"
  12. )
  13. var (
  14. // when the remote server does not allow range requests (Accept-Ranges was not set)
  15. ErrRangeRequestsNotSupported = errors.New("Range requests are not supported by the remote server")
  16. // ErrInvalidRange is returned by Read when trying to read past the end of the file
  17. ErrInvalidRange = errors.New("Invalid range")
  18. )
  19. type ChunkInfo struct {
  20. Fid string `json:"fid"`
  21. Offset int64 `json:"offset"`
  22. Size int64 `json:"size"`
  23. }
  24. type ChunkList []*ChunkInfo
  25. type ChunkManifest struct {
  26. Name string `json:"name,omitempty"`
  27. Mime string `json:"mime,omitempty"`
  28. Size int64 `json:"size,omitempty"`
  29. Chunks ChunkList `json:"chunks,omitempty"`
  30. }
  31. // seekable chunked file reader
  32. type ChunkedFileReader struct {
  33. Manifest *ChunkManifest
  34. Master string
  35. pos int64
  36. pr *io.PipeReader
  37. pw *io.PipeWriter
  38. mutex sync.Mutex
  39. }
  40. func (s ChunkList) Len() int { return len(s) }
  41. func (s ChunkList) Less(i, j int) bool { return s[i].Offset < s[j].Offset }
  42. func (s ChunkList) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
  43. func LoadChunkManifest(buffer []byte, isGzipped bool) (*ChunkManifest, error) {
  44. if isGzipped {
  45. var err error
  46. if buffer, err = UnGzipData(buffer); err != nil {
  47. return nil, err
  48. }
  49. }
  50. cm := ChunkManifest{}
  51. if e := json.Unmarshal(buffer, &cm); e != nil {
  52. return nil, e
  53. }
  54. sort.Sort(cm.Chunks)
  55. return &cm, nil
  56. }
  57. func (cm *ChunkManifest) GetData() ([]byte, error) {
  58. return json.Marshal(cm)
  59. }
  60. func (cm *ChunkManifest) DeleteChunks(master string) error {
  61. deleteError := 0
  62. for _, ci := range cm.Chunks {
  63. if e := DeleteFile(master, ci.Fid, ""); e != nil {
  64. deleteError++
  65. glog.V(0).Infoln("delete error:", e, ci.Fid)
  66. }
  67. }
  68. if deleteError > 0 {
  69. return errors.New("Not all chunks deleted.")
  70. }
  71. return nil
  72. }
  73. //func (cm *ChunkManifest) StoredHelper() error {
  74. // return nil
  75. //}
  76. func httpRangeDownload(fileUrl string, w io.Writer, offset int64) (written int64, e error) {
  77. req, err := http.NewRequest("GET", fileUrl, nil)
  78. if err != nil {
  79. return written, err
  80. }
  81. if offset > 0 {
  82. req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
  83. }
  84. resp, err := util.Do(req)
  85. if err != nil {
  86. return written, err
  87. }
  88. defer resp.Body.Close()
  89. switch resp.StatusCode {
  90. case http.StatusRequestedRangeNotSatisfiable:
  91. return written, ErrInvalidRange
  92. case http.StatusOK:
  93. if offset > 0 {
  94. return written, ErrRangeRequestsNotSupported
  95. }
  96. case http.StatusPartialContent:
  97. break
  98. default:
  99. return written, fmt.Errorf("Read Needle http error: [%d] %s", resp.StatusCode, fileUrl)
  100. }
  101. return io.Copy(w, resp.Body)
  102. }
  103. func (cf *ChunkedFileReader) Seek(offset int64, whence int) (int64, error) {
  104. var err error
  105. switch whence {
  106. case 0:
  107. case 1:
  108. offset += cf.pos
  109. case 2:
  110. offset = cf.Manifest.Size - offset
  111. }
  112. if offset > cf.Manifest.Size {
  113. err = ErrInvalidRange
  114. }
  115. if cf.pos != offset {
  116. cf.Close()
  117. }
  118. cf.pos = offset
  119. return cf.pos, err
  120. }
  121. func (cf *ChunkedFileReader) WriteTo(w io.Writer) (n int64, err error) {
  122. cm := cf.Manifest
  123. chunkIndex := -1
  124. chunkStartOffset := int64(0)
  125. for i, ci := range cm.Chunks {
  126. if cf.pos >= ci.Offset && cf.pos < ci.Offset+ci.Size {
  127. chunkIndex = i
  128. chunkStartOffset = cf.pos - ci.Offset
  129. break
  130. }
  131. }
  132. if chunkIndex < 0 {
  133. return n, ErrInvalidRange
  134. }
  135. for ; chunkIndex < cm.Chunks.Len(); chunkIndex++ {
  136. ci := cm.Chunks[chunkIndex]
  137. // if we need read date from local volume server first?
  138. fileUrl, lookupError := LookupFileId(cf.Master, ci.Fid)
  139. if lookupError != nil {
  140. return n, lookupError
  141. }
  142. if wn, e := httpRangeDownload(fileUrl, w, chunkStartOffset); e != nil {
  143. return n, e
  144. } else {
  145. n += wn
  146. cf.pos += wn
  147. }
  148. chunkStartOffset = 0
  149. }
  150. return n, nil
  151. }
  152. func (cf *ChunkedFileReader) ReadAt(p []byte, off int64) (n int, err error) {
  153. cf.Seek(off, 0)
  154. return cf.Read(p)
  155. }
  156. func (cf *ChunkedFileReader) Read(p []byte) (int, error) {
  157. return cf.getPipeReader().Read(p)
  158. }
  159. func (cf *ChunkedFileReader) Close() (e error) {
  160. cf.mutex.Lock()
  161. defer cf.mutex.Unlock()
  162. return cf.closePipe()
  163. }
  164. func (cf *ChunkedFileReader) closePipe() (e error) {
  165. if cf.pr != nil {
  166. if err := cf.pr.Close(); err != nil {
  167. e = err
  168. }
  169. }
  170. cf.pr = nil
  171. if cf.pw != nil {
  172. if err := cf.pw.Close(); err != nil {
  173. e = err
  174. }
  175. }
  176. cf.pw = nil
  177. return e
  178. }
  179. func (cf *ChunkedFileReader) getPipeReader() io.Reader {
  180. cf.mutex.Lock()
  181. defer cf.mutex.Unlock()
  182. if cf.pr != nil && cf.pw != nil {
  183. return cf.pr
  184. }
  185. cf.closePipe()
  186. cf.pr, cf.pw = io.Pipe()
  187. go func(pw *io.PipeWriter) {
  188. _, e := cf.WriteTo(pw)
  189. pw.CloseWithError(e)
  190. }(cf.pw)
  191. return cf.pr
  192. }