/
s3upload.go
233 lines (193 loc) · 5.26 KB
/
s3upload.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
package main
import (
"crypto/md5"
"encoding/hex"
"flag"
"fmt"
"github.com/goamz/goamz/aws"
"github.com/goamz/goamz/s3"
"io/ioutil"
"log"
"mime"
"os"
"path"
"strings"
"time"
)
const programName = "s3upload"
const veryLongTime = time.Duration(876600) * time.Hour // 100 years
// variables set by command line flags
var bucketName string
var baseDir string
var showHelp bool
var verbose bool
var recursive bool
var includeUnknownMimeTypes bool
var ignore string
var s3BasePrefix string
var timeout time.Duration
// contains information about every object in the bucket
// maps the object key name to its etag
var s3Objects = make(map[string]string)
var ignoreNames = make(map[string]string)
var stopTime time.Time
func main() {
flag.StringVar(&bucketName, "bucket", "", "S3 Bucket Name (required)")
flag.StringVar(&baseDir, "dir", "", "Local directory (required)")
flag.BoolVar(&verbose, "verbose", false, "Print extra log messages")
flag.BoolVar(&showHelp, "help", false, "Show this help")
flag.BoolVar(&recursive, "recursive", false, "recurse into sub-directories")
flag.BoolVar(&includeUnknownMimeTypes, "include-unknown-mime-types", false, "upload files with unknown mime types")
flag.StringVar(&ignore, "ignore", "", "Comma-separated list of files/directories to ignore")
flag.StringVar(&s3BasePrefix, "s3-prefix", "", "Prefix for s3 objects")
flag.DurationVar(&timeout, "timeout", 0, "Max time to run in seconds, 0=indefinite")
flag.Parse()
if showHelp {
fmt.Fprintf(os.Stderr, "usage: %s [ options ]\noptions:\n", programName)
flag.PrintDefaults()
return
}
if bucketName == "" {
log.Fatalf("Must specify bucket: use '%s -help' for usage", programName)
}
if baseDir == "" {
log.Fatalf("Must specify directory: use '%s -help' for usage", programName)
}
if timeout == time.Duration(0) {
timeout = veryLongTime
}
stopTime = time.Now().Add(timeout)
for _, name := range strings.Split(ignore, ",") {
ignoreNames[name] = name
}
if s3BasePrefix != "" {
if !strings.HasSuffix(s3BasePrefix, "/") {
s3BasePrefix += "/"
}
if verbose {
log.Printf("s3-prefix = '%s'", s3BasePrefix)
log.Printf("dir = %s", baseDir)
}
}
auth, err := aws.EnvAuth()
if err != nil {
log.Fatal(err)
}
s3Config := s3.New(auth, aws.APSoutheast2)
bucket := &s3.Bucket{S3: s3Config, Name: bucketName}
if verbose {
log.Println("Listing objects in bucket")
}
marker := ""
for {
listResp, err := bucket.List(s3BasePrefix, "", marker, 1000)
if err != nil {
log.Fatal(err)
}
for _, key := range listResp.Contents {
s3Objects[key.Key] = key.ETag
marker = key.Key
}
if verbose {
log.Printf("%d objects loaded", len(s3Objects))
}
if !listResp.IsTruncated {
break
}
if time.Now().After(stopTime) {
log.Fatal("Timeout limit reached")
}
}
processDir(baseDir, s3BasePrefix, bucket)
}
func processDir(dirName string, s3KeyPrefix string, bucket *s3.Bucket) {
if verbose {
log.Printf("Processing directory %s", dirName)
}
fileInfos, err := ioutil.ReadDir(dirName)
if err != nil {
log.Fatal(err)
}
for _, fileInfo := range fileInfos {
if time.Now().After(stopTime) {
log.Fatal("Timeout limit reached")
}
filePath := path.Join(dirName, fileInfo.Name())
// Ignore symlinks for now.
// TODO: add option to follow symlinks
if (fileInfo.Mode() & os.ModeSymlink) != 0 {
continue
}
if fileInfo.IsDir() {
if shouldRecurseInto(fileInfo.Name()) {
subDirName := path.Join(dirName, fileInfo.Name())
processDir(subDirName, s3KeyPrefix+fileInfo.Name()+"/", bucket)
}
continue
}
if ignoreNames[fileInfo.Name()] != "" {
continue
}
s3Key := s3KeyPrefix + fileInfo.Name()
putRequired := false
var data []byte
s3ETag := s3Objects[s3Key]
if s3ETag == "" {
if verbose {
log.Printf("Not found in S3 bucket: %s", s3Key)
}
putRequired = true
}
data, err := ioutil.ReadFile(filePath)
if err != nil {
log.Fatal(err)
}
// if the object exists, then we check the MD5 of the file to determine whether
// the file needs to be uploaded
if !putRequired {
digest := md5.Sum(data)
// note the need to convert digest to a slice because it is a byte array ([16]byte)
fileETag := "\"" + hex.EncodeToString(digest[:]) + "\""
if fileETag != s3ETag {
if verbose {
log.Printf("Need to upload %s: expected ETag = %s, actual = %s", filePath, fileETag, s3ETag)
}
putRequired = true
}
}
if putRequired {
// TODO: this should be configurable, but for now if the mime-type cannot
// be determined, do not upload
contentType := mime.TypeByExtension(path.Ext(strings.ToLower(fileInfo.Name())))
if contentType == "" && includeUnknownMimeTypes {
contentType = "application/octet-stream"
}
if contentType != "" {
err = bucket.Put(s3Key, data, contentType, s3.Private, s3.Options{})
if err != nil {
log.Fatal(err)
}
log.Printf("Uploaded %s\n", s3Key)
}
} else {
if verbose {
log.Printf("Identical file, no upload required: %s", filePath)
}
}
}
}
func shouldRecurseInto(dirName string) bool {
if !recursive {
return false
}
if strings.HasPrefix(dirName, ".") || strings.HasPrefix(dirName, "_") {
return false
}
if ignoreNames[dirName] != "" {
return false
}
if dirName == "lost+found" {
return false
}
return true
}