transfer_client.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. package storage
  2. /*
  3. Chunked transfer protocol - client side. Every request is one signed ACN
  4. call of at most MaxChunkSize bytes, so a transfer survives proxies that
  5. cap request size or duration.
  6. */
  7. import (
  8. "context"
  9. "crypto/sha256"
  10. "encoding/hex"
  11. "encoding/json"
  12. "errors"
  13. "io"
  14. "net/http"
  15. "net/url"
  16. "strconv"
  17. "strings"
  18. "imuslab.com/arozos/mod/cluster/acn"
  19. )
  20. // Client moves files to and from other nodes' volumes.
  21. type Client struct {
  22. Transport *acn.Transport
  23. }
  24. const chunkRetries = 3
  25. func (c *Client) postJSON(ctx context.Context, nodeID string, path string, in interface{}, out interface{}) error {
  26. return c.Transport.DoJSON(ctx, nodeID, http.MethodPost, path, in, out)
  27. }
  28. // Upload sends size bytes from r to the volume on nodeID, resuming a
  29. // previous attempt of the same file when the target still has chunks.
  30. func (c *Client) Upload(ctx context.Context, nodeID string, volumeID string, logical string, fileID string, r io.Reader, size int64, checksum string, progress func(done int64)) error {
  31. var begin BeginResponse
  32. if err := c.postJSON(ctx, nodeID, pathBegin, BeginRequest{VolumeID: volumeID, Path: logical, Size: size, Checksum: checksum, FileID: fileID}, &begin); err != nil {
  33. return err
  34. }
  35. have := map[int]bool{}
  36. for _, i := range begin.Have {
  37. have[i] = true
  38. }
  39. buf := make([]byte, ChunkSize)
  40. var done int64
  41. for index := 0; int64(index)*ChunkSize < size; index++ {
  42. want := ChunkSize
  43. if remaining := size - int64(index)*ChunkSize; remaining < int64(want) {
  44. want = int(remaining)
  45. }
  46. n, err := io.ReadFull(r, buf[:want])
  47. if err != nil {
  48. return err
  49. }
  50. done += int64(n)
  51. if have[index] {
  52. if progress != nil {
  53. progress(done)
  54. }
  55. continue
  56. }
  57. chunk := buf[:n]
  58. sum := sha256.Sum256(chunk)
  59. q := url.Values{"session": {begin.SessionID}, "index": {strconv.Itoa(index)}}
  60. var lastErr error
  61. for attempt := 0; attempt < chunkRetries; attempt++ {
  62. if ctx.Err() != nil {
  63. return ctx.Err()
  64. }
  65. resp, err := c.doRaw(ctx, nodeID, pathChunk+"?"+q.Encode(), chunk, http.Header{HeaderChunkSha: {hex.EncodeToString(sum[:])}, "Content-Type": {"application/octet-stream"}})
  66. if err == nil && resp.Status == http.StatusOK {
  67. lastErr = nil
  68. break
  69. }
  70. if err != nil {
  71. lastErr = err
  72. } else {
  73. lastErr = resp.Error()
  74. if resp.Status == http.StatusNotFound || resp.Status == http.StatusBadRequest {
  75. break //not retryable
  76. }
  77. }
  78. }
  79. if lastErr != nil {
  80. return lastErr
  81. }
  82. if progress != nil {
  83. progress(done)
  84. }
  85. }
  86. var commit CommitResponse
  87. if err := c.postJSON(ctx, nodeID, pathCommit, SessionRequest{SessionID: begin.SessionID}, &commit); err != nil {
  88. return err
  89. }
  90. if !strings.EqualFold(commit.Checksum, checksum) {
  91. return ErrChecksum
  92. }
  93. return nil
  94. }
  95. // doRaw sends a raw body with extra headers through the transport. The ACN
  96. // signature covers the body; extra headers ride along unsigned (the chunk
  97. // hash is re-verified against the signed body on the receiver).
  98. func (c *Client) doRaw(ctx context.Context, nodeID string, path string, body []byte, extra http.Header) (*acn.Response, error) {
  99. return c.Transport.DoWithHeaders(ctx, nodeID, http.MethodPost, path, body, extra)
  100. }
  101. // Download streams the file on the given volume into w, verifying every
  102. // chunk and the whole-file checksum when expectChecksum is set.
  103. func (c *Client) Download(ctx context.Context, nodeID string, volumeID string, logical string, w io.Writer, expectChecksum string, progress func(done int64)) error {
  104. h := sha256.New()
  105. var offset int64
  106. var total int64 = -1
  107. for {
  108. if ctx.Err() != nil {
  109. return ctx.Err()
  110. }
  111. q := url.Values{
  112. "volume": {volumeID},
  113. "path": {logical},
  114. "offset": {strconv.FormatInt(offset, 10)},
  115. "length": {strconv.Itoa(ChunkSize)},
  116. }
  117. resp, err := c.Transport.Do(ctx, nodeID, http.MethodGet, pathRead+"?"+q.Encode(), nil)
  118. if err != nil {
  119. return err
  120. }
  121. if err := resp.Error(); err != nil {
  122. return err
  123. }
  124. if total < 0 {
  125. total, _ = strconv.ParseInt(resp.Header.Get(HeaderFileSize), 10, 64)
  126. if total == 0 {
  127. break
  128. }
  129. }
  130. sum := sha256.Sum256(resp.Body)
  131. if !strings.EqualFold(hex.EncodeToString(sum[:]), resp.Header.Get(HeaderChunkSha)) {
  132. return ErrChecksum
  133. }
  134. if _, err := w.Write(resp.Body); err != nil {
  135. return err
  136. }
  137. h.Write(resp.Body)
  138. offset += int64(len(resp.Body))
  139. if progress != nil {
  140. progress(offset)
  141. }
  142. if len(resp.Body) == 0 || offset >= total {
  143. break
  144. }
  145. }
  146. if expectChecksum != "" && !strings.EqualFold(hex.EncodeToString(h.Sum(nil)), expectChecksum) {
  147. return ErrChecksum
  148. }
  149. return nil
  150. }
  151. // Stat asks a node about a path on one of its volumes.
  152. func (c *Client) Stat(ctx context.Context, nodeID string, volumeID string, logical string) (*StatResponse, error) {
  153. q := url.Values{"volume": {volumeID}, "path": {logical}}
  154. resp, err := c.Transport.Do(ctx, nodeID, http.MethodGet, pathStatFile+"?"+q.Encode(), nil)
  155. if err != nil {
  156. return nil, err
  157. }
  158. if err := resp.Error(); err != nil {
  159. return nil, err
  160. }
  161. var st StatResponse
  162. if err := json.Unmarshal(resp.Body, &st); err != nil {
  163. return nil, err
  164. }
  165. return &st, nil
  166. }
  167. // Mkdir creates a directory on a remote volume.
  168. func (c *Client) Mkdir(ctx context.Context, nodeID string, volumeID string, logical string) error {
  169. return c.postJSON(ctx, nodeID, pathMkdir, PathRequest{VolumeID: volumeID, Path: logical}, nil)
  170. }
  171. // Delete removes a path on a remote volume.
  172. func (c *Client) Delete(ctx context.Context, nodeID string, volumeID string, logical string, recursive bool) error {
  173. return c.postJSON(ctx, nodeID, pathDelete, PathRequest{VolumeID: volumeID, Path: logical, Recursive: recursive}, nil)
  174. }
  175. // Rename moves a path within a remote volume.
  176. func (c *Client) Rename(ctx context.Context, nodeID string, volumeID string, from string, to string) error {
  177. return c.postJSON(ctx, nodeID, pathRename, PathRequest{VolumeID: volumeID, Path: from, NewPath: to}, nil)
  178. }
  179. // List reads a directory on a remote volume.
  180. func (c *Client) List(ctx context.Context, nodeID string, volumeID string, logical string) ([]ListEntry, error) {
  181. q := url.Values{"volume": {volumeID}, "path": {logical}}
  182. resp, err := c.Transport.Do(ctx, nodeID, http.MethodGet, pathList+"?"+q.Encode(), nil)
  183. if err != nil {
  184. return nil, err
  185. }
  186. if err := resp.Error(); err != nil {
  187. return nil, err
  188. }
  189. var out []ListEntry
  190. if err := json.Unmarshal(resp.Body, &out); err != nil {
  191. return nil, err
  192. }
  193. return out, nil
  194. }
  195. // Checksum asks a node to hash a file on one of its volumes.
  196. func (c *Client) Checksum(ctx context.Context, nodeID string, volumeID string, logical string) (*ChecksumResponse, error) {
  197. var out ChecksumResponse
  198. if err := c.postJSON(ctx, nodeID, pathChecksum, PathRequest{VolumeID: volumeID, Path: logical}, &out); err != nil {
  199. return nil, err
  200. }
  201. if out.Checksum == "" {
  202. return nil, errors.New("empty checksum")
  203. }
  204. return &out, nil
  205. }