-
Notifications
You must be signed in to change notification settings - Fork 88
/
updatechecker.go
332 lines (279 loc) · 9.31 KB
/
updatechecker.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
package updatechecker
import (
"fmt"
"io/ioutil"
"os"
"sync"
"time"
"github.com/pkg/errors"
"github.com/replicatedhq/kots/pkg/app"
license "github.com/replicatedhq/kots/pkg/kotsadmlicense"
upstream "github.com/replicatedhq/kots/pkg/kotsadmupstream"
"github.com/replicatedhq/kots/pkg/kotsutil"
"github.com/replicatedhq/kots/pkg/logger"
kotspull "github.com/replicatedhq/kots/pkg/pull"
"github.com/replicatedhq/kots/pkg/reporting"
"github.com/replicatedhq/kots/pkg/store"
storetypes "github.com/replicatedhq/kots/pkg/store/types"
"github.com/replicatedhq/kots/pkg/util"
"github.com/replicatedhq/kots/pkg/version"
cron "github.com/robfig/cron/v3"
"go.uber.org/zap"
)
// jobs maps app ids to their cron jobs
var jobs = make(map[string]*cron.Cron)
var mtx sync.Mutex
// Start will start the update checker
// the frequency of those update checks are app specific and can be modified by the user
func Start() error {
logger.Debug("starting update checker")
appsList, err := store.GetStore().ListInstalledApps()
if err != nil {
return errors.Wrap(err, "failed to list installed apps")
}
for _, a := range appsList {
if a.IsAirgap {
continue
}
if err := Configure(a.ID); err != nil {
logger.Error(errors.Wrapf(err, "failed to configure app %s", a.Slug))
}
}
return nil
}
// Configure will check if the app has scheduled update checks enabled and:
// if enabled, and cron job was NOT found: add a new cron job to check app updates
// if enabled, and a cron job was found, update the existing cron job with the latest cron spec
// if disabled: stop the current running cron job (if exists)
// no-op for airgap applications
func Configure(appID string) error {
a, err := store.GetStore().GetApp(appID)
if err != nil {
return errors.Wrap(err, "failed to get app")
}
if a.IsAirgap {
return nil
}
logger.Debug("configure update checker for app",
zap.String("slug", a.Slug))
mtx.Lock()
defer mtx.Unlock()
cronSpec := a.UpdateCheckerSpec
if cronSpec == "@never" || cronSpec == "" {
Stop(a.ID)
return nil
}
if cronSpec == "@default" {
// check for updates every 4 hours
t := time.Now()
m := t.Minute()
h := t.Hour() % 4
cronSpec = fmt.Sprintf("%d %d/4 * * *", m, h)
}
job, ok := jobs[a.ID]
if ok {
// job already exists, remove entries
entries := job.Entries()
for _, entry := range entries {
job.Remove(entry.ID)
}
} else {
// job does not exist, create a new one
job = cron.New(cron.WithChain(
cron.Recover(cron.DefaultLogger),
))
}
jobAppID := a.ID
jobAppSlug := a.Slug
_, err = job.AddFunc(cronSpec, func() {
logger.Debug("checking updates for app", zap.String("slug", jobAppSlug))
availableUpdates, err := CheckForUpdates(jobAppID, false, false, false)
if err != nil {
logger.Error(errors.Wrapf(err, "failed to check updates for app %s", jobAppSlug))
return
}
if availableUpdates > 0 {
logger.Debug("updates found for app",
zap.String("slug", jobAppSlug),
zap.Int64("available updates", availableUpdates))
} else {
logger.Debug("no updates found for app", zap.String("slug", jobAppSlug))
}
})
if err != nil {
return errors.Wrap(err, "failed to add func")
}
job.Start()
jobs[a.ID] = job
return nil
}
// Stop will stop a running cron job (if exists) for a specific app
func Stop(appID string) {
if jobs == nil {
logger.Debug("no cron jobs found")
return
}
if job, ok := jobs[appID]; ok {
job.Stop()
} else {
logger.Debug("cron job not found for app", zap.String("appID", appID))
}
}
// CheckForUpdates checks (and downloads) latest updates for a specific app
// if "deploy" is set to true, the latest version/update will be deployed
// returns the number of available updates
func CheckForUpdates(appID string, deploy bool, skipPreflights bool, isCLI bool) (int64, error) {
currentStatus, _, err := store.GetStore().GetTaskStatus("update-download")
if err != nil {
return 0, errors.Wrap(err, "failed to get task status")
}
if currentStatus == "running" {
logger.Debug("update-download is already running, not starting a new one")
return 0, nil
}
if err := store.GetStore().ClearTaskStatus("update-download"); err != nil {
return 0, errors.Wrap(err, "failed to clear task status")
}
a, err := store.GetStore().GetApp(appID)
if err != nil {
return 0, errors.Wrap(err, "failed to get app")
}
// sync license, this method is only called when online
_, _, err = license.Sync(a, "", false)
if err != nil {
return 0, errors.Wrap(err, "failed to sync license")
}
// reload app because license sync could have created a new release
a, err = store.GetStore().GetApp(appID)
if err != nil {
return 0, errors.Wrap(err, "failed to get app")
}
archiveDir, err := ioutil.TempDir("", "kotsadm")
if err != nil {
return 0, errors.Wrap(err, "failed to create temp dir")
}
removeArchiveDir := true
defer func() {
if removeArchiveDir {
os.RemoveAll(archiveDir)
}
}()
err = store.GetStore().GetAppVersionArchive(a.ID, a.CurrentSequence, archiveDir)
if err != nil {
return 0, errors.Wrap(err, "failed to get app version archive")
}
// we need a few objects from the app to check for updates
kotsKinds, err := kotsutil.LoadKotsKindsFromPath(archiveDir)
if err != nil {
return 0, errors.Wrap(err, "failed to load kotskinds from path")
}
latestLicense, err := store.GetStore().GetLatestLicenseForApp(a.ID)
if err != nil {
return 0, errors.Wrap(err, "failed to get latest license")
}
getUpdatesOptions := kotspull.GetUpdatesOptions{
License: latestLicense,
CurrentCursor: kotsKinds.Installation.Spec.UpdateCursor,
CurrentChannelID: kotsKinds.Installation.Spec.ChannelID,
CurrentChannelName: kotsKinds.Installation.Spec.ChannelName,
CurrentVersionLabel: kotsKinds.Installation.Spec.VersionLabel,
Silent: false,
ReportingInfo: reporting.GetReportingInfo(a.ID),
}
// get updates
updates, err := kotspull.GetUpdates(fmt.Sprintf("replicated://%s", kotsKinds.License.Spec.AppSlug), getUpdatesOptions)
if err != nil {
return 0, errors.Wrap(err, "failed to get updates")
}
// update last updated at time
t := app.LastUpdateAtTime(a.ID)
if t != nil {
return 0, errors.Wrap(err, "failed to update last updated at time")
}
downstreams, err := store.GetStore().ListDownstreamsForApp(a.ID)
if err != nil {
return 0, errors.Wrap(err, "failed to list downstreams for app")
}
if len(downstreams) == 0 {
return 0, errors.Errorf("no downstreams found for app %q", a.Slug)
}
downstream := downstreams[0]
// if there are updates, go routine it
if len(updates) == 0 {
if !deploy {
return 0, nil
}
// ensure that the latest version is deployed
allVersions, err := version.GetVersions(a.ID)
if err != nil {
return 0, errors.Wrap(err, "failed to list app versions")
}
// get the first version, the array must contain versions at this point
// this function can't run without an app
if len(allVersions) == 0 {
return 0, errors.New("no versions found")
}
latestVersion := allVersions[len(allVersions)-1]
downstreamParentSequence, err := store.GetStore().GetCurrentParentSequence(a.ID, downstream.ClusterID)
if err != nil {
return 0, errors.Wrap(err, "failed to get current downstream parent sequence")
}
if latestVersion.Sequence != downstreamParentSequence {
status, err := store.GetStore().GetStatusForVersion(a.ID, downstream.ClusterID, latestVersion.Sequence)
if err != nil {
return 0, errors.Wrap(err, "failed to get update downstream status")
}
if status == storetypes.VersionPendingConfig {
return 0, util.ActionableError{
NoRetry: true,
Message: fmt.Sprintf("Version %d cannot be deployed because it needs configuration", latestVersion.Sequence),
}
}
if err := version.DeployVersion(a.ID, latestVersion.Sequence); err != nil {
return 0, errors.Wrap(err, "failed to deploy latest version")
}
}
return 0, nil
}
availableUpdates := int64(len(updates))
// this is to avoid a race condition where the UI polls the task status before it is set by the goroutine
status := fmt.Sprintf("%d Updates available...", availableUpdates)
if err := store.GetStore().SetTaskStatus("update-download", status, "running"); err != nil {
return 0, errors.Wrap(err, "failed to set task status")
}
removeArchiveDir = false
go func() {
defer os.RemoveAll(archiveDir)
for index, update := range updates {
// the latest version is in archive dir
sequence, err := upstream.DownloadUpdate(a.ID, archiveDir, update.Cursor, skipPreflights)
if err != nil {
logger.Error(errors.Wrap(err, "failed to download update"))
continue
}
if !deploy || index != len(updates)-1 {
continue
}
status, err := store.GetStore().GetStatusForVersion(a.ID, downstream.ClusterID, sequence)
if err != nil {
logger.Error(errors.Wrap(err, "failed to get update downstream status"))
continue
}
if status == storetypes.VersionPendingConfig {
logger.Infof("not deploying version %d because it's %s", sequence, status)
continue
}
if err := version.DeployVersion(a.ID, sequence); err != nil {
logger.Error(errors.Wrap(err, "failed to queue update for deployment"))
}
// preflights reporting
go func() {
err = reporting.ReportAppInfo(a.ID, sequence, skipPreflights, isCLI)
if err != nil {
logger.Debugf("failed to update preflights reports: %v", err)
}
}()
}
}()
return availableUpdates, nil
}