Repository navigation
Expand file tree
/
Copy pathapp_update.go
More file actions
396 lines (368 loc) · 10.4 KB
/
Copy pathapp_update.go
File metadata and controls
396 lines (368 loc) · 10.4 KB
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
package main
// Updating bowel itself. A running program cannot swap its own code, so an
// update is a new version installed beside this one and a restart into it.
// They are two steps, as only the restart drops the network: mygo.Updater
// downloads the update, checks its signature and puts it in place while
// this version runs on, and the restart waits for the user, or for the next
// time bowel quits and opens. On macOS the new bundle replaces this one once
// the app has exited, however it exits; on Linux and Windows the files are
// replaced at once, and the next launch is the new version. The restart
// goes through the ordinary quit, which puts the system proxy and the
// gateway back and ends the core. Should the new version not come up, the
// Mac is left with its own network, not a proxy that is gone.
import (
"context"
"encoding/json"
"errors"
"log"
"os"
"path/filepath"
"sync"
"time"
"github.com/egoist/mygo"
)
const (
updateAvailable = "available"
updateDownloading = "downloading"
updateReady = "ready" // installed, waiting for a restart
updateRestarting = "restarting"
updateFailed = "failed"
// updateMarker says that a new version was installed, so that the next
// launch can tell whether it runs it.
updateMarker = "update-restart.json"
)
var (
// After the core is up, so that the check can use its nodes.
updateFirstCheck = 20 * time.Second
updateEvery = 6 * time.Hour
updateRetry = 30 * time.Minute
// updateSettle is the most a restart waits for changes under way.
updateSettle = 15 * time.Second
)
// foundUpdate is a newer version that can be installed, with its section of
// CHANGELOG.md (Markdown), which the release's manifest carries.
type foundUpdate struct {
Version string
Notes string
Date time.Time
install func(ctx context.Context, progress func(done, total int64)) error
}
// osUpdate is what installs updates. Tests replace it, so that they can
// never replace or restart the app.
var osUpdate = struct {
enabled func() bool
check func(context.Context) (*foundUpdate, error)
relaunch func()
}{
enabled: mygo.Updater.Enabled,
check: func(ctx context.Context) (*foundUpdate, error) {
up, err := mygo.Updater.Check(ctx)
if err != nil || up == nil {
return nil, err
}
return &foundUpdate{Version: up.Version, Notes: up.Notes, Date: up.Date, install: up.Install}, nil
},
relaunch: func() { mygo.App.Relaunch() },
}
// updateState is where updating has got to.
type updateState struct {
mu sync.Mutex
found *foundUpdate
status string // "" when there is nothing to show
percent int
errText string
cancel context.CancelFunc
done chan struct{} // closed when the download has ended
notify func() // the state changed
// can: this copy can update itself. checking and latest are the check
// the user asked for.
can, checking, latest bool
just *JustUpdated
from string
}
func (u *updateState) changed() {
if u.notify != nil {
u.notify()
}
}
// updateView is the state for the interface, nil when there is no update.
func (a *App) updateView() *UpdateView {
u := &a.upd
u.mu.Lock()
defer u.mu.Unlock()
if u.status == "" || u.found == nil {
return nil
}
f := u.found
return &UpdateView{Status: u.status, Version: f.Version, Notes: f.Notes, Date: f.Date, Percent: u.percent, Error: u.errText}
}
// updateLoop looks for new versions for as long as the app runs. Builds
// that cannot update themselves, as those of a package manager, never look.
func (a *App) updateLoop() {
if !osUpdate.enabled() {
return
}
a.upd.mu.Lock()
a.upd.can = true
a.upd.mu.Unlock()
a.upd.changed()
wait := updateFirstCheck
for {
time.Sleep(wait)
wait = updateEvery
if err := a.checkUpdate(); err != nil {
log.Println("update:", err) // offline, most likely: nothing to show
wait = updateRetry
}
}
}
// checkUpdate asks whether there is a newer version. It leaves an update
// under way or installed alone, and keeps a failure on show until a newer
// version comes.
func (a *App) checkUpdate() error {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
up, err := osUpdate.check(ctx)
if err != nil {
return err
}
u := &a.upd
u.mu.Lock()
switch {
case u.status == updateDownloading || u.status == updateReady || u.status == updateRestarting:
case up == nil:
u.found, u.status, u.errText = nil, "", ""
case u.status == updateFailed && u.found != nil && u.found.Version == up.Version:
u.found = up
default:
u.found, u.status, u.errText = up, updateAvailable, ""
}
u.mu.Unlock()
u.changed()
return nil
}
// startUpdate downloads and installs the update, and leaves the restart to
// the user (restartUpdate). Anything but an update waiting to start is
// ignored, so that a second click does nothing.
func (a *App) startUpdate() {
if a.isQuitting() {
return
}
u := &a.upd
u.mu.Lock()
if u.found == nil || (u.status != updateAvailable && u.status != updateFailed) {
u.mu.Unlock()
return
}
found := u.found
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
u.status, u.percent, u.errText, u.cancel, u.done = updateDownloading, 0, "", cancel, done
u.mu.Unlock()
u.changed()
go func() {
defer close(done)
defer cancel()
err := found.install(ctx, a.updateProgress)
if err == nil {
// The next launch runs the new version, whenever it comes.
if err := a.writeUpdateMarker(updateRestart{From: mygo.App.Version(), To: found.Version}); err != nil {
log.Println("update:", err) // only the message after the restart is lost
}
}
u.mu.Lock()
switch {
case err == nil:
u.status = updateReady
case errors.Is(err, context.Canceled) || ctx.Err() != nil:
u.status, u.percent = updateAvailable, 0
default:
log.Println("update:", err)
u.status, u.percent, u.errText = updateFailed, 0, err.Error()
}
u.mu.Unlock()
u.changed()
}()
}
// restartUpdate restarts into the version installed: the click on 立即重启.
// Anything but an installed update is ignored, so that a second click does
// nothing.
func (a *App) restartUpdate() {
if a.isQuitting() {
return
}
u := &a.upd
u.mu.Lock()
if u.found == nil || u.status != updateReady {
u.mu.Unlock()
return
}
u.status = updateRestarting
u.mu.Unlock()
u.changed()
a.restartForUpdate(context.Background())
}
// updateProgress keeps the percentage. Whole percents only, as each one
// rebuilds the snapshot. A failed delta makes the download start over, so
// it may go down.
func (a *App) updateProgress(done, total int64) {
if total <= 0 {
return
}
pct := min(int(done*100/total), 100)
u := &a.upd
u.mu.Lock()
same := u.percent == pct
u.percent = pct
u.mu.Unlock()
if !same {
u.changed()
}
}
// cancelUpdate stops a download. Once it has ended there is nothing to stop.
func (a *App) cancelUpdate() {
u := &a.upd
u.mu.Lock()
defer u.mu.Unlock()
if u.status == updateDownloading && u.cancel != nil {
u.cancel()
}
}
// restartForUpdate restarts into the version installed, once what is being
// changed has been saved.
func (a *App) restartForUpdate(ctx context.Context) {
wait, cancel := context.WithTimeout(ctx, updateSettle)
defer cancel()
a.settle(wait)
if a.isQuitting() {
return // the user quit first; the new version runs at the next launch
}
osUpdate.relaunch()
}
// settle waits for the actions under way, and a change of settings, to end.
func (a *App) settle(ctx context.Context) {
for {
a.mu.Lock()
n := len(a.pending)
a.mu.Unlock()
if n == 0 {
break
}
select {
case <-ctx.Done():
return
case <-time.After(50 * time.Millisecond):
}
}
done := make(chan struct{})
go func() {
a.setMu.Lock()
defer a.setMu.Unlock()
close(done)
}()
select {
case <-done:
case <-ctx.Done():
}
}
// quitUpdate ends a download, which removes its files. A restart for an
// update is this very quit, and has nothing left to end.
func (a *App) quitUpdate(ctx context.Context) {
u := &a.upd
u.mu.Lock()
status, cancel, done := u.status, u.cancel, u.done
u.mu.Unlock()
if status != updateDownloading || cancel == nil {
return
}
cancel()
select {
case <-done:
case <-ctx.Done():
}
}
// updateRestart is the content of updateMarker.
type updateRestart struct {
From string `json:"from"`
To string `json:"to"`
}
func (a *App) writeUpdateMarker(m updateRestart) error {
b, err := json.Marshal(m)
if err != nil {
return err
}
path := filepath.Join(a.dataDir, updateMarker)
if err := os.WriteFile(path+".tmp", b, 0o600); err != nil {
return err
}
return os.Rename(path+".tmp", path)
}
// updateLast keeps the update this version came from, for the changelog.
const updateLast = "update-last.json"
// loadUpdateOutcome reads what the last run asked for, once, and what this
// version was updated from.
func (a *App) loadUpdateOutcome(current string) {
dir := a.dataDir
var just *JustUpdated
path := filepath.Join(dir, updateMarker)
if b, err := os.ReadFile(path); err == nil {
_ = os.Remove(path)
var m updateRestart
if json.Unmarshal(b, &m) == nil && m.To != "" {
just = &JustUpdated{From: m.From, To: m.To, OK: m.To == current}
log.Printf("update: asked for %s, running %s", m.To, current)
if just.OK {
if b, err := json.Marshal(m); err == nil {
_ = os.WriteFile(filepath.Join(dir, updateLast), b, 0o600)
}
}
}
}
from := ""
if b, err := os.ReadFile(filepath.Join(dir, updateLast)); err == nil {
var m updateRestart
// Only while this is still the version it led to: installed by hand
// since, it says nothing about this one.
if json.Unmarshal(b, &m) == nil && m.To == current {
from = m.From
}
}
u := &a.upd
u.mu.Lock()
u.just, u.from = just, from
u.mu.Unlock()
}
// dismissUpdated takes the word about the last update away.
func (a *App) dismissUpdated() {
u := &a.upd
u.mu.Lock()
u.just = nil
u.mu.Unlock()
u.changed()
}
func (a *App) updateInfo() UpdateInfo {
u := &a.upd
u.mu.Lock()
defer u.mu.Unlock()
return UpdateInfo{Can: u.can, Checking: u.checking, Latest: u.latest, Just: u.just, From: u.from}
}
// checkUpdateNow looks for a new version because the user asked: what it
// finds shows as the periodic check's does, and "nothing newer" is said too.
func (a *App) checkUpdateNow() error {
u := &a.upd
u.mu.Lock()
if u.checking {
u.mu.Unlock()
return nil
}
u.checking, u.latest = true, false
u.mu.Unlock()
u.changed()
err := a.checkUpdate()
u.mu.Lock()
u.checking = false
u.latest = err == nil && u.found == nil
u.mu.Unlock()
u.changed()
return err
}