-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathseeds.go
511 lines (458 loc) · 14 KB
/
seeds.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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
package seeds
import (
"encoding/json"
"fmt"
"math/rand"
"strconv"
"time"
"github.com/content-services/content-sources-backend/pkg/config"
"github.com/content-services/content-sources-backend/pkg/models"
"github.com/content-services/content-sources-backend/pkg/utils"
"github.com/google/uuid"
"golang.org/x/exp/slices"
"gorm.io/gorm"
)
type SeedOptions struct {
OrgID string
BatchSize int
Arch *string
Versions *[]string
Status *string
ContentType *string
Origin *string
Version *string
TaskID string
}
type IntrospectionStatusMetadata struct {
LastIntrospectionStatus *string
lastIntrospectionTime *time.Time
lastIntrospectionSuccessTime *time.Time
lastIntrospectionUpdateTime *time.Time
lastIntrospectionError *string
}
const (
batchSize = 500
)
func randomURL() string {
return fmt.Sprintf("https://%s.com/%s", RandStringBytes(20), RandStringBytes(5))
}
func randomRepositoryRpmName() string {
return RandStringBytes(12)
}
var (
archs = []string{
"x86_64",
"noarch",
}
)
func randomRepositoryRpmArch() string {
return archs[rand.Int()%len(archs)]
}
func SeedRepositoryConfigurations(db *gorm.DB, size int, options SeedOptions) ([]models.RepositoryConfiguration, error) {
var repos []models.Repository
var repoConfigurations []models.RepositoryConfiguration
if options.BatchSize != 0 {
db.CreateBatchSize = options.BatchSize
}
if options.ContentType == nil {
options.ContentType = utils.Ptr(config.ContentTypeRpm)
}
if options.Origin == nil {
options.Origin = utils.Ptr(config.OriginExternal)
}
for i := 0; i < size; i++ {
introspectionMetadata := randomIntrospectionStatusMetadata(options.Status)
repo := models.Repository{
URL: randomURL(),
LastIntrospectionTime: introspectionMetadata.lastIntrospectionTime,
LastIntrospectionSuccessTime: introspectionMetadata.lastIntrospectionSuccessTime,
LastIntrospectionUpdateTime: introspectionMetadata.lastIntrospectionUpdateTime,
LastIntrospectionError: introspectionMetadata.lastIntrospectionError,
LastIntrospectionStatus: *introspectionMetadata.LastIntrospectionStatus,
Origin: *options.Origin,
ContentType: *options.ContentType,
}
repos = append(repos, repo)
}
if err := db.Create(&repos).Error; err != nil {
return nil, err
}
for i := 0; i < size; i++ {
repoConfig := models.RepositoryConfiguration{
Name: fmt.Sprintf("%s - %s - %s", RandStringBytes(2), "TestRepo", RandStringBytes(10)),
Label: fmt.Sprintf("%s - %s - %s", RandStringBytes(2), "TestRepo", RandStringBytes(10)),
Versions: createVersionArray(options.Versions),
Arch: createArch(options.Arch),
AccountID: fmt.Sprintf("%d", rand.Intn(9999)),
OrgID: createOrgId(options.OrgID),
RepositoryUUID: repos[i].UUID,
LastSnapshotTaskUUID: options.TaskID,
Snapshot: true,
}
repoConfigurations = append(repoConfigurations, repoConfig)
}
if err := db.Create(&repoConfigurations).Error; err != nil {
return nil, fmt.Errorf("could not save seed: %w", err)
}
return repoConfigurations, nil
}
func randomIntrospectionStatusMetadata(existingStatus *string) IntrospectionStatusMetadata {
var metadata IntrospectionStatusMetadata
if existingStatus != nil {
metadata = getIntrospectionTimestamps(*existingStatus)
return metadata
}
statuses := []string{config.StatusPending, config.StatusValid, config.StatusInvalid, config.StatusUnavailable}
index := rand.Intn(4)
return getIntrospectionTimestamps(statuses[index])
}
func getIntrospectionTimestamps(lastIntrospectionStatus string) IntrospectionStatusMetadata {
timestamp := time.Now()
metadata := IntrospectionStatusMetadata{LastIntrospectionStatus: &lastIntrospectionStatus}
switch lastIntrospectionStatus {
case config.StatusValid:
metadata.lastIntrospectionTime = ×tamp
metadata.lastIntrospectionSuccessTime = ×tamp
metadata.lastIntrospectionUpdateTime = ×tamp
case config.StatusInvalid:
metadata.lastIntrospectionError = utils.Ptr("bad introspection")
case config.StatusUnavailable:
metadata.lastIntrospectionTime = ×tamp
metadata.lastIntrospectionSuccessTime = ×tamp
metadata.lastIntrospectionUpdateTime = ×tamp
metadata.lastIntrospectionError = utils.Ptr("bad introspection")
}
return metadata
}
func SeedRepository(db *gorm.DB, size int, options SeedOptions) error {
var repos []models.Repository
// Add size random Repository entries
countRecords := 0
for i := 0; i < size; i++ {
introspectionMetadata := randomIntrospectionStatusMetadata(options.Status)
repo := models.Repository{
URL: randomURL(),
LastIntrospectionTime: introspectionMetadata.lastIntrospectionTime,
LastIntrospectionSuccessTime: introspectionMetadata.lastIntrospectionSuccessTime,
LastIntrospectionUpdateTime: introspectionMetadata.lastIntrospectionUpdateTime,
LastIntrospectionError: introspectionMetadata.lastIntrospectionError,
LastIntrospectionStatus: *introspectionMetadata.LastIntrospectionStatus,
Public: true,
}
repos = append(repos, repo)
if len(repos) >= batchSize {
if r := db.Create(repos); r != nil && r.Error != nil {
return r.Error
}
countRecords += len(repos)
repos = []models.Repository{}
fmt.Printf("repoConfig: %d \r", countRecords)
}
}
// Add remaining records
if len(repos) > 0 {
r := db.Create(&repos)
if r.Error != nil {
return r.Error
}
countRecords += len(repos)
fmt.Printf("repoConfig: %d \r", countRecords)
}
return nil
}
func SeedSnapshots(db *gorm.DB, repoConfigUuid string, size int) ([]models.Snapshot, error) {
created := []models.Snapshot{}
for i := 0; i < size; i++ {
path := fmt.Sprintf("/seed/%v/%v", repoConfigUuid, i)
snap := models.Snapshot{
VersionHref: path,
PublicationHref: path,
DistributionPath: path,
DistributionHref: path,
RepositoryConfigurationUUID: repoConfigUuid,
ContentCounts: models.ContentCountsType{},
AddedCounts: models.ContentCountsType{},
RemovedCounts: models.ContentCountsType{},
}
res := db.Create(&snap)
created = append(created, snap)
if res.Error != nil {
return nil, res.Error
}
}
return created, nil
}
type TemplateSeedOptions struct {
OrgID string
BatchSize int
Arch *string
Version *string
RepositoryConfigUUIDs []string
Snapshots []models.Snapshot
UseLatest bool
}
func SeedTemplates(db *gorm.DB, size int, options TemplateSeedOptions) ([]models.Template, error) {
orgID := RandomOrgId()
templates := []models.Template{}
if options.OrgID != "" {
orgID = options.OrgID
}
for i := 0; i < size; i++ {
t := models.Template{
Base: models.Base{
UUID: uuid.NewString(),
},
Name: RandStringBytes(10),
OrgID: orgID,
Description: "description",
Version: createVersion(options.Version),
Arch: createArch(options.Arch),
CreatedBy: "user",
LastUpdatedBy: "user",
UseLatest: options.UseLatest,
}
if !options.UseLatest {
t.Date = time.Now()
}
err := db.Create(&t).Error
if err != nil {
return nil, err
}
var tRepos []models.TemplateRepositoryConfiguration
for _, rcUUID := range options.RepositoryConfigUUIDs {
snapIndex := slices.IndexFunc(options.Snapshots, func(s models.Snapshot) bool {
return s.RepositoryConfigurationUUID == rcUUID
})
tRepos = append(tRepos, models.TemplateRepositoryConfiguration{
RepositoryConfigurationUUID: rcUUID,
TemplateUUID: t.UUID,
SnapshotUUID: options.Snapshots[snapIndex].UUID,
})
}
err = db.Create(&tRepos).Error
templates = append(templates, t)
if err != nil {
return nil, err
}
}
return templates, nil
}
// SeedRpms Populate database with random package information
// db The database descriptor.
// size The number of rpm packages per repository to be generated.
func SeedRpms(db *gorm.DB, repo *models.Repository, size int) error {
if db == nil {
return fmt.Errorf("db cannot be nil")
}
if repo == nil {
return fmt.Errorf("repo cannot be nil")
}
if size < 0 {
return fmt.Errorf("size cannot be lower than 0")
}
if size == 0 {
return nil
}
var rpms []models.Rpm
var repositories_rpms []map[string]interface{}
// For each repo add 'size' rpm random packages
for i := 0; i < size; i++ {
rpm := models.Rpm{
Name: randomRepositoryRpmName(),
Arch: randomRepositoryRpmArch(),
Version: fmt.Sprintf("%d.%d.%d", rand.Int()%6, rand.Int()%16, rand.Int()%64),
Release: fmt.Sprintf("%d", rand.Int()%128),
Epoch: 0,
Summary: "Package summary",
Checksum: RandStringBytes(64),
}
rpms = append(rpms, rpm)
}
if err := db.Create(rpms).Error; err != nil {
return err
}
for _, rpm := range rpms {
repositories_rpms = append(repositories_rpms, map[string]interface{}{
"repository_uuid": repo.Base.UUID,
"rpm_uuid": rpm.Base.UUID,
})
}
if err := db.Table(models.TableNameRpmsRepositories).Create(&repositories_rpms).Error; err != nil {
return err
}
return nil
}
func RandomOrgId() string {
return strconv.Itoa(rand.Intn(99999999))
}
func RandomAccountId() string {
return strconv.Itoa(rand.Intn(99999999))
}
// createOrgId aims to mainly create most entities in the same org
// but also create some in other random orgs
func createOrgId(existingOrgId string) string {
orgId := "4234"
if existingOrgId != "" {
orgId = existingOrgId
} else {
randomNum := rand.Intn(5)
if randomNum == 3 {
orgId = RandomOrgId()
}
}
return orgId
}
func createVersionArray(existingVersionArray *[]string) []string {
if existingVersionArray != nil && len(*existingVersionArray) != 0 {
return *existingVersionArray
}
versionArray := make([]string, 0)
distVersLength := len(config.DistributionVersions)
for k := rand.Intn(distVersLength - 1); k < distVersLength; k++ {
ver := config.DistributionVersions[k].Label
if ver != config.ANY_VERSION {
versionArray = append(versionArray, ver)
}
}
return versionArray
}
func createVersion(existingVersion *string) string {
version := config.El9
if existingVersion != nil && *existingVersion != "" {
version = *existingVersion
return version
}
randomNum := rand.Intn(20)
if randomNum < 4 {
version = config.El8
}
if randomNum > 4 && randomNum < 6 {
version = config.El7
}
return version
}
func createArch(existingArch *string) string {
arch := config.X8664
if existingArch != nil && *existingArch != "" {
arch = *existingArch
return arch
}
randomNum := rand.Intn(20)
if randomNum < 4 {
arch = config.ANY_ARCH
}
if randomNum > 4 && randomNum < 6 {
arch = config.S390x
}
return arch
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// RandStringWithChars Return a random string of size n using the lookup
// table.
// n size of the string to be returned
// lookup A string representing the lookup table.
// Return the random string.
func RandStringWithChars(n int, lookup string) string {
b := make([]byte, n)
for i := range b {
b[i] = lookup[rand.Intn(len(lookup))]
}
return string(b)
}
func RandStringBytes(n int) string {
return RandStringWithChars(n, letterBytes)
}
type TaskSeedOptions struct {
AccountID string
OrgID string
BatchSize int
Status string
Error *string
Typename string
RepoConfigUUID string
RepoUUID string
QueuedAt *time.Time
FinishedAt *time.Time
}
func SeedTasks(db *gorm.DB, size int, options TaskSeedOptions) ([]models.TaskInfo, error) {
var err error
var tasks []models.TaskInfo
var repoUUID string
if options.BatchSize != 0 {
db.CreateBatchSize = options.BatchSize
}
orgId := createOrgId(options.OrgID)
if options.RepoUUID == "" {
repo := models.Repository{
URL: randomURL(),
}
if err := db.Create(&repo).Error; err != nil {
return tasks, err
}
repoUUID = repo.UUID
} else {
repoUUID = options.RepoUUID
}
if options.AccountID != "" || options.RepoConfigUUID != "" {
var repoConfig models.RepositoryConfiguration
if options.RepoConfigUUID != "" {
err = db.Where("uuid = ? ", options.RepoConfigUUID).First(&repoConfig).Error
} else {
repoConfig = models.RepositoryConfiguration{
RepositoryUUID: repoUUID,
AccountID: options.AccountID,
Name: fmt.Sprintf("%s - %s - %s", RandStringBytes(2), "TestRepo", RandStringBytes(10)),
OrgID: orgId,
}
err = db.Create(&repoConfig).Error
}
repoUUID = repoConfig.RepositoryUUID
orgId = createOrgId(repoConfig.OrgID)
if err != nil {
return tasks, err
}
}
typename := "example type"
if options.Typename != "" {
typename = options.Typename
}
payloadData := map[string]string{"url": "https://example.com"}
payload, err := json.Marshal(payloadData)
if err != nil {
return tasks, err
}
tasks = make([]models.TaskInfo, size)
repoUUIDParsed := uuid.MustParse(repoUUID)
for i := 0; i < size; i++ {
queued := time.Now().Add(time.Minute * time.Duration(i))
if options.QueuedAt != nil {
queued = *options.QueuedAt
}
started := time.Now().Add(time.Minute * time.Duration(i+5))
finished := time.Now().Add(time.Minute * time.Duration(i+10))
if options.FinishedAt != nil {
started = (*options.FinishedAt).Add(-5 * time.Minute)
finished = *options.FinishedAt
}
tasks[i] = models.TaskInfo{
Id: uuid.New(),
Typename: typename,
Payload: payload,
OrgId: orgId,
AccountId: options.AccountID,
ObjectUUID: repoUUIDParsed,
ObjectType: utils.Ptr(config.ObjectTypeRepository),
Dependencies: make([]string, 0),
Token: uuid.New(),
Queued: &queued,
Started: &started,
Finished: &finished,
Error: options.Error,
Status: options.Status,
}
}
if createErr := db.Create(&tasks).Error; createErr != nil {
return tasks, createErr
}
return tasks, nil
}