gendummydata.py 8.1 KB
Newer Older
1
#!/usr/bin/python3
eric's avatar
eric committed
2
3
4
"""
usage: gendummydata.py outputfilename.sql
"""
eric's avatar
eric committed
5
6
7
8
9
10
11
#
# This script seeds the AUR database with dummy data for
# use during development/testing.  It uses random entries
# from /usr/share/dict/words to create user accounts and
# package names.  It generates the SQL statements to
# insert these users/packages into the AUR database.
#
12
13
14
15
import random
import time
import os
import sys
16
17
import io
import subprocess
18
import logging
19

20
LOG_LEVEL = logging.DEBUG # logging level. set to logging.INFO to reduce output
eric's avatar
eric committed
21
SEED_FILE = "/usr/share/dict/words"
22
23
24
25
DB_HOST   = os.getenv("DB_HOST", "localhost")
DB_NAME   = os.getenv("DB_NAME", "AUR")
DB_USER   = os.getenv("DB_USER", "aur")
DB_PASS   = os.getenv("DB_PASS", "aur")
eric's avatar
eric committed
26
USER_ID   = 5          # Users.ID of first bogus user
eric's avatar
eric committed
27
PKG_ID    = 1          # Packages.ID of first package
Loui Chang's avatar
Loui Chang committed
28
MAX_USERS = 300        # how many users to 'register'
eric's avatar
eric committed
29
30
MAX_DEVS  = .1         # what percentage of MAX_USERS are Developers
MAX_TUS   = .2         # what percentage of MAX_USERS are Trusted Users
Loui Chang's avatar
Loui Chang committed
31
MAX_PKGS  = 900       # how many packages to load
32
33
PKG_DEPS  = (1, 5)     # min/max depends a package has
PKG_SRC   = (1, 3)     # min/max sources a package has
eric's avatar
eric committed
34
PKG_CMNTS = (1, 5)     # min/max number of comments a package has
35
CATEGORIES_COUNT = 17  # the number of categories from aur-schema
eric's avatar
eric committed
36
VOTING    = (0, .30)   # percentage range for package voting
eric's avatar
eric committed
37
38
39
RANDOM_TLDS = ("edu", "com", "org", "net", "tw", "ru", "pl", "de", "es")
RANDOM_URL = ("http://www.", "ftp://ftp.", "http://", "ftp://")
RANDOM_LOCS = ("pub", "release", "files", "downloads", "src")
40
FORTUNE_CMD = "/usr/bin/fortune"
41

42
43
44
45
# setup logging
logformat = "%(levelname)s: %(message)s"
logging.basicConfig(format=logformat, level=LOG_LEVEL)
log = logging.getLogger()
eric's avatar
eric committed
46
47

if len(sys.argv) != 2:
48
	log.error("Missing output filename argument")
eric's avatar
eric committed
49
50
51
52
53
	raise SystemExit

# make sure the seed file exists
#
if not os.path.exists(SEED_FILE):
54
	log.error("Please install the 'words' Arch package")
55
	raise SystemExit
eric's avatar
eric committed
56

57
58
59
60
61
62
# make sure comments can be created
#
if not os.path.exists(FORTUNE_CMD):
	log.error("Please install the 'fortune-mod' Arch package")
	raise SystemExit

eric's avatar
eric committed
63
64
65
66
67
68
69
70
# track what users/package names have been used
#
seen_users = {}
seen_pkgs = {}
user_keys = []

# some functions to generate random data
#
71
def genVersion():
eric's avatar
eric committed
72
73
74
	ver = []
	ver.append("%d" % random.randrange(0,10))
	ver.append("%d" % random.randrange(0,20))
eric's avatar
eric committed
75
	if random.randrange(0,2) == 0:
eric's avatar
eric committed
76
		ver.append("%d" % random.randrange(0,100))
77
	return ".".join(ver) + "-u%d" % random.randrange(1,11)
eric's avatar
eric committed
78
def genCategory():
79
	return random.randrange(1,CATEGORIES_COUNT)
eric's avatar
eric committed
80
81
82
83
84
85
def genUID():
	return seen_users[user_keys[random.randrange(0,len(user_keys))]]


