forked from content-services/content-sources-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseeds.go
345 lines (299 loc) · 9.12 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
package seeds
import (
"encoding/json"
"errors"
"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/google/uuid"
"github.com/openlyinc/pointy"
"gorm.io/gorm"
)
type SeedOptions struct {
OrgID string
BatchSize int
Arch *string
Versions *[]string
Status *string
}
type IntrospectionStatusMetadata struct {
status *string
lastIntrospectionTime *time.Time
lastIntrospectionSuccessTime *time.Time
lastIntrospectionUpdateTime *time.Time
lastIntrospectionError *string
}
const (
batchSize = 500
)
func init() {
rand.Seed(time.Now().UnixNano())
}
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) error {
var repos []models.Repository
var repoConfigurations []models.RepositoryConfiguration
if options.BatchSize != 0 {
db.CreateBatchSize = options.BatchSize
}
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,
Status: *introspectionMetadata.status,
}
repos = append(repos, repo)
}
if err := db.Create(&repos).Error; err != nil {
return err
}
for i := 0; i < size; i++ {
repoConfig := models.RepositoryConfiguration{
Name: 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,
}
repoConfigurations = append(repoConfigurations, repoConfig)
}
if err := db.Create(&repoConfigurations).Error; err != nil {
return errors.New("could not save seed")
}
return 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(status string) IntrospectionStatusMetadata {
timestamp := time.Now()
metadata := IntrospectionStatusMetadata{status: &status}
switch status {
case config.StatusValid:
metadata.lastIntrospectionTime = ×tamp
metadata.lastIntrospectionSuccessTime = ×tamp
metadata.lastIntrospectionUpdateTime = ×tamp
case config.StatusInvalid:
metadata.lastIntrospectionError = pointy.String("bad introspection")
case config.StatusUnavailable:
metadata.lastIntrospectionTime = ×tamp
metadata.lastIntrospectionSuccessTime = ×tamp
metadata.lastIntrospectionUpdateTime = ×tamp
metadata.lastIntrospectionError = pointy.String("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,
Status: *introspectionMetadata.status,
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 {
if r := db.Create(repos); r != nil && r.Error != nil {
return r.Error
}
countRecords += len(repos)
fmt.Printf("repoConfig: %d \r", countRecords)
}
return 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 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 {
OrgID string
BatchSize int
Status string
Error *string
}
func SeedTasks(db *gorm.DB, size int, options TaskSeedOptions) error {
if options.BatchSize != 0 {
db.CreateBatchSize = options.BatchSize
}
payloadData := map[string]string{"url": "https://example.com"}
payload, err := json.Marshal(payloadData)
if err != nil {
return err
}
tasks := make([]models.TaskInfo, size)
for i := 0; i < size; i++ {
queued := time.Now().Add(time.Minute * time.Duration(i))
started := time.Now().Add(time.Minute * time.Duration(i+5))
finished := time.Now().Add(time.Minute * time.Duration(i+10))
tasks[i] = models.TaskInfo{
Id: uuid.New(),
Typename: "example type",
Payload: payload,
OrgId: createOrgId(options.OrgID),
RepositoryUUID: uuid.New(),
Dependencies: make([]uuid.UUID, 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 createErr
}
return nil
}