/
db.py
1580 lines (1354 loc) · 72.1 KB
/
db.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
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from collections import defaultdict
from copy import copy
from os import path
import pprint
import re
import simplejson as json
import sys
import time
from sqlalchemy import Table, Column, Integer, Text, String, MetaData, \
create_engine, select, BigInteger, Boolean, join
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.sql.expression import null
import migrate.versioning.schema
import migrate.versioning.api
import dictdiffer
import dictdiffer.merge
from auslib.global_state import cache, dbo
from auslib.AUS import isForbiddenUrl
from auslib.blobs.base import createBlob
from auslib.util.comparison import string_compare, version_compare
import logging
def rowsToDicts(fn):
"""Decorator that converts the result of any function returning a dict-like
object to an actual dict. Eg, converts read-only row objects to writable
dicts."""
def convertRows(*args, **kwargs):
ret = []
for row in fn(*args, **kwargs):
d = {}
for key in row.keys():
d[key] = row[key]
ret.append(d)
return ret
return convertRows
class AlreadySetupError(Exception):
def __str__(self):
return "Can't connect to new database, still connected to previous one"
class PermissionDeniedError(Exception):
pass
class TransactionError(SQLAlchemyError):
"""Raised when a transaction fails for any reason."""
class OutdatedDataError(SQLAlchemyError):
"""Raised when an update or delete fails because of outdated data."""
class WrongNumberOfRowsError(SQLAlchemyError):
"""Raised when an update or delete fails because the clause matches more than one row."""
class ReadOnlyError(SQLAlchemyError):
"""Raised when a release marked as read-only is attempted to be changed."""
class AUSTransaction(object):
"""Manages a single transaction. Requires a connection object.
@param conn: connection object to perform the transaction on
@type conn: sqlalchemy.engine.base.Connection
"""
def __init__(self, engine):
self.engine = engine
self.conn = self.engine.connect()
self.trans = self.conn.begin()
self.log = logging.getLogger(self.__class__.__name__)
def __enter__(self):
return self
def __exit__(self, *exc):
try:
# If something that executed in the context raised an Exception,
# rollback and re-raise it.
self.log.debug("exc is:", exc_info=True)
if exc[0]:
self.rollback()
raise exc[0], exc[1], exc[2]
# Also need to check for exceptions during commit!
try:
self.commit()
except:
self.rollback()
raise
finally:
# Always make sure the connection is closed, bug 740360
self.close()
def close(self):
# For some reason, sometimes the connection appears to close itself...
if not self.conn.closed:
self.conn.close()
def execute(self, statement):
try:
self.log.debug("Attempting to execute %s" % statement)
return self.conn.execute(statement)
except:
self.log.debug("Caught exception")
# We want to raise our own Exception, so that errors are easily
# caught by consumers. The dance below lets us do that without
# losing the original Traceback, which will be much more
# informative than one starting from this point.
klass, e, tb = sys.exc_info()
self.rollback()
e = TransactionError(e.args)
raise TransactionError, e, tb
def commit(self):
try:
self.trans.commit()
except:
klass, e, tb = sys.exc_info()
self.rollback()
e = TransactionError(e.args)
raise TransactionError, e, tb
def rollback(self):
self.trans.rollback()
class AUSTable(object):
"""Base class for all AUS Tables. By default, all tables have a history
table created for them, too, which mirrors their own structure and adds
a record of who made a change, and when the change happened.
@param history: Whether or not to create a history table for this table.
When True, a History object will be created for this
table, and all changes will be logged to it. Defaults
to True.
@type history: bool
@param versioned: Whether or not this table is versioned. When True,
an additional 'data_version' column will be added
to the Table, and its version increased with every
update. This is useful for detecting colliding
updates.
@type versioned: bool
@param onInsert: A callback that will be called whenever an insert is
made to the table. It must accept the following 4
parameters:
* The table object the query is being performed on
* The type of query being performed (eg: INSERT)
* The name of the user making the change
* The query object that will be execeuted
If the callback raises an exception the change will
be aborted.
@type onInsert: callable
@param onDelete: See onInsert
@type onDelete: callable
@param onUpdate: See onInsert
@type onUpdate: callable
"""
def __init__(self, dialect, history=True, versioned=True, onInsert=None,
onUpdate=None, onDelete=None):
self.t = self.table
# Enable versioning, if required
if versioned:
self.t.append_column(Column('data_version', Integer, nullable=False))
self.versioned = versioned
self.onInsert = onInsert
self.onUpdate = onUpdate
self.onDelete = onDelete
# Mirror the columns as attributes for easy access
self.primary_key = []
for col in self.table.get_children():
setattr(self, col.name, col)
if col.primary_key:
self.primary_key.append(col)
# Set-up a history table to do logging in, if required
if history:
self.history = History(dialect, self.t.metadata, self)
else:
self.history = None
self.log = logging.getLogger(self.__class__.__name__)
# Can't do this in the constructor, because the engine is always
# unset when we're instantiated
def getEngine(self):
return self.t.metadata.bind
def _returnRowOrRaise(self, where, columns=None, transaction=None):
"""Return the row matching the where clause supplied. If no rows match or multiple rows match,
a WrongNumberOfRowsError will be raised."""
rows = self.select(where=where, columns=columns, transaction=transaction)
if len(rows) == 0:
raise WrongNumberOfRowsError("where clause matched no rows")
if len(rows) > 1:
raise WrongNumberOfRowsError("where clause matches multiple rows (primary keys: %s)" % rows)
return rows[0]
def _selectStatement(self, columns=None, where=None, order_by=None, limit=None, offset=None, distinct=False):
"""Create a SELECT statement on this table.
@param columns: Column objects to select. Defaults to None, meaning select all columns
@type columns: A sequence of sqlalchemy.schema.Column objects or column names as strings
@param where: Conditions to apply on this select. Defaults to None, meaning no conditions
@type where: A sequence of sqlalchemy.sql.expression.ClauseElement objects
@param order_by: Columns to sort the rows by. Defaults to None, meaning no ORDER BY clause
@type order_by: A sequence of sqlalchemy.schema.Column objects
@param limit: Limit results to this many. Defaults to None, meaning no limit
@type limit: int
@param distinct: Whether or not to return only distinct rows. Default: False.
@type distinct: bool
@rtype: sqlalchemy.sql.expression.Select
"""
if columns:
query = select(columns, order_by=order_by, limit=limit, offset=offset, distinct=distinct)
else:
query = self.t.select(order_by=order_by, limit=limit, offset=offset, distinct=distinct)
if where:
for cond in where:
query = query.where(cond)
return query
@rowsToDicts
def select(self, transaction=None, **kwargs):
"""Perform a SELECT statement on this table.
See AUSTable._selectStatement for possible arguments.
@rtype: sqlalchemy.engine.base.ResultProxy
"""
query = self._selectStatement(**kwargs)
if transaction:
return transaction.execute(query).fetchall()
else:
return query.execute().fetchall()
def _insertStatement(self, **columns):
"""Create an INSERT statement for this table
@param columns: Data to insert
@type colmuns: dict
@rtype: sqlalchemy.sql.express.Insert
"""
return self.t.insert(values=columns)
def _prepareInsert(self, trans, changed_by, **columns):
"""Prepare an INSERT statement for commit. If this table has versioning enabled,
data_version will be set to 1. If this table has history enabled, two rows
will be created in that table: one representing the current state (NULL),
and one representing the new state.
@rtype: sqlalchemy.engine.base.ResultProxy
"""
data = columns.copy()
if self.versioned:
data['data_version'] = 1
query = self._insertStatement(**data)
if self.onInsert:
self.onInsert(self, "INSERT", changed_by, query)
ret = trans.execute(query)
if self.history:
for q in self.history.forInsert(ret.inserted_primary_key, data, changed_by):
trans.execute(q)
return ret
def insert(self, changed_by=None, transaction=None, **columns):
"""Perform an INSERT statement on this table. See AUSTable._insertStatement for
a description of columns.
@param changed_by: The username of the person inserting the row. Required when
history is enabled. Unused otherwise. No authorization checks are done
at this level.
@type changed_by: str
@param transaction: A transaction object to add the insert statement (and history changes) to.
If provided, you must commit the transaction yourself. If None, they will
be added to a locally-scoped transaction and committed.
@rtype: sqlalchemy.engine.base.ResultProxy
"""
if self.history and not changed_by:
raise ValueError("changed_by must be passed for Tables that have history")
if transaction:
return self._prepareInsert(transaction, changed_by, **columns)
else:
with AUSTransaction(self.getEngine()) as trans:
return self._prepareInsert(trans, changed_by, **columns)
def _deleteStatement(self, where):
"""Create a DELETE statement for this table.
@param where: Conditions to apply on this select.
@type where: A sequence of sqlalchemy.sql.expression.ClauseElement objects
@rtype: sqlalchemy.sql.expression.Delete
"""
query = self.t.delete()
if where:
for cond in where:
query = query.where(cond)
return query
def _prepareDelete(self, trans, where, changed_by, old_data_version):
"""Prepare a DELETE statament for commit. If this table has history enabled,
a row will be created in that table representing the new state of the
row being deleted (NULL). If versioning is enabled and old_data_version
doesn't match the current version of the row to be deleted, an OutdatedDataError
will be raised.
@rtype: sqlalchemy.engine.base.ResultProxy
"""
row = self._returnRowOrRaise(where=where, columns=self.primary_key, transaction=trans)
if self.versioned:
where = copy(where)
where.append(self.data_version == old_data_version)
query = self._deleteStatement(where)
if self.onDelete:
self.onDelete(self, "DELETE", changed_by, query)
ret = trans.execute(query)
if ret.rowcount != 1:
raise OutdatedDataError("Failed to delete row, old_data_version doesn't match current data_version")
if self.history:
trans.execute(self.history.forDelete(row, changed_by))
return ret
def delete(self, where, changed_by=None, old_data_version=None, transaction=None):
"""Perform a DELETE statement on this table. See AUSTable._deleteStatement for
a description of `where'. To simplify versioning, this method can only
delete a single row per invocation. If the where clause given would delete
zero or multiple rows, a WrongNumberOfRowsError is raised.
@param changed_by: The username of the person deleting the row(s). Required when
history is enabled. Unused otherwise. No authorization checks are done
at this level.
@type changed_by: str
@param old_data_version: Previous version of the row to be deleted. If this version doesn't
match the current version of the row, an OutdatedDataError will be
raised and the delete will fail. Required when versioning is enabled.
@type old_data_version: int
@rtype: sqlalchemy.engine.base.ResultProxy
"""
if self.history and not changed_by:
raise ValueError("changed_by must be passed for Tables that have history")
if self.versioned and not old_data_version:
raise ValueError("old_data_version must be passed for Tables that are versioned")
if transaction:
return self._prepareDelete(transaction, where, changed_by, old_data_version)
else:
with AUSTransaction(self.getEngine()) as trans:
return self._prepareDelete(trans, where, changed_by, old_data_version)
def _updateStatement(self, where, what):
"""Create an UPDATE statement for this table
@param where: Conditions to apply to this UPDATE.
@type where: A sequence of sqlalchemy.sql.expression.ClauseElement objects.
@param what: Data to update
@type what: dict
@rtype: sqlalchemy.sql.expression.Update
"""
query = self.t.update(values=what)
if where:
for cond in where:
query = query.where(cond)
return query
def _prepareUpdate(self, trans, where, what, changed_by, old_data_version):
"""Prepare an UPDATE statement for commit. If this table has versioning enabled,
data_version will be increased by 1. If this table has history enabled, a
row will be added to that table represent the new state of the data.
@rtype: sqlalchemy.engine.base.ResultProxy
"""
row = self._returnRowOrRaise(where=where, transaction=trans)
if self.versioned:
where = copy(where)
where.append(self.data_version == old_data_version)
row['data_version'] += 1
# Copy the new data into the row
for col in what:
row[col] = what[col]
query = self._updateStatement(where, row)
if self.onUpdate:
self.onUpdate(self, "UPDATE", changed_by, query)
ret = trans.execute(query)
if self.history:
trans.execute(self.history.forUpdate(row, changed_by))
if ret.rowcount != 1:
raise OutdatedDataError("Failed to update row, old_data_version doesn't match current data_version")
return ret
def update(self, where, what, changed_by=None, old_data_version=None, transaction=None):
"""Perform an UPDATE statement on this stable. See AUSTable._updateStatement for
a description of `where' and `what'. This method can only update a single row
per invocation. If the where clause given would update zero or multiple rows, a
WrongNumberOfRowsError is raised.
@param changed_by: The username of the person inserting the row. Required when
history is enabled. Unused otherwise. No authorization checks are done
at this level.
@type changed_by: str
@param old_data_version: Previous version of the row to be deleted. If this version doesn't
match the current version of the row, an OutdatedDataError will be
raised and the delete will fail. Required when versioning is enabled.
@type old_data_version: int
@rtype: sqlalchemy.engine.base.ResultProxy
"""
if self.history and not changed_by:
raise ValueError("changed_by must be passed for Tables that have history")
if self.versioned and not old_data_version:
raise ValueError("update: old_data_version must be passed for Tables that are versioned")
if transaction:
return self._prepareUpdate(transaction, where, what, changed_by, old_data_version)
else:
with AUSTransaction(self.getEngine()) as trans:
return self._prepareUpdate(trans, where, what, changed_by, old_data_version)
def getRecentChanges(self, limit=10, transaction=None):
return self.history.select(transaction=transaction,
limit=limit,
order_by=self.history.timestamp.desc())
class History(AUSTable):
"""Represents a history table that may be attached to another AUSTable.
History tables mirror the structure of their `baseTable', with the exception
that nullable and primary_key attributes are always overwritten to be
True and False respectively. Additionally, History tables have a unique
change_id for each row, and record the username making a change, and the
timestamp of each change. The methods forInsert, forDelete, and forUpdate
will generate appropriate INSERTs to the History table given appropriate
inputs, and are documented below. History tables are never versioned,
and cannot have history of their own."""
def __init__(self, dialect, metadata, baseTable):
self.baseTable = baseTable
self.table = Table('%s_history' % baseTable.t.name, metadata,
Column('change_id', Integer, primary_key=True, autoincrement=True),
Column('changed_by', String(100), nullable=False),
)
# Timestamps are stored as an integer, but actually contain
# precision down to the millisecond, achieved through
# multiplication.
# SQLAlchemy's SQLite dialect doesn't support fully support BigInteger.
# The Column will work, but it ends up being a NullType Column which
# breaks our upgrade unit tests. Because of this, we make sure to use
# a plain Integer column for SQLite. In MySQL, an Integer is
# Integer(11), which is too small for our needs.
if dialect == 'sqlite':
self.table.append_column(Column('timestamp', Integer, nullable=False))
else:
self.table.append_column(Column('timestamp', BigInteger, nullable=False))
self.base_primary_key = [pk.name for pk in baseTable.primary_key]
for col in baseTable.t.get_children():
newcol = col.copy()
if col.primary_key:
newcol.primary_key = False
else:
newcol.nullable = True
self.table.append_column(newcol)
AUSTable.__init__(self, dialect, history=False, versioned=False)
def getTimestamp(self):
t = int(time.time() * 1000)
return t
def forInsert(self, insertedKeys, columns, changed_by):
"""Inserts cause two rows in the History table to be created. The first
one records the primary key data and NULLs for other row data. This
represents that the row did not exist prior to the insert. The
timestamp for this row is 1 millisecond behind the real timestamp to
reflect this. The second row records the full data of the row at the
time of insert."""
primary_key_data = {}
queries = []
for i in range(0, len(self.base_primary_key)):
name = self.base_primary_key[i]
primary_key_data[name] = insertedKeys[i]
# Make sure the primary keys are included in the second row as well
columns[name] = insertedKeys[i]
ts = self.getTimestamp()
queries.append(self._insertStatement(changed_by=changed_by, timestamp=ts - 1, **primary_key_data))
queries.append(self._insertStatement(changed_by=changed_by, timestamp=ts, **columns))
return queries
def forDelete(self, rowData, changed_by):
"""Deletes cause a single row to be created, which only contains the
primary key data. This represents that the row no longer exists."""
row = {}
for k in rowData:
row[str(k)] = rowData[k]
# Tack on history table information to the row
row['changed_by'] = changed_by
row['timestamp'] = self.getTimestamp()
return self._insertStatement(**row)
def forUpdate(self, rowData, changed_by):
"""Updates cause a single row to be created, which contains the full,
new data of the row at the time of the update."""
row = {}
for k in rowData:
row[str(k)] = rowData[k]
row['changed_by'] = changed_by
row['timestamp'] = self.getTimestamp()
return self._insertStatement(**row)
def getChange(self, change_id=None, column_values=None, data_version=None, transaction=None):
""" Returns the unique change that matches the give change_id or
combination of data_version and values for the specified columns.
column_values is a dict that contains the column names that are
versioned and their values.
Ignores non primary key attributes specified in column_values."""
# if change_id is not None, we use it to get the change, ignoring
# data_version and column_values
by_change_id = False if change_id is None else True
# column_names lists all primary keys as string keys with the column
# objects as values
column_names = {col.name: col for col in self.table.columns if col.name in self.base_primary_key}
if not by_change_id:
# we check if the entire primary key is present in column_values,
# since there might be multiple rows that match an incomplete
# primary key
for col in column_names.keys():
if col not in column_values.keys():
raise ValueError("Entire primary key not present")
# data_version can only be queried for versioned tables
if not self.baseTable.versioned:
raise ValueError("data_version queried for non-versioned table")
where = [self.data_version == data_version]
for col in column_names.keys():
where.append(column_names[col] == column_values[col])
changes = self.select(where=where,
transaction=transaction)
else:
changes = self.select(where=[self.change_id == change_id], transaction=transaction)
found = len(changes)
if found > 1 or found == 0:
self.log.debug("Found %s changes, should have been 1", found)
return None
return changes[0]
def getPrevChange(self, change_id, row_primary_keys, transaction=None):
""" Returns the most recent change to a given row in the base table """
where = [self.change_id < change_id]
for i in range(0, len(self.base_primary_key)):
self_prim = getattr(self, self.base_primary_key[i])
where.append((self_prim == row_primary_keys[i]))
changes = self.select(where=where, transaction=transaction, limit=1, order_by=self.change_id.desc())
length = len(changes)
if(length == 0):
self.log.debug("No previous changes found")
return None
return changes[0]
def _stripNullColumns(self, change):
# We know a bunch of columns are going to be empty...easier to strip them out
# than to be super verbose (also should let this test continue to work even
# if the schema changes).
for key in change.keys():
if change[key] is None:
del change[key]
return change
def _stripHistoryColumns(self, change):
""" Will strip history specific columns as well as data_version from the given change """
del change['change_id']
del change['changed_by']
del change['timestamp']
del change['data_version']
return change
def _isNull(self, change, row_primary_keys):
# Define a row that's empty except for the primary keys
# This is what the NULL rows for inserts and deletes will look like.
null_row = dict()
for i in range(0, len(self.base_primary_key)):
null_row[self.base_primary_key[i]] = row_primary_keys[i]
return self._stripNullColumns(change) == null_row
def _isDelete(self, cur_base_state, row_primary_keys):
return self._isNull(cur_base_state.copy(), row_primary_keys)
def _isInsert(self, prev_base_state, row_primary_keys):
return self._isNull(prev_base_state.copy(), row_primary_keys)
def _isUpdate(self, cur_base_state, prev_base_state, row_primary_keys):
return (not self._isNull(cur_base_state.copy(), row_primary_keys)) and (not self._isNull(prev_base_state.copy(), row_primary_keys))
def rollbackChange(self, change_id, changed_by, transaction=None):
""" Rollback the change given by the change_id,
Will handle all cases: insert, delete, update """
change = self.getChange(change_id=change_id, transaction=transaction)
# Get the values of the primary keys for the given row
row_primary_keys = [0] * len(self.base_primary_key)
for i in range(0, len(self.base_primary_key)):
row_primary_keys[i] = change[self.base_primary_key[i]]
# Strip the History Specific Columns from the cahgnes
prev_base_state = self._stripHistoryColumns(self.getPrevChange(change_id, row_primary_keys, transaction))
cur_base_state = self._stripHistoryColumns(change.copy())
# Define a row that's empty except for the primary keys
# This is what the NULL rows for inserts and deletes will look like.
null_row = dict()
for i in range(0, len(self.base_primary_key)):
null_row[self.base_primary_key[i]] = row_primary_keys[i]
# If the row has all NULLS, then the operation we're rolling back is a DELETE
# We need to do an insert, with the data from the previous change
if self._isDelete(cur_base_state, row_primary_keys):
self.log.debug("reverting a DELETE")
self.baseTable.insert(changed_by=changed_by, transaction=transaction, **prev_base_state)
# If the previous change is NULL, then the operation is an INSERT
# We will need to do a delete.
elif self._isInsert(prev_base_state, row_primary_keys):
self.log.debug("reverting an INSERT")
where = []
for i in range(0, len(self.base_primary_key)):
self_prim = getattr(self.baseTable, self.base_primary_key[i])
where.append((self_prim == row_primary_keys[i]))
self.baseTable.delete(changed_by=changed_by, transaction=transaction, where=where, old_data_version=change['data_version'])
elif self._isUpdate(cur_base_state, prev_base_state, row_primary_keys):
# If this operation is an UPDATE
# We will need to do an update to the previous change's state
self.log.debug("reverting an UPDATE")
where = []
for i in range(0, len(self.base_primary_key)):
self_prim = getattr(self.baseTable, self.base_primary_key[i])
where.append((self_prim == row_primary_keys[i]))
what = prev_base_state
old_data_version = change['data_version']
self.baseTable.update(changed_by=changed_by, where=where, what=what, old_data_version=old_data_version, transaction=transaction)
else:
self.log.debug("ERROR, change doesn't correspond to any known operation")
class Rules(AUSTable):
def __init__(self, metadata, dialect):
self.table = Table('rules', metadata,
Column('rule_id', Integer, primary_key=True, autoincrement=True),
Column('alias', String(50), unique=True),
Column('priority', Integer),
Column('mapping', String(100)),
Column('backgroundRate', Integer),
Column('update_type', String(15), nullable=False),
Column('product', String(15)),
Column('version', String(10)),
Column('channel', String(75)),
Column('buildTarget', String(75)),
Column('buildID', String(20)),
Column('locale', String(200)),
Column('osVersion', String(1000)),
Column('systemCapabilities', String(1000)),
Column('distribution', String(100)),
Column('distVersion', String(100)),
Column('headerArchitecture', String(10)),
Column('comment', String(500)),
Column('whitelist', String(100)),
)
AUSTable.__init__(self, dialect)
def _matchesRegex(self, foo, bar):
# Expand wildcards and use ^/$ to make sure we don't succeed on partial
# matches. Eg, 3.6* matches 3.6, 3.6.1, 3.6b3, etc.
test = foo.replace('.', '\.').replace('*', '.*')
test = '^%s$' % test
if re.match(test, bar):
return True
return False
def _channelMatchesRule(self, ruleChannel, queryChannel, fallbackChannel):
"""Decides whether a channel from the rules matches an incoming one.
If the ruleChannel is null, we match any queryChannel. We also match
if the channels match exactly, or match after wildcards in ruleChannel
are resolved. Channels may have a fallback specified, too, so we must
check if the fallback version of the queryChannel matches the ruleChannel."""
if ruleChannel is None:
return True
if self._matchesRegex(ruleChannel, queryChannel):
return True
if self._matchesRegex(ruleChannel, fallbackChannel):
return True
def _matchesList(self, ruleString, queryString):
"""Decides whether a ruleString from a rule matches an incoming string.
The rule may specify multiple matches, delimited by a comma. Once
split we look for an exact match against the string from the queries.
We want an exact match so (eg) we only get the locales we specify"""
if ruleString is None:
return True
for subString in ruleString.split(','):
if subString == queryString:
return True
def _versionMatchesRule(self, ruleVersion, queryVersion):
"""Decides whether a version from the rules matches an incoming version.
If the ruleVersion is null, we match any queryVersion. If it's not
null, we must either match exactly, or match a comparison operator."""
self.log.debug('ruleVersion: %s, queryVersion: %s', ruleVersion, queryVersion)
if ruleVersion is None:
return True
return version_compare(queryVersion, ruleVersion)
def _buildIDMatchesRule(self, ruleBuildID, queryBuildID):
"""Decides whether a buildID from the rules matches an incoming one.
If the ruleBuildID is null, we match any queryBuildID. If it's not
null, we must either match exactly, or match with a camparison
operator."""
if ruleBuildID is None:
return True
return string_compare(queryBuildID, ruleBuildID)
def _csvMatchesRule(self, ruleString, queryString, substring=True):
"""Decides whether a column from a rule matches an incoming one.
Some columns in a rule may specify multiple values delimited by a
comma. Once split we do a full or substring match against the query
string. Because we support substring matches, there's no need
to support globbing as well."""
if ruleString is None:
return True
for part in ruleString.split(','):
if substring and part in queryString:
return True
elif part == queryString:
return True
return False
def _localeMatchesRule(self, ruleLocales, queryLocale):
"""Decides if a comma seperated list of locales in a rule matches an
update request"""
return self._matchesList(ruleLocales, queryLocale)
def _isAlias(self, id_or_alias):
if re.match("^[a-zA-Z][a-zA-Z0-9-]*$", str(id_or_alias)):
return True
return False
def addRule(self, changed_by, what, transaction=None):
ret = self.insert(changed_by=changed_by, transaction=transaction, **what)
return ret.inserted_primary_key[0]
def getOrderedRules(self, transaction=None):
"""Returns all of the rules, sorted in ascending order"""
return self.select(order_by=(self.priority, self.version, self.mapping), transaction=transaction)
def countRules(self, transaction=None):
"""Returns a number of the count of rules"""
count, = self.t.count().execute().fetchone()
return count
def getRulesMatchingQuery(self, updateQuery, fallbackChannel, transaction=None):
"""Returns all of the rules that match the given update query.
For cases where a particular updateQuery channel has no
fallback, fallbackChannel should match the channel from the query."""
def getRawMatches():
where = [
((self.product == updateQuery['product']) | (self.product == null())) &
((self.buildTarget == updateQuery['buildTarget']) | (self.buildTarget == null())) &
((self.headerArchitecture == updateQuery['headerArchitecture']) | (self.headerArchitecture == null()))
]
# Query version 2 doesn't have distribution information, and to keep
# us maximally flexible, we won't match any rules that have
# distribution update set.
if updateQuery['queryVersion'] == 2:
where.extend([(self.distribution == null()) & (self.distVersion == null())])
# Only query versions 3 and 4 have distribution information, so we
# need to consider it.
if updateQuery['queryVersion'] in (3, 4):
where.extend([
((self.distribution == updateQuery['distribution']) | (self.distribution == null())) &
((self.distVersion == updateQuery['distVersion']) | (self.distVersion == null()))
])
if not updateQuery['force']:
where.append(self.backgroundRate > 0)
self.log.debug("where: %s" % where)
return self.select(where=where, transaction=transaction)
# This cache key is constructed from all parts of the updateQuery that
# are used in the select() to get the "raw" rule matches. For the most
# part, product and buildTarget will be the only applicable ones which
# means we should get very high cache hit rates, as there's not a ton
# of variability of possible combinations for those.
cache_key = "%s:%s:%s:%s:%s:%s" % \
(updateQuery["product"], updateQuery["buildTarget"], updateQuery["headerArchitecture"],
updateQuery.get("distribution"), updateQuery.get("distVersion"), updateQuery["force"])
rules = cache.get("rules", cache_key, getRawMatches)
self.log.debug("Raw matches:")
matchingRules = []
for rule in rules:
self.log.debug(rule)
# Resolve special means for channel, version, and buildID - dropping
# rules that don't match after resolution.
if not self._channelMatchesRule(rule['channel'], updateQuery['channel'], fallbackChannel):
self.log.debug("%s doesn't match %s", rule['channel'], updateQuery['channel'])
continue
if not self._versionMatchesRule(rule['version'], updateQuery['version']):
self.log.debug("%s doesn't match %s", rule['version'], updateQuery['version'])
continue
if not self._buildIDMatchesRule(rule['buildID'], updateQuery['buildID']):
self.log.debug("%s doesn't match %s", rule['buildID'], updateQuery['buildID'])
continue
# To help keep the rules table compact, multiple OS versions may be
# specified in a single rule. They are comma delimited, so we need to
# break them out and create clauses for each one.
if not self._csvMatchesRule(rule['osVersion'], updateQuery['osVersion']):
self.log.debug("%s doesn't match %s", rule['osVersion'], updateQuery['osVersion'])
continue
# Same deal for system capabilities
if not self._csvMatchesRule(rule['systemCapabilities'], updateQuery.get('systemCapabilities', ""), substring=False):
self.log.debug("%s doesn't match %s", rule['systemCapabilities'], updateQuery.get('systemCapabilities'))
continue
# Locales may be a comma delimited rule too, exact matches only
if not self._localeMatchesRule(rule['locale'], updateQuery['locale']):
self.log.debug("%s doesn't match %s", rule['locale'], updateQuery['locale'])
continue
# If a rule has a whitelist attached to it, the rule is only
# considered "matching" if it passes the whitelist check.
# The decision about matching or not is delegated to the whitelist blob.
if rule.get("whitelist"):
self.log.debug("Matching rule requires a whitelist")
try:
whitelist = dbo.releases.getReleaseBlob(name=rule["whitelist"], transaction=transaction)
if whitelist and not whitelist.shouldServeUpdate(updateQuery):
continue
# It shouldn't be possible for the whitelist blob not to exist,
# but just in case...
except KeyError:
self.log.warning("Got exeception when looking for whitelist blob %s", rule["whitelist"], exc_info=True)
matchingRules.append(rule)
self.log.debug("Reduced matches:")
if self.log.isEnabledFor(logging.DEBUG):
for r in matchingRules:
self.log.debug(r)
return matchingRules
def getRule(self, id_or_alias, transaction=None):
""" Returns the unique rule that matches the give rule_id or alias."""
where = []
# Figuring out which column to use ahead of times means there's only
# one potential index for the database to use, which should make
# queries faster (it will always use the most efficient one).
if self._isAlias(id_or_alias):
where.append(self.alias == id_or_alias)
else:
where.append(self.rule_id == id_or_alias)
rules = self.select(where=where, transaction=transaction)
found = len(rules)
if found > 1 or found == 0:
self.log.debug("Found %s rules, should have been 1", found)
return None
return rules[0]
def updateRule(self, changed_by, id_or_alias, what, old_data_version, transaction=None):
""" Update the rule given by rule_id or alias with the parameter what """
where = []
if self._isAlias(id_or_alias):
where.append(self.alias == id_or_alias)
else:
where.append(self.rule_id == id_or_alias)
self.update(changed_by=changed_by, where=where, what=what, old_data_version=old_data_version, transaction=transaction)
def deleteRule(self, changed_by, id_or_alias, old_data_version, transaction=None):
where = []
if self._isAlias(id_or_alias):
where.append(self.alias == id_or_alias)
else:
where.append(self.rule_id == id_or_alias)
self.delete(changed_by=changed_by, where=where, old_data_version=old_data_version, transaction=transaction)
class Releases(AUSTable):
def __init__(self, metadata, dialect):
self.domainWhitelist = []
self.table = Table('releases', metadata,
Column('name', String(100), primary_key=True),
Column('product', String(15), nullable=False),
Column('read_only', Boolean, default=False),
)
if dialect == 'mysql':
from sqlalchemy.dialects.mysql import LONGTEXT
dataType = LONGTEXT
else:
dataType = Text
self.table.append_column(Column('data', dataType, nullable=False))
AUSTable.__init__(self, dialect)
def setDomainWhitelist(self, domainWhitelist):
self.domainWhitelist = domainWhitelist
# TODO: This should really be part of the blob class(es) because it depends
# on a lot of blob schema specific stuff.
def containsForbiddenDomain(self, data, product):
"""Returns True if "data" contains any file URLs that contain a
domain that we're not allowed to serve updates to."""
# Check the top level URLs, if the exist.
for c in data.get('fileUrls', {}).values():
# New-style
if isinstance(c, dict):
for from_ in c.values():
for url in from_.values():
if isForbiddenUrl(url, product, self.domainWhitelist):
return True
# Old-style
else:
if isForbiddenUrl(c, product, self.domainWhitelist):
return True
# And also the locale-level URLs.
for platform in data.get('platforms', {}).values():
for locale in platform.get('locales', {}).values():
for type_ in ('partial', 'complete'):
if type_ in locale and 'fileUrl' in locale[type_]:
if isForbiddenUrl(locale[type_]['fileUrl'], product, self.domainWhitelist):
return True
for type_ in ('partials', 'completes'):
for update in locale.get(type_, {}):
if 'fileUrl' in update:
if isForbiddenUrl(update["fileUrl"], product, self.domainWhitelist):
return True
return False
def getReleases(self, name=None, product=None, limit=None, transaction=None):
self.log.debug("Looking for releases with:")
self.log.debug("name: %s", name)
self.log.debug("product: %s", product)
where = []
if name:
where.append(self.name == name)
if product:
where.append(self.product == product)
# We could get the "data" column here too, but getReleaseBlob knows how
# to grab cached versions of that, so it's better to let it take care
# of it.
rows = self.select(columns=[self.name, self.product, self.data_version],
where=where, limit=limit, transaction=transaction)
for row in rows:
row["data"] = self.getReleaseBlob(row["name"], transaction)
return rows
def countReleases(self, transaction=None):
"""Returns a number of the count of releases"""
count, = self.t.count().execute().fetchone()
return count
def getReleaseInfo(self, product=None, limit=None,
transaction=None, nameOnly=False, name_prefix=None):
where = []
if product:
where.append(self.product == product)
if name_prefix:
where.append(self.name.startswith(name_prefix))
if nameOnly: