-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
3680 lines (3139 loc) · 132 KB
/
main.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
#!/usr/bin/env python
#
# Copyright 2008 Google Inc.
#
# 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.
#
"""PubSubHubbub protocol Hub implementation built on Google App Engine.
=== Model classes:
* Subscription: A single subscriber's lease on a topic URL. Also represents a
work item of a subscription that is awaiting confirmation (sub. or unsub).
* FeedToFetch: Work item inserted when a publish event occurs. This will be
moved to the Task Queue API once available.
* KnownFeed: Materialized view of all distinct topic URLs. Written by
background task every time a new subscription is made for a topic URL.
Used for mapping from input topic URLs to feed IDs and then back to topic
URLs, to properly handle any feed aliases. Also used for doing bootstrap
polling of feeds.
* KnownFeedIdentity: Reverse index of feed ID to topic URLs. Used in
conjunction with KnownFeed to properly canonicalize feed aliases on
subscription and pinging.
* FeedRecord: Metadata information about a feed, the last time it was polled,
and any headers that may affect future polling. Also contains any debugging
information about the last feed fetch and why it may have failed.
* FeedEntryRecord: Record of a single entry in a single feed. May eventually
be garbage collected after enough time has passed since it was last seen.
* EventToDeliver: Work item that contains the content to deliver for a feed
event. Maintains current position in subscribers and number of delivery
failures. Used to coordinate delivery retries. Will be deleted in successful
cases or stick around in the event of complete failures for debugging.
* PollingMarker: Work item that keeps track of the last time all KnownFeed
instances were fetched. Used to do bootstrap polling.
=== Entity groups:
Subscription entities are in their own entity group to allow for a high number
of simultaneous subscriptions for the same topic URL. FeedToFetch is also in
its own entity group for the same reason. FeedRecord, FeedEntryRecord, and
EventToDeliver entries are all in the same entity group, however, to ensure that
each feed polling is either full committed and delivered to subscribers or fails
and will be retried at a later time.
------------
| FeedRecord |
-----+------
|
|
+-------------+-------------+
| |
| |
--------+-------- --------+-------
| FeedEntryRecord | | EventToDeliver |
----------------- ----------------
"""
# Bigger TODOs (in priority order)
#
# - Add subscription counting to PushEventHandler so we can deliver a header
# with the number of subscribers the feed has. This will simply just keep
# count of the subscribers seen so far and then when the pushing is done it
# will save that total back on the FeedRecord instance.
#
# - Improve polling algorithm to keep stats on each feed.
#
# - Do not poll a feed if we've gotten an event from the publisher in less
# than the polling period.
import datetime
import gc
import hashlib
import hmac
import logging
import os
import random
import sgmllib
import time
import traceback
import urllib
import urlparse
import wsgiref.handlers
import xml.sax
#SMOB: Start import libraries
import sparql_connect
import read_foaf
from BeautifulSoup import BeautifulStoneSoup
from sets import Set
reader = read_foaf.ReadFOAF()
connect=sparql_connect.VirtuosoConnect()
#SMOB: End
from google.appengine import runtime
from google.appengine.api import datastore_types
from google.appengine.api import memcache
from google.appengine.api import urlfetch
from google.appengine.api import urlfetch_errors
from google.appengine.api import users
from google.appengine.api.labs import taskqueue
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.runtime import apiproxy_errors
import async_apiproxy
import dos
import feed_diff
import feed_identifier
import fork_join_queue
import urlfetch_async
import mapreduce.control
import mapreduce.model
async_proxy = async_apiproxy.AsyncAPIProxy()
################################################################################
# Config parameters
DEBUG = True
if DEBUG:
logging.getLogger().setLevel(logging.DEBUG)
# How many subscribers to contact at a time when delivering events.
EVENT_SUBSCRIBER_CHUNK_SIZE = 50
# Maximum number of times to attempt a subscription retry.
MAX_SUBSCRIPTION_CONFIRM_FAILURES = 4
# Period to use for exponential backoff on subscription confirm retries.
SUBSCRIPTION_RETRY_PERIOD = 30 # seconds
# Maximum number of times to attempt to pull a feed.
MAX_FEED_PULL_FAILURES = 4
# Period to use for exponential backoff on feed pulling.
FEED_PULL_RETRY_PERIOD = 30 # seconds
# Maximum number of times to attempt to deliver a feed event.
MAX_DELIVERY_FAILURES = 4
# Period to use for exponential backoff on feed event delivery.
DELIVERY_RETRY_PERIOD = 30 # seconds
# Period at which feed IDs should be refreshed.
FEED_IDENTITY_UPDATE_PERIOD = (10 * 24 * 60 * 60) # 10 days
# Number of polling feeds to fetch from the Datastore at a time.
BOOSTRAP_FEED_CHUNK_SIZE = 50
# Maximum age in seconds of a failed EventToDeliver before it is cleaned up.
EVENT_CLEANUP_MAX_AGE_SECONDS = (10 * 24 * 60 * 60) # 10 days
# How many completely failed EventToDeliver instances to clean up at a time.
EVENT_CLEANUP_CHUNK_SIZE = 50
# How many old Subscription instances to clean up at a time.
SUBSCRIPTION_CLEANUP_CHUNK_SIZE = 100
# How far before expiration to refresh subscriptions.
SUBSCRIPTION_CHECK_BUFFER_SECONDS = (24 * 60 * 60) # 24 hours
# How many mapper shards to use for reconfirming subscriptions.
SUBSCRIPTION_RECONFIRM_SHARD_COUNT = 4
# How often to poll feeds.
POLLING_BOOTSTRAP_PERIOD = 10800 # in seconds; 3 hours
# Default expiration time of a lease.
DEFAULT_LEASE_SECONDS = (5 * 24 * 60 * 60) # 5 days
# Maximum expiration time of a lease.
MAX_LEASE_SECONDS = (10 * 24 * 60 * 60) # 10 days
# Maximum number of redirects to follow when feed fetching.
MAX_REDIRECTS = 7
# Maximum time to wait for fetching a feed in seconds.
MAX_FETCH_SECONDS = 10
# Number of times to try to split FeedEntryRecord, EventToDeliver, and
# FeedRecord entities when putting them and their size is too large.
PUT_SPLITTING_ATTEMPTS = 10
# Maximum number of FeedEntryRecord entries to look up in parallel.
MAX_FEED_ENTRY_RECORD_LOOKUPS = 500
# Maximum number of FeedEntryRecord entries to save at the same time when
# a new EventToDeliver is being written.
MAX_FEED_RECORD_SAVES = 100
# Maximum number of new FeedEntryRecords to process and insert at a time. Any
# remaining will be split into another EventToDeliver instance.
MAX_NEW_FEED_ENTRY_RECORDS = 200
################################################################################
# URL scoring Parameters
# Fetching feeds
FETCH_SCORER = dos.UrlScorer(
period=300, # Seconds
min_requests=5, # per second
max_failure_percentage=1, # TODO: Drop this to something more reasonable!
prefix='pull_feed')
# Pushing events
DELIVERY_SCORER = dos.UrlScorer(
period=300, # Seconds
min_requests=0.5, # per second
max_failure_percentage=1, # TODO: Drop this to something more reasonable!
prefix='deliver_events')
################################################################################
# Fetching samplers
FETCH_URL_SAMPLE_MINUTE = dos.ReservoirConfig(
'fetch_url_1m',
period=60,
samples=10000,
by_url=True,
value_units='% errors')
FETCH_URL_SAMPLE_30_MINUTE = dos.ReservoirConfig(
'fetch_url_30m',
period=1800,
samples=10000,
by_url=True,
value_units='% errors')
FETCH_URL_SAMPLE_HOUR = dos.ReservoirConfig(
'fetch_url_1h',
period=3600,
samples=10000,
by_url=True,
value_units='% errors')
FETCH_URL_SAMPLE_DAY = dos.ReservoirConfig(
'fetch_url_1d',
period=86400,
samples=10000,
by_url=True,
value_units='% errors')
FETCH_DOMAIN_SAMPLE_MINUTE = dos.ReservoirConfig(
'fetch_domain_1m',
period=60,
samples=10000,
by_domain=True,
value_units='% errors')
FETCH_DOMAIN_SAMPLE_30_MINUTE = dos.ReservoirConfig(
'fetch_domain_30m',
period=1800,
samples=10000,
by_domain=True,
value_units='% errors')
FETCH_DOMAIN_SAMPLE_HOUR = dos.ReservoirConfig(
'fetch_domain_1h',
period=3600,
samples=10000,
by_domain=True,
value_units='% errors')
FETCH_DOMAIN_SAMPLE_DAY = dos.ReservoirConfig(
'fetch_domain_1d',
period=86400,
samples=10000,
by_domain=True,
value_units='% errors')
FETCH_URL_SAMPLE_MINUTE_LATENCY = dos.ReservoirConfig(
'fetch_url_1m_latency',
period=60,
samples=10000,
by_url=True,
value_units='ms')
FETCH_URL_SAMPLE_30_MINUTE_LATENCY = dos.ReservoirConfig(
'fetch_url_30m_latency',
period=1800,
samples=10000,
by_url=True,
value_units='ms')
FETCH_URL_SAMPLE_HOUR_LATENCY = dos.ReservoirConfig(
'fetch_url_1h_latency',
period=3600,
samples=10000,
by_url=True,
value_units='ms')
FETCH_URL_SAMPLE_DAY_LATENCY = dos.ReservoirConfig(
'fetch_url_1d_latency',
period=86400,
samples=10000,
by_url=True,
value_units='ms')
FETCH_DOMAIN_SAMPLE_MINUTE_LATENCY = dos.ReservoirConfig(
'fetch_domain_1m_latency',
period=60,
samples=10000,
by_domain=True,
value_units='ms')
FETCH_DOMAIN_SAMPLE_30_MINUTE_LATENCY = dos.ReservoirConfig(
'fetch_domain_30m_latency',
period=1800,
samples=10000,
by_domain=True,
value_units='ms')
FETCH_DOMAIN_SAMPLE_HOUR_LATENCY = dos.ReservoirConfig(
'fetch_domain_1h_latency',
period=3600,
samples=10000,
by_domain=True,
value_units='ms')
FETCH_DOMAIN_SAMPLE_DAY_LATENCY = dos.ReservoirConfig(
'fetch_domain_1d_latency',
period=86400,
samples=10000,
by_domain=True,
value_units='ms')
def report_fetch(reporter, url, success, latency):
"""Reports statistics information for a feed fetch.
Args:
reporter: dos.Reporter instance.
url: The URL of the topic URL that was fetched.
success: True if the fetch was successful, False otherwise.
latency: End-to-end fetch latency in milliseconds.
"""
value = 100 * int(not success)
reporter.set(url, FETCH_URL_SAMPLE_MINUTE, value)
reporter.set(url, FETCH_URL_SAMPLE_30_MINUTE, value)
reporter.set(url, FETCH_URL_SAMPLE_HOUR, value)
reporter.set(url, FETCH_URL_SAMPLE_DAY, value)
reporter.set(url, FETCH_DOMAIN_SAMPLE_MINUTE, value)
reporter.set(url, FETCH_DOMAIN_SAMPLE_30_MINUTE, value)
reporter.set(url, FETCH_DOMAIN_SAMPLE_HOUR, value)
reporter.set(url, FETCH_DOMAIN_SAMPLE_DAY, value)
reporter.set(url, FETCH_URL_SAMPLE_MINUTE_LATENCY, latency)
reporter.set(url, FETCH_URL_SAMPLE_30_MINUTE_LATENCY, latency)
reporter.set(url, FETCH_URL_SAMPLE_HOUR_LATENCY, latency)
reporter.set(url, FETCH_URL_SAMPLE_DAY_LATENCY, latency)
reporter.set(url, FETCH_DOMAIN_SAMPLE_MINUTE_LATENCY, latency)
reporter.set(url, FETCH_DOMAIN_SAMPLE_30_MINUTE_LATENCY, latency)
reporter.set(url, FETCH_DOMAIN_SAMPLE_HOUR_LATENCY, latency)
reporter.set(url, FETCH_DOMAIN_SAMPLE_DAY_LATENCY, latency)
FETCH_SAMPLER = dos.MultiSampler([
FETCH_URL_SAMPLE_MINUTE,
FETCH_URL_SAMPLE_30_MINUTE,
FETCH_URL_SAMPLE_HOUR,
FETCH_URL_SAMPLE_DAY,
FETCH_DOMAIN_SAMPLE_MINUTE,
FETCH_DOMAIN_SAMPLE_30_MINUTE,
FETCH_DOMAIN_SAMPLE_HOUR,
FETCH_DOMAIN_SAMPLE_DAY,
FETCH_URL_SAMPLE_MINUTE_LATENCY,
FETCH_URL_SAMPLE_30_MINUTE_LATENCY,
FETCH_URL_SAMPLE_HOUR_LATENCY,
FETCH_URL_SAMPLE_DAY_LATENCY,
FETCH_DOMAIN_SAMPLE_MINUTE_LATENCY,
FETCH_DOMAIN_SAMPLE_30_MINUTE_LATENCY,
FETCH_DOMAIN_SAMPLE_HOUR_LATENCY,
FETCH_DOMAIN_SAMPLE_DAY_LATENCY,
])
################################################################################
# Delivery samplers
DELIVERY_URL_SAMPLE_MINUTE = dos.ReservoirConfig(
'delivery_url_1m',
period=60,
samples=10000,
by_url=True,
value_units='% errors')
DELIVERY_URL_SAMPLE_30_MINUTE = dos.ReservoirConfig(
'delivery_url_30m',
period=1800,
samples=10000,
by_url=True,
value_units='% errors')
DELIVERY_URL_SAMPLE_HOUR = dos.ReservoirConfig(
'delivery_url_1h',
period=3600,
samples=10000,
by_url=True,
value_units='% errors')
DELIVERY_URL_SAMPLE_DAY = dos.ReservoirConfig(
'delivery_url_1d',
period=86400,
samples=10000,
by_url=True,
value_units='% errors')
DELIVERY_DOMAIN_SAMPLE_MINUTE = dos.ReservoirConfig(
'delivery_domain_1m',
period=60,
samples=10000,
by_domain=True,
value_units='% errors')
DELIVERY_DOMAIN_SAMPLE_30_MINUTE = dos.ReservoirConfig(
'delivery_domain_30m',
period=1800,
samples=10000,
by_domain=True,
value_units='% errors')
DELIVERY_DOMAIN_SAMPLE_HOUR = dos.ReservoirConfig(
'delivery_domain_1h',
period=3600,
samples=10000,
by_domain=True,
value_units='% errors')
DELIVERY_DOMAIN_SAMPLE_DAY = dos.ReservoirConfig(
'delivery_domain_1d',
period=86400,
samples=10000,
by_domain=True,
value_units='% errors')
DELIVERY_URL_SAMPLE_MINUTE_LATENCY = dos.ReservoirConfig(
'delivery_url_1m_latency',
period=60,
samples=10000,
by_url=True,
value_units='ms')
DELIVERY_URL_SAMPLE_30_MINUTE_LATENCY = dos.ReservoirConfig(
'delivery_url_30m_latency',
period=1800,
samples=10000,
by_url=True,
value_units='ms')
DELIVERY_URL_SAMPLE_HOUR_LATENCY = dos.ReservoirConfig(
'delivery_url_1h_latency',
period=3600,
samples=10000,
by_url=True,
value_units='ms')
DELIVERY_URL_SAMPLE_DAY_LATENCY = dos.ReservoirConfig(
'delivery_url_1d_latency',
period=86400,
samples=10000,
by_url=True,
value_units='ms')
DELIVERY_DOMAIN_SAMPLE_MINUTE_LATENCY = dos.ReservoirConfig(
'delivery_domain_1m_latency',
period=60,
samples=10000,
by_domain=True,
value_units='ms')
DELIVERY_DOMAIN_SAMPLE_30_MINUTE_LATENCY = dos.ReservoirConfig(
'delivery_domain_30m_latency',
period=1800,
samples=10000,
by_domain=True,
value_units='ms')
DELIVERY_DOMAIN_SAMPLE_HOUR_LATENCY = dos.ReservoirConfig(
'delivery_domain_1h_latency',
period=3600,
samples=10000,
by_domain=True,
value_units='ms')
DELIVERY_DOMAIN_SAMPLE_DAY_LATENCY = dos.ReservoirConfig(
'delivery_domain_1d_latency',
period=86400,
samples=10000,
by_domain=True,
value_units='ms')
def report_delivery(reporter, url, success, latency):
"""Reports statistics information for a event delivery to a callback.
Args:
reporter: dos.Reporter instance.
url: The URL of the callback that received the event.
success: True if the delivery was successful, False otherwise.
latency: End-to-end fetch latency in milliseconds.
"""
value = 100 * int(not success)
reporter.set(url, DELIVERY_URL_SAMPLE_MINUTE, value)
reporter.set(url, DELIVERY_URL_SAMPLE_30_MINUTE, value)
reporter.set(url, DELIVERY_URL_SAMPLE_HOUR, value)
reporter.set(url, DELIVERY_URL_SAMPLE_DAY, value)
reporter.set(url, DELIVERY_DOMAIN_SAMPLE_MINUTE, value)
reporter.set(url, DELIVERY_DOMAIN_SAMPLE_30_MINUTE, value)
reporter.set(url, DELIVERY_DOMAIN_SAMPLE_HOUR, value)
reporter.set(url, DELIVERY_DOMAIN_SAMPLE_DAY, value)
reporter.set(url, DELIVERY_URL_SAMPLE_MINUTE_LATENCY, latency)
reporter.set(url, DELIVERY_URL_SAMPLE_30_MINUTE_LATENCY, latency)
reporter.set(url, DELIVERY_URL_SAMPLE_HOUR_LATENCY, latency)
reporter.set(url, DELIVERY_URL_SAMPLE_DAY_LATENCY, latency)
reporter.set(url, DELIVERY_DOMAIN_SAMPLE_MINUTE_LATENCY, latency)
reporter.set(url, DELIVERY_DOMAIN_SAMPLE_30_MINUTE_LATENCY, latency)
reporter.set(url, DELIVERY_DOMAIN_SAMPLE_HOUR_LATENCY, latency)
reporter.set(url, DELIVERY_DOMAIN_SAMPLE_DAY_LATENCY, latency)
DELIVERY_SAMPLER = dos.MultiSampler([
DELIVERY_URL_SAMPLE_MINUTE,
DELIVERY_URL_SAMPLE_30_MINUTE,
DELIVERY_URL_SAMPLE_HOUR,
DELIVERY_URL_SAMPLE_DAY,
DELIVERY_DOMAIN_SAMPLE_MINUTE,
DELIVERY_DOMAIN_SAMPLE_30_MINUTE,
DELIVERY_DOMAIN_SAMPLE_HOUR,
DELIVERY_DOMAIN_SAMPLE_DAY,
DELIVERY_URL_SAMPLE_MINUTE_LATENCY,
DELIVERY_URL_SAMPLE_30_MINUTE_LATENCY,
DELIVERY_URL_SAMPLE_HOUR_LATENCY,
DELIVERY_URL_SAMPLE_DAY_LATENCY,
DELIVERY_DOMAIN_SAMPLE_MINUTE_LATENCY,
DELIVERY_DOMAIN_SAMPLE_30_MINUTE_LATENCY,
DELIVERY_DOMAIN_SAMPLE_HOUR_LATENCY,
DELIVERY_DOMAIN_SAMPLE_DAY_LATENCY,
])
################################################################################
# Constants
ATOM = 'atom'
RSS = 'rss'
ARBITRARY = 'arbitrary'
VALID_PORTS = frozenset([
'80', '443', '4443', '8080', '8081', '8082', '8083', '8084', '8085',
'8086', '8087', '8088', '8089', '8188', '8444', '8990'])
EVENT_QUEUE = 'event-delivery'
EVENT_RETRIES_QUEUE = 'event-delivery-retries'
FEED_QUEUE = 'feed-pulls'
FEED_RETRIES_QUEUE = 'feed-pulls-retries'
POLLING_QUEUE = 'polling'
SUBSCRIPTION_QUEUE = 'subscriptions'
MAPPINGS_QUEUE = 'mappings'
################################################################################
# Helper functions
def utf8encoded(data):
"""Encodes a string as utf-8 data and returns an ascii string.
Args:
data: The string data to encode.
Returns:
An ascii string, or None if the 'data' parameter was None.
"""
if data is None:
return None
if isinstance(data, unicode):
return unicode(data).encode('utf-8')
else:
return data
def normalize_iri(url):
"""Converts a URL (possibly containing unicode characters) to an IRI.
Args:
url: String (normal or unicode) containing a URL, presumably having
already been percent-decoded by a web framework receiving request
parameters in a POST body or GET request's URL.
Returns:
A properly encoded IRI (see RFC 3987).
"""
def chr_or_escape(unicode_char):
if ord(unicode_char) > 0x7f:
return urllib.quote(unicode_char.encode('utf-8'))
else:
return unicode_char
return ''.join(chr_or_escape(c) for c in unicode(url))
def sha1_hash(value):
"""Returns the sha1 hash of the supplied value."""
return hashlib.sha1(utf8encoded(value)).hexdigest()
def get_hash_key_name(value):
"""Returns a valid entity key_name that's a hash of the supplied value."""
return 'hash_' + sha1_hash(value)
def sha1_hmac(secret, data):
"""Returns the sha1 hmac for a chunk of data and a secret."""
return hmac.new(secret, data, hashlib.sha1).hexdigest()
def is_dev_env():
"""Returns True if we're running in the development environment."""
return 'Dev' in os.environ.get('SERVER_SOFTWARE', '')
def work_queue_only(func):
"""Decorator that only allows a request if from cron job, task, or an admin.
Also allows access if running in development server environment.
Args:
func: A webapp.RequestHandler method.
Returns:
Function that will return a 401 error if not from an authorized source.
"""
def decorated(myself, *args, **kwargs):
if ('X-AppEngine-Cron' in myself.request.headers or
'X-AppEngine-TaskName' in myself.request.headers or
is_dev_env() or users.is_current_user_admin()):
return func(myself, *args, **kwargs)
elif users.get_current_user() is None:
myself.redirect(users.create_login_url(myself.request.url))
else:
myself.response.set_status(401)
myself.response.out.write('Handler only accessible for work queues')
return decorated
def is_valid_url(url):
"""Returns True if the URL is valid, False otherwise."""
split = urlparse.urlparse(url)
if not split.scheme in ('http', 'https'):
logging.debug('URL scheme is invalid: %s', url)
return False
netloc, port = (split.netloc.split(':', 1) + [''])[:2]
if port and not is_dev_env() and port not in VALID_PORTS:
logging.debug('URL port is invalid: %s', url)
return False
if split.fragment:
logging.debug('URL includes fragment: %s', url)
return False
return True
_VALID_CHARS = (
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_',
)
def get_random_challenge():
"""Returns a string containing a random challenge token."""
return ''.join(random.choice(_VALID_CHARS) for i in xrange(128))
################################################################################
# Models
class Subscription(db.Model):
"""Represents a single subscription to a topic for a callback URL."""
STATE_NOT_VERIFIED = 'not_verified'
STATE_VERIFIED = 'verified'
STATE_TO_DELETE = 'to_delete'
STATES = frozenset([
STATE_NOT_VERIFIED,
STATE_VERIFIED,
STATE_TO_DELETE,
])
callback = db.TextProperty(required=True)
callback_hash = db.StringProperty(required=True)
topic = db.TextProperty(required=True)
topic_hash = db.StringProperty(required=True)
created_time = db.DateTimeProperty(auto_now_add=True)
last_modified = db.DateTimeProperty(auto_now=True)
lease_seconds = db.IntegerProperty(default=DEFAULT_LEASE_SECONDS)
expiration_time = db.DateTimeProperty(required=True)
eta = db.DateTimeProperty(auto_now_add=True)
confirm_failures = db.IntegerProperty(default=0)
verify_token = db.TextProperty()
secret = db.TextProperty()
hmac_algorithm = db.TextProperty()
subscription_state = db.StringProperty(default=STATE_NOT_VERIFIED,
choices=STATES)
@staticmethod
def create_key_name(callback, topic):
"""Returns the key name for a Subscription entity.
Args:
callback: URL of the callback subscriber.
topic: URL of the topic being subscribed to.
Returns:
String containing the key name for the corresponding Subscription.
"""
return get_hash_key_name(u'%s\n%s' % (callback, topic))
#SMOB: Startcode to insert the foaf profile
# Added the foaf profile as a parameter
@classmethod
def insert(cls,
callback,
topic,
foaf,
verify_token,
secret,
hash_func='sha1',
lease_seconds=DEFAULT_LEASE_SECONDS,
now=datetime.datetime.now):
"""Marks a callback URL as being subscribed to a topic.
Creates a new subscription if None already exists. Forces any existing,
pending request (i.e., async) to immediately enter the verified state.
Args:
callback: URL that will receive callbacks.
topic: The topic to subscribe to.
verify_token: The verification token to use to confirm the
subscription request.
secret: Shared secret used for HMACs.
hash_func: String with the name of the hash function to use for HMACs.
lease_seconds: Number of seconds the client would like the subscription
to last before expiring. Must be a number.
now: Callable that returns the current time as a datetime instance. Used
for testing
Returns:
True if the subscription was newly created, False otherwise.
"""
"SMOB: This is the place I am collecting the data and inserting into a map"
"Start: Print"
logging.info('Start: Subscription Insertion, '
'callback = %s, topic = %s', callback, topic)
"End: Print"
key_name = cls.create_key_name(callback, topic)
now_time = now()
def txn():
sub_is_new = False
sub = cls.get_by_key_name(key_name)
if sub is None:
sub_is_new = True
sub = cls(key_name=key_name,
callback=callback,
callback_hash=sha1_hash(callback),
topic=topic,
topic_hash=sha1_hash(topic),
verify_token=verify_token,
secret=secret,
hash_func=hash_func,
lease_seconds=lease_seconds,
expiration_time=now_time)
sub.subscription_state = cls.STATE_VERIFIED
sub.expiration_time = now_time + datetime.timedelta(seconds=lease_seconds)
sub.confirm_failures = 0
sub.verify_token = verify_token
sub.secret = secret
sub.put()
#SMOB: Start Code == to connect and insert few details of the subscriber
#The object can be instantiated only once to connect and multiple inserts can be done
#Parse the FOAF and obtain triples including the PUsH vocab triples
logging.info('Is it a problem here??')
triples = reader.parsefoaf(foaf, False, topic, callback)
#Add the triples to the triple store
connect.insertTriples(triples)
#connect.insert(foaf)
#SMOB: END code
return sub_is_new
return db.run_in_transaction(txn)
@classmethod
def request_insert(cls,
callback,
topic,
verify_token,
secret,
auto_reconfirm=False,
hash_func='sha1',
lease_seconds=DEFAULT_LEASE_SECONDS,
now=datetime.datetime.now):
"""Records that a callback URL needs verification before being subscribed.
Creates a new subscription request (for asynchronous verification) if None
already exists. Any existing subscription request will be overridden;
for instance, if a subscription has already been verified, this method
will cause it to be reconfirmed.
Args:
callback: URL that will receive callbacks.
topic: The topic to subscribe to.
verify_token: The verification token to use to confirm the
subscription request.
secret: Shared secret used for HMACs.
auto_reconfirm: True if this task is being run by the auto-reconfirmation
offline process; False if this is a user-requested task. Defaults
to False.
hash_func: String with the name of the hash function to use for HMACs.
lease_seconds: Number of seconds the client would like the subscription
to last before expiring. Must be a number.
now: Callable that returns the current time as a datetime instance. Used
for testing
Returns:
True if the subscription request was newly created, False otherwise.
"""
key_name = cls.create_key_name(callback, topic)
def txn():
sub_is_new = False
sub = cls.get_by_key_name(key_name)
if sub is None:
sub_is_new = True
sub = cls(key_name=key_name,
callback=callback,
callback_hash=sha1_hash(callback),
topic=topic,
topic_hash=sha1_hash(topic),
secret=secret,
hash_func=hash_func,
verify_token=verify_token,
lease_seconds=lease_seconds,
expiration_time=(
now() + datetime.timedelta(seconds=lease_seconds)))
sub.confirm_failures = 0
sub.put()
sub.enqueue_task(cls.STATE_VERIFIED,
verify_token,
secret=secret,
auto_reconfirm=auto_reconfirm)
return sub_is_new
return db.run_in_transaction(txn)
@classmethod
def remove(cls, callback, topic):
"""Causes a callback URL to no longer be subscribed to a topic.
If the callback was not already subscribed to the topic, this method
will do nothing. Otherwise, the subscription will immediately be removed.
Args:
callback: URL that will receive callbacks.
topic: The topic to subscribe to.
Returns:
True if the subscription had previously existed, False otherwise.
"""
key_name = cls.create_key_name(callback, topic)
def txn():
sub = cls.get_by_key_name(key_name)
if sub is not None:
sub.delete()
return True
return False
return db.run_in_transaction(txn)
@classmethod
def request_remove(cls, callback, topic, verify_token):
"""Records that a callback URL needs to be unsubscribed.
Creates a new request to unsubscribe a callback URL from a topic (where
verification should happen asynchronously). If an unsubscribe request
has already been made, this method will do nothing.
Args:
callback: URL that will receive callbacks.
topic: The topic to subscribe to.
verify_token: The verification token to use to confirm the
unsubscription request.
Returns:
True if the Subscription to remove actually exists, False otherwise.
"""
key_name = cls.create_key_name(callback, topic)
def txn():
sub = cls.get_by_key_name(key_name)
if sub is not None:
sub.confirm_failures = 0
sub.put()
sub.enqueue_task(cls.STATE_TO_DELETE, verify_token)
return True
else:
return False
return db.run_in_transaction(txn)
@classmethod
def archive(cls, callback, topic):
"""Archives a subscription as no longer active.
Args:
callback: URL that will receive callbacks.
topic: The topic to subscribe to.
"""
key_name = cls.create_key_name(callback, topic)
def txn():
sub = cls.get_by_key_name(key_name)
if sub is not None:
sub.subscription_state = cls.STATE_TO_DELETE
sub.confirm_failures = 0
sub.put()
return db.run_in_transaction(txn)
@classmethod
def has_subscribers(cls, topic):
"""Check if a topic URL has verified subscribers.
Args:
topic: The topic URL to check for subscribers.
Returns:
True if it has verified subscribers, False otherwise.
"""
if (cls.all().filter('topic_hash =', sha1_hash(topic))
.filter('subscription_state =', cls.STATE_VERIFIED).get() is not None):
return True
else:
return False
@classmethod
def get_subscribers(cls, topic, count, starting_at_callback=None):
"""Gets the list of subscribers starting at an offset.
Args:
topic: The topic URL to retrieve subscribers for.
count: How many subscribers to retrieve.
starting_at_callback: A string containing the callback hash to offset
to when retrieving more subscribers. The callback at the given offset
*will* be included in the results. If None, then subscribers will
be retrieved from the beginning.
Returns:
List of Subscription objects that were found, or an empty list if none
were found.
"""
query = cls.all()
query.filter('topic_hash =', sha1_hash(topic))
query.filter('subscription_state = ', cls.STATE_VERIFIED)
if starting_at_callback:
query.filter('callback_hash >=', sha1_hash(starting_at_callback))
query.order('callback_hash')
return query.fetch(count)
def enqueue_task(self,
next_state,
verify_token,
auto_reconfirm=False,
secret=None):
"""Enqueues a task to confirm this Subscription.
Args:
next_state: The next state this subscription should be in.
verify_token: The verify_token to use when confirming this request.
auto_reconfirm: True if this task is being run by the auto-reconfirmation
offline process; False if this is a user-requested task. Defaults
to False.