forked from drone-plugins/drone-gcs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
284 lines (215 loc) · 5.41 KB
/
plugin.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
package main
import (
"compress/gzip"
"context"
"fmt"
"io"
"log"
"math/rand"
"mime"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"cloud.google.com/go/storage"
"github.com/pkg/errors"
)
type (
Config struct {
Token string
// Indicates the files ACL's to apply
ACL []string
// Copies the files from the specified directory.
Source string
// Destination to copy files to, including bucket name
Target string
// Exclude files matching this pattern.
Ignore string
Gzip []string
CacheControl string
Metadata map[string]string
}
Plugin struct {
Config Config
bucket *storage.BucketHandle
printf func(string, ...interface{})
fatalf func(string, ...interface{})
ecodeMu sync.Mutex
ecode int
}
)
// maxConcurrent is the highest upload concurrency.
// It cannot be 0.
const maxConcurrent = 100
// Exec executes the plugin
func (p *Plugin) Exec(client *storage.Client) error {
sort.Strings(p.Config.Gzip)
rand.Seed(time.Now().UnixNano())
p.printf = log.Printf
p.fatalf = log.Fatalf
// extract bucket name from the target path
tgt := strings.SplitN(p.Config.Target, "/", 2)
bname := tgt[0]
if len(tgt) == 1 {
p.Config.Target = ""
} else {
p.Config.Target = tgt[1]
}
p.bucket = client.Bucket(strings.Trim(bname, "/"))
// create a list of files to upload
if !strings.HasPrefix(p.Config.Source, "/") {
pwd, err := os.Getwd()
if err != nil {
return errors.Wrap(err, "failed to get working dir")
}
p.printf("source path relative to %s", pwd)
p.Config.Source = filepath.Join(pwd, p.Config.Source)
}
src, err := p.walkFiles()
if err != nil {
p.fatalf("local files: %v", err)
}
// result contains upload result of a single file
type result struct {
name string
err error
}
// upload all files in a goroutine, maxConcurrent at a time
buf := make(chan struct{}, maxConcurrent)
res := make(chan *result, len(src))
for _, f := range src {
buf <- struct{}{} // alloc one slot
go func(f string) {
rel, err := filepath.Rel(p.Config.Source, f)
if err != nil {
res <- &result{f, err}
return
}
err = p.uploadFile(path.Join(p.Config.Target, rel), f)
res <- &result{rel, err}
<-buf // free up
}(f)
}
// wait for all files to be uploaded or stop at first error
for range src {
r := <-res
if r.err != nil {
p.fatalf("%s: %v", r.name, r.err)
}
p.printf(r.name)
}
return nil
}
// errorf sets exit code to a non-zero value and outputs using printf.
func (p *Plugin) errorf(format string, args ...interface{}) {
p.ecodeMu.Lock()
p.ecode = 1
p.ecodeMu.Unlock()
p.printf(format, args...)
}
// uploadFile uploads the file to dst using global bucket.
// To get a more robust upload use retryUpload instead.
func (p *Plugin) uploadFile(dst, file string) error {
r, gz, err := p.gzipper(file)
if err != nil {
return err
}
defer r.Close()
rel, err := filepath.Rel(p.Config.Source, file)
if err != nil {
return err
}
name := path.Join(p.Config.Target, rel)
w := p.bucket.Object(name).NewWriter(context.Background())
w.CacheControl = p.Config.CacheControl
w.Metadata = p.Config.Metadata
for _, s := range p.Config.ACL {
a := strings.SplitN(s, ":", 2)
if len(a) != 2 {
return fmt.Errorf("%s: invalid ACL %q", name, s)
}
w.ACL = append(w.ACL, storage.ACLRule{
Entity: storage.ACLEntity(a[0]),
Role: storage.ACLRole(a[1]),
})
}
w.ContentType = mime.TypeByExtension(filepath.Ext(file))
if w.ContentType == "" {
w.ContentType = "application/octet-stream"
}
if gz {
w.ContentEncoding = "gzip"
}
if _, err := io.Copy(w, r); err != nil {
return err
}
return w.Close()
}
// gzipper returns a stream of file and a boolean indicating
// whether the stream is gzip-compressed.
//
// The stream is compressed if p.Gzip contains file extension.
func (p *Plugin) gzipper(file string) (io.ReadCloser, bool, error) {
r, err := os.Open(file)
if err != nil || !p.matchGzip(file) {
return r, false, err
}
pr, pw := io.Pipe()
w := gzip.NewWriter(pw)
go func() {
_, err := io.Copy(w, r)
if err != nil {
p.errorf("%s: io.Copy: %v", file, err)
}
if err := w.Close(); err != nil {
p.errorf("%s: gzip: %v", file, err)
}
if err := pw.Close(); err != nil {
p.errorf("%s: pipe: %v", file, err)
}
r.Close()
}()
return pr, true, nil
}
// matchGzip reports whether the file should be gzip-compressed during upload.
// Compressed files should be uploaded with "gzip" content-encoding.
func (p *Plugin) matchGzip(file string) bool {
ext := filepath.Ext(file)
if ext == "" {
return false
}
ext = ext[1:]
i := sort.SearchStrings(p.Config.Gzip, ext)
return i < len(p.Config.Gzip) && p.Config.Gzip[i] == ext
}
// walkFiles creates a complete set of files to upload
// by walking p.Source recursively.
//
// It excludes files matching p.Ignore pattern.
// The ignore pattern is matched using filepath.Match against a partial
// file name, relative to p.Source.
func (p *Plugin) walkFiles() ([]string, error) {
var items []string
err := filepath.Walk(p.Config.Source, func(path string, fi os.FileInfo, err error) error {
if err != nil || fi.IsDir() {
return err
}
rel, err := filepath.Rel(p.Config.Source, path)
if err != nil {
return err
}
var ignore bool
if p.Config.Ignore != "" {
ignore, err = filepath.Match(p.Config.Ignore, rel)
}
if err != nil || ignore {
return err
}
items = append(items, path)
return nil
})
return items, err
}