-
Notifications
You must be signed in to change notification settings - Fork 39
/
applications.go
410 lines (365 loc) · 11.3 KB
/
applications.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
401
402
403
404
405
406
407
408
409
410
package api
import (
"database/sql"
"fmt"
"regexp"
"strings"
"sync"
"time"
"github.com/doug-martin/goqu/v9"
"github.com/jmoiron/sqlx"
"gopkg.in/guregu/null.v4"
)
type appsCache map[string]string
var (
// cachedApps caches the mapping of apps' product-ids and UUIDs to apps' UUIDs.
// The UUID -> UUID seeming redundancy is because this way we can use it to
// validate also the UUIDs against existing apps.
// It must not be modified directly but replaced (atomically or via lock)
// by a new map to prevent data races.
// An update must be triggered through clearCachedAppIDs() each time
// an apps change. A RW lock was chosen to prevent data
// races over the pointer itself.
cachedAppIDs appsCache
cachedAppsIDsLock sync.RWMutex
)
const (
flatcarAppID = "e96281a6-d1af-4bde-9a0a-97b76e56dc57"
)
// Application represents a Nebraska application instance.
type Application struct {
ID string `db:"id" json:"id"`
ProductID null.String `db:"product_id" json:"product_id"`
Name string `db:"name" json:"name"`
Description string `db:"description" json:"description"`
CreatedTs time.Time `db:"created_ts" json:"created_ts"`
TeamID string `db:"team_id" json:"-"`
Groups []*Group `db:"groups" json:"groups"`
Channels []*Channel `db:"channels" json:"channels"`
Instances struct {
Count int `db:"count" json:"count"`
} `db:"instances" json:"instances,omitempty"`
}
// AddApp registers the provided application.
func (api *API) AddApp(app *Application) (*Application, error) {
if err := validateProductID(app.ProductID); err != nil {
return nil, fmt.Errorf("cannot add application %v: %w", app.ID, err)
}
query, _, err := goqu.Insert("application").
Cols("name", "product_id", "description", "team_id").
Vals(goqu.Vals{app.Name, app.ProductID, app.Description, app.TeamID}).
Returning(goqu.T("application").All()).
ToSQL()
if err != nil {
return nil, err
}
err = api.db.QueryRowx(query).StructScan(app)
if err != nil {
return nil, err
}
api.clearCachedAppIDs()
return app, nil
}
// AddAppCloning registers the provided application, cloning the groups and
// channels from an existing application. Channels' packages will be set to null
// as packages won't be cloned.
func (api *API) AddAppCloning(app *Application, sourceAppID string) (*Application, error) {
app, err := api.AddApp(app)
if err != nil {
return nil, err
}
// NOTE: cloning operation is not transactional and something could go wrong
if sourceAppID != "" {
sourceApp, err := api.GetApp(sourceAppID)
if err != nil {
logger.Error().Err(err).Msg("AddAppCloning - could not get source app")
return app, nil
}
channelsIDsMappings := make(map[string]null.String)
for _, channel := range sourceApp.Channels {
originalChannelID := channel.ID
channel.ApplicationID = app.ID
channel.PackageID = null.String{}
channelCopy, err := api.AddChannel(channel)
if err != nil {
logger.Error().Err(err).Msg("AddAppCloning - could not add channel")
return app, nil // FIXME - think about what we should return to the caller
}
channelsIDsMappings[originalChannelID] = null.StringFrom(channelCopy.ID)
}
for _, group := range sourceApp.Groups {
group.ApplicationID = app.ID
if group.ChannelID.String != "" {
group.ChannelID = channelsIDsMappings[group.ChannelID.String]
}
group.PolicyUpdatesEnabled = true
group.ID = ""
if _, err := api.AddGroup(group); err != nil {
logger.Error().Err(err).Msg("AddAppCloning - could not add group")
return app, nil // FIXME - think about what we should return to the caller
}
}
}
// Even though AddApp will invalidate the cache, we need to do it again here
// to prevent eventual race issues.
api.clearCachedAppIDs()
return app, nil
}
func validateProductID(productID null.String) error {
if productID.Ptr() == nil {
return nil
}
if len(*productID.Ptr()) > 155 {
return fmt.Errorf("product ID %v is not valid (max length 155)", *productID.Ptr())
}
// This regex matches an ID that matches
// * At least two segments.
// * All characters must be alphanumeric, a dash.
// Each segment must start with a letter.
// Each segment must not end with a dash.
regMatcher := "^[a-zA-Z]+([a-zA-Z0-9\\-]*[a-zA-Z0-9])*(\\.[a-zA-Z]+([a-zA-Z0-1\\-]*[a-zA-Z0-9])*)+$"
matches, err := regexp.MatchString(regMatcher, *productID.Ptr())
if err != nil {
return err
}
if !matches {
return fmt.Errorf("product ID %v is not valid (has to be in the form e.g. io.example.App)", *productID.Ptr())
}
return nil
}
// UpdateApp updates an existing application using the content of the
// application provided.
func (api *API) UpdateApp(app *Application) error {
if err := validateProductID(app.ProductID); err != nil {
return fmt.Errorf("cannot add application %v: %w", app.ID, err)
}
query, _, err := goqu.Update("application").
Set(
goqu.Record{
"name": app.Name,
"product_id": app.ProductID,
"description": app.Description,
},
).
Where(goqu.C("id").Eq(app.ID)).
ToSQL()
if err != nil {
return err
}
result, err := api.db.Exec(query)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return ErrNoRowsAffected
}
api.clearCachedAppIDs()
return nil
}
// DeleteApp removes the application identified by the id provided.
func (api *API) DeleteApp(appID string) error {
query, _, err := goqu.Delete("application").Where(goqu.C("id").Eq(appID)).ToSQL()
if err != nil {
return err
}
result, err := api.db.Exec(query)
if err != nil {
return err
}
rowsAffected, err := result.RowsAffected()
if err != nil {
return err
}
if rowsAffected == 0 {
return ErrNoRowsAffected
}
api.clearCachedAppIDs()
return nil
}
// GetApp returns the application identified by the id provided.
func (api *API) GetApp(appID string) (*Application, error) {
var app Application
query, _, err := goqu.From("application").
Where(goqu.C("id").Eq(appID)).ToSQL()
if err != nil {
return nil, err
}
if err := api.db.QueryRowx(query).StructScan(&app); err != nil {
return nil, err
}
groups, err := api.getGroups(app.ID)
if err == nil || err == sql.ErrNoRows {
app.Groups = groups
} else {
return nil, err
}
channels, err := api.getChannels(app.ID)
if err == nil || err == sql.ErrNoRows {
app.Channels = channels
} else {
return nil, err
}
app.Instances.Count, err = api.getInstanceCount(app.ID, "", validityInterval)
if err != nil {
return nil, err
}
return &app, nil
}
func (api *API) GetAppsCount(teamID string) (int, error) {
query := goqu.From("application").Where(goqu.C("team_id").Eq(teamID)).Select(goqu.L("count(*)"))
return api.GetCountQuery(query)
}
// GetApps returns all applications that belong to the team id provided.
func (api *API) GetApps(teamID string, page, perPage uint64) ([]*Application, error) {
page, perPage = validatePaginationParams(page, perPage)
var apps []*Application
limit, offset := sqlPaginate(page, perPage)
query, _, err := api.appsQuery().
Where(goqu.C("team_id").Eq(teamID)).
Limit(limit).
Offset(offset).
ToSQL()
if err != nil {
return nil, err
}
rows, err := api.db.Queryx(query)
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
app := Application{}
err := rows.StructScan(&app)
if err != nil {
return nil, err
}
groups, err := api.getGroups(app.ID)
if err == nil || err == sql.ErrNoRows {
app.Groups = groups
} else {
return nil, err
}
channels, err := api.getChannels(app.ID)
if err == nil || err == sql.ErrNoRows {
app.Channels = channels
} else {
return nil, err
}
app.Instances.Count, err = api.getInstanceCount(app.ID, "", validityInterval)
if err != nil {
return nil, err
}
apps = append(apps, &app)
}
if err := rows.Err(); err != nil {
return nil, err
}
return apps, nil
}
// clearCachedAppIDs invalidates the cached app IDs in cachedApps and
// must be called whenever the apps entries are modified.
func (api *API) clearCachedAppIDs() {
cachedAppsIDsLock.Lock()
cachedAppIDs = nil
// Generating the map is not always possible here because the database
// can be closed.
cachedAppsIDsLock.Unlock()
}
func (api *API) GetAppID(appOrProductID string) (string, error) {
var cachedAppsRef appsCache
cachedAppsIDsLock.RLock()
if cachedAppIDs != nil {
// Keep a reference to the map that we found.
cachedAppsRef = cachedAppIDs
}
cachedAppsIDsLock.RUnlock()
// Generate map on startup or if invalidated.
if cachedAppsRef == nil {
cachedAppsIDsLock.Lock()
cachedAppsRef = cachedAppIDs
if cachedAppsRef == nil {
cachedAppIDs = make(appsCache)
query, _, err := goqu.From("application").ToSQL()
var rows *sqlx.Rows
if err == nil {
rows, err = api.db.Queryx(query)
}
if err == nil {
defer rows.Close()
for rows.Next() {
app := Application{}
err := rows.StructScan(&app)
if err != nil {
logger.Warn().Err(err).Msg("Failed to read app from DB")
}
if prodIDPtr := app.ProductID.Ptr(); prodIDPtr != nil {
// lower case so lookups are case insensitive
prodIDLower := strings.ToLower(*prodIDPtr)
cachedAppIDs[prodIDLower] = app.ID
}
// So we can quickly validate the UUID based IDs
cachedAppIDs[app.ID] = app.ID
}
} else {
logger.Error().Err(err).Msg("Failed to get apps")
}
cachedAppsRef = cachedAppIDs
}
cachedAppsIDsLock.Unlock()
}
// Trim space and the {} that may surround the ID
appIDNoBrackets := strings.TrimSpace(appOrProductID)
lastIdx := len(appIDNoBrackets) - 1
if len(appIDNoBrackets) > 2 && appIDNoBrackets[0] == '{' && appIDNoBrackets[lastIdx] == '}' {
appIDNoBrackets = strings.TrimSpace(appIDNoBrackets[1:lastIdx])
}
// Case insensitive, so use lower case as key
appIDNoBrackets = strings.ToLower(appIDNoBrackets)
cachedAppID, ok := cachedAppsRef[appIDNoBrackets]
if !ok {
return "", fmt.Errorf("no app found for ID %v", appOrProductID)
}
return cachedAppID, nil
}
// appsQuery returns a SelectDataset prepared to return all applications.
// This query is meant to be extended later in the methods using it to filter
// by a specific application id, all applications that belong to a given team,
// specify how to query the rows or their destination.
func (api *API) appsQuery() *goqu.SelectDataset {
query := goqu.From("application").
Select("id", "product_id", "name", "description", "created_ts").
Order(goqu.I("created_ts").Desc())
return query
}
func (api *API) getInstanceCount(appID, groupID string, duration postgresDuration) (int, error) {
query, _, err := api.appInstancesCountQuery(appID, groupID, duration).ToSQL()
if err != nil {
return 0, err
}
count := 0
if err := api.db.QueryRow(query).Scan(&count); err != nil {
return 0, err
}
return count, nil
}
// appInstancesCountQuery returns a SelectDataset prepared to return the number of
// instances running a given application.
func (api *API) appInstancesCountQuery(appID, groupID string, duration postgresDuration) *goqu.SelectDataset {
query := goqu.From("instance_application").
Select(goqu.COUNT("*")).
Where(
goqu.L("last_check_for_updates > now() at time zone 'utc' - interval ?", duration),
goqu.L(ignoreFakeInstanceCondition("instance_id")),
)
if appID != "" {
query = query.Where(goqu.C("application_id").Eq(appID))
}
if groupID != "" {
query = query.Where(goqu.C("group_id").Eq(groupID))
}
return query
}