/
artifact_downloader.go
204 lines (168 loc) · 5.52 KB
/
artifact_downloader.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
package agent
import (
"context"
"errors"
"fmt"
"net/http"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/buildkite/agent/v3/api"
iartifact "github.com/buildkite/agent/v3/internal/artifact"
"github.com/buildkite/agent/v3/logger"
"github.com/buildkite/agent/v3/pool"
)
type ArtifactDownloaderConfig struct {
// The ID of the Build
BuildID string
// The query used to find the artifacts
Query string
// Which step should we look at for the jobs
Step string
// Whether to include artifacts from retried jobs in the search
IncludeRetriedJobs bool
// Where we'll be downloading artifacts to
Destination string
// Whether to show HTTP debugging
DebugHTTP bool
}
type ArtifactDownloader struct {
// The config for downloading
conf ArtifactDownloaderConfig
// The logger instance to use
logger logger.Logger
// The APIClient that will be used when uploading jobs
apiClient APIClient
}
func NewArtifactDownloader(l logger.Logger, ac APIClient, c ArtifactDownloaderConfig) ArtifactDownloader {
return ArtifactDownloader{
logger: l,
apiClient: ac,
conf: c,
}
}
func (a *ArtifactDownloader) Download(ctx context.Context) error {
// Turn the download destination into an absolute path and confirm it exists
destination, _ := filepath.Abs(a.conf.Destination)
fileInfo, err := os.Stat(destination)
if err != nil {
return fmt.Errorf("Could not find information about destination: %s %v",
destination, err)
}
if !fileInfo.IsDir() {
return fmt.Errorf("%s is not a directory", destination)
}
artifacts, err := NewArtifactSearcher(a.logger, a.apiClient, a.conf.BuildID).
Search(ctx, a.conf.Query, a.conf.Step, a.conf.IncludeRetriedJobs, false)
if err != nil {
return err
}
artifactCount := len(artifacts)
if artifactCount == 0 {
return errors.New("No artifacts found for downloading")
}
a.logger.Info("Found %d artifacts. Starting to download to: %s", artifactCount, destination)
p := pool.New(pool.MaxConcurrencyLimit)
errors := []error{}
s3Clients, err := a.generateS3Clients(artifacts)
if err != nil {
return fmt.Errorf("failed to generate S3 clients for artifact upload: %w", err)
}
for _, artifact := range artifacts {
p.Spawn(func() {
// Convert windows paths to slashes, otherwise we get a literal
// download of "dir/dir/file" vs sub-directories on non-windows agents
path := artifact.Path
if runtime.GOOS != "windows" {
path = strings.Replace(path, `\`, `/`, -1)
}
dler := a.createDownloader(artifact, path, destination, s3Clients)
// If the downloaded encountered an error, lock
// the pool, collect it, then unlock the pool
// again.
if err := dler.Start(ctx); err != nil {
a.logger.Error("Failed to download artifact: %s", err)
p.Lock()
errors = append(errors, err)
p.Unlock()
}
})
}
p.Wait()
if len(errors) > 0 {
return fmt.Errorf("There were errors with downloading some of the artifacts")
}
return nil
}
// We want to have as few S3 clients as possible, as creating them is kind of an expensive operation
// But it's also theoretically possible that we'll have multiple artifacts with different S3 buckets, and each
// S3Client only applies to one bucket, so we need to store the S3 clients in a map, one for each bucket
func (a *ArtifactDownloader) generateS3Clients(artifacts []*api.Artifact) (map[string]*s3.S3, error) {
s3Clients := map[string]*s3.S3{}
for _, artifact := range artifacts {
if !strings.HasPrefix(artifact.UploadDestination, "s3://") {
continue
}
bucketName, _ := ParseS3Destination(artifact.UploadDestination)
if _, has := s3Clients[bucketName]; !has {
client, err := NewS3Client(a.logger, bucketName)
if err != nil {
return nil, fmt.Errorf("failed to create S3 client for bucket %s: %w", bucketName, err)
}
s3Clients[bucketName] = client
}
}
return s3Clients, nil
}
type downloader interface {
Start(context.Context) error
}
func (a *ArtifactDownloader) createDownloader(artifact *api.Artifact, path, destination string, s3Clients map[string]*s3.S3) downloader {
// Handle downloading from S3, GS, RT, or Azure
switch {
case strings.HasPrefix(artifact.UploadDestination, "s3://"):
bucketName, _ := ParseS3Destination(artifact.UploadDestination)
return NewS3Downloader(a.logger, S3DownloaderConfig{
S3Client: s3Clients[bucketName],
Path: path,
S3Path: artifact.UploadDestination,
Destination: destination,
Retries: 5,
DebugHTTP: a.conf.DebugHTTP,
})
case strings.HasPrefix(artifact.UploadDestination, "gs://"):
return NewGSDownloader(a.logger, GSDownloaderConfig{
Path: path,
Bucket: artifact.UploadDestination,
Destination: destination,
Retries: 5,
DebugHTTP: a.conf.DebugHTTP,
})
case strings.HasPrefix(artifact.UploadDestination, "rt://"):
return NewArtifactoryDownloader(a.logger, ArtifactoryDownloaderConfig{
Path: path,
Repository: artifact.UploadDestination,
Destination: destination,
Retries: 5,
DebugHTTP: a.conf.DebugHTTP,
})
case iartifact.IsAzureBlobPath(artifact.UploadDestination):
return iartifact.NewAzureBlobDownloader(a.logger, iartifact.AzureBlobDownloaderConfig{
Path: path,
Repository: artifact.UploadDestination,
Destination: destination,
Retries: 5,
DebugHTTP: a.conf.DebugHTTP,
})
default:
return NewDownload(a.logger, http.DefaultClient, DownloadConfig{
URL: artifact.URL,
Path: path,
Destination: destination,
Retries: 5,
DebugHTTP: a.conf.DebugHTTP,
})
}
}