forked from goreleaser/goreleaser
/
upload.go
251 lines (218 loc) · 6.44 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
package blob
import (
"fmt"
"io"
"net/url"
"os"
"path"
"strings"
"github.com/caarlos0/log"
"github.com/triarius/goreleaser/internal/artifact"
"github.com/triarius/goreleaser/internal/extrafiles"
"github.com/triarius/goreleaser/internal/semerrgroup"
"github.com/triarius/goreleaser/internal/tmpl"
"github.com/triarius/goreleaser/pkg/config"
"github.com/triarius/goreleaser/pkg/context"
"gocloud.dev/blob"
"gocloud.dev/secrets"
// Import the blob packages we want to be able to open.
_ "gocloud.dev/blob/azureblob"
_ "gocloud.dev/blob/gcsblob"
_ "gocloud.dev/blob/s3blob"
// import the secrets packages we want to be able to be used.
_ "gocloud.dev/secrets/awskms"
_ "gocloud.dev/secrets/azurekeyvault"
_ "gocloud.dev/secrets/gcpkms"
)
func urlFor(ctx *context.Context, conf config.Blob) (string, error) {
bucket, err := tmpl.New(ctx).Apply(conf.Bucket)
if err != nil {
return "", err
}
provider, err := tmpl.New(ctx).Apply(conf.Provider)
if err != nil {
return "", err
}
bucketURL := fmt.Sprintf("%s://%s", provider, bucket)
if provider != "s3" {
return bucketURL, nil
}
query := url.Values{}
endpoint, err := tmpl.New(ctx).Apply(conf.Endpoint)
if err != nil {
return "", err
}
if endpoint != "" {
query.Add("endpoint", endpoint)
query.Add("s3ForcePathStyle", "true")
}
region, err := tmpl.New(ctx).Apply(conf.Region)
if err != nil {
return "", err
}
if region != "" {
query.Add("region", region)
}
if conf.DisableSSL {
query.Add("disableSSL", "true")
}
if len(query) > 0 {
bucketURL = bucketURL + "?" + query.Encode()
}
return bucketURL, nil
}
// Takes goreleaser context(which includes artificats) and bucketURL for
// upload to destination (eg: gs://gorelease-bucket) using the given uploader
// implementation.
func doUpload(ctx *context.Context, conf config.Blob) error {
folder, err := tmpl.New(ctx).Apply(conf.Folder)
if err != nil {
return err
}
folder = strings.TrimPrefix(folder, "/")
bucketURL, err := urlFor(ctx, conf)
if err != nil {
return err
}
filter := artifact.Or(
artifact.ByType(artifact.UploadableArchive),
artifact.ByType(artifact.UploadableBinary),
artifact.ByType(artifact.UploadableSourceArchive),
artifact.ByType(artifact.Checksum),
artifact.ByType(artifact.Signature),
artifact.ByType(artifact.Certificate),
artifact.ByType(artifact.LinuxPackage),
artifact.ByType(artifact.SBOM),
)
if len(conf.IDs) > 0 {
filter = artifact.And(filter, artifact.ByIDs(conf.IDs...))
}
up := &productionUploader{}
if err := up.Open(ctx, bucketURL); err != nil {
return handleError(err, bucketURL)
}
defer up.Close()
g := semerrgroup.New(ctx.Parallelism)
for _, artifact := range ctx.Artifacts.Filter(filter).List() {
artifact := artifact
g.Go(func() error {
// TODO: replace this with ?prefix=folder on the bucket url
dataFile := artifact.Path
uploadFile := path.Join(folder, artifact.Name)
return uploadData(ctx, conf, up, dataFile, uploadFile, bucketURL)
})
}
files, err := extrafiles.Find(ctx, conf.ExtraFiles)
if err != nil {
return err
}
for name, fullpath := range files {
name := name
fullpath := fullpath
g.Go(func() error {
uploadFile := path.Join(folder, name)
return uploadData(ctx, conf, up, fullpath, uploadFile, bucketURL)
})
}
return g.Wait()
}
func uploadData(ctx *context.Context, conf config.Blob, up uploader, dataFile, uploadFile, bucketURL string) error {
data, err := getData(ctx, conf, dataFile)
if err != nil {
return err
}
if err := up.Upload(ctx, uploadFile, data); err != nil {
return handleError(err, bucketURL)
}
return nil
}
// errorContains check if error contains specific string.
func errorContains(err error, subs ...string) bool {
for _, sub := range subs {
if strings.Contains(err.Error(), sub) {
return true
}
}
return false
}
func handleError(err error, url string) error {
switch {
case errorContains(err, "NoSuchBucket", "ContainerNotFound", "notFound"):
return fmt.Errorf("provided bucket does not exist: %s: %w", url, err)
case errorContains(err, "NoCredentialProviders"):
return fmt.Errorf("check credentials and access to bucket: %s: %w", url, err)
case errorContains(err, "InvalidAccessKeyId"):
return fmt.Errorf("aws access key id you provided does not exist in our records: %w", err)
case errorContains(err, "AuthenticationFailed"):
return fmt.Errorf("azure storage key you provided is not valid: %w", err)
case errorContains(err, "invalid_grant"):
return fmt.Errorf("google app credentials you provided is not valid: %w", err)
case errorContains(err, "no such host"):
return fmt.Errorf("azure storage account you provided is not valid: %w", err)
case errorContains(err, "ServiceCode=ResourceNotFound"):
return fmt.Errorf("missing azure storage key for provided bucket %s: %w", url, err)
default:
return fmt.Errorf("failed to write to bucket: %w", err)
}
}
func getData(ctx *context.Context, conf config.Blob, path string) ([]byte, error) {
data, err := os.ReadFile(path)
if err != nil {
return data, fmt.Errorf("failed to open file %s: %w", path, err)
}
if conf.KMSKey == "" {
return data, nil
}
keeper, err := secrets.OpenKeeper(ctx, conf.KMSKey)
if err != nil {
return data, fmt.Errorf("failed to open kms %s: %w", conf.KMSKey, err)
}
defer keeper.Close()
data, err = keeper.Encrypt(ctx, data)
if err != nil {
return data, fmt.Errorf("failed to encrypt with kms: %w", err)
}
return data, err
}
// uploader implements upload.
type uploader interface {
io.Closer
Open(ctx *context.Context, url string) error
Upload(ctx *context.Context, path string, data []byte) error
}
// productionUploader actually do upload to.
type productionUploader struct {
bucket *blob.Bucket
}
func (u *productionUploader) Close() error {
if u.bucket == nil {
return nil
}
return u.bucket.Close()
}
func (u *productionUploader) Open(ctx *context.Context, bucket string) error {
log.WithFields(log.Fields{
"bucket": bucket,
}).Debug("uploading")
conn, err := blob.OpenBucket(ctx, bucket)
if err != nil {
return err
}
u.bucket = conn
return nil
}
func (u *productionUploader) Upload(ctx *context.Context, filepath string, data []byte) error {
log.WithField("path", filepath).Info("uploading")
opts := &blob.WriterOptions{
ContentDisposition: "attachment; filename=" + path.Base(filepath),
}
w, err := u.bucket.NewWriter(ctx, filepath, opts)
if err != nil {
return err
}
defer func() { _ = w.Close() }()
if _, err = w.Write(data); err != nil {
return err
}
return w.Close()
}