# load the words, and make sure there are enough words for users/pkgs
#
86
log.debug("Grabbing words from seed file...")
eric's avatar
eric committed
87
88
89
90
91
92
93
94
95
96
97
98
99
100
fp = open(SEED_FILE, "r")
contents = fp.readlines()
fp.close()
if MAX_USERS > len(contents):
	MAX_USERS = len(contents)
if MAX_PKGS > len(contents):
	MAX_PKGS = len(contents)
if len(contents) - MAX_USERS > MAX_PKGS:
	need_dupes = 0
else:
	need_dupes = 1

# select random usernames
#
101
log.debug("Generating random user names...")
eric's avatar
eric committed
102
103
104
user_id = USER_ID
while len(seen_users) < MAX_USERS:
	user = random.randrange(0, len(contents))
eric's avatar
eric committed
105
106
	word = contents[user].replace("'", "").replace(".","").replace(" ", "_")
	word = word.strip().lower()
107
	if word not in seen_users:
eric's avatar
eric committed
108
109
		seen_users[word] = user_id
		user_id += 1
110
user_keys = list(seen_users.keys())
eric's avatar
eric committed
111
112
113

# select random package names
#
114
log.debug("Generating random package names...")
eric's avatar
eric committed
115
116
117
num_pkgs = PKG_ID
while len(seen_pkgs) < MAX_PKGS:
	pkg = random.randrange(0, len(contents))
eric's avatar
eric committed
118
119
	word = contents[pkg].replace("'", "").replace(".","").replace(" ", "_")
	word = word.strip().lower()
eric's avatar
eric committed
120
	if not need_dupes:
121
		if word not in seen_pkgs and word not in seen_users:
eric's avatar
eric committed
122
123
124
			seen_pkgs[word] = num_pkgs
			num_pkgs += 1
	else:
125
		if word not in seen_pkgs:
eric's avatar
eric committed
126
127
128
			seen_pkgs[word] = num_pkgs
			num_pkgs += 1

eric's avatar
eric committed
129
130
131
132
# free up contents memory
#
contents = None

133
134
135
136
137
138
139
# developer/tu IDs
#
developers = []
trustedusers = []
has_devs = 0
has_tus = 0

140
141
142
143
144
# Just let python throw the errors if any happen
#
out = open(sys.argv[1], "w")
out.write("BEGIN;\n")

eric's avatar
eric committed
145
146
# Begin by creating the User statements
#
147
log.debug("Creating SQL statements for users.")
eric's avatar
eric committed
148
for u in user_keys:
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
	account_type = 1  # default to normal user
	if not has_devs or not has_tus:
		account_type = random.randrange(1, 4)
		if account_type == 3 and not has_devs:
			# this will be a dev account
			#
			developers.append(seen_users[u])
			if len(developers) >= MAX_DEVS * MAX_USERS:
				has_devs = 1
		elif account_type == 2 and not has_tus:
			# this will be a trusted user account
			#
			trustedusers.append(seen_users[u])
			if len(trustedusers) >= MAX_TUS * MAX_USERS:
				has_tus = 1
		else:
			# a normal user account
			#
			pass
168

169
170
171
	s = ("INSERT INTO Users (ID, AccountTypeID, Username, Email, Passwd)"
		 " VALUES (%d, %d, '%s', '%s@example.com', MD5('%s'));\n")
	s = s % (seen_users[u], account_type, u, u, u)
eric's avatar
eric committed
172
	out.write(s)
173
174
175
176
177

log.debug("Number of developers: %d" % len(developers))
log.debug("Number of trusted users: %d" % len(trustedusers))
log.debug("Number of users: %d" % (MAX_USERS-len(developers)-len(trustedusers)))
log.debug("Number of packages: %d" % MAX_PKGS)
eric's avatar
eric committed
178
179
180

# Create the package statements
#
181
log.debug("Creating SQL statements for packages.")
eric's avatar
eric committed
182
count = 0
183
for p in list(seen_pkgs.keys()):
eric's avatar
eric committed
184
	NOW = int(time.time())
185
186
187
188
189
190
191
	if count % 2 == 0:
		muid = developers[random.randrange(0,len(developers))]
	else:
		muid = trustedusers[random.randrange(0,len(trustedusers))]
	if count % 20 == 0: # every so often, there are orphans...
		muid = 0

eric's avatar
eric committed
192
193
	uuid = genUID() # the submitter/user

194
	if muid == 0:
195
196
197
198
		s = ("INSERT INTO Packages (ID, Name, Version, CategoryID,"
			 " SubmittedTS, SubmitterUID, MaintainerUID) VALUES"
			 " (%d, '%s', '%s', %d, %d, %d, NULL);\n")
		s = s % (seen_pkgs[p], p, genVersion(), genCategory(), NOW, uuid)
199
	else:
200
201
202
203
		s = ("INSERT INTO Packages (ID, Name, Version, CategoryID,"
			 " SubmittedTS, SubmitterUID, MaintainerUID) VALUES "
			 " (%d, '%s', '%s', %d, %d, %d, %d);\n")
		s = s % (seen_pkgs[p], p, genVersion(), genCategory(), NOW, uuid, muid)
204

eric's avatar
eric committed
205
206
207
	out.write(s)
	count += 1

eric's avatar
eric committed
208
209
210
211
	# create random comments for this package
	#
	num_comments = random.randrange(PKG_CMNTS[0], PKG_CMNTS[1])
	for i in range(0, num_comments):
212
		fortune = subprocess.getoutput(FORTUNE_CMD).replace("'","")
eric's avatar
eric committed
213
		now = NOW + random.randrange(400, 86400*3)
214
215
216
		s = ("INSERT INTO PackageComments (PackageID, UsersID,"
			 " Comments, CommentTS) VALUES (%d, %d, '%s', %d);\n")
		s = s % (seen_pkgs[p], genUID(), fortune, now)
eric's avatar
eric committed
217
218
		out.write(s)

eric's avatar
eric committed
219
220
# Cast votes
#
221
track_votes = {}
222
log.debug("Casting votes for packages.")
eric's avatar
eric committed
223
for u in user_keys:
224
225
	num_votes = random.randrange(int(len(seen_pkgs)*VOTING[0]),
			int(len(seen_pkgs)*VOTING[1]))
eric's avatar
eric committed
226
227
	pkgvote = {}
	for v in range(num_votes):
228
		pkg = random.randrange(1, len(seen_pkgs) + 1)
229
		if pkg not in pkgvote:
230
231
232
			s = ("INSERT INTO PackageVotes (UsersID, PackageID)"
				 " VALUES (%d, %d);\n")
			s = s % (seen_users[u], pkg)
eric's avatar
eric committed
233
			pkgvote[pkg] = 1
234
			if pkg not in track_votes:
235
236
				track_votes[pkg] = 0
			track_votes[pkg] += 1
eric's avatar
eric committed
237
238
			out.write(s)

239
240
# Update statements for package votes
#
241
for p in list(track_votes.keys()):
242
243
	s = "UPDATE Packages SET NumVotes = %d WHERE ID = %d;\n"
	s = s % (track_votes[p], p)
244
245
	out.write(s)

246
247
# Create package dependencies and sources
#
248
log.debug("Creating statements for package depends/sources.")
249
for p in list(seen_pkgs.keys()):
250
251
252
253
	num_deps = random.randrange(PKG_DEPS[0], PKG_DEPS[1])
	this_deps = {}
	i = 0
	while i != num_deps:
254
		dep = random.choice([k for k in seen_pkgs])
255
		if dep not in this_deps:
256
			s = "INSERT INTO PackageDepends VALUES (%d, '%s', NULL);\n"
257
			s = s % (seen_pkgs[p], dep)
258
259
260
261
262
263
264
265
266
267
268
			out.write(s)
			i += 1

	num_sources = random.randrange(PKG_SRC[0], PKG_SRC[1])
	for i in range(num_sources):
		src_file = user_keys[random.randrange(0, len(user_keys))]
		src = "%s%s.%s/%s/%s-%s.tar.gz" % (
				RANDOM_URL[random.randrange(0,len(RANDOM_URL))],
				p, RANDOM_TLDS[random.randrange(0,len(RANDOM_TLDS))],
				RANDOM_LOCS[random.randrange(0,len(RANDOM_LOCS))],
				src_file, genVersion())
269
270
		s = "INSERT INTO PackageSources VALUES (%d, '%s');\n"
		s = s % (seen_pkgs[p], src)
271
272
		out.write(s)

eric's avatar
eric committed
273
274
# close output file
#
275
out.write("COMMIT;\n")
eric's avatar
eric committed
276
277
out.write("\n")
out.close()
278
log.debug("Done.")