forked from buildkite/agent
-
Notifications
You must be signed in to change notification settings - Fork 8
/
artifact_uploader.go
302 lines (245 loc) · 7.75 KB
/
artifact_uploader.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
package agent
import (
"crypto/sha1"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/buildkite/agent/api"
"github.com/buildkite/agent/glob"
"github.com/buildkite/agent/logger"
"github.com/buildkite/agent/pool"
"github.com/buildkite/agent/retry"
)
type ArtifactUploader struct {
// The APIClient that will be used when uploading jobs
APIClient *api.Client
// The ID of the Job
JobID string
// The path of the uploads
Paths string
// Where we'll be uploading artifacts
Destination string
}
func (a *ArtifactUploader) Upload() error {
// Create artifact structs for all the files we need to upload
artifacts, err := a.Collect()
if err != nil {
return err
}
if len(artifacts) == 0 {
logger.Info("No files matched paths: %s", a.Paths)
} else {
logger.Info("Found %d files that match \"%s\"", len(artifacts), a.Paths)
err := a.upload(artifacts)
if err != nil {
return err
}
}
return nil
}
func (a *ArtifactUploader) Collect() (artifacts []*api.Artifact, err error) {
globPaths := strings.Split(a.Paths, ";")
for _, globPath := range globPaths {
workingDirectory := glob.Root(globPath)
globPath = strings.TrimSpace(globPath)
if globPath != "" {
logger.Debug("Searching for %s", filepath.Join(workingDirectory, globPath))
files, err := glob.Glob(workingDirectory, globPath)
if err != nil {
return nil, err
}
for _, file := range files {
// Generate an absolute path for the artifact
absolutePath, err := filepath.Abs(file)
if err != nil {
return nil, err
}
if isDir, _ := glob.IsDir(absolutePath); isDir {
logger.Debug("Skipping directory %s", file)
continue
}
// Create a relative path (from the workingDirectory) to the artifact, by removing the
// first part of the absolutePath that is the workingDirectory.
relativePath := strings.Replace(absolutePath, workingDirectory, "", 1)
// Ensure the relativePath doesn't have a file seperator "/" as the first character
relativePath = strings.TrimPrefix(relativePath, string(os.PathSeparator))
// Build an artifact object using the paths we have.
artifact, err := a.build(relativePath, absolutePath, globPath)
if err != nil {
return nil, err
}
artifacts = append(artifacts, artifact)
}
}
}
return artifacts, nil
}
func (a *ArtifactUploader) build(relativePath string, absolutePath string, globPath string) (*api.Artifact, error) {
// Temporarily open the file to get it's size
file, err := os.Open(absolutePath)
if err != nil {
return nil, err
}
defer file.Close()
// Grab it's file info (which includes it's file size)
fileInfo, err := file.Stat()
if err != nil {
return nil, err
}
// Generate a sha1 checksum for the file
hash := sha1.New()
io.Copy(hash, file)
checksum := fmt.Sprintf("%x", hash.Sum(nil))
// Create our new artifact data structure
artifact := &api.Artifact{
Path: relativePath,
AbsolutePath: absolutePath,
GlobPath: globPath,
FileSize: fileInfo.Size(),
Sha1Sum: checksum,
}
return artifact, nil
}
func (a *ArtifactUploader) upload(artifacts []*api.Artifact) error {
var uploader Uploader
// Determine what uploader to use
if a.Destination != "" {
if strings.HasPrefix(a.Destination, "s3://") {
uploader = new(S3Uploader)
} else {
return errors.New("Unknown upload destination: " + a.Destination)
}
} else {
uploader = new(FormUploader)
}
// Setup the uploader
err := uploader.Setup(a.Destination, a.APIClient.DebugHTTP)
if err != nil {
return err
}
// Set the URL's of the artifacts based on the uploader
for _, artifact := range artifacts {
artifact.URL = uploader.URL(artifact)
}
// Create the artifacts on Buildkite
batchCreator := ArtifactBatchCreator{
APIClient: a.APIClient,
JobID: a.JobID,
Artifacts: artifacts,
UploadDestination: a.Destination,
}
artifacts, err = batchCreator.Create()
if err != nil {
return err
}
// Prepare a concurrency pool to upload the artifacts
p := pool.New(pool.MaxConcurrencyLimit)
errors := []error{}
var errorsMutex sync.Mutex
// Create a wait group so we can make sure the uploader waits for all
// the artifact states to upload before finishing
var stateUploaderWaitGroup sync.WaitGroup
stateUploaderWaitGroup.Add(1)
// A map to keep track of artifact states and how many we've uploaded
artifactStates := make(map[string]string)
artifactStatesUploaded := 0
var artifactStatesMutex sync.Mutex
// Spin up a gourtine that'll uploading artifact statuses every few
// seconds in batches
go func() {
for artifactStatesUploaded < len(artifacts) {
statesToUpload := make(map[string]string)
// Grab all the states we need to upload, and remove
// them from the tracking map
//
// Since we mutate the artifactStates variable in
// multiple routines, we need to lock it to make sure
// nothing else is changing it at the same time.
artifactStatesMutex.Lock()
for id, state := range artifactStates {
statesToUpload[id] = state
delete(artifactStates, id)
}
artifactStatesMutex.Unlock()
if len(statesToUpload) > 0 {
artifactStatesUploaded += len(statesToUpload)
for id, state := range statesToUpload {
logger.Debug("Artifact `%s` has state `%s`", id, state)
}
// Update the states of the artifacts in bulk.
err = retry.Do(func(s *retry.Stats) error {
_, err = a.APIClient.Artifacts.Update(a.JobID, statesToUpload)
if err != nil {
logger.Warn("%s (%s)", err, s)
}
return err
}, &retry.Config{Maximum: 10, Interval: 5 * time.Second})
if err != nil {
logger.Error("Error uploading artifact states: %s", err)
// Track the error that was raised. We need to
// aquire a lock since we mutate the errors
// slice in mutliple routines.
errorsMutex.Lock()
errors = append(errors, err)
errorsMutex.Unlock()
}
logger.Debug("Uploaded %d artfact states (%d/%d)", len(statesToUpload), artifactStatesUploaded, len(artifacts))
}
// Check again for states to upload in a few seconds
time.Sleep(1 * time.Second)
}
stateUploaderWaitGroup.Done()
}()
for _, artifact := range artifacts {
// Create new instance of the artifact for the goroutine
// See: http://golang.org/doc/effective_go.html#channels
artifact := artifact
p.Spawn(func() {
// Show a nice message that we're starting to upload the file
logger.Info("Uploading artifact %s %s (%d bytes)", artifact.ID, artifact.Path, artifact.FileSize)
// Upload the artifact and then set the state depending
// on whether or not it passed. We'll retry the upload
// a couple of times before giving up.
err = retry.Do(func(s *retry.Stats) error {
err := uploader.Upload(artifact)
if err != nil {
logger.Warn("%s (%s)", err, s)
}
return err
}, &retry.Config{Maximum: 10, Interval: 5 * time.Second})
var state string
// Did the upload eventually fail?
if err != nil {
logger.Error("Error uploading artifact \"%s\": %s", artifact.Path, err)
// Track the error that was raised. We need to
// aquire a lock since we mutate the errors
// slice in mutliple routines.
errorsMutex.Lock()
errors = append(errors, err)
errorsMutex.Unlock()
state = "error"
} else {
state = "finished"
}
// Since we mutate the artifactStates variable in
// multiple routines, we need to lock it to make sure
// nothing else is changing it at the same time.
artifactStatesMutex.Lock()
artifactStates[artifact.ID] = state
artifactStatesMutex.Unlock()
})
}
// Wait for the pool to finish
p.Wait()
// Wait for the statuses to finish uploading
stateUploaderWaitGroup.Wait()
if len(errors) > 0 {
logger.Fatal("There were errors with uploading some of the artifacts")
}
return nil
}