forked from itchio/butler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
push.go
400 lines (324 loc) · 10.4 KB
/
push.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
396
397
398
399
400
package main
import (
"fmt"
"io"
"math"
"net/http"
"time"
"github.com/dustin/go-humanize"
"github.com/go-errors/errors"
"github.com/itchio/butler/comm"
"github.com/itchio/go-itchio"
"github.com/itchio/httpkit/uploader"
"github.com/itchio/wharf/counter"
"github.com/itchio/wharf/pools"
"github.com/itchio/wharf/pwr"
"github.com/itchio/wharf/state"
"github.com/itchio/wharf/tlc"
"github.com/itchio/wharf/wsync"
)
// AlmostThereThreshold is the amount of data left where the progress indicator isn't indicative anymore.
// At this point, we're basically waiting for build files to be finalized.
const AlmostThereThreshold int64 = 10 * 1024
func push(buildPath string, specStr string, userVersion string, fixPerms bool) {
go versionCheck()
must(doPush(buildPath, specStr, userVersion, fixPerms))
}
func doPush(buildPath string, specStr string, userVersion string, fixPerms bool) error {
// start walking source container while waiting on auth flow
sourceContainerChan := make(chan walkResult)
walkErrs := make(chan error)
go doWalk(buildPath, sourceContainerChan, walkErrs, fixPerms)
spec, err := itchio.ParseSpec(specStr)
if err != nil {
return errors.Wrap(err, 1)
}
err = spec.EnsureChannel()
if err != nil {
return errors.Wrap(err, 1)
}
client, err := authenticateViaOauth()
if err != nil {
return errors.Wrap(err, 1)
}
newBuildRes, err := client.CreateBuild(spec.Target, spec.Channel, userVersion)
if err != nil {
return errors.Wrap(err, 1)
}
buildID := newBuildRes.Build.ID
parentID := newBuildRes.Build.ParentBuild.ID
var targetSignature *pwr.SignatureInfo
if parentID == 0 {
comm.Opf("For channel `%s`: pushing first build", spec.Channel)
targetSignature = &pwr.SignatureInfo{
Container: &tlc.Container{},
Hashes: make([]wsync.BlockHash, 0),
}
} else {
comm.Opf("For channel `%s`: last build is %d, downloading its signature", spec.Channel, parentID)
var buildFiles itchio.ListBuildFilesResponse
buildFiles, err = client.ListBuildFiles(parentID)
if err != nil {
return errors.Wrap(err, 1)
}
signatureFile := itchio.FindBuildFile(itchio.BuildFileType_SIGNATURE, buildFiles.Files)
if signatureFile == nil {
comm.Dief("Could not find signature for parent build %d, aborting", parentID)
}
var signatureReader io.Reader
signatureReader, err = client.DownloadBuildFile(parentID, signatureFile.ID)
if err != nil {
return errors.Wrap(err, 1)
}
targetSignature, err = pwr.ReadSignature(signatureReader)
if err != nil {
return errors.Wrap(err, 1)
}
}
newPatchRes, newSignatureRes, err := createBothFiles(client, buildID)
if err != nil {
return errors.Wrap(err, 1)
}
uploadDone := make(chan bool)
uploadErrs := make(chan error)
patchWriter, err := uploader.NewResumableUpload(newPatchRes.File.UploadURL,
uploadDone, uploadErrs, comm.NewStateConsumer())
patchWriter.MaxChunkGroup = *appArgs.maxChunkGroup
if err != nil {
return errors.Wrap(err, 1)
}
signatureWriter, err := uploader.NewResumableUpload(newSignatureRes.File.UploadURL,
uploadDone, uploadErrs, comm.NewStateConsumer())
signatureWriter.MaxChunkGroup = *appArgs.maxChunkGroup
if err != nil {
return errors.Wrap(err, 1)
}
comm.Debugf("Launching patch & signature channels")
patchCounter := counter.NewWriter(patchWriter)
signatureCounter := counter.NewWriter(signatureWriter)
// we started walking the source container in the beginning,
// we actually need it now.
// note that we could actually start diffing before all the file
// creation & upload setup is done
var sourceContainer *tlc.Container
var sourcePool wsync.Pool
comm.Debugf("Waiting for source container")
select {
case walkErr := <-walkErrs:
return errors.Wrap(walkErr, 1)
case walkies := <-sourceContainerChan:
comm.Debugf("Got sourceContainer!")
sourceContainer = walkies.container
sourcePool = walkies.pool
break
}
comm.Logf("")
comm.Opf("Pushing %s (%s)", humanize.IBytes(uint64(sourceContainer.Size)), sourceContainer.Stats())
comm.Debugf("Building diff context")
var readBytes int64
bytesPerSec := float64(0)
lastUploadedBytes := int64(0)
stopTicking := make(chan struct{})
updateProgress := func() {
uploadedBytes := int64(float64(patchWriter.UploadedBytes))
// input bytes that aren't in output, for example:
// - bytes that have been compressed away
// - bytes that were in old build and were simply reused
goneBytes := readBytes - patchWriter.TotalBytes
conservativeTotalBytes := sourceContainer.Size - goneBytes
leftBytes := conservativeTotalBytes - uploadedBytes
if leftBytes > AlmostThereThreshold {
netStatus := "- network idle"
if bytesPerSec > 1 {
netStatus = fmt.Sprintf("@ %s/s", humanize.IBytes(uint64(bytesPerSec)))
}
comm.ProgressLabel(fmt.Sprintf("%s, %s left", netStatus, humanize.IBytes(uint64(leftBytes))))
} else {
comm.ProgressLabel(fmt.Sprintf("- almost there"))
}
conservativeProgress := float64(uploadedBytes) / float64(conservativeTotalBytes)
conservativeProgress = min(1.0, conservativeProgress)
comm.Progress(conservativeProgress)
comm.ProgressScale(float64(readBytes) / float64(sourceContainer.Size))
}
go func() {
ticker := time.NewTicker(time.Second * time.Duration(2))
for {
select {
case <-ticker.C:
bytesPerSec = float64(patchWriter.UploadedBytes-lastUploadedBytes) / 2.0
lastUploadedBytes = patchWriter.UploadedBytes
updateProgress()
case <-stopTicking:
break
}
}
}()
patchWriter.OnProgress = updateProgress
stateConsumer := &state.Consumer{
OnProgress: func(progress float64) {
readBytes = int64(float64(sourceContainer.Size) * progress)
updateProgress()
},
}
dctx := &pwr.DiffContext{
Compression: &pwr.CompressionSettings{
Algorithm: pwr.CompressionAlgorithm_BROTLI,
Quality: 1,
},
SourceContainer: sourceContainer,
Pool: sourcePool,
TargetContainer: targetSignature.Container,
TargetSignature: targetSignature.Hashes,
Consumer: stateConsumer,
}
comm.StartProgress()
comm.ProgressScale(0.0)
err = dctx.WritePatch(patchCounter, signatureCounter)
if err != nil {
return errors.Wrap(err, 1)
}
// close in a goroutine to avoid deadlocking
doClose := func(c io.Closer, done chan bool, errs chan error) {
closeErr := c.Close()
if closeErr != nil {
errs <- errors.Wrap(closeErr, 1)
return
}
done <- true
}
go doClose(patchWriter, uploadDone, uploadErrs)
go doClose(signatureWriter, uploadDone, uploadErrs)
for c := 0; c < 4; c++ {
select {
case uploadErr := <-uploadErrs:
return errors.Wrap(uploadErr, 1)
case <-uploadDone:
comm.Debugf("upload done")
}
}
close(stopTicking)
comm.ProgressLabel("finalizing build")
finalDone := make(chan bool)
finalErrs := make(chan error)
doFinalize := func(fileID int64, fileSize int64, done chan bool, errs chan error) {
_, err = client.FinalizeBuildFile(buildID, fileID, fileSize)
if err != nil {
errs <- errors.Wrap(err, 1)
return
}
done <- true
}
go doFinalize(newPatchRes.File.ID, patchCounter.Count(), finalDone, finalErrs)
go doFinalize(newSignatureRes.File.ID, signatureCounter.Count(), finalDone, finalErrs)
for i := 0; i < 2; i++ {
select {
case err := <-finalErrs:
return errors.Wrap(err, 1)
case <-finalDone:
}
}
comm.EndProgress()
{
prettyPatchSize := humanize.IBytes(uint64(patchCounter.Count()))
percReused := 100.0 * float64(dctx.ReusedBytes) / float64(dctx.FreshBytes+dctx.ReusedBytes)
relToNew := 100.0 * float64(patchCounter.Count()) / float64(sourceContainer.Size)
prettyFreshSize := humanize.IBytes(uint64(dctx.FreshBytes))
savings := 100.0 - relToNew
if dctx.ReusedBytes > 0 {
comm.Statf("Re-used %.2f%% of old, added %s fresh data", percReused, prettyFreshSize)
} else {
comm.Statf("Added %s fresh data", prettyFreshSize)
}
if savings > 0 && !math.IsNaN(savings) {
comm.Statf("%s patch (%.2f%% savings)", prettyPatchSize, 100.0-relToNew)
} else {
comm.Statf("%s patch (no savings)", prettyPatchSize)
}
}
comm.Opf("Build is now processing, should be up in a bit (see `butler status`)")
return nil
}
type fileSlot struct {
Type itchio.BuildFileType
Response itchio.NewBuildFileResponse
}
func createBothFiles(client *itchio.Client, buildID int64) (patch itchio.NewBuildFileResponse, signature itchio.NewBuildFileResponse, err error) {
createFile := func(buildType itchio.BuildFileType, done chan fileSlot, errs chan error) {
var res itchio.NewBuildFileResponse
res, err = client.CreateBuildFile(buildID, buildType, itchio.BuildFileSubType_DEFAULT, itchio.UploadType_DEFERRED_RESUMABLE)
if err != nil {
errs <- errors.Wrap(err, 1)
}
comm.Debugf("Created %s build file: %+v", buildType, res.File)
// TODO: resumable upload session creation sounds like it belongs in an external lib, go-itchio maybe?
req, reqErr := http.NewRequest("POST", res.File.UploadURL, nil)
if reqErr != nil {
errs <- errors.Wrap(reqErr, 1)
}
req.ContentLength = 0
for k, v := range res.File.UploadHeaders {
req.Header.Add(k, v)
}
gcsRes, gcsErr := client.HTTPClient.Do(req)
if gcsErr != nil {
errs <- errors.Wrap(gcsErr, 1)
}
if gcsRes.StatusCode != 201 {
errs <- errors.Wrap(fmt.Errorf("could not create resumable upload session (got HTTP %d)", gcsRes.StatusCode), 1)
}
comm.Debugf("Started resumable upload session %s", gcsRes.Header.Get("Location"))
res.File.UploadHeaders = nil
res.File.UploadURL = gcsRes.Header.Get("Location")
done <- fileSlot{buildType, res}
}
done := make(chan fileSlot)
errs := make(chan error)
go createFile(itchio.BuildFileType_PATCH, done, errs)
go createFile(itchio.BuildFileType_SIGNATURE, done, errs)
for i := 0; i < 2; i++ {
select {
case err = <-errs:
err = errors.Wrap(err, 1)
return
case slot := <-done:
switch slot.Type {
case itchio.BuildFileType_PATCH:
patch = slot.Response
case itchio.BuildFileType_SIGNATURE:
signature = slot.Response
}
}
}
return
}
type walkResult struct {
container *tlc.Container
pool wsync.Pool
}
func doWalk(path string, out chan walkResult, errs chan error, fixPerms bool) {
container, err := tlc.WalkAny(path, filterPaths)
if err != nil {
errs <- errors.Wrap(err, 1)
return
}
pool, err := pools.New(container, path)
if err != nil {
errs <- errors.Wrap(err, 1)
return
}
result := walkResult{
container: container,
pool: pool,
}
if fixPerms {
result.container.FixPermissions(result.pool)
}
out <- result
}
func min(a, b float64) float64 {
if a < b {
return a
}
return b
}