/
upload.go
306 lines (253 loc) · 7.81 KB
/
upload.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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
// Copyright © 2021 NAME HERE <EMAIL ADDRESS>
//
// 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 cmd
import (
"bytes"
"crypto/md5"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"os"
"os/user"
"path/filepath"
"strings"
"github.com/apex/log"
"github.com/gorilla/websocket"
"github.com/materials-commons/mcft/pkg/protocol"
"github.com/saracen/walker"
"github.com/spf13/cobra"
)
var (
uploadTo string
serverAddress string
projectID int
)
// uploadCmd represents the upload command
var uploadCmd = &cobra.Command{
Use: "upload <files-or-directories>",
Aliases: []string{"up"},
Short: "Upload files/directories to Materials Commons",
Long: `Upload files/directories to Materials Commons`,
Args: cobra.MinimumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if uploadTo == "" {
log.Fatalf("You must specify an upload path")
}
if projectID < 1 {
log.Fatalf("You must specify a project id to upload to")
}
apiKey := mustReadApiKey()
for _, fileOrDirPath := range args {
basePath, _ := filepath.Abs(fileOrDirPath)
basePath = filepath.Dir(basePath)
fi, err := os.Stat(fileOrDirPath)
if err != nil {
log.Errorf("Unable to read %s, skipping...", err)
continue
}
if fi.IsDir() {
// walk function called for every path found
walkFn := func(pathname string, fi os.FileInfo) error {
if !fi.Mode().IsRegular() {
return nil
}
if !strings.HasPrefix(pathname, "/") {
pathname, _ = filepath.Abs(pathname)
}
pathname = filepath.Clean(pathname)
uploadPath := filepath.Join("/", strings.Replace(pathname, basePath, uploadTo, 1))
fmt.Printf("Uploading file: %s to %s\n\n", pathname, uploadPath)
if err := uploadFile(pathname, uploadPath, apiKey); err != nil {
log.Errorf("Upload failed for %s: %s", pathname, err)
}
return nil
}
// error function called for every error encountered
errorCallbackOption := walker.WithErrorCallback(func(pathname string, err error) error {
// ignore permission errors
if os.IsPermission(err) {
return nil
}
// halt traversal on any other error
return err
})
_ = walker.Walk(fileOrDirPath, walkFn, errorCallbackOption)
} else {
if !strings.HasPrefix(fileOrDirPath, "/") {
fileOrDirPath, _ = filepath.Abs(fileOrDirPath)
}
uploadPath := filepath.Join("/", strings.Replace(fileOrDirPath, basePath, uploadTo, 1))
fi, err := os.Stat(fileOrDirPath)
if err != nil {
log.Errorf("Unable to Stat(%s): %s", fileOrDirPath, err)
continue
}
if !fi.Mode().IsRegular() {
continue
}
fileOrDirPath = filepath.Clean(fileOrDirPath)
fmt.Printf("Uploading file: %s to %s\n\n", fileOrDirPath, uploadPath)
if err := uploadFile(fileOrDirPath, uploadPath, apiKey); err != nil {
log.Errorf("Upload failed for %s: %s", fileOrDirPath, err)
}
}
}
},
}
func uploadFile(pathToFile, uploadToPath, apiKey string) error {
// Websocket connection defaults to wss, but can be overridden. Useful for local testing.
wsScheme := os.Getenv("MC_WS_SCHEME")
if wsScheme == "" {
wsScheme = "wss"
}
u := url.URL{Scheme: wsScheme, Host: serverAddress, Path: "/ws"}
websocket.DefaultDialer.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
c, _, err := websocket.DefaultDialer.Dial(u.String(), nil)
if err != nil {
log.Fatalf("Unable to connect to %s: %s", u.String(), err)
}
defer c.Close()
f, err := os.Open(pathToFile)
if err != nil {
log.Fatalf("Unable to open %s: %s", pathToFile, err)
}
defer f.Close()
var incomingReq protocol.IncomingRequestType
if !authenticate(c, apiKey) {
log.Fatalf("Unable to authenticate")
}
incomingReq.RequestType = protocol.UploadFileReq
if err := c.WriteJSON(incomingReq); err != nil {
//log.Errorf("Unable to initiate upload: %s", err)
return err
}
// First send notice of upload
uploadMsg := protocol.UploadFileRequest{
Path: uploadToPath,
}
if err := c.WriteJSON(uploadMsg); err != nil {
//log.Errorf("Unable to initiate upload: %s", err)
return err
}
var status protocol.StatusResponse
if err := c.ReadJSON(&status); err != nil {
log.Errorf("Unable to read upload status: %s", err)
return err
}
if status.IsError {
log.Errorf("Error starting file transfer: %s", status.Status)
return errors.New("failed to start transfer")
}
data := make([]byte, 32*1024*1024)
fb := protocol.FileBlockRequest{}
hasher := md5.New()
for {
n, err := f.Read(data)
if err != nil {
if err != io.EOF {
//log.Errorf("Read returned error: %s", err)
return err
}
break
}
incomingReq.RequestType = protocol.FileBlockReq
if err := c.WriteJSON(incomingReq); err != nil {
log.Errorf("Error during upload: %s", err)
return err
}
fb.Block = data[:n]
if err := c.WriteJSON(fb); err != nil {
//log.Errorf("WriteJSON failed: %s", err)
return err
}
_, _ = io.Copy(hasher, bytes.NewBuffer(data[:n]))
var status protocol.StatusResponse
if err := c.ReadJSON(&status); err != nil {
log.Errorf("Unable to read upload status: %s", err)
return err
}
if status.IsError {
log.Errorf("Error uploading file: %s", status.Status)
return errors.New("failed upload")
}
}
// compute checksum and check that they match by sending to the server
var finishUploadRequest protocol.FinishUploadRequest
finishUploadRequest.FileChecksum = fmt.Sprintf("%x", hasher.Sum(nil))
finishUploadRequest.Path = uploadToPath
incomingReq.RequestType = protocol.FinishUploadReq
if err := c.WriteJSON(incomingReq); err != nil {
log.Errorf("Error during upload: %s", err)
return err
}
if err := c.WriteJSON(&finishUploadRequest); err != nil {
log.Errorf("Error during upload: %s", err)
return err
}
if err := c.ReadJSON(&status); err != nil {
log.Errorf("Unable to read upload status: %s", err)
return err
}
// Uh oh the checksums didn't match
if status.IsError {
log.Errorf("Error uploading file: %s", status.Status)
return errors.New("failed upload - checksums didn't match")
}
return nil
}
func authenticate(c *websocket.Conn, key string) bool {
var req protocol.IncomingRequestType
req.RequestType = protocol.AuthenticateReq
if err := c.WriteJSON(req); err != nil {
return false
}
auth := protocol.AuthenticateRequest{
APIToken: key,
ProjectID: projectID,
}
if err := c.WriteJSON(auth); err != nil {
return false
}
return true
}
func mustReadApiKey() string {
if apikey := os.Getenv("MCAPIKEY"); apikey != "" {
return apikey
}
u, err := user.Current()
if err != nil {
log.Fatalf("Unable to identify user: %s", err)
}
configPath := filepath.Join(u.HomeDir, ".materialscommmons", "config.json")
contents, err := os.ReadFile(configPath)
if err != nil {
log.Fatalf("Unable to read %s: %s", configPath, err)
}
var config struct {
APIKey string `json:"api_key"`
}
if err := json.Unmarshal(contents, &config); err != nil {
log.Fatalf("Unable to parse (%s): %s", configPath, err)
}
return config.APIKey
}
func init() {
rootCmd.AddCommand(uploadCmd)
uploadCmd.PersistentFlags().StringVarP(&uploadTo, "upload-to", "t", "", "Path to upload to in project")
uploadCmd.PersistentFlags().IntVarP(&projectID, "project-id", "p", -1, "Project ID to upload to")
uploadCmd.PersistentFlags().StringVarP(&serverAddress, "server-address", "s", "materialscommons.org", "Server to connect to")
}