forked from peak/s5cmd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
worker.go
350 lines (306 loc) · 7.9 KB
/
worker.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
package core
import (
"context"
"crypto/tls"
"io"
"log"
"net/http"
"net/url"
"os"
"strconv"
"sync"
"sync/atomic"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
"github.com/cenkalti/backoff"
"github.com/peak/s5cmd/stats"
)
// WorkerPoolParams is the common parameters of all worker pools.
type WorkerPoolParams struct {
NumWorkers int
UploadChunkSizeBytes int64
UploadConcurrency int
DownloadChunkSizeBytes int64
DownloadConcurrency int
Retries int
EndpointURL string
NoVerifySSL bool
}
// WorkerPool is the state of our worker pool.
type WorkerPool struct {
ctx context.Context
params *WorkerPoolParams
jobQueue chan *Job
subJobQueue chan *Job
wg *sync.WaitGroup
awsSession *session.Session
cancelFunc context.CancelFunc
st *stats.Stats
idlingCounter int32
}
// WorkerParams is the params/state of a single worker.
type WorkerParams struct {
s3svc *s3.S3
s3dl *s3manager.Downloader
s3ul *s3manager.Uploader
ctx context.Context
poolParams *WorkerPoolParams
st *stats.Stats
subJobQueue *chan *Job
idlingCounter *int32
}
// NewAwsSession initializes a new AWS session with region fallback and custom options
func NewAwsSession(maxRetries int, endpointURL string, region string, noVerifySSL bool) (*session.Session, error) {
newSession := func(c *aws.Config) (*session.Session, error) {
useSharedConfig := session.SharedConfigEnable
// Reverse of what the SDK does: if AWS_SDK_LOAD_CONFIG is 0 (or a falsy value) disable shared configs
loadCfg := os.Getenv("AWS_SDK_LOAD_CONFIG")
if loadCfg != "" {
if enable, _ := strconv.ParseBool(loadCfg); !enable {
useSharedConfig = session.SharedConfigDisable
}
}
return session.NewSessionWithOptions(session.Options{Config: *c, SharedConfigState: useSharedConfig})
}
awsCfg := aws.NewConfig().
WithMaxRetries(maxRetries).
WithCredentialsChainVerboseErrors(true)
if endpointURL != "" {
endpoint, err := url.Parse(endpointURL)
if err != nil {
return nil, err
}
awsCfg = awsCfg.WithEndpoint(endpointURL).WithS3ForcePathStyle(true)
const acceleratedHost = "s3-accelerate.amazonaws.com"
if endpoint.Hostname() == acceleratedHost {
awsCfg = awsCfg.WithS3UseAccelerate(true).WithS3ForcePathStyle(false)
}
verboseLog("Setting Endpoint to %s on AWS Config", endpointURL)
}
if noVerifySSL {
awsCfg = awsCfg.WithHTTPClient(&http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}})
}
if region != "" {
awsCfg = awsCfg.WithRegion(region)
return newSession(awsCfg)
}
ses, err := newSession(awsCfg)
if err != nil {
return nil, err
}
if (*ses).Config.Region == nil || *(*ses).Config.Region == "" { // No region specified in env or config, fallback to us-east-1
awsCfg = awsCfg.WithRegion(endpoints.UsEast1RegionID)
ses, err = newSession(awsCfg)
}
return ses, err
}
// NewWorkerPool creates a new worker pool and start the workers.
func NewWorkerPool(ctx context.Context, params *WorkerPoolParams, st *stats.Stats) *WorkerPool {
ses, err := NewAwsSession(params.Retries, params.EndpointURL, "", params.NoVerifySSL)
if err != nil {
log.Fatal(err)
}
cancelFunc := ctx.Value(CancelFuncKey).(context.CancelFunc)
p := &WorkerPool{
ctx: ctx,
params: params,
jobQueue: make(chan *Job),
subJobQueue: make(chan *Job),
wg: &sync.WaitGroup{},
awsSession: ses,
cancelFunc: cancelFunc,
st: st,
}
for i := 0; i < params.NumWorkers; i++ {
p.wg.Add(1)
go p.runWorker(st, &p.idlingCounter, i)
}
return p
}
// runWorker is the main function of a single worker.
func (p *WorkerPool) runWorker(st *stats.Stats, idlingCounter *int32, id int) {
defer p.wg.Done()
defer verboseLog("Exiting goroutine %d", id)
wp := WorkerParams{
s3.New(p.awsSession),
// Give each worker its own s3manager
s3manager.NewDownloader(p.awsSession),
s3manager.NewUploader(p.awsSession),
p.ctx,
p.params,
st,
&p.subJobQueue,
idlingCounter,
}
bkf := backoff.NewExponentialBackOff()
bkf.InitialInterval = time.Second
bkf.MaxInterval = time.Minute
bkf.Multiplier = 2
bkf.MaxElapsedTime = 0
bkf.Reset()
run := true
lastSetIdle := false
setIdle := func() {
if !lastSetIdle {
atomic.AddInt32(idlingCounter, 1)
lastSetIdle = true
}
}
setWorking := func() {
if lastSetIdle {
atomic.AddInt32(idlingCounter, ^int32(0))
lastSetIdle = false
}
}
defer setIdle()
for run {
select {
case <-time.After(100 * time.Millisecond):
setIdle()
case job, ok := <-p.jobQueue:
if !ok {
verboseLog("Channel closed %d", id)
return
}
setWorking()
tries := 0
for job != nil {
err := job.Run(&wp)
var acceptableErr AcceptableError
if err != nil {
acceptableErr = IsAcceptableError(err)
if acceptableErr != nil {
err = nil
}
}
if err != nil {
errCode, doRetry := IsRetryableError(err)
if doRetry && p.params.Retries > 0 && tries < p.params.Retries {
tries++
sleepTime := bkf.NextBackOff()
log.Printf(`?%s "%s", sleep for %v`, errCode, job, sleepTime)
select {
case <-time.After(sleepTime):
wp.st.Increment(stats.RetryOp)
continue
case <-p.ctx.Done():
run = false // if Canceled during sleep, report ERR and immediately process failCommand
}
}
job.PrintErr(err)
wp.st.Increment(stats.Fail)
job.Notify(false)
job = job.failCommand
} else {
if acceptableErr != ErrDisplayedHelp {
job.PrintOK(acceptableErr)
}
job.Notify(true)
job = job.successCommand
}
tries = 0
bkf.Reset()
}
case <-p.ctx.Done():
return
}
}
}
func (p *WorkerPool) parseJob(line string) *Job {
job, err := ParseJob(line)
if err != nil {
log.Print(`-ERR "`, line, `": `, err)
p.st.Increment(stats.Fail)
return nil
}
return job
}
func (p *WorkerPool) queueJob(job *Job) bool {
select {
case <-p.ctx.Done():
return false
case p.jobQueue <- job:
return true
}
}
func (p *WorkerPool) pumpJobQueues() {
verboseLog("Start pumping...")
var idc int32
for {
select {
case <-time.After(500 * time.Millisecond):
idc = atomic.LoadInt32(&p.idlingCounter)
verboseLog("idlingCounter is %d, expected to be %d", idc, p.params.NumWorkers)
if idc == int32(p.params.NumWorkers) {
log.Print("# All workers idle, finishing up...")
return
}
case <-p.ctx.Done():
return
case j, ok := <-p.subJobQueue:
if ok {
select {
case p.jobQueue <- j:
case <-p.ctx.Done():
return
}
}
}
}
}
// RunCmd will run a single command (and subsequent sub-commands) in the worker pool, wait for it to finish, clean up and return.
func (p *WorkerPool) RunCmd(commandLine string) {
j := p.parseJob(commandLine)
if j != nil {
p.queueJob(j)
if j.operation.IsBatch() {
p.pumpJobQueues()
}
}
close(p.jobQueue)
p.wg.Wait()
}
// Run runs the commands in filename in the worker pool, on EOF it will wait for all commands to finish, clean up and return.
func (p *WorkerPool) Run(filename string) {
var r io.ReadCloser
var err error
if filename == "-" {
r = os.Stdin
} else {
r, err = os.Open(filename)
if err != nil {
log.Fatal(err)
}
defer r.Close()
}
s := NewCancelableScanner(p.ctx, r).Start()
var j *Job
isAnyBatch := false
for {
line, err := s.ReadOne(p.subJobQueue, p.jobQueue)
if err != nil {
if err == context.Canceled || err == io.EOF {
break
}
log.Printf("-ERR Error reading: %v", err)
break
}
j = p.parseJob(line)
if j != nil {
isAnyBatch = isAnyBatch || j.operation.IsBatch()
p.queueJob(j)
}
}
if isAnyBatch {
p.pumpJobQueues()
}
close(p.jobQueue)
//log.Print("# Waiting...")
p.wg.Wait()
}