This repository has been archived by the owner on Sep 15, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 49
/
generate.py
692 lines (600 loc) · 22.1 KB
/
generate.py
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
# BEGIN LICENSE BLOCK
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License Version
# 1.1 (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS" basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
# for the specific language governing rights and limitations under the
# License.
#
# The Original Code is Places Test code.
#
# The Initial Developer of the Original Code is Mozilla Corp.
# Portions created by the Initial Developer are Copyright (C) 2009
# the Initial Developer. All Rights Reserved.
#
# Contributor(s):
# David Dahl <ddahl@mozilla.com>
#
# Alternatively, the contents of this file may be used under the terms of
# either the GNU General Public License Version 2 or later (the "GPL"), or
# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
# in which case the provisions of the GPL or the LGPL are applicable instead
# of those above. If you wish to allow use of your version of this file only
# under the terms of either the GPL or the LGPL, and not to allow others to
# use your version of this file under the terms of the MPL, indicate your
# decision by deleting the provisions above and replace them with the notice
# and other provisions required by the GPL or the LGPL. If you do not delete
# the provisions above, a recipient may use your version of this file under
# the terms of any one of the MPL, the GPL or the LGPL.
#
# END LICENSE BLOCK
"""
using the 'Places generator'
----------------------------
Requirements: django.db - you should have a full install of django 1.0.2 release. We are using django solely for it's ORM and 'manage.py inspectdb' utility which reverse-engineers a db schema into django Model classes.
You must have django and the 'places' python module in your PYTHONPATH
in my ~/.zshrc I have:
export PYTHONPATH=$PYTHONPATH:~/code/python:~/code/mozilla-central/mozilla/toolkit/components/places/tests/generator/places
inside ~/code/mozilla-central/mozilla/toolkit/components/places/tests/generator is the places/ Django 'project'
You must set 2 ENV VARS:
1) PLACES_DB_PATH
e.g.: export PLACES_DB_PATH=~/code/python/places/places.sqlite
2) DJANGO_SETTINGS_MODULE
e.g.: export DJANGO_SETTINGS_MODULE=places.settings
Generate Script Docs:
python places/builddb/generate.py --help
================================================
This will pump your places.sqlite with a bunch of
ficticious places, history and bookmarks based on the current 'max' aggregation at https://places-stats.mozilla.com/
"""
import os
from optparse import OptionParser
import random
import urllib2
import random
import time
from copy import deepcopy
from math import ceil, floor
from places import uuid
from places.builddb.models import *
from places.builddb.http import get_web_data
"""
Places data generator. Create as many places/history/bookmarks as needed for testing Places queries for performance.
Tunable parameters: absolute # visits, bookmarks, age:
create random dates up to today,
"""
DEBUG = True
PERCENT_PLACES_TYPED = 0.3
TWENTY_FOUR_HOURS = (60 * 60 * 24 * 1000 * 1000)
from django.db import connection, transaction
class DateForward(object):
"""
go through the places db and increment the dates by one day
moz_annos.dateAdded
moz_annos.lastModified
moz_annos.expiration
moz_bookmarks.dateAdded
moz_bookmarks.lastModified
moz_favicons.expiration
moz_historyvisits.visit_date
moz_items_annos.dateAdded
moz_items_annos.expiration
moz_items_annos.lastModified
"""
def __init__(self):
pass
def table_column(self):
"""
keeps track of the tables/columns that need to be updated
"""
table_cols = {'moz_annos':['dateadded', 'lastmodified', 'expiration',],
'moz_bookmarks': ['dateadded', 'lastmodified',],
'moz_favicons': ['expiration'],
'moz_historyvisits': ['visit_date'],
'moz_items_annos': ['dateadded', 'lastmodified', 'expiration',]}
return table_cols
def place_id(self):
sql = """select id from moz_places where title = 'Places Testing Placeholder'"""
cursor = connection.cursor()
rows = cursor.execute(sql, [])
id = rows.fetchall()[0][0]
return id
def last_update(self):
"""
get the last update date
"""
id = self.place_id()
sql = """SELECT visit_date FROM moz_historyvisits WHERE place_id = %s ORDER BY id DESC""" % id
cursor = connection.cursor()
rows = cursor.execute(sql)
_rows= rows.fetchall()
return _rows[0][0]
def increment_dates(self):
"""
update the dates
"""
last_update_seconds = ((self.last_update() / 1000) / 1000)
now = int(time.time())
self.now_micro_secs = ((now * 1000) * 1000)
if DEBUG:
print "last update microseconds: %s" % self.last_update()
print "now: %s" % self.now_micro_secs
time_diff = (now - last_update_seconds)
self.time_diff = ((time_diff * 1000) * 1000)
if DEBUG:
print "\nTIME DIFF (microseconds): %s\n\n" % str(self.time_diff)
if DEBUG:
print "Incrementing History"
self.increment_history()
if DEBUG:
print "Incrementing Bookmarks"
self.increment_bookmarks()
if DEBUG:
print "Incrementing Favicons"
self.increment_favicons()
if DEBUG:
print "Incrementing Annos"
self.increment_annos()
if DEBUG:
print "Incrementing Items Annos"
self.increment_items_annos()
if DEBUG:
print "VACUUM/REINDEX"
self.vacuum_and_reindex()
last_time_run()
def increment_history(self):
self.increment_query('moz_historyvisits', 'visit_date', restrict_update=True)
def increment_bookmarks(self):
self.increment_query('moz_bookmarks', 'dateadded')
self.increment_query('moz_bookmarks', 'lastmodified')
def date_missing(self, _date):
"""
check to see if the date is None or 0, if so, return True
"""
if _date == 0 or _date is None or _date == '':
return True
else:
return False
def increment_query(self, table_name, col_name, restrict_update=False):
"""
shorter, faster updates of the date column
"""
if restrict_update:
# get the place_id
place_id = self.place_id()
try:
sql = "UPDATE %s SET %s " % (table_name, col_name,)
sql = sql + " = %s + %s"
if restrict_update:
where = " WHERE %s < %s AND place_id != %s AND %s != ''" % (col_name, self.now_micro_secs, place_id, col_name,)
else:
where = " WHERE %s < %s AND %s != ''" % \
(col_name, self.now_micro_secs, col_name, )
sql = sql + where
debug_sql = sql % (col_name, self.time_diff,)
if DEBUG:
print debug_sql
cursor = connection.cursor()
cursor.execute(debug_sql)
cursor.close()
except Exception, e:
print """************ ERROR *******************"""
print """***%s""" % e
raise
def increment_favicons(self):
"""
uses a simpler approach via a cursor
"""
self.increment_query('moz_favicons', 'expiration')
def increment_annos(self):
self.increment_query('moz_annos', 'dateadded')
self.increment_query('moz_annos', 'lastmodified')
self.increment_query('moz_annos', 'expiration')
def increment_items_annos(self):
self.increment_query('moz_items_annos', 'dateadded')
self.increment_query('moz_items_annos', 'lastmodified')
self.increment_query('moz_items_annos', 'expiration')
def vacuum_and_reindex(self):
try:
v_sql = "VACUUM;"
r_sql = "REINDEX;"
cursor = connection.cursor()
cursor.execute(v_sql)
cursor.execute(r_sql)
cursor.close()
except Exception, e:
print """************ ERROR *******************"""
print """***%s""" % e
raise
def right_now():
"""
right now! in microseconds
"""
return time.time() * 1000 * 1000
def six_months_ago():
"""
time in microseconds six months ago (roughly)
"""
six_months = (60*60*24*180*1000*1000)
n = right_now()
smo = n - six_months
return smo
def random_date():
"""
a random date (in microseconds since epoch) up to six months ago
"""
six_months = six_months_ago()
now = right_now()
s = random.randint(int(six_months), int(now))
return s
def alpha():
return map(chr, range(97, 123))
ALPHA = alpha()
def numbers():
return [0,1,2,3,4,5,6,7,8,9]
def new_favicon():
"""
create a new, unique favicon
"""
guid = uuid.generate()
url = 'http://tld.tld/%s.ico' % guid
favicon = MozFavicons.objects.create(
url=url,
data='wootuyiuyeryuwyerywueyurywueyruuewryueyuryuewyurkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjsdhjshjdhjshdjhjsdhjshjkdhjshjdhjshkjdhsjkhdkjhsjdhjshjhdd;sklfnlk;dnfjnklwmnkldjfklhadlfgjkhrnfjkgb;jlshgn;ruignifng;irgn;srhg;rnv;irn;',
mime_type='image/png',
expiration=random_date())
return favicon
def reverse_host(url):
"""
reverse the host
"""
parts = urllib2.urlparse.urlparse(url)
ru = "".join(reversed(parts[1])) + '.'
return ru
def url_parts():
"""
return a dictionary like: {'proto':'http'
'host':'www',
'domain':'foo',
'tld':'com'}
"""
protocol = ['https','http','ftp']
host_len = random.randint(4,26)
host = "".join(random.sample(ALPHA,host_len))
domain_len = random.randint(2,26)
domain = "".join(random.sample(ALPHA,domain_len))
tld_len = random.randint(2,3)
tld = "".join(random.sample(ALPHA,tld_len))
proto_idx = random.randint(0, 2)
proto = protocol[proto_idx]
return {'proto':proto,'host':host,'domain':domain,'tld':tld}
def new_title():
"""
return a random title
"""
title_len = random.randint(3,26)
title = "".join(random.sample(ALPHA,title_len))
return title
def keyword_gen(n):
kw_list, kw_count = make_keywords(n)
def gen():
for obj in kw_list:
yield obj
return gen()
def make_keywords(n):
"""
make num_keywords
"""
kw_list = []
i = 0
while n > 0:
keyword_len = random.randint(3,18)
kw = "".join(random.sample(ALPHA,keyword_len))
keyword = MozKeywords(keyword=kw)
keyword.save()
k = MozKeywords.objects.get(keyword=kw)
kw_list.append(k)
n = n - 1
i = i + 1
return (kw_list,i)
def expo(MEAN,round_ceil='ceil'):
"""
returns a value for a exponential dustribution
"""
lambd = 1.0 / MEAN # the lambda value for the random generator
val = random.expovariate(lambd)
if round_ceil == 'ceil':
val = int(ceil(val))
val = int(round(val))
return val
def test_expo(num,MEAN):
"""
test the curvyness
"""
f = []
while num > 0:
f.append(expo(MEAN))
num = num -1
return f
def frecency():
"""
calculate an exponential frecency value
"""
MEAN = 146 # 146 is our mean value, because ddahl's is 146
lambd = 1.0 / MEAN # the lambda value for the random generator
val = random.expovariate(lambd)
if val < 1:
# flip a coin:
if random.randint(0, 1) == 0:
return 0
else:
return -1
f_ceil = ceil(val)
return f_ceil
def test_frecency(num):
frec_list = []
while num > 0:
frec_list.append(frecency())
num = num - 1
frec_list.sort()
return frec_list
def flip_coin():
return random.randint(0,1)
def slant(rows,heads):
"""
slant the coin toss to a percentage
"""
results = []
num_heads = round(int(rows * heads))
num_tails = rows - num_heads
while num_heads > 0:
results.append(1)
num_heads = num_heads - 1
while num_tails > 0:
results.append(0)
num_tails = num_tails - 1
return results
def flip_coin_slant(rows,heads):
results = slant(rows,heads)
def fcs():
for r in results:
yield r
return fcs
def last_time_run():
"""
Use get_or_create to make/get a url that keeps track of when this operation was last run on the database
returns date in microseconds of when this place was last updated
"""
my_url = "http://mozilla.com/places_test_placeholder"
my_title = "Places Testing Placeholder"
p, created = place = MozPlaces.objects.get_or_create(url=my_url,title=my_title,rev_host=reverse_host(my_url),visit_count=1,hidden=0,typed=1,frecency=-1)
sql = """select id from moz_places where title = 'Places Testing Placeholder'"""
cursor = connection.cursor()
rows = cursor.execute(sql)
id = rows.fetchall()[0][0]
# insert the latest record into historyvisits
sql = """INSERT INTO moz_historyvisits (from_visit, place_id, visit_date, visit_type, session ) VALUES (0, %s, %s, 1, 0 )""" % (int(id), right_now(),)
cursor.execute(sql)
transaction.commit_unless_managed()
sql = """SELECT visit_date FROM moz_historyvisits WHERE place_id = %s ORDER BY id DESC""" % id
rows = cursor.execute(sql)
_rows = rows.fetchall()
visit_date = _rows[0][0]
return visit_date
def new_place(places_typed_gen):
"""
create a new place
"""
guid = uuid.generate()
parts = url_parts()
my_url = '%s://%s.%s.%s/%s' % (parts['proto'],
parts['host'],
parts['domain'],
parts['tld'],
guid)
if DEBUG:
print my_url
my_title = new_title()
frec = frecency()
try:
place = MozPlaces(
url=my_url,
title=my_title,
rev_host=reverse_host(my_url),
visit_count=expo(8), # using 8 for MEAN for the fun of it for now
hidden=0,
typed=places_typed_gen.next(),
favicon=new_favicon(),
frecency=frec)
place.save()
p = MozPlaces.objects.filter(rev_host=place.rev_host)[0]
return p
except Exception, e:
print e
raise
def new_inputhistory(place):
"""
create an inputhistory record for the place object passed in
"""
input_len = random.randint(3,20)
ih = "".join(random.sample(ALPHA,input_len))
ih_multi = random.randint(2,9)
uc = ih_multi * 0.9
inp_hist = MozInputhistory(place_id=place.id,input=ih,use_count=uc)
inp_hist.save()
return inp_hist
def new_history(place,qty=5):
"""
create a history record
"""
rndm_date = random_date()
try:
while qty > 0:
history = MozHistoryvisits.objects.create(
from_visit=0, # other visit this is related to/from/etc
place=place,
visit_date=rndm_date,
visit_type=1,
session=0
)
qty = qty -1
except:
print "ERROR: cannot create historyvisit for %s" % str(place.id)
raise
def new_bookmark(place,kw_gen):
"""
make a bookmark item
"""
try:
k_obj = kw_gen.next()
except Exception, e:
print str(e)
k_obj = None
try:
bookmark = MozBookmarks.objects.create(
_type=1, # XXX: what should this be?
fk=place.id,
parent=5, # XXX: what is unfiled bookmarks id?
position=-1, # XXX: what should this be?
title=place.title,
folder_type=1, # XXX: what should this be?
dateadded=random_date(),
lastmodified=random_date(),
keyword=k_obj
)
return bookmark
except Exception, e:
print str(e)
print "Err: Could not create bookmark from place: %s" % place.id
def parse_places_stats_obj(obj,source_idx):
"""
Parse and massage the input for the places generator
"""
class Options(object):
def __init__(self,stats_obj,source_idx):
# XXX: check names in json obj
self.source = 'places_stats_site'
self.path = None
self.source_idx = source_idx
src_obj = stats_obj[source_idx]
self.n_places = int(float(stats_obj[source_idx]['moz_places_cnt']))
self.h_mult = int(float(stats_obj[source_idx]['moz_historyvisits_cnt']) / float(stats_obj[source_idx]['moz_places_cnt']))
self.b_mod = int(float(stats_obj[source_idx]['moz_places_cnt']) / float(stats_obj[source_idx]['moz_bookmarks_cnt']))
kw_count = int(float(stats_obj[source_idx]['moz_keywords_cnt']))
bm_count = int(float(stats_obj[source_idx]['moz_bookmarks_cnt']))
self.n_keywords = kw_count
self.n_inputhistory = \
int(float(stats_obj[source_idx]['moz_inputhistory_cnt']))
if DEBUG:
print "########################################################"
print "Creating %s Places" % self.n_places
print "Creating about %s History Visits" % stats_obj[source_idx]['moz_historyvisits_cnt']
print "Creating about %s Bookmarks" % stats_obj[source_idx]['moz_bookmarks_cnt']
print "Creating %s Keywords" % self.n_keywords
print "Creating %s Input History Records" % self.n_inputhistory
print "########################################################"
else:
print "Starting Places DB Generation"
time.sleep(3)
options = Options(obj,source_idx)
return options
def main(source,
source_idx,
num_places,
bookmarks_mod,
history_mult,
n_keywords,
n_inputhistory,
path,
debug):
"""
configure and run the whole operation of creating data in places.sqlite
"""
DEBUG = False
if debug:
DEBUG = True
if path:
os.environ['PLACES_DB_PATH'] = path
counter = 1
if DEBUG:
print "Creating %s Places" % num_places
PERCENT_PLACES_TYPED = 0.3
kw_gen = keyword_gen(n_keywords)
places_typed_gen = flip_coin_slant(num_places,PERCENT_PLACES_TYPED)()
while num_places > 0:
if DEBUG:
print 'Place #%s created' % counter
place = new_place(places_typed_gen) # create a place
if n_inputhistory > 0:
inp_hist = new_inputhistory(place)
n_inputhistory = n_inputhistory - 1
history = new_history(place) # create 5 history records
if num_places % bookmarks_mod == 0:
nb = new_bookmark(place,kw_gen) # create a bookmark
num_places = num_places - 1
counter = counter + 1
# update the time this was last run. The value is stored in a
# moz_historyvisits row as 'visit_date' for the place with the
# uri of "http://mozilla.com/places_test_placeholder'
if DEBUG:
print "Updating last time run timestamp"
try:
last_time_run()
except Exception, e:
print e
raise
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-p", "--path", dest="path", default=None,
help="Path to SQLite db", metavar="PATH")
parser.add_option("-s", "--source",
dest="source",
default='places_stats_site',
help="'made_up' data or 'places_stats_site' data?",
metavar="SOURCE")
parser.add_option("-i", "--source_idx", dest="source_idx",
default='max',
help="Source object index: avg, min, max",
metavar="SOURCE_IDX")
parser.add_option("-n", "--num-places", dest="n_places", default=300,
help="Number of Places to create",
metavar="NUM_PLACES")
parser.add_option("-b", "--bookmarks-modulus", dest="b_mod", default=4,
help="Bookmarks Modulus, the number of places for which a single bookmark is created",
metavar="BOOKMARKS_MODULUS")
parser.add_option("-k", "--num-keywords", dest="n_keywords", default=15,
help="Number of total Keywords",
metavar="KEYWORDS")
parser.add_option("-t", "--input-history", dest="n_inputhistory", default=50,
help="Number of Input History rows",
metavar="INPUT_HISTORY")
parser.add_option("-m", "--history-mult", dest="h_mult", default=5,
help="The number of history items to create for each place", metavar="HISTORY_MULT")
parser.add_option("-v", action="store_true", dest="debug",
default=True, help="Turn DEBUG on")
parser.add_option("-q", action="store_false", dest="debug",
default=False, help="Turn DEBUG off")
(options, args) = parser.parse_args()
if options.source == 'places_stats_site':
cmd_line_options = options
stats_obj = get_web_data()
options = parse_places_stats_obj(stats_obj,
cmd_line_options.source_idx)
options.path = cmd_line_options.path
options.debug = cmd_line_options.debug
KEYWORD_COUNT = 0
KEYWORD_IDS = []
main(options.source,
options.source_idx,
options.n_places,
int(options.b_mod),
int(options.h_mult),
options.n_keywords,
options.n_inputhistory,
options.path,
options.debug)