16535: Support delimiter/rollup option in list API.
[arvados.git] / services / keep-web / s3.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "encoding/xml"
9         "errors"
10         "fmt"
11         "io"
12         "net/http"
13         "os"
14         "path/filepath"
15         "sort"
16         "strconv"
17         "strings"
18
19         "git.arvados.org/arvados.git/sdk/go/arvados"
20         "git.arvados.org/arvados.git/sdk/go/ctxlog"
21         "git.arvados.org/arvados.git/tmp/GOPATH/src/github.com/AdRoll/goamz/s3"
22 )
23
24 // serveS3 handles r and returns true if r is a request from an S3
25 // client, otherwise it returns false.
26 func (h *handler) serveS3(w http.ResponseWriter, r *http.Request) bool {
27         var token string
28         if auth := r.Header.Get("Authorization"); strings.HasPrefix(auth, "AWS ") {
29                 split := strings.SplitN(auth[4:], ":", 2)
30                 if len(split) < 2 {
31                         w.WriteHeader(http.StatusUnauthorized)
32                         return true
33                 }
34                 token = split[0]
35         } else if strings.HasPrefix(auth, "AWS4-HMAC-SHA256 ") {
36                 w.WriteHeader(http.StatusBadRequest)
37                 fmt.Println(w, "V4 signature is not supported")
38                 return true
39         } else {
40                 return false
41         }
42
43         _, kc, client, release, err := h.getClients(r.Header.Get("X-Request-Id"), token)
44         if err != nil {
45                 http.Error(w, "Pool failed: "+h.clientPool.Err().Error(), http.StatusInternalServerError)
46                 return true
47         }
48         defer release()
49
50         fs := client.SiteFileSystem(kc)
51         fs.ForwardSlashNameSubstitution(h.Config.cluster.Collections.ForwardSlashNameSubstitution)
52
53         switch {
54         case r.Method == "GET" && strings.Count(strings.TrimSuffix(r.URL.Path, "/"), "/") == 1:
55                 // Path is "/{uuid}" or "/{uuid}/", has no object name
56                 h.s3list(w, r, fs)
57                 return true
58         case r.Method == "GET":
59                 fspath := "/by_id" + r.URL.Path
60                 fi, err := fs.Stat(fspath)
61                 if os.IsNotExist(err) ||
62                         (err != nil && err.Error() == "not a directory") ||
63                         (fi != nil && fi.IsDir()) {
64                         http.Error(w, "not found", http.StatusNotFound)
65                         return true
66                 }
67                 // shallow copy r, and change URL path
68                 r := *r
69                 r.URL.Path = fspath
70                 http.FileServer(fs).ServeHTTP(w, &r)
71                 return true
72         case r.Method == "PUT":
73                 if strings.HasSuffix(r.URL.Path, "/") {
74                         http.Error(w, "invalid object name (trailing '/' char)", http.StatusBadRequest)
75                         return true
76                 }
77                 fspath := "by_id" + r.URL.Path
78                 _, err = fs.Stat(fspath)
79                 if err != nil && err.Error() == "not a directory" {
80                         // requested foo/bar, but foo is a file
81                         http.Error(w, "object name conflicts with existing object", http.StatusBadRequest)
82                         return true
83                 }
84                 f, err := fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
85                 if os.IsNotExist(err) {
86                         // create missing intermediate directories, then try again
87                         for i, c := range fspath {
88                                 if i > 0 && c == '/' {
89                                         dir := fspath[:i]
90                                         if strings.HasSuffix(dir, "/") {
91                                                 err = errors.New("invalid object name (consecutive '/' chars)")
92                                                 http.Error(w, err.Error(), http.StatusBadRequest)
93                                                 return true
94                                         }
95                                         err := fs.Mkdir(dir, 0755)
96                                         if err != nil && err != os.ErrExist {
97                                                 err = fmt.Errorf("mkdir %q failed: %w", dir, err)
98                                                 http.Error(w, err.Error(), http.StatusInternalServerError)
99                                                 return true
100                                         }
101                                 }
102                         }
103                         f, err = fs.OpenFile(fspath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
104                 }
105                 if err != nil {
106                         err = fmt.Errorf("open %q failed: %w", r.URL.Path, err)
107                         http.Error(w, err.Error(), http.StatusBadRequest)
108                         return true
109                 }
110                 defer f.Close()
111                 _, err = io.Copy(f, r.Body)
112                 if err != nil {
113                         err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
114                         http.Error(w, err.Error(), http.StatusBadGateway)
115                         return true
116                 }
117                 err = f.Close()
118                 if err != nil {
119                         err = fmt.Errorf("write to %q failed: %w", r.URL.Path, err)
120                         http.Error(w, err.Error(), http.StatusBadGateway)
121                         return true
122                 }
123                 err = fs.Sync()
124                 if err != nil {
125                         err = fmt.Errorf("sync failed: %w", err)
126                         http.Error(w, err.Error(), http.StatusInternalServerError)
127                         return true
128                 }
129                 w.WriteHeader(http.StatusOK)
130                 return true
131         default:
132                 http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
133                 return true
134         }
135 }
136
137 func walkFS(fs arvados.CustomFileSystem, path string, ignoreNotFound bool, fn func(path string, fi os.FileInfo) error) error {
138         f, err := fs.Open(path)
139         if os.IsNotExist(err) && ignoreNotFound {
140                 return nil
141         } else if err != nil {
142                 return fmt.Errorf("open %q: %w", path, err)
143         }
144         defer f.Close()
145         if path == "/" {
146                 path = ""
147         }
148         fis, err := f.Readdir(-1)
149         if err != nil {
150                 return err
151         }
152         sort.Slice(fis, func(i, j int) bool { return fis[i].Name() < fis[j].Name() })
153         for _, fi := range fis {
154                 err = fn(path+"/"+fi.Name(), fi)
155                 if err == filepath.SkipDir {
156                         continue
157                 } else if err != nil {
158                         return err
159                 }
160                 if fi.IsDir() {
161                         err = walkFS(fs, path+"/"+fi.Name(), false, fn)
162                         if err != nil {
163                                 return err
164                         }
165                 }
166         }
167         return nil
168 }
169
170 var errDone = errors.New("done")
171
172 func (h *handler) s3list(w http.ResponseWriter, r *http.Request, fs arvados.CustomFileSystem) {
173         var params struct {
174                 bucket    string
175                 delimiter string
176                 marker    string
177                 maxKeys   int
178                 prefix    string
179         }
180         params.bucket = strings.SplitN(r.URL.Path[1:], "/", 2)[0]
181         params.delimiter = r.FormValue("delimiter")
182         params.marker = r.FormValue("marker")
183         if mk, _ := strconv.ParseInt(r.FormValue("max-keys"), 10, 64); mk > 0 {
184                 params.maxKeys = int(mk)
185         } else {
186                 params.maxKeys = 100
187         }
188         params.prefix = r.FormValue("prefix")
189
190         bucketdir := "by_id/" + params.bucket
191         // walkpath is the directory (relative to bucketdir) we need
192         // to walk: the innermost directory that is guaranteed to
193         // contain all paths that have the requested prefix. Examples:
194         // prefix "foo/bar"  => walkpath "foo"
195         // prefix "foo/bar/" => walkpath "foo/bar"
196         // prefix "foo"      => walkpath ""
197         // prefix ""         => walkpath ""
198         walkpath := params.prefix
199         if cut := strings.LastIndex(walkpath, "/"); cut >= 0 {
200                 walkpath = walkpath[:cut]
201         } else {
202                 walkpath = ""
203         }
204
205         resp := s3.ListResp{
206                 Name:      strings.SplitN(r.URL.Path[1:], "/", 2)[0],
207                 Prefix:    params.prefix,
208                 Delimiter: params.delimiter,
209                 Marker:    params.marker,
210                 MaxKeys:   params.maxKeys,
211         }
212         commonPrefixes := map[string]bool{}
213         err := walkFS(fs, strings.TrimSuffix(bucketdir+"/"+walkpath, "/"), true, func(path string, fi os.FileInfo) error {
214                 path = path[len(bucketdir)+1:]
215                 if len(path) <= len(params.prefix) {
216                         if path > params.prefix[:len(path)] {
217                                 // with prefix "foobar", walking "fooz" means we're done
218                                 return errDone
219                         }
220                         if path < params.prefix[:len(path)] {
221                                 // with prefix "foobar", walking "foobag" is pointless
222                                 return filepath.SkipDir
223                         }
224                         if fi.IsDir() && !strings.HasPrefix(params.prefix+"/", path+"/") {
225                                 // with prefix "foo/bar", walking "fo"
226                                 // is pointless (but walking "foo" or
227                                 // "foo/bar" is necessary)
228                                 return filepath.SkipDir
229                         }
230                         if len(path) < len(params.prefix) {
231                                 // can't skip anything, and this entry
232                                 // isn't in the results, so just
233                                 // continue descent
234                                 return nil
235                         }
236                 } else {
237                         if path[:len(params.prefix)] > params.prefix {
238                                 // with prefix "foobar", nothing we
239                                 // see after "foozzz" is relevant
240                                 return errDone
241                         }
242                 }
243                 if path < params.marker || path < params.prefix {
244                         return nil
245                 }
246                 if fi.IsDir() {
247                         return nil
248                 }
249                 if params.delimiter != "" {
250                         idx := strings.Index(path[len(params.prefix):], params.delimiter)
251                         if idx >= 0 {
252                                 // with prefix "foobar" and delimiter
253                                 // "z", when we hit "foobar/baz", we
254                                 // add "/baz" to commonPrefixes and
255                                 // stop descending (note that even if
256                                 // delimiter is "/" we don't add
257                                 // anything to commonPrefixes when
258                                 // seeing a dir: we wait until we see
259                                 // a file, so we don't incorrectly
260                                 // return results for empty dirs)
261                                 commonPrefixes[path[:len(params.prefix)+idx+1]] = true
262                                 return filepath.SkipDir
263                         }
264                 }
265                 if len(resp.Contents)+len(commonPrefixes) >= params.maxKeys {
266                         resp.IsTruncated = true
267                         if params.delimiter != "" {
268                                 resp.NextMarker = path
269                         }
270                         return errDone
271                 }
272                 resp.Contents = append(resp.Contents, s3.Key{
273                         Key: path,
274                 })
275                 return nil
276         })
277         if err != nil && err != errDone {
278                 http.Error(w, err.Error(), http.StatusInternalServerError)
279                 return
280         }
281         if params.delimiter != "" {
282                 for prefix := range commonPrefixes {
283                         resp.CommonPrefixes = append(resp.CommonPrefixes, prefix)
284                         sort.Strings(resp.CommonPrefixes)
285                 }
286         }
287         if err := xml.NewEncoder(w).Encode(resp); err != nil {
288                 ctxlog.FromContext(r.Context()).WithError(err).Error("error writing xml response")
289         }
290 }