thumbnail.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  1. package storage
  2. /*
  3. Thumbnails rendered where the file is
  4. A thumbnail of a cluster:/ file is rendered by a node that holds a copy
  5. of it, from the copy on its own volume, and only the small image crosses
  6. the network. The node asking picks the holder:
  7. - this node, when it holds a healthy copy: nothing is sent at all
  8. - otherwise the online holders, nearest (lowest measured round trip)
  9. first, skipping those that lack a tool the format needs (ffmpeg for
  10. video) according to their capability manifest
  11. A file that has no thumbnail (arozfs.ErrNoThumbnail) has none on any
  12. copy, so that answer ends the search; any other failure moves on to the
  13. next holder. The bytes of the file itself are never pulled for this.
  14. POST store/thumbnail {VolumeID, Path} -> {Image}
  15. Rendering itself is not this package's business: the core passes
  16. Option.Thumbnailer, which runs the ordinary renderers on an OS path.
  17. */
  18. import (
  19. "context"
  20. "encoding/json"
  21. "errors"
  22. "net/http"
  23. "os"
  24. "sort"
  25. "imuslab.com/arozos/mod/cluster/acn"
  26. "imuslab.com/arozos/mod/cluster/metadata"
  27. "imuslab.com/arozos/mod/filesystem/arozfs"
  28. )
  29. const (
  30. pathThumbnail = acn.BasePath + "/store/thumbnail"
  31. // ThumbnailConcurrency is how many thumbnails one node renders at once,
  32. // for itself and for the nodes asking it together.
  33. ThumbnailConcurrency = 2
  34. // MaxThumbnailBytes is the largest thumbnail a node sends or accepts.
  35. MaxThumbnailBytes = ChunkSize
  36. )
  37. var (
  38. // ErrNoThumbnailer is returned by a node that was started without a
  39. // thumbnail renderer.
  40. ErrNoThumbnailer = errors.New("this node does not render thumbnails")
  41. // ErrNoThumbnailHolder is returned when no online node holding a copy
  42. // can render the thumbnail (e.g. none of them has ffmpeg for a video).
  43. ErrNoThumbnailHolder = errors.New("no online node holding a copy can render this thumbnail")
  44. )
  45. type ThumbnailRequest struct {
  46. VolumeID string `json:"volumeId"`
  47. Path string `json:"path"`
  48. }
  49. type ThumbnailResponse struct {
  50. Image []byte `json:"image"`
  51. }
  52. // Thumbnail returns the thumbnail of a namespace file, rendered by a node
  53. // holding a copy. feature names a tool the renderer needs ("" for none).
  54. func (s *Service) Thumbnail(ctx context.Context, logical string, feature string) ([]byte, error) {
  55. if !s.Ready() {
  56. return nil, metadata.ErrNotInCluster
  57. }
  58. rec, err := s.meta.Stat(logical)
  59. if err != nil {
  60. return nil, os.ErrNotExist
  61. }
  62. if rec.IsDir {
  63. return nil, arozfs.ErrNoThumbnail
  64. }
  65. locs := s.orderedLocations(rec)
  66. if len(locs) == 0 {
  67. return nil, ErrNoHealthyCopy
  68. }
  69. candidates := s.thumbnailCandidates(locs, feature)
  70. if len(candidates) == 0 {
  71. return nil, ErrNoThumbnailHolder
  72. }
  73. var lastErr error = ErrNoThumbnailHolder
  74. for _, loc := range candidates {
  75. var data []byte
  76. if loc.NodeID == s.m.NodeID() {
  77. data, err = s.renderLocalThumbnail(ctx, loc.VolumeID, rec.Path)
  78. } else {
  79. data, err = s.remoteThumbnail(ctx, loc, rec.Path)
  80. }
  81. if err == nil {
  82. return data, nil
  83. }
  84. if errors.Is(err, arozfs.ErrNoThumbnail) || ctx.Err() != nil {
  85. return nil, err
  86. }
  87. lastErr = err
  88. }
  89. return nil, lastErr
  90. }
  91. // thumbnailCandidates orders the copies to ask for a thumbnail: this node
  92. // first, then the other holders nearest first, leaving out the nodes that
  93. // lack the feature. One entry per node, as a node renders any of its copies.
  94. func (s *Service) thumbnailCandidates(locs []metadata.Location, feature string) []metadata.Location {
  95. views := map[string]struct {
  96. latency float64
  97. capable bool
  98. }{}
  99. for _, n := range s.m.NodeViews() {
  100. capable := feature == "" || n.Capabilities.Has(feature)
  101. views[n.ID] = struct {
  102. latency float64
  103. capable bool
  104. }{n.LatencyMs, capable}
  105. }
  106. me := s.m.NodeID()
  107. seen := map[string]bool{}
  108. local := []metadata.Location{}
  109. remote := []metadata.Location{}
  110. for _, loc := range locs {
  111. if seen[loc.NodeID] {
  112. continue
  113. }
  114. view, known := views[loc.NodeID]
  115. if !known || !view.capable {
  116. continue
  117. }
  118. seen[loc.NodeID] = true
  119. if loc.NodeID == me {
  120. local = append(local, loc)
  121. } else {
  122. remote = append(remote, loc)
  123. }
  124. }
  125. //Nearest first; a node never measured (-1) goes after the measured ones
  126. sort.SliceStable(remote, func(i, j int) bool {
  127. a, b := views[remote[i].NodeID].latency, views[remote[j].NodeID].latency
  128. if (a < 0) != (b < 0) {
  129. return b < 0
  130. }
  131. return a < b
  132. })
  133. return append(local, remote...)
  134. }
  135. // renderLocalThumbnail renders the copy on one of this node's volumes.
  136. func (s *Service) renderLocalThumbnail(ctx context.Context, volumeID string, logical string) ([]byte, error) {
  137. if s.opt.Thumbnailer == nil {
  138. return nil, ErrNoThumbnailer
  139. }
  140. _, real, err := s.localVolumePath(volumeID, logical)
  141. if err != nil {
  142. return nil, err
  143. }
  144. info, err := os.Stat(real)
  145. if err != nil {
  146. return nil, os.ErrNotExist
  147. }
  148. if info.IsDir() {
  149. return nil, arozfs.ErrNoThumbnail
  150. }
  151. select {
  152. case s.thumbSem <- struct{}{}:
  153. defer func() { <-s.thumbSem }()
  154. case <-ctx.Done():
  155. return nil, ctx.Err()
  156. }
  157. data, err := s.opt.Thumbnailer(real)
  158. if err != nil {
  159. return nil, err
  160. }
  161. if len(data) == 0 {
  162. return nil, arozfs.ErrNoThumbnail
  163. }
  164. if len(data) > MaxThumbnailBytes {
  165. return nil, errors.New("thumbnail too large")
  166. }
  167. return data, nil
  168. }
  169. // remoteThumbnail asks the node holding loc to render the thumbnail.
  170. func (s *Service) remoteThumbnail(ctx context.Context, loc metadata.Location, logical string) ([]byte, error) {
  171. resp, err := s.client.Transport.DoJSON2(ctx, loc.NodeID, http.MethodPost, pathThumbnail,
  172. ThumbnailRequest{VolumeID: loc.VolumeID, Path: logical})
  173. if err != nil {
  174. return nil, err
  175. }
  176. if resp.Status == http.StatusUnprocessableEntity {
  177. return nil, arozfs.ErrNoThumbnail
  178. }
  179. if err := resp.Error(); err != nil {
  180. return nil, err
  181. }
  182. var out ThumbnailResponse
  183. if err := json.Unmarshal(resp.Body, &out); err != nil {
  184. return nil, err
  185. }
  186. if len(out.Image) == 0 {
  187. return nil, arozfs.ErrNoThumbnail
  188. }
  189. if len(out.Image) > MaxThumbnailBytes {
  190. return nil, errors.New("thumbnail too large")
  191. }
  192. return out.Image, nil
  193. }
  194. // handleThumbnail renders a thumbnail of a copy on this node for another one.
  195. func (s *Service) handleThumbnail(w http.ResponseWriter, r *http.Request, sender *acn.SignedIdentity, body []byte) {
  196. var req ThumbnailRequest
  197. if err := json.Unmarshal(body, &req); err != nil {
  198. acn.WriteError(w, http.StatusBadRequest, "invalid request")
  199. return
  200. }
  201. data, err := s.renderLocalThumbnail(r.Context(), req.VolumeID, req.Path)
  202. if err != nil {
  203. switch {
  204. case errors.Is(err, arozfs.ErrNoThumbnail):
  205. //The content has no thumbnail: the asking node stops looking
  206. acn.WriteError(w, http.StatusUnprocessableEntity, err.Error())
  207. case errors.Is(err, ErrNoThumbnailer):
  208. acn.WriteError(w, http.StatusNotImplemented, err.Error())
  209. default:
  210. acn.WriteError(w, statusFor(err), err.Error())
  211. }
  212. return
  213. }
  214. acn.WriteJSON(w, ThumbnailResponse{Image: data})
  215. }