This repository was archived by the owner on Feb 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathload.py
More file actions
561 lines (476 loc) · 14.1 KB
/
load.py
File metadata and controls
561 lines (476 loc) · 14.1 KB
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
import os
import sys
import time
import urllib2
import base64
import json
import ssl
import zlib
import threading
from threading import Lock
from httplib import *
from config import Config
from apiclient.errors import *
import logging.config
import tweepy
from utils import Utils
NEWLINE = '\r\n'
SLEEP_TIME = 10
f = file("./config")
config = Config(f)
class GnipListener(object):
CHUNK_SIZE = 4 * 1024
KEEP_ALIVE = 30 # seconds
HEADERS = { 'Accept': 'application/json',
'Connection': 'Keep-Alive',
'Accept-Encoding' : 'gzip',
'Authorization' : 'Basic %s' % base64.encodestring('%s:%s' % (config.GNIP_STREAM_USERNAME, config.GNIP_STREAM_PASSWORD)) }
"""docstring for ClassName"""
def __init__(self, schema, table_mapping, logger=None):
self.schema = schema
self.table_mapping = table_mapping
self.default_table = table_mapping.values()[0]
self.count = 0
self.logger = logger
def on_data(self, data):
# get bulk records, but process individually based on tag-based routing
records_str = data.strip().split(NEWLINE)
for r in records_str:
record = json.loads(r)
if not record.get('delete', None):
tags = self.get_table_tags(record)
if not tags:
tags = [self.default_table]
# process multiple tags on a record
for tag in tags:
table = None
if not tag:
table = self.default_table
else:
table = self.table_mapping.get(tag, None)
if not table:
table = tag.split(".")
created = Utils.insert_table(table[0], table[1]) #, self.schema)
# Brand new table
if created and created != True:
self.logger.info('Created BQ table: %s' % tag)
self.table_mapping[tag] = table
record_scrubbed = Utils.scrub(record)
Utils.insert_records(table[0], table[1], [record_scrubbed])
if self.logger:
self.logger.info('@%s: %s (%s)' % (record['actor']['preferredUsername'], record['body'].encode('ascii', 'ignore'), tags))
self.count = self.count + 1
return True
def get_table_tags(self, record):
gnip = record.get('gnip', None)
if gnip:
matching_rules = gnip.get('matching_rules', None)
if matching_rules:
return [rule.get("tag", None) for rule in matching_rules]
return None
@staticmethod
def start(schema, logger):
# initialize table mapping for default table
# BUGBUG: initialize based on query to prod
table_mapping = {
config.DATASET_ID + "." + config.TABLE_ID : [config.DATASET_ID, config.TABLE_ID]
}
datasets = Utils.get_bq().datasets().list(projectId=config.PROJECT_ID).execute()
datasets = datasets.get("datasets", None)
for d in datasets:
ref = d.get("datasetReference", None)
bq_tables = Utils.get_bq().tables().list(projectId=ref.get("projectId"), datasetId=ref.get("datasetId")).execute()
if bq_tables['totalItems'] > 0:
for t in bq_tables.get("tables", None):
ref = t.get("tableReference", None)
dataset_id = ref.get("datasetId", None)
table_id = ref.get("tableId", None)
key = Utils.make_tag(dataset_id, table_id)
table_mapping[key] = [dataset_id, table_id]
print("Initialized tables: %s" % table_mapping)
listener = GnipListener(schema, table_mapping, logger=logger)
while True:
stream = None
try:
# clean gnip headers
_headers = GnipListener.HEADERS
headers = {}
for k, v in _headers.items():
headers[k] = v.strip()
#req = urllib2.Request(config.GNIP_STREAM_URL, headers=GnipListener.HEADERS)
req = urllib2.Request(config.GNIP_STREAM_URL, headers=headers)
response = urllib2.urlopen(req, timeout=(1+GnipListener.KEEP_ALIVE))
decompressor = zlib.decompressobj(16+zlib.MAX_WBITS)
remainder = ''
while True:
tmp = decompressor.decompress(response.read(GnipListener.CHUNK_SIZE))
if tmp == '':
return
[records, remainder] = ''.join([remainder, tmp]).rsplit(NEWLINE,1)
listener.on_data(records)
get_stream(listener)
except:
logger.exception("Unexpected error:");
if stream:
stream.disconnect()
time.sleep(SLEEP_TIME)
# Write records to BigQuery
class TwitterListener(tweepy.StreamListener):
# items to track if you're doing a public track call
_TRACK_ITEMS = [
'@JetBlue',
'@southwestair',
'@AirAsia',
'@AmericanAir',
'@flyPAL',
'@TAMAirlines',
'@Delta',
'@virginamerica',
'@klm',
'@turkishairlines',
'@BritishAirways',
'@usairways',
'@British_Airways',
'@westjet',
'@MAS',
'@United',
'@baltiausa',
'@Lufthansa_DE',
'@virginatlantic',
'@virginaustralia',
'@AlaskaAir',
'@DeltaAssist',
'@aircanada',
'@easyJet',
'@vueling'
]
TRACK_ITEMS = [
'#data15',
'#SelfServeAnalytics',
'#SelfServeAtTableau',
'#ServerEmailAlert',
'#ServerPermission',
'#ServerToolbox',
'#ShipTableau',
'#SlalomDrive',
'#SmartDriveData',
'#SolarWindsData',
'#SquareData',
'#StatControl',
'#StateStreetData',
'#StJosephData',
'#StoryPointsData',
'#StubbornCalcs',
'#SwedishData',
'#SyscoData',
'#SyscoSupplyChain',
'#TabCmD',
'#Tabjolt',
'#TableauAcrossDepartments',
'#TableauAuth',
'#TableauAWSEC2',
'#TableauConsultant',
'#TableauDataGov',
'#TableauForecast',
'#TableauGA',
'#TableauITService',
'#TableauJedi',
'#TableauJediCalcs',
'#TableauLogs',
'#TableauOLAP',
'#TableauOnlineAdmin',
'#TableauSAP',
'#TableauSFDC',
'#TableauShoestring',
'#TableauSith',
'#TableauSocialData',
'#TacomaCCData',
'#TargetData',
'#TCFData',
'#TDBankData',
'#TDEFast',
'#TDEROI',
'#TimeInTableau',
'#ToughData',
'#TripAdvisorData',
'#TruecarData',
'#UnderstandingLOD',
'#UndertoneData',
'#UnifundData',
'#UnlockData',
'#UpliftData',
'#UpPerformance',
'#USDeptLaborData',
'#UtahStateData',
'#UTAustinData',
'#UTElPasoData',
'#VisualPipeline',
'#VitamixData',
'#VizBestPractice',
'#VizTips',
'#VSPData',
'#WalmartData',
'#WantToAdmin',
'#WayfairData',
'#WebDataConnect',
'#WildData',
'#YouDidWhat',
'#ZenAppDesign',
'#ZenJourney',
'#ZilliantData',
'#ZotecData',
'#TCRumors',
'#TCCRumors',
'#Rundata15',
'#Watchmeviz',
'#tableauontableau',
'#data15rumors',
'#tableaugroups',
'#datanightout',
'#data15keynote',
'#datapluswomen',
'#tableauzenmaster',
'#ironviz',
'#salesdashboards',
'#3tierdata',
'#50shadesdata',
'#AddValueJSAPI',
'#ADPdata',
'#advancedcalcs',
'#advancedlods',
'#advancedmaps',
'#advancedrstats',
'#advtablecalcs',
'#aljazeeradata',
'#allstatedata',
'#amazondata',
'#AnalyticsAtScale',
'#AnalyticsPane',
'#ArbysData',
'#AxisData',
'#BasicStats',
'#BCBSData',
'#BeyondMarkTypes',
'#BeyondSparkler',
'#BIalyticsStories',
'#BJCData',
'#BlendingQuestions',
'#BoeingData',
'#BoogalooViz',
'#BostonData',
'#BostonSciData',
'#CachingQueries',
'#tableau',
'#CalcMethods',
'#CareerbuilderData',
'#CarlsonRezidorData',
'#CarsData',
'#CartographerTips',
'#CaterpillarData',
'#CentsOfData',
'#CernerData',
'#CiscoBigDataViz',
'#CiscoData',
'#CiscoSupplyChain',
'#ClevelandClinicData',
'#ClimateCorpData',
'#Cloud9Tableau',
'#ColumbiaData',
'#ComcastData',
'#ComicsStorytelling',
'#ConcurData',
'#ConEdData',
'#CoreQuery',
'#CreativeCalcs',
'#CreditSuisseData',
'#CustomAdminViews',
'#CustomSQL',
'#DashboardImpossible',
'#DashboardsMyWay',
'#DashboardTurbo',
'#DataToTheCloud',
'#DataWrangle',
'#DCPSData',
'#DearDataTwo',
'#DeepDiveQueries',
'#DeloitteData',
'#DemystifyR',
'#DenseData',
'#DePaulData',
'#DesMoinesData',
'#DiscoveryStats',
'#DisneyData',
'#DoubleDownDataServer',
'#DrawWithTableau',
'#DriveAnalytics',
'#DukeData',
'#DwollaData',
'#easyJetData',
'#eBayData',
'#EbolaData',
'#EmbedSFDC',
'#EmbedTableau',
'#EMCData',
'#EnvironicsData',
'#ExcelWithTableau',
'#ExelonData',
'#ExtractAPIPython',
'#ExtremeParameters',
'#ExtremeViz',
'#EYData',
'#FacebookData',
'#FloridaDJJData',
'#FreescaleData',
'#FresnoStateData',
'#GamesInTableau',
'#GetMoreREST',
'#GlidewellData',
'#GoogleData',
'#GrouponData',
'#GuaranteedRateData',
'#HadoopItRight',
'#HandsOnMapping',
'#HandsOnStats',
'#HCAData',
'#HireRockstars',
'#HomeDepotData',
'#HootsuiteData',
'#HotDirtySets',
'#InteractionsData',
'#InteractiveParameters',
'#IntroAPIS',
'#IntroCalcs',
'#IntroMapping',
'#IntroToLOD',
'#JandJData',
'#KaiserData',
'#KantarData',
'#KatyISDData',
'#KiewitData',
'#KKIntlData',
'#KoboData',
'#LargestDeployment',
'#LieWithStats',
'#LifelineData',
'#LinguisticData',
'#LinkedInAnalytics',
'#LODsOfFun',
'#LovesSets',
'#MacysData',
'#MagicWithMarks',
'#MapboxFab',
'#MaximData',
'#MerkleData',
'#MichiganData',
'#MinorityReportUX',
'#MobileWithTableau',
'#MtSinaiData',
'#MylanData',
'#NetAppData',
'#NetflixData',
'#NeuroscienceStorytell',
'#NextelData',
'#NotInShowMe',
'#OIdata',
'#OldcastleData',
'#OptimizeLiveQuery',
'#OrderOfOps',
'#PaloAltoData',
'#PiedmontData',
'#PluralsightData',
'#PracticalDashboards',
'#ProgressiveData',
'#QuestionDrivenViz',
'#QuickenData',
'#RDeepDive',
'#RealtorData',
'#RenderTableau',
'#RetailMeNotData',
'#RosettaData',
'#RubbermaidData',
'#RunTheTable',
]
def __init__(self, dataset_id, table_id, logger=None):
self.dataset_id = dataset_id
self.table_id = table_id
self.count = 0
self.logger = logger
self.calm_count = 0
def on_data(self, data):
self.calm_count = 0
# Twitter returns data in JSON format - we need to decode it first
record = json.loads(data)
if not record.get('delete', None):
record_scrubbed = Utils.scrub(record)
Utils.insert_records(self.dataset_id, self.table_id, [record_scrubbed])
if self.logger:
self.logger.info('@%s: %s' % (record['user']['screen_name'], record['text'].encode('ascii', 'ignore')))
self.count = self.count + 1
return True
#handle errors without closing stream:
def on_error(self, status_code):
if status_code == 420:
self.backoff('Status 420')
return True
if self.logger:
self.logger.info('Error with status code: %s' % status_code)
return False
# got disconnect notice
def on_disconnect(self, notice):
self.backoff('Disconnect')
return False
def on_timeout(self):
self.backoff('Timeout')
return False
def on_exception(self, exception):
if self.logger:
self.logger.exception('Exception')
return False
def backoff(self, msg):
self.calm_count = self.calm_count + 1
sleep_time = 60 * self.calm_count
if sleep_time > 320:
sleep_time = 320
if self.logger:
self.logger.info(msg + ", sleeping for %s" % sleep_time)
time.sleep(60 * self.calm_count)
return
@staticmethod
def start(schema, logger):
listener = TwitterListener(config.DATASET_ID, config.TABLE_ID, logger=logger)
auth = tweepy.OAuthHandler(config.CONSUMER_KEY, config.CONSUMER_SECRET)
auth.set_access_token(config.ACCESS_TOKEN, config.ACCESS_TOKEN_SECRET)
while True:
logger.info("Connecting to Twitter stream")
stream = None
try:
stream = tweepy.Stream(auth, listener, headers = {"Accept-Encoding": "deflate, gzip"})
# Choose stream: filtered or sample
stream.sample()
# stream.filter(track=TwitterListener.TRACK_ITEMS)
except:
logger.exception("Unexpected error");
if stream:
stream.disconnect()
time.sleep(60)
def main():
if config.MODE not in ['gnip', 'twitter']:
print "Invalid mode: %s" % config.MODE
exit()
logger = Utils.enable_logging()
print "Running in mode: %s" % config.MODE
schema_file = None
if config.MODE == 'gnip':
schema_file = "./schema/schema_gnip.json"
else:
schema_file = "./schema/schema_twitter.json"
schema_str = Utils.read_file(schema_file)
schema = json.loads(schema_str)
Utils.insert_table(config.DATASET_ID, config.TABLE_ID, schema)
print "Default table: %s.%s" % (config.DATASET_ID, config.TABLE_ID)
if config.MODE == 'gnip':
GnipListener.start(schema, logger)
elif config.MODE == 'twitter':
TwitterListener.start(schema, logger)
if __name__ == "__main__":
main()