This repository has been archived by the owner on Feb 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 136
/
sql.py
8507 lines (6797 loc) · 276 KB
/
sql.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
# -*- test-case-name: txdav.caldav.datastore.test.test_sql,txdav.carddav.datastore.test.test_sql -*-
##
# Copyright (c) 2010-2014 Apple Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
##
"""
SQL data store.
"""
__all__ = [
"CommonDataStore",
"CommonStoreTransaction",
"CommonHome",
]
from cStringIO import StringIO
from pycalendar.datetime import DateTime
from twext.enterprise.dal.syntax import (
Delete, utcNowSQL, Union, Insert, Len, Max, Parameter, SavepointAction,
Select, Update, ColumnSyntax, TableSyntax, Upper, Count, ALL_COLUMNS, Sum,
DatabaseLock, DatabaseUnlock)
from twext.enterprise.ienterprise import AlreadyFinishedError
from twext.enterprise.jobqueue import LocalQueuer
from twext.enterprise.util import parseSQLTimestamp
from twext.internet.decorate import memoizedKey, Memoizable
from twext.python.clsprop import classproperty
from twext.python.log import Logger
from txweb2.http_headers import MimeType
from twisted.application.service import Service
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, returnValue, succeed
from twisted.python import hashlib
from twisted.python.failure import Failure
from twisted.python.modules import getModule
from twisted.python.util import FancyEqMixin
from twistedcaldav.config import config
from twistedcaldav.dateops import datetimeMktime, pyCalendarTodatetime
from txdav.base.datastore.util import QueryCacher
from txdav.base.datastore.util import normalizeUUIDOrNot
from txdav.base.propertystore.base import PropertyName
from txdav.base.propertystore.none import PropertyStore as NonePropertyStore
from txdav.base.propertystore.sql import PropertyStore
from txdav.caldav.icalendarstore import ICalendarTransaction, ICalendarStore
from txdav.carddav.iaddressbookstore import IAddressBookTransaction
from txdav.common.datastore.common import HomeChildBase
from txdav.common.datastore.podding.conduit import PoddingConduit
from txdav.common.datastore.sql_tables import _BIND_MODE_DIRECT, \
_BIND_MODE_INDIRECT, _BIND_MODE_OWN, _BIND_STATUS_ACCEPTED, \
_BIND_STATUS_DECLINED, _BIND_STATUS_DELETED, _BIND_STATUS_INVALID, \
_BIND_STATUS_INVITED, _HOME_STATUS_EXTERNAL, _HOME_STATUS_NORMAL, \
_HOME_STATUS_PURGING, schema, splitSQLString
from txdav.common.icommondatastore import ConcurrentModification, \
RecordNotAllowedError, ExternalShareFailed, ShareNotAllowed, \
IndexedSearchException, NotFoundError
from txdav.common.icommondatastore import HomeChildNameNotAllowedError, \
HomeChildNameAlreadyExistsError, NoSuchHomeChildError, \
ObjectResourceNameNotAllowedError, ObjectResourceNameAlreadyExistsError, \
NoSuchObjectResourceError, AllRetriesFailed, InvalidSubscriptionValues, \
InvalidIMIPTokenValues, TooManyObjectResourcesError, \
SyncTokenValidException
from txdav.common.idirectoryservice import IStoreDirectoryService, \
DirectoryRecordNotFoundError
from txdav.common.inotifications import INotificationCollection, \
INotificationObject
from txdav.idav import ChangeCategory
from txdav.who.delegates import Delegates
from txdav.xml import element
from uuid import uuid4, UUID
from zope.interface import implements, directlyProvides
from collections import namedtuple
import datetime
import inspect
import itertools
import json
import sys
import time
current_sql_schema = getModule(__name__).filePath.sibling("sql_schema").child("current.sql").getContent()
log = Logger()
ECALENDARTYPE = 0
EADDRESSBOOKTYPE = 1
ENOTIFICATIONTYPE = 2
# Labels used to identify the class of resource being modified, so that
# notification systems can target the correct application
NotifierPrefixes = {
ECALENDARTYPE: "CalDAV",
EADDRESSBOOKTYPE: "CardDAV",
}
class CommonDataStore(Service, object):
"""
Shared logic for SQL-based data stores, between calendar and addressbook
storage.
@ivar sqlTxnFactory: A 0-arg factory callable that produces an
L{IAsyncTransaction}.
@ivar _notifierFactories: a C{dict} of L{IStoreNotifierFactory} objects
from which the store can create notifiers for store objects. The keys
are "tokens" that determine the type of notifier.
@ivar attachmentsPath: a L{FilePath} indicating a directory where
attachments may be stored.
@ivar enableCalendars: a boolean, C{True} if this data store should provide
L{ICalendarStore}, C{False} if not.
@ivar enableAddressBooks: a boolean, C{True} if this data store should
provide L{IAddressbookStore}, C{False} if not.
@ivar label: A string, used for tagging debug messages in the case where
there is more than one store. (Useful mostly for unit tests.)
@ivar quota: the amount of space granted to each calendar home (in bytes)
for storing attachments, or C{None} if quota should not be enforced.
@type quota: C{int} or C{NoneType}
@ivar queuer: An object with an C{enqueueWork} method, from
L{twext.enterprise.jobqueue}. Initially, this is a L{LocalQueuer}, so it
is always usable, but in a properly configured environment it will be
upgraded to a more capable object that can distribute work throughout a
cluster.
"""
implements(ICalendarStore)
def __init__(
self,
sqlTxnFactory,
notifierFactories,
directoryService,
attachmentsPath,
attachmentsURIPattern,
enableCalendars=True,
enableAddressBooks=True,
enableManagedAttachments=True,
label="unlabeled",
quota=(2 ** 20),
logLabels=False,
logStats=False,
logStatsLogFile=None,
logSQL=False,
logTransactionWaits=0,
timeoutTransactions=0,
cacheQueries=True,
cachePool="Default",
cacheExpireSeconds=3600
):
assert enableCalendars or enableAddressBooks
self.sqlTxnFactory = sqlTxnFactory
self._notifierFactories = notifierFactories if notifierFactories is not None else {}
self._directoryService = IStoreDirectoryService(directoryService) if directoryService is not None else None
self.attachmentsPath = attachmentsPath
self.attachmentsURIPattern = attachmentsURIPattern
self.enableCalendars = enableCalendars
self.enableAddressBooks = enableAddressBooks
self.enableManagedAttachments = enableManagedAttachments
self.label = label
self.quota = quota
self.logLabels = logLabels
self.logStats = logStats
self.logStatsLogFile = logStatsLogFile
self.logSQL = logSQL
self.logTransactionWaits = logTransactionWaits
self.timeoutTransactions = timeoutTransactions
self.queuer = LocalQueuer(self.newTransaction)
self._migrating = False
self._enableNotifications = True
self._newTransactionCallbacks = set()
if cacheQueries:
self.queryCacher = QueryCacher(
cachePool=cachePool,
cacheExpireSeconds=cacheExpireSeconds
)
else:
self.queryCacher = None
self.conduit = PoddingConduit(self)
# Always import these here to trigger proper "registration" of the calendar and address book
# home classes
__import__("txdav.caldav.datastore.sql")
__import__("txdav.carddav.datastore.sql")
def availablePrimaryStoreTypes(self):
"""
The list of store home types supported.
"""
return (ECALENDARTYPE, EADDRESSBOOKTYPE,)
def directoryService(self):
return self._directoryService
def setDirectoryService(self, directoryService):
self._directoryService = directoryService
def callWithNewTransactions(self, callback):
"""
Registers a method to be called whenever a new transaction is
created.
@param callback: callable taking a single argument, a transaction
"""
self._newTransactionCallbacks.add(callback)
@inlineCallbacks
def _withEachHomeDo(self, homeTable, homeFromTxn, action, batchSize, processExternal=False):
"""
Implementation of L{ICalendarStore.withEachCalendarHomeDo} and
L{IAddressbookStore.withEachAddressbookHomeDo}.
"""
txn = yield self.newTransaction()
try:
allUIDs = yield (Select([homeTable.OWNER_UID], From=homeTable).on(txn))
for [uid] in allUIDs:
home = yield homeFromTxn(txn, uid)
if not processExternal and home.external():
continue
yield action(txn, (yield homeFromTxn(txn, uid)))
except:
a, b, c = sys.exc_info()
yield txn.abort()
raise a, b, c
else:
yield txn.commit()
def withEachCalendarHomeDo(self, action, batchSize=None, processExternal=False):
"""
Implementation of L{ICalendarStore.withEachCalendarHomeDo}.
"""
return self._withEachHomeDo(
schema.CALENDAR_HOME,
lambda txn, uid: txn.calendarHomeWithUID(uid),
action, batchSize, processExternal
)
def withEachAddressbookHomeDo(self, action, batchSize=None, processExternal=False):
"""
Implementation of L{IAddressbookStore.withEachAddressbookHomeDo}.
"""
return self._withEachHomeDo(
schema.ADDRESSBOOK_HOME,
lambda txn, uid: txn.addressbookHomeWithUID(uid),
action, batchSize, processExternal
)
def newTransaction(self, label="unlabeled", disableCache=False, authz_uid=None):
"""
@see: L{IDataStore.newTransaction}
"""
txn = CommonStoreTransaction(
self,
self.sqlTxnFactory(label=label),
self.enableCalendars,
self.enableAddressBooks,
self._notifierFactories if self._enableNotifications else {},
label,
self._migrating,
disableCache,
authz_uid,
)
if self.logTransactionWaits or self.timeoutTransactions:
CommonStoreTransactionMonitor(txn, self.logTransactionWaits,
self.timeoutTransactions)
for callback in self._newTransactionCallbacks:
callback(txn)
return txn
@inlineCallbacks
def inTransaction(self, label, operation, transactionCreator=None):
"""
Perform the given operation in a transaction, committing or aborting as
required.
@param label: the label to pass to the transaction creator
@param operation: a 1-arg callable that takes an L{IAsyncTransaction} and
returns a value.
@param transactionCreator: a 1-arg callable that takes a "label" arg and
returns a transaction
@return: a L{Deferred} that fires with C{operation}'s result or fails with
its error, unless there is an error creating, aborting or committing
the transaction.
"""
if transactionCreator is None:
transactionCreator = self.newTransaction
txn = transactionCreator(label=label)
try:
result = yield operation(txn)
except:
f = Failure()
yield txn.abort()
returnValue(f)
else:
yield txn.commit()
returnValue(result)
def setMigrating(self, state):
"""
Set the "migrating" state
"""
self._migrating = state
self._enableNotifications = not state
def setUpgrading(self, state):
"""
Set the "upgrading" state
"""
self._enableNotifications = not state
@inlineCallbacks
def dropboxAllowed(self, txn):
"""
Determine whether dropbox attachments are allowed. Once we have migrated to managed attachments,
we should never allow dropbox-style attachments to be created.
"""
if not hasattr(self, "_dropbox_ok"):
already_migrated = (yield txn.calendarserverValue("MANAGED-ATTACHMENTS", raiseIfMissing=False))
self._dropbox_ok = already_migrated is None
returnValue(self._dropbox_ok)
def queryCachingEnabled(self):
"""
Indicate whether SQL statement query caching is enabled. Also controls whether propstore caching is done.
@return: C{True} if enabled, else C{False}
@rtype: C{bool}
"""
return self.queryCacher is not None
@inlineCallbacks
def uidInStore(self, txn, uid):
"""
Indicate whether the specified user UID is hosted in the current store, or
possibly in another pod.
@param txn: transaction to use
@type txn: L{CommonStoreTransaction}
@param uid: the user UID to test
@type uid: L{str}
@return: a tuple of L{bool}, L{str} - the first indicates whether the user is
hosted, the second the serviceNodeUID of the pod hosting the user or
C{None} if on this pod.
@rtype: L{tuple}
"""
# Check if locally stored first
for storeType in self.availablePrimaryStoreTypes():
home = yield txn.homeWithUID(storeType, uid)
if home is not None:
if home.external():
# TODO: locate the pod where the user is hosted
returnValue((True, "unknown",))
else:
returnValue((True, None,))
else:
returnValue((False, None,))
class TransactionStatsCollector(object):
"""
Used to log each SQL query and statistics about that query during the course of a single transaction.
Results can be printed out where ever needed at the end of the transaction.
"""
def __init__(self, label, logFileName=None):
self.label = label
self.logFileName = logFileName
self.statements = []
self.startTime = time.time()
def startStatement(self, sql, args):
"""
Called prior to an SQL query being run.
@param sql: the SQL statement to execute
@type sql: C{str}
@param args: the arguments (binds) to the SQL statement
@type args: C{list}
@return: C{tuple} containing the index in the statement list for this statement, and the start time
"""
args = ["%s" % (arg,) for arg in args]
args = [((arg[:10] + "...") if len(arg) > 40 else arg) for arg in args]
self.statements.append(["%s %s" % (sql, args,), 0, 0, 0])
return len(self.statements) - 1, time.time()
def endStatement(self, context, rows):
"""
Called after an SQL query has executed.
@param context: the tuple returned from startStatement
@type context: C{tuple}
@param rows: number of rows returned from the query
@type rows: C{int}
"""
index, tstamp = context
t = time.time()
self.statements[index][1] = len(rows) if rows else 0
self.statements[index][2] = t - tstamp
self.statements[index][3] = t
def printReport(self):
"""
Print a report of all the SQL statements executed to date.
"""
total_statements = len(self.statements)
total_rows = sum([statement[1] for statement in self.statements])
total_time = sum([statement[2] for statement in self.statements]) * 1000.0
toFile = StringIO()
toFile.write("*** SQL Stats ***\n")
toFile.write("\n")
toFile.write("Label: %s\n" % (self.label,))
toFile.write("Unique statements: %d\n" % (len(set([statement[0] for statement in self.statements]),),))
toFile.write("Total statements: %d\n" % (total_statements,))
toFile.write("Total rows: %d\n" % (total_rows,))
toFile.write("Total time (ms): %.3f\n" % (total_time,))
t_last_end = self.startTime
for sql, rows, t_taken, t_end in self.statements:
toFile.write("\n")
toFile.write("SQL: %s\n" % (sql,))
toFile.write("Rows: %s\n" % (rows,))
toFile.write("Time (ms): %.3f\n" % (t_taken * 1000.0,))
toFile.write("Idle (ms): %.3f\n" % ((t_end - t_taken - t_last_end) * 1000.0,))
toFile.write("Elapsed (ms): %.3f\n" % ((t_end - self.startTime) * 1000.0,))
t_last_end = t_end
toFile.write("Commit (ms): %.3f\n" % ((time.time() - t_last_end) * 1000.0,))
toFile.write("***\n\n")
if self.logFileName:
open(self.logFileName, "a").write(toFile.getvalue())
else:
log.error(toFile.getvalue())
return (total_statements, total_rows, total_time,)
class CommonStoreTransactionMonitor(object):
"""
Object that monitors the state of a transaction over time and logs or times out
the transaction.
"""
callLater = reactor.callLater
def __init__(self, txn, logTimerSeconds, timeoutSeconds):
self.txn = txn
self.delayedLog = None
self.delayedTimeout = None
self.logTimerSeconds = logTimerSeconds
self.timeoutSeconds = timeoutSeconds
self.txn.postCommit(self._cleanTxn)
self.txn.postAbort(self._cleanTxn)
self._installLogTimer()
self._installTimeout()
def _cleanTxn(self):
self.txn = None
if self.delayedLog:
self.delayedLog.cancel()
self.delayedLog = None
if self.delayedTimeout:
self.delayedTimeout.cancel()
self.delayedTimeout = None
return succeed(None)
def _installLogTimer(self):
def _logTransactionWait():
if self.txn is not None:
log.error(
"Transaction wait: {me.txn}, "
"Statements: {me.txn.statementCount:d}, "
"IUDs: {me.txn.iudCount:d}, "
"Statement: {me.txn.currentStatement}",
me=self
)
self.delayedLog = self.callLater(
self.logTimerSeconds, _logTransactionWait
)
if self.logTimerSeconds:
self.delayedLog = self.callLater(
self.logTimerSeconds, _logTransactionWait
)
def _installTimeout(self):
def _forceAbort():
if self.txn is not None:
log.error(
"Transaction abort too long: {me.txn}, "
"Statements: {me.txn.statementCount:d}, "
"IUDs: {me.txn.iudCount:d}, "
"Statement: {me.txn.currentStatement}",
me=self
)
self.delayedTimeout = None
if self.delayedLog:
self.delayedLog.cancel()
self.delayedLog = None
self.txn.timeout()
if self.timeoutSeconds:
self.delayedTimeout = self.callLater(
self.timeoutSeconds, _forceAbort
)
class CommonStoreTransaction(object):
"""
Transaction implementation for SQL database.
"""
_homeClass = {}
id = 0
def __init__(
self, store, sqlTxn,
enableCalendars, enableAddressBooks,
notifierFactories, label, migrating=False, disableCache=False,
authz_uid=None,
):
if label == "unlabeled" or not label:
tr = inspect.getframeinfo(inspect.currentframe().f_back.f_back)
label = "{}#{}${}".format(tr.filename, tr.lineno, tr.function)
self._store = store
self._queuer = self._store.queuer
self._calendarHomes = {}
self._addressbookHomes = {}
self._notificationHomes = {}
self._notifierFactories = notifierFactories
self._notifiedAlready = set()
self._bumpedRevisionAlready = set()
self._label = label
self._migrating = migrating
self._primaryHomeType = None
self._disableCache = disableCache or not store.queryCachingEnabled()
if disableCache:
self._queryCacher = None
else:
self._queryCacher = store.queryCacher
self._authz_uid = authz_uid
CommonStoreTransaction.id += 1
self._txid = CommonStoreTransaction.id
extraInterfaces = []
if enableCalendars:
extraInterfaces.append(ICalendarTransaction)
self._primaryHomeType = ECALENDARTYPE
if enableAddressBooks:
extraInterfaces.append(IAddressBookTransaction)
if self._primaryHomeType is None:
self._primaryHomeType = EADDRESSBOOKTYPE
directlyProvides(self, *extraInterfaces)
self._sqlTxn = sqlTxn
self.paramstyle = sqlTxn.paramstyle
self.dialect = sqlTxn.dialect
self._stats = (
TransactionStatsCollector(self._label, self._store.logStatsLogFile)
if self._store.logStats else None
)
self.statementCount = 0
self.iudCount = 0
self.currentStatement = None
self.timedout = False
self.logItems = {}
def enqueue(self, workItem, **kw):
"""
Enqueue a L{twext.enterprise.jobqueue.WorkItem} for later execution.
For example::
yield (txn.enqueue(MyWorkItem, workDescription="some work to do"))
@return: a work proposal describing various events in the work's
life-cycle.
@rtype: L{twext.enterprise.jobqueue.WorkProposal}
"""
return self._store.queuer.enqueueWork(self, workItem, **kw)
def store(self):
return self._store
def directoryService(self):
return self._store.directoryService()
def __repr__(self):
return 'PG-TXN<%s>' % (self._label,)
@classproperty
def _calendarserver(cls):
cs = schema.CALENDARSERVER
return Select(
[cs.VALUE, ],
From=cs,
Where=cs.NAME == Parameter('name'),
)
@inlineCallbacks
def calendarserverValue(self, key, raiseIfMissing=True):
result = yield self._calendarserver.on(self, name=key)
if result and len(result) == 1:
returnValue(result[0][0])
if raiseIfMissing:
raise RuntimeError("Database key %s cannot be determined." % (key,))
else:
returnValue(None)
@inlineCallbacks
def setCalendarserverValue(self, key, value):
cs = schema.CALENDARSERVER
yield Insert(
{cs.NAME: key, cs.VALUE: value},
).on(self)
@inlineCallbacks
def updateCalendarserverValue(self, key, value):
cs = schema.CALENDARSERVER
yield Update(
{cs.VALUE: value},
Where=cs.NAME == key,
).on(self)
def _determineMemo(self, storeType, uid, create=False, authzUID=None):
"""
Determine the memo dictionary to use for homeWithUID.
"""
if storeType == ECALENDARTYPE:
return self._calendarHomes
else:
return self._addressbookHomes
@inlineCallbacks
def homes(self, storeType):
"""
Load all calendar or addressbook homes.
"""
# Get all UIDs and load them - this will memoize all existing ones
uids = (yield self._homeClass[storeType].listHomes(self))
for uid in uids:
yield self.homeWithUID(storeType, uid, create=False)
# Return the memoized list directly
returnValue([kv[1] for kv in sorted(self._determineMemo(storeType, None).items(), key=lambda x: x[0])])
@memoizedKey("uid", _determineMemo)
def homeWithUID(self, storeType, uid, create=False, authzUID=None):
"""
We need to distinguish between various different users "looking" at a home and its
child resources because we have per-user properties that depend on which user is "looking".
By default the viewer is set to the authz_uid on the transaction, or the owner if no authz,
but it can be overridden using L{authzUID}. This is useful when the store needs to get to
other user's homes with the viewer being the owner of that home as opposed to authz_uid. That
often happens when manipulating shares.
"""
if storeType not in (ECALENDARTYPE, EADDRESSBOOKTYPE):
raise RuntimeError("Unknown home type.")
return self._homeClass[storeType].homeWithUID(self, uid, create, authzUID)
def calendarHomeWithUID(self, uid, create=False, authzUID=None):
return self.homeWithUID(ECALENDARTYPE, uid, create=create, authzUID=authzUID)
def addressbookHomeWithUID(self, uid, create=False, authzUID=None):
return self.homeWithUID(EADDRESSBOOKTYPE, uid, create=create, authzUID=authzUID)
@inlineCallbacks
def homeWithResourceID(self, storeType, rid):
"""
Load a calendar or addressbook home by its integer resource ID.
"""
uid = (yield self._homeClass[storeType].homeUIDWithResourceID(self, rid))
if uid:
# Always get the owner's view of the home = i.e., authzUID=uid
result = (yield self.homeWithUID(storeType, uid, authzUID=uid))
else:
result = None
returnValue(result)
def calendarHomeWithResourceID(self, rid):
return self.homeWithResourceID(ECALENDARTYPE, rid)
def addressbookHomeWithResourceID(self, rid):
return self.homeWithResourceID(EADDRESSBOOKTYPE, rid)
@memoizedKey("uid", "_notificationHomes")
def notificationsWithUID(self, uid, create=True):
"""
Implement notificationsWithUID.
"""
return NotificationCollection.notificationsWithUID(self, uid, create)
@memoizedKey("rid", "_notificationHomes")
def notificationsWithResourceID(self, rid):
"""
Implement notificationsWithResourceID.
"""
return NotificationCollection.notificationsWithResourceID(self, rid)
@classproperty
def _insertAPNSubscriptionQuery(cls):
apn = schema.APN_SUBSCRIPTIONS
return Insert({
apn.TOKEN: Parameter("token"),
apn.RESOURCE_KEY: Parameter("resourceKey"),
apn.MODIFIED: Parameter("modified"),
apn.SUBSCRIBER_GUID: Parameter("subscriber"),
apn.USER_AGENT: Parameter("userAgent"),
apn.IP_ADDR: Parameter("ipAddr")
})
@classproperty
def _updateAPNSubscriptionQuery(cls):
apn = schema.APN_SUBSCRIPTIONS
return Update(
{
apn.MODIFIED: Parameter("modified"),
apn.SUBSCRIBER_GUID: Parameter("subscriber"),
apn.USER_AGENT: Parameter("userAgent"),
apn.IP_ADDR: Parameter("ipAddr")
},
Where=(apn.TOKEN == Parameter("token")).And(
apn.RESOURCE_KEY == Parameter("resourceKey"))
)
@classproperty
def _selectAPNSubscriptionQuery(cls):
apn = schema.APN_SUBSCRIPTIONS
return Select(
[apn.MODIFIED, apn.SUBSCRIBER_GUID],
From=apn,
Where=(apn.TOKEN == Parameter("token")).And(
apn.RESOURCE_KEY == Parameter("resourceKey")
)
)
@inlineCallbacks
def addAPNSubscription(
self, token, key, timestamp, subscriber,
userAgent, ipAddr
):
if not (token and key and timestamp and subscriber):
raise InvalidSubscriptionValues()
# Cap these values at 255 characters
userAgent = userAgent[:255]
ipAddr = ipAddr[:255]
row = yield self._selectAPNSubscriptionQuery.on(
self,
token=token, resourceKey=key
)
if not row: # Subscription does not yet exist
try:
yield self._insertAPNSubscriptionQuery.on(
self,
token=token, resourceKey=key, modified=timestamp,
subscriber=subscriber, userAgent=userAgent,
ipAddr=ipAddr)
except Exception:
# Subscription may have been added by someone else, which is fine
pass
else: # Subscription exists, so update with new timestamp and subscriber
try:
yield self._updateAPNSubscriptionQuery.on(
self,
token=token, resourceKey=key, modified=timestamp,
subscriber=subscriber, userAgent=userAgent,
ipAddr=ipAddr)
except Exception:
# Subscription may have been added by someone else, which is fine
pass
@classproperty
def _removeAPNSubscriptionQuery(cls):
apn = schema.APN_SUBSCRIPTIONS
return Delete(From=apn,
Where=(apn.TOKEN == Parameter("token")).And(
apn.RESOURCE_KEY == Parameter("resourceKey")))
def removeAPNSubscription(self, token, key):
return self._removeAPNSubscriptionQuery.on(
self,
token=token, resourceKey=key)
@classproperty
def _purgeOldAPNSubscriptionQuery(cls):
apn = schema.APN_SUBSCRIPTIONS
return Delete(From=apn,
Where=(apn.MODIFIED < Parameter("olderThan")))
def purgeOldAPNSubscriptions(self, olderThan):
return self._purgeOldAPNSubscriptionQuery.on(
self,
olderThan=olderThan)
@classproperty
def _apnSubscriptionsByTokenQuery(cls):
apn = schema.APN_SUBSCRIPTIONS
return Select([apn.RESOURCE_KEY, apn.MODIFIED, apn.SUBSCRIBER_GUID],
From=apn, Where=apn.TOKEN == Parameter("token"))
def apnSubscriptionsByToken(self, token):
return self._apnSubscriptionsByTokenQuery.on(self, token=token)
@classproperty
def _apnSubscriptionsByKeyQuery(cls):
apn = schema.APN_SUBSCRIPTIONS
return Select([apn.TOKEN, apn.SUBSCRIBER_GUID],
From=apn, Where=apn.RESOURCE_KEY == Parameter("resourceKey"))
def apnSubscriptionsByKey(self, key):
return self._apnSubscriptionsByKeyQuery.on(self, resourceKey=key)
@classproperty
def _apnSubscriptionsBySubscriberQuery(cls):
apn = schema.APN_SUBSCRIPTIONS
return Select([apn.TOKEN, apn.RESOURCE_KEY, apn.MODIFIED, apn.USER_AGENT, apn.IP_ADDR],
From=apn, Where=apn.SUBSCRIBER_GUID == Parameter("subscriberGUID"))
def apnSubscriptionsBySubscriber(self, guid):
return self._apnSubscriptionsBySubscriberQuery.on(self, subscriberGUID=guid)
# Create IMIP token
@classproperty
def _insertIMIPTokenQuery(cls):
imip = schema.IMIP_TOKENS
return Insert({
imip.TOKEN: Parameter("token"),
imip.ORGANIZER: Parameter("organizer"),
imip.ATTENDEE: Parameter("attendee"),
imip.ICALUID: Parameter("icaluid"),
})
@inlineCallbacks
def imipCreateToken(self, organizer, attendee, icaluid, token=None):
if not (organizer and attendee and icaluid):
raise InvalidIMIPTokenValues()
if token is None:
token = str(uuid4())
try:
yield self._insertIMIPTokenQuery.on(
self,
token=token, organizer=organizer, attendee=attendee,
icaluid=icaluid)
except Exception:
# TODO: is it okay if someone else created the same row just now?
pass
returnValue(token)
# Lookup IMIP organizer+attendee+icaluid for token
@classproperty
def _selectIMIPTokenByTokenQuery(cls):
imip = schema.IMIP_TOKENS
return Select([imip.ORGANIZER, imip.ATTENDEE, imip.ICALUID], From=imip,
Where=(imip.TOKEN == Parameter("token")))
def imipLookupByToken(self, token):
return self._selectIMIPTokenByTokenQuery.on(self, token=token)
# Lookup IMIP token for organizer+attendee+icaluid
@classproperty
def _selectIMIPTokenQuery(cls):
imip = schema.IMIP_TOKENS
return Select(
[imip.TOKEN],
From=imip,
Where=(imip.ORGANIZER == Parameter("organizer")).And(
imip.ATTENDEE == Parameter("attendee")).And(
imip.ICALUID == Parameter("icaluid"))
)
@classproperty
def _updateIMIPTokenQuery(cls):
imip = schema.IMIP_TOKENS
return Update(
{imip.ACCESSED: utcNowSQL, },
Where=(imip.ORGANIZER == Parameter("organizer")).And(
imip.ATTENDEE == Parameter("attendee")).And(
imip.ICALUID == Parameter("icaluid"))
)
@inlineCallbacks
def imipGetToken(self, organizer, attendee, icaluid):
row = (yield self._selectIMIPTokenQuery.on(
self, organizer=organizer,
attendee=attendee, icaluid=icaluid))
if row:
token = row[0][0]
# update the timestamp