-
Notifications
You must be signed in to change notification settings - Fork 776
/
storagesvc.go
215 lines (185 loc) · 6.2 KB
/
storagesvc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*
Copyright 2017 The Fission Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package storagesvc
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"time"
"github.com/gorilla/mux"
_ "github.com/graymeta/stow/local"
"github.com/pkg/errors"
"go.opencensus.io/plugin/ochttp"
"go.uber.org/zap"
)
type (
StorageService struct {
logger *zap.Logger
storageClient *StowClient
port int
}
UploadResponse struct {
ID string `json:"id"`
}
)
// Handle multipart file uploads.
func (ss *StorageService) uploadHandler(w http.ResponseWriter, r *http.Request) {
// handle upload
r.ParseMultipartForm(0)
file, handler, err := r.FormFile("uploadfile")
if err != nil {
http.Error(w, "missing upload file", http.StatusBadRequest)
return
}
defer file.Close()
// stow wants the file size, but that's different from the
// content length, the content length being the size of the
// encoded file in the HTTP request. So we require an
// "X-File-Size" header in bytes.
fileSizeS, ok := r.Header["X-File-Size"]
if !ok {
ss.logger.Error("upload is missing the 'X-File-Size' header",
zap.String("filename", handler.Filename))
http.Error(w, "missing X-File-Size header", http.StatusBadRequest)
return
}
fileSize, err := strconv.Atoi(fileSizeS[0])
if err != nil {
ss.logger.Error("error parsing 'X-File-Size' header",
zap.Error(err),
zap.Strings("header", fileSizeS),
zap.String("filename", handler.Filename))
http.Error(w, "missing or bad X-File-Size header", http.StatusBadRequest)
return
}
// TODO: allow headers to add more metadata (e.g. environment and function metadata)
ss.logger.Debug("handling upload",
zap.String("filename", handler.Filename))
id, err := ss.storageClient.putFile(file, int64(fileSize))
if err != nil {
ss.logger.Error("error saving uploaded file",
zap.Error(err),
zap.String("filename", handler.Filename))
http.Error(w, "Error saving uploaded file", http.StatusInternalServerError)
return
}
// respond with an ID that can be used to retrieve the file
ur := &UploadResponse{
ID: id,
}
resp, err := json.Marshal(ur)
if err != nil {
ss.logger.Error("error marshaling uploaded file response",
zap.Error(err),
zap.String("filename", handler.Filename))
http.Error(w, "Error marshaling response", http.StatusInternalServerError)
return
}
w.Write(resp)
}
func (ss *StorageService) getIdFromRequest(r *http.Request) (string, error) {
values := r.URL.Query()
ids, ok := values["id"]
if !ok || len(ids) == 0 {
return "", errors.New("missing `id' query param")
}
return ids[0], nil
}
func (ss *StorageService) deleteHandler(w http.ResponseWriter, r *http.Request) {
// get id from request
fileId, err := ss.getIdFromRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = ss.storageClient.removeFileByID(fileId)
if err != nil {
msg := fmt.Sprintf("Error deleting item: %v", err)
http.Error(w, msg, http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
func (ss *StorageService) downloadHandler(w http.ResponseWriter, r *http.Request) {
// get id from request
fileId, err := ss.getIdFromRequest(r)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Get the file (called "item" in stow's jargon), open it,
// stream it to response
err = ss.storageClient.copyFileToStream(fileId, w)
if err != nil {
ss.logger.Error("error getting file from storage client", zap.Error(err), zap.String("file_id", fileId))
if err == ErrNotFound {
http.Error(w, "Error retrieving item: not found", http.StatusNotFound)
} else if err == ErrRetrievingItem {
http.Error(w, "Error retrieving item", http.StatusBadRequest)
} else if err == ErrOpeningItem {
http.Error(w, "Error opening item", http.StatusBadRequest)
} else if err == ErrWritingFileIntoResponse {
http.Error(w, "Error writing response", http.StatusInternalServerError)
}
return
}
}
func (ss *StorageService) healthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}
func MakeStorageService(logger *zap.Logger, storageClient *StowClient, port int) *StorageService {
return &StorageService{
logger: logger.Named("storage_service"),
storageClient: storageClient,
port: port,
}
}
func (ss *StorageService) Start(port int) {
r := mux.NewRouter()
r.HandleFunc("/v1/archive", ss.uploadHandler).Methods("POST")
r.HandleFunc("/v1/archive", ss.downloadHandler).Methods("GET")
r.HandleFunc("/v1/archive", ss.deleteHandler).Methods("DELETE")
r.HandleFunc("/healthz", ss.healthHandler).Methods("GET")
address := fmt.Sprintf(":%v", port)
err := http.ListenAndServe(address, &ochttp.Handler{
Handler: r,
})
ss.logger.Fatal("done listening", zap.Error(err))
}
func RunStorageService(logger *zap.Logger, storageType StorageType, storagePath string, containerName string, port int, enablePruner bool) *StorageService {
// create a storage client
storageClient, err := MakeStowClient(logger, storageType, storagePath, containerName)
if err != nil {
logger.Fatal("error creating stowClient", zap.Error(err))
}
// create http handlers
storageService := MakeStorageService(logger, storageClient, port)
go storageService.Start(port)
// enablePruner prevents storagesvc unit test from needing to talk to kubernetes
if enablePruner {
// get the prune interval and start the archive pruner
pruneInterval, err := strconv.Atoi(os.Getenv("PRUNE_INTERVAL"))
if err != nil {
pruneInterval = defaultPruneInterval
}
pruner, err := MakeArchivePruner(logger, storageClient, time.Duration(pruneInterval))
if err != nil {
logger.Fatal("error creating archivePruner", zap.Error(err))
}
go pruner.Start()
}
logger.Info("storage service started")
return storageService
}