-
-
Notifications
You must be signed in to change notification settings - Fork 912
/
http.go
395 lines (342 loc) · 10.6 KB
/
http.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
// Package http implements functionality common to HTTP uploading pipelines.
package http
import (
"bytes"
"crypto/tls"
"crypto/x509"
"fmt"
"html/template"
"io"
h "net/http"
"os"
"runtime"
"strings"
"github.com/apex/log"
"github.com/pkg/errors"
"github.com/goreleaser/goreleaser/internal/artifact"
"github.com/goreleaser/goreleaser/internal/pipe"
"github.com/goreleaser/goreleaser/internal/semerrgroup"
"github.com/goreleaser/goreleaser/pkg/config"
"github.com/goreleaser/goreleaser/pkg/context"
)
const (
// ModeBinary uploads only compiled binaries
ModeBinary = "binary"
// ModeArchive uploads release archives
ModeArchive = "archive"
)
type asset struct {
ReadCloser io.ReadCloser
Size int64
}
type assetOpenFunc func(string, *artifact.Artifact) (*asset, error)
// nolint: gochecknoglobals
var assetOpen assetOpenFunc
// TODO: fix this.
// nolint: gochecknoinits
func init() {
assetOpenReset()
}
func assetOpenReset() {
assetOpen = assetOpenDefault
}
func assetOpenDefault(kind string, a *artifact.Artifact) (*asset, error) {
f, err := os.Open(a.Path)
if err != nil {
return nil, err
}
s, err := f.Stat()
if err != nil {
return nil, err
}
if s.IsDir() {
return nil, errors.Errorf("%s: upload failed: the asset to upload can't be a directory", kind)
}
return &asset{
ReadCloser: f,
Size: s.Size(),
}, nil
}
// Defaults sets default configuration options on upload structs
func Defaults(uploads []config.Upload) error {
for i := range uploads {
defaults(&uploads[i])
}
return nil
}
func defaults(upload *config.Upload) {
if upload.Mode == "" {
upload.Mode = ModeArchive
}
if upload.Method == "" {
upload.Method = h.MethodPut
}
}
// CheckConfig validates an upload configuration returning a descriptive error when appropriate
func CheckConfig(ctx *context.Context, upload *config.Upload, kind string) error {
if upload.Target == "" {
return misconfigured(kind, upload, "missing target")
}
if upload.Name == "" {
return misconfigured(kind, upload, "missing name")
}
if upload.Mode != ModeArchive && upload.Mode != ModeBinary {
return misconfigured(kind, upload, "mode must be 'binary' or 'archive'")
}
if _, err := getUsername(ctx, upload, kind); err != nil {
return err
}
if _, err := getPassword(ctx, upload, kind); err != nil {
return err
}
if upload.TrustedCerts != "" && !x509.NewCertPool().AppendCertsFromPEM([]byte(upload.TrustedCerts)) {
return misconfigured(kind, upload, "no certificate could be added from the specified trusted_certificates configuration")
}
return nil
}
func getUsername(ctx *context.Context, upload *config.Upload, kind string) (string, error) {
if upload.Username != "" {
return upload.Username, nil
}
var key = fmt.Sprintf("%s_%s_USERNAME", strings.ToUpper(kind), strings.ToUpper(upload.Name))
user, ok := ctx.Env[key]
if !ok {
return "", misconfigured(kind, upload, fmt.Sprintf("missing username or %s environment variable", key))
}
return user, nil
}
func getPassword(ctx *context.Context, upload *config.Upload, kind string) (string, error) {
var key = fmt.Sprintf("%s_%s_SECRET", strings.ToUpper(kind), strings.ToUpper(upload.Name))
pwd, ok := ctx.Env[key]
if !ok {
return "", misconfigured(kind, upload, fmt.Sprintf("missing %s environment variable", key))
}
return pwd, nil
}
func misconfigured(kind string, upload *config.Upload, reason string) error {
return pipe.Skip(fmt.Sprintf("%s section '%s' is not configured properly (%s)", kind, upload.Name, reason))
}
// ResponseChecker is a function capable of validating an http server response.
// It must return and error when the response must be considered a failure.
type ResponseChecker func(*h.Response) error
// Upload does the actual uploading work
func Upload(ctx *context.Context, uploads []config.Upload, kind string, check ResponseChecker) error {
if ctx.SkipPublish {
return pipe.ErrSkipPublishEnabled
}
// Handle every configured upload
for _, upload := range uploads {
upload := upload
filters := []artifact.Filter{}
if upload.Checksum {
filters = append(filters, artifact.ByType(artifact.Checksum))
}
if upload.Signature {
filters = append(filters, artifact.ByType(artifact.Signature))
}
// We support two different modes
// - "archive": Upload all artifacts
// - "binary": Upload only the raw binaries
switch v := strings.ToLower(upload.Mode); v {
case ModeArchive:
filters = append(filters,
artifact.ByType(artifact.UploadableArchive),
artifact.ByType(artifact.LinuxPackage),
)
case ModeBinary:
filters = append(filters, artifact.ByType(artifact.UploadableBinary))
default:
err := fmt.Errorf("%s: mode \"%s\" not supported", kind, v)
log.WithFields(log.Fields{
kind: upload.Name,
"mode": v,
}).Error(err.Error())
return err
}
var filter = artifact.Or(filters...)
if len(upload.IDs) > 0 {
filter = artifact.And(filter, artifact.ByIDs(upload.IDs...))
}
if err := uploadWithFilter(ctx, &upload, filter, kind, check); err != nil {
return err
}
}
return nil
}
func uploadWithFilter(ctx *context.Context, upload *config.Upload, filter artifact.Filter, kind string, check ResponseChecker) error {
var artifacts = ctx.Artifacts.Filter(filter).List()
log.Debugf("will upload %d artifacts", len(artifacts))
var g = semerrgroup.New(ctx.Parallelism)
for _, artifact := range artifacts {
artifact := artifact
g.Go(func() error {
return uploadAsset(ctx, upload, artifact, kind, check)
})
}
return g.Wait()
}
// uploadAsset uploads file to target and logs all actions
func uploadAsset(ctx *context.Context, upload *config.Upload, artifact *artifact.Artifact, kind string, check ResponseChecker) error {
username, err := getUsername(ctx, upload, kind)
if err != nil {
return err
}
secret, err := getPassword(ctx, upload, kind)
if err != nil {
return err
}
// Generate the target url
targetURL, err := resolveTargetTemplate(ctx, upload, artifact)
if err != nil {
msg := fmt.Sprintf("%s: error while building the target url", kind)
log.WithField("instance", upload.Name).WithError(err).Error(msg)
return errors.Wrap(err, msg)
}
// Handle the artifact
asset, err := assetOpen(kind, artifact)
if err != nil {
return err
}
defer asset.ReadCloser.Close() // nolint: errcheck
// The target url needs to contain the artifact name
if !strings.HasSuffix(targetURL, "/") {
targetURL += "/"
}
targetURL += artifact.Name
var headers = map[string]string{}
if upload.ChecksumHeader != "" {
sum, err := artifact.Checksum("sha256")
if err != nil {
return err
}
headers[upload.ChecksumHeader] = sum
}
res, err := uploadAssetToServer(ctx, upload, targetURL, username, secret, headers, asset, check)
if err != nil {
msg := fmt.Sprintf("%s: upload failed", kind)
log.WithError(err).WithFields(log.Fields{
"instance": upload.Name,
"username": username,
}).Error(msg)
return errors.Wrap(err, msg)
}
if err := res.Body.Close(); err != nil {
log.WithError(err).Warn("failed to close response body")
}
log.WithFields(log.Fields{
"instance": upload.Name,
"mode": upload.Mode,
}).Info("uploaded successful")
return nil
}
// uploadAssetToServer uploads the asset file to target
func uploadAssetToServer(ctx *context.Context, upload *config.Upload, target, username, secret string, headers map[string]string, a *asset, check ResponseChecker) (*h.Response, error) {
req, err := newUploadRequest(upload.Method, target, username, secret, headers, a)
if err != nil {
return nil, err
}
return executeHTTPRequest(ctx, upload, req, check)
}
// newUploadRequest creates a new h.Request for uploading
func newUploadRequest(method, target, username, secret string, headers map[string]string, a *asset) (*h.Request, error) {
req, err := h.NewRequest(method, target, a.ReadCloser)
if err != nil {
return nil, err
}
req.ContentLength = a.Size
req.SetBasicAuth(username, secret)
for k, v := range headers {
req.Header.Add(k, v)
}
return req, err
}
func getHTTPClient(upload *config.Upload) (*h.Client, error) {
if upload.TrustedCerts == "" {
return h.DefaultClient, nil
}
pool, err := x509.SystemCertPool()
if err != nil {
if runtime.GOOS == "windows" {
// on windows ignore errors until golang issues #16736 & #18609 get fixed
pool = x509.NewCertPool()
} else {
return nil, err
}
}
pool.AppendCertsFromPEM([]byte(upload.TrustedCerts)) // already validated certs checked by CheckConfig
return &h.Client{
Transport: &h.Transport{
TLSClientConfig: &tls.Config{
RootCAs: pool,
},
},
}, nil
}
// executeHTTPRequest processes the http call with respect of context ctx
func executeHTTPRequest(ctx *context.Context, upload *config.Upload, req *h.Request, check ResponseChecker) (*h.Response, error) {
client, err := getHTTPClient(upload)
if err != nil {
return nil, err
}
log.Debugf("executing request: %s %s (headers: %v)", req.Method, req.URL, req.Header)
resp, err := client.Do(req)
if err != nil {
// If we got an error, and the context has been canceled,
// the context's error is probably more useful.
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, err
}
defer resp.Body.Close() // nolint: errcheck
err = check(resp)
if err != nil {
// even though there was an error, we still return the response
// in case the caller wants to inspect it further
return resp, err
}
return resp, err
}
// targetData is used as a template struct for
// Artifactory.Target
type targetData struct {
Version string
Tag string
ProjectName string
// Only supported in mode binary
Os string
Arch string
Arm string
}
// resolveTargetTemplate returns the resolved target template with replaced variables
// Those variables can be replaced by the given context, goos, goarch, goarm and more
// TODO: replace this with our internal template pkg
func resolveTargetTemplate(ctx *context.Context, upload *config.Upload, artifact *artifact.Artifact) (string, error) {
data := targetData{
Version: ctx.Version,
Tag: ctx.Git.CurrentTag,
ProjectName: ctx.Config.ProjectName,
}
if upload.Mode == ModeBinary {
// TODO: multiple archives here
data.Os = replace(ctx.Config.Archives[0].Replacements, artifact.Goos)
data.Arch = replace(ctx.Config.Archives[0].Replacements, artifact.Goarch)
data.Arm = replace(ctx.Config.Archives[0].Replacements, artifact.Goarm)
}
var out bytes.Buffer
t, err := template.New(ctx.Config.ProjectName).Parse(upload.Target)
if err != nil {
return "", err
}
err = t.Execute(&out, data)
return out.String(), err
}
func replace(replacements map[string]string, original string) string {
result := replacements[original]
if result == "" {
return original
}
return result
}