/
snapshots.go
402 lines (345 loc) · 11.6 KB
/
snapshots.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
package dao
import (
"context"
"fmt"
"regexp"
"time"
"github.com/content-services/content-sources-backend/pkg/api"
"github.com/content-services/content-sources-backend/pkg/config"
ce "github.com/content-services/content-sources-backend/pkg/errors"
"github.com/content-services/content-sources-backend/pkg/models"
"github.com/content-services/content-sources-backend/pkg/pulp_client"
"golang.org/x/exp/slices"
"gorm.io/gorm"
)
type snapshotDaoImpl struct {
db *gorm.DB
pulpClient pulp_client.PulpClient
ctx context.Context
}
func GetSnapshotDao(db *gorm.DB) SnapshotDao {
return &snapshotDaoImpl{
db: db,
ctx: context.Background(),
}
}
func (sDao *snapshotDaoImpl) WithContext(ctx context.Context) SnapshotDao {
cpy := *sDao
cpy.ctx = ctx
return &cpy
}
// Create records a snapshot of a repository
func (sDao *snapshotDaoImpl) Create(s *models.Snapshot) error {
trans := sDao.db.Create(s)
if trans.Error != nil {
return trans.Error
}
updateResult := trans.
Exec(`
UPDATE repository_configurations
SET last_snapshot_uuid = ?
WHERE repository_configurations.uuid = ?`,
s.UUID,
s.RepositoryConfigurationUUID,
)
if updateResult.Error != nil {
fmt.Printf("%v", updateResult.Error.Error())
return updateResult.Error
}
return nil
}
// List the snapshots for a given repository config
func (sDao *snapshotDaoImpl) List(
orgID string,
repoConfigUUID string,
paginationData api.PaginationData,
_ api.FilterData,
) (api.SnapshotCollectionResponse, int64, error) {
var snaps []models.Snapshot
var totalSnaps int64
var repoConfig models.RepositoryConfiguration
// First check if repo config exists
result := sDao.db.Where(
"repository_configurations.org_id IN (?,?) AND uuid = ?",
orgID,
config.RedHatOrg,
UuidifyString(repoConfigUUID)).
First(&repoConfig)
if result.Error != nil {
if result.Error == gorm.ErrRecordNotFound {
return api.SnapshotCollectionResponse{}, totalSnaps, &ce.DaoError{
Message: "Could not find repository with UUID " + repoConfigUUID,
NotFound: true,
}
}
return api.SnapshotCollectionResponse{}, totalSnaps, DBErrorToApi(result.Error)
}
sortMap := map[string]string{
"created_at": "created_at",
}
order := convertSortByToSQL(paginationData.SortBy, sortMap, "created_at desc")
filteredDB := readableSnapshots(sDao.db, orgID).
Where("repository_configuration_uuid = ?", UuidifyString(repoConfigUUID))
// Get count
filteredDB.Count(&totalSnaps)
if filteredDB.Error != nil {
return api.SnapshotCollectionResponse{}, 0, filteredDB.Error
}
// Get Data
filteredDB.Order(order).
Limit(paginationData.Limit).
Offset(paginationData.Offset).
Find(&snaps)
if filteredDB.Error != nil {
return api.SnapshotCollectionResponse{}, 0, filteredDB.Error
}
if len(snaps) == 0 {
return api.SnapshotCollectionResponse{Data: []api.SnapshotResponse{}}, totalSnaps, nil
}
pulpContentPath, err := sDao.pulpClient.WithContext(sDao.ctx).GetContentPath()
if err != nil {
return api.SnapshotCollectionResponse{}, 0, err
}
resp := snapshotConvertToResponses(snaps, pulpContentPath)
return api.SnapshotCollectionResponse{Data: resp}, totalSnaps, nil
}
func readableSnapshots(db *gorm.DB, orgId string) *gorm.DB {
return db.Model(&models.Snapshot{}).
Joins("JOIN repository_configurations ON repository_configuration_uuid = repository_configurations.uuid").
Where("repository_configurations.org_id IN (?,?)", orgId, config.RedHatOrg)
}
func (sDao *snapshotDaoImpl) Fetch(uuid string) (api.SnapshotResponse, error) {
var snapAPI api.SnapshotResponse
snapModel, err := sDao.fetch(uuid)
if err != nil {
return api.SnapshotResponse{}, err
}
snapshotModelToApi(snapModel, &snapAPI)
return snapAPI, nil
}
func (sDao *snapshotDaoImpl) fetch(uuid string) (models.Snapshot, error) {
var snapshot models.Snapshot
result := sDao.db.Where("uuid = ?", UuidifyString(uuid)).First(&snapshot)
if result.Error != nil {
if result.Error == gorm.ErrRecordNotFound {
return models.Snapshot{}, &ce.DaoError{
Message: "Could not find snapshot with UUID " + uuid,
NotFound: true,
}
}
return models.Snapshot{}, result.Error
}
return snapshot, nil
}
func (sDao *snapshotDaoImpl) GetRepositoryConfigurationFile(orgID, snapshotUUID, host string) (string, error) {
var repoID string
snapshot, err := sDao.fetch(snapshotUUID)
if err != nil {
return "", err
}
rcDao := repositoryConfigDaoImpl{db: sDao.db}
repoConfig, err := rcDao.fetchRepoConfig(orgID, snapshot.RepositoryConfigurationUUID, true)
if err != nil {
return "", err
}
pc := sDao.pulpClient.WithContext(sDao.ctx)
contentPath, err := pc.GetContentPath()
if err != nil {
return "", err
}
contentURL := pulpContentURL(contentPath, snapshot.RepositoryPath)
// Replace any nonalphanumeric characters with an underscore
// e.g: "!!my repo?test15()" => "__my_repo_test15__"
re, err := regexp.Compile(`[^a-zA-Z0-9:space]`)
if err != nil {
return "", err
}
if repoConfig.IsRedHat() {
repoID = repoConfig.Label
} else {
repoID = re.ReplaceAllString(repoConfig.Name, "_")
}
var gpgCheck, repoGpgCheck int
var gpgKeyField string
if repoConfig.GpgKey != "" {
gpgCheck = 1
if repoConfig.IsRedHat() {
gpgKeyField = config.RedHatGpgKeyPath
} else {
gpgKeyField = fmt.Sprintf("https://%v%v/repository_gpg_key/%v", host, api.FullRootPath(), repoConfig.UUID) // host includes trailing slash
}
}
moduleHotfixes := 0
if repoConfig.ModuleHotfixes {
moduleHotfixes = 1
}
// TODO purposefully setting repo_gpgcheck to 0 for now until pulp issue is resolved
// normally set to 1 when metadata verification is enabled
repoGpgCheck = 0
fileConfig := fmt.Sprintf(""+
"[%v]\n"+
"name=%v\n"+
"baseurl=%v\n"+
"module_hotfixes=%v\n"+
"gpgcheck=%v\n"+ // set to verify packages
"repo_gpgcheck=%v\n"+ // set to verify metadata
"enabled=1\n"+
"gpgkey=%v\n"+
"sslclientcert=/etc/pki/consumer/cert.pem\n"+
"sslclientkey=/etc/pki/consumer/key.pem\n",
repoID, repoConfig.Name, contentURL, moduleHotfixes, gpgCheck, repoGpgCheck, gpgKeyField)
return fileConfig, nil
}
func (sDao *snapshotDaoImpl) FetchForRepoConfigUUID(repoConfigUUID string) ([]models.Snapshot, error) {
var snaps []models.Snapshot
result := sDao.db.Model(&models.Snapshot{}).
Where("repository_configuration_uuid = ?", repoConfigUUID).
Find(&snaps)
if result.Error != nil {
return snaps, result.Error
}
return snaps, nil
}
func (sDao *snapshotDaoImpl) Delete(snapUUID string) error {
var snap models.Snapshot
result := sDao.db.Where("uuid = ?", snapUUID).First(&snap)
if result.Error != nil {
return result.Error
}
result = sDao.db.Delete(snap)
if result.Error != nil {
return result.Error
}
return nil
}
func (sDao *snapshotDaoImpl) FetchLatestSnapshot(repoConfigUUID string) (api.SnapshotResponse, error) {
var snap models.Snapshot
snap, err := sDao.fetchLatestSnapshot(repoConfigUUID)
if err != nil {
return api.SnapshotResponse{}, err
}
var apiSnap api.SnapshotResponse
snapshotModelToApi(snap, &apiSnap)
return apiSnap, nil
}
func (sDao *snapshotDaoImpl) fetchLatestSnapshot(repoConfigUUID string) (models.Snapshot, error) {
var snap models.Snapshot
result := sDao.db.
Where("snapshots.repository_configuration_uuid = ?", repoConfigUUID).
Order("created_at DESC").
First(&snap)
if result.Error != nil {
return models.Snapshot{}, result.Error
}
return snap, nil
}
func (sDao *snapshotDaoImpl) FetchSnapshotByVersionHref(repoConfigUUID string, versionHref string) (*api.SnapshotResponse, error) {
var snap models.Snapshot
result := sDao.db.
Where("snapshots.repository_configuration_uuid = ? AND version_href = ?", repoConfigUUID, versionHref).
Order("created_at DESC").
Limit(1).
Find(&snap)
if result.Error != nil {
return nil, result.Error
}
if snap.UUID == "" {
return nil, nil
}
var apiSnap api.SnapshotResponse
snapshotModelToApi(snap, &apiSnap)
return &apiSnap, nil
}
func (sDao *snapshotDaoImpl) FetchSnapshotsModelByDateAndRepository(orgID string, request api.ListSnapshotByDateRequest) ([]models.Snapshot, error) {
snaps := []models.Snapshot{}
date, _ := time.Parse(time.DateOnly, request.Date)
date = date.AddDate(0, 0, 1) // Set the date to 24 hours later, inclusive of the current day
query := sDao.db.Raw(`
SELECT snapshots.*
FROM snapshots
INNER JOIN
(SELECT combined.repository_configuration_uuid,
min(created_at) AS created_at
FROM
(SELECT repository_configuration_uuid,
max(snapshots.created_at) AS created_at
FROM snapshots
INNER JOIN repository_configurations ON repository_configuration_uuid = repository_configurations.uuid
WHERE repository_configurations.org_id in (?,?)
AND repository_configuration_uuid in ?
AND snapshots.created_at < ?
GROUP BY repository_configuration_uuid
UNION
SELECT repository_configuration_uuid,
min(snapshots.created_at) AS created_at
FROM snapshots
INNER JOIN repository_configurations ON repository_configuration_uuid = repository_configurations.uuid
WHERE repository_configurations.org_id in (?,?)
AND repository_configuration_uuid in ?
AND snapshots.created_at >= ?
GROUP BY repository_configuration_uuid) AS combined
GROUP BY combined.repository_configuration_uuid) AS single
ON single.repository_configuration_uuid = snapshots.repository_configuration_uuid
AND single.created_at = snapshots.created_at;`,
orgID,
config.RedHatOrg,
UuidifyStrings(request.RepositoryUUIDS),
date,
orgID,
config.RedHatOrg,
UuidifyStrings(request.RepositoryUUIDS),
date).
Scan(&snaps)
if query.Error != nil {
return nil, query.Error
}
return snaps, nil
}
// FetchSnapshotsByDateAndRepository returns a list of snapshots by date.
func (sDao *snapshotDaoImpl) FetchSnapshotsByDateAndRepository(orgID string, request api.ListSnapshotByDateRequest) (api.ListSnapshotByDateResponse, error) {
var snaps []models.Snapshot
layout := "2006-01-02"
date, _ := time.Parse(layout, request.Date)
date = date.AddDate(0, 0, 1) // Set the date to 24 hours later, inclusive of the current day
snaps, err := sDao.FetchSnapshotsModelByDateAndRepository(orgID, request)
if err != nil {
return api.ListSnapshotByDateResponse{}, err
}
repoUUIDCount := len(request.RepositoryUUIDS)
listResponse := make([]api.SnapshotForDate, repoUUIDCount)
for i, uuid := range request.RepositoryUUIDS {
listResponse[i].RepositoryUUID = uuid
listResponse[i].IsAfter = false
indx := slices.IndexFunc(snaps, func(c models.Snapshot) bool {
return c.RepositoryConfigurationUUID == uuid
})
if indx != -1 {
apiResponse := api.SnapshotResponse{}
snapshotModelToApi(snaps[indx], &apiResponse)
listResponse[i].Match = &apiResponse
}
listResponse[i].IsAfter = indx != -1 && snaps[indx].Base.CreatedAt.After(date)
}
return api.ListSnapshotByDateResponse{Data: listResponse}, nil
}
// Converts the database models to our response objects
func snapshotConvertToResponses(snapshots []models.Snapshot, pulpContentPath string) []api.SnapshotResponse {
snapsAPI := make([]api.SnapshotResponse, len(snapshots))
for i := 0; i < len(snapshots); i++ {
snapshotModelToApi(snapshots[i], &snapsAPI[i])
snapsAPI[i].URL = pulpContentURL(pulpContentPath, snapshots[i].RepositoryPath)
}
return snapsAPI
}
func snapshotModelToApi(model models.Snapshot, resp *api.SnapshotResponse) {
resp.UUID = model.UUID
resp.CreatedAt = model.CreatedAt
resp.RepositoryPath = model.RepositoryPath
resp.ContentCounts = model.ContentCounts
resp.AddedCounts = model.AddedCounts
resp.RemovedCounts = model.RemovedCounts
}
// pulpContentURL combines content path and repository path to get content URL
func pulpContentURL(pulpContentPath string, repositoryPath string) string {
return pulpContentPath + repositoryPath + "/"
}