-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTableETL.py
597 lines (347 loc) · 14 KB
/
TableETL.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
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import sqlalchemy as sa
from datetime import datetime, timedelta
from collections import defaultdict
from json import JSONEncoder,JSONDecoder
import requests
import threading
from queue import Queue
from time import sleep
from simple_salesforce import Salesforce
from os import environ, sys
from dotenv import load_dotenv
_ = load_dotenv()
# In[2]:
transformThreadCount = 3
logFileName = "TableETL_KippFoundation.log"
sqlSchema = 'etl'
saveFileBaseName = "SalesForceEduCloud_KippFound_%s.csv"
outputTableBaseName = "SalesForceEduCloud_KippFound_%s"
jsonConfigFileName = "TableETL-KippFoundation.json"
# In[3]:
logQueue = Queue()
def lprint(val):
outstr = f"[{datetime.now()}] ({threading.current_thread().name}) {val}"
print(outstr)
logQueue.put(outstr)
lprint("Started...")
# In[4]:
handleThreadError_Super = threading.excepthook
def handleThreadError(args):
lprint(f"ERROR!!! {args.exc_type} \"{args.exc_value}\" in thread {args.thread} ERROR!!!")
handleThreadError_Super(args)
threading.excepthook = handleThreadError
# In[5]:
def lprintDaemon():
with open(logFileName,"w") as logfile:
while True:
logfile.write(logQueue.get())
logfile.write("\n")
logfile.flush()
logQueue.task_done()
lprintDaemonThread = threading.Thread(target=lprintDaemon)
lprintDaemonThread.daemon = True
lprintDaemonThread.name = "lprintDaemon"
lprintDaemonThread.start()
# In[6]:
#sfusername = environ.get('KFsfusername')
#sfpassword = environ.get('KFsfpassword')
#sfsecret = environ.get("KFsfsecret")
sfclientid = environ.get("KFsfclientid")
sfclientsecret = environ.get("KFsfclientsecret")
sfinstanceurl = environ.get("KFsfinstanceurl")
connstr = environ.get("KNOS_Datawarehouse")
# In[7]:
lprint("Creating engine")
engine = sa.create_engine(connstr, fast_executemany=True, isolation_level="READ UNCOMMITTED")
# In[8]:
jsonDecoder = JSONDecoder()
# In[9]:
lprint(f"Reading config file {jsonConfigFileName}")
with open(jsonConfigFileName) as f:
jsonConfig = jsonDecoder.decode( f.read() )
lprint(jsonConfig)
# In[10]:
lprint("Setting destired tables")
desiredTables = list(jsonConfig['Tables'].keys())
lprint(desiredTables)
# In[11]:
#soqlFilters = defaultdict(lambda: "where IsDeleted = false LIMIT 1000", {})
soqlFilters = defaultdict(lambda: "where IsDeleted = false", {})
# In[12]:
lprint(f"Getting access token for {sfclientid} from instance {sfinstanceurl}")
sfVersion='58.0'
payload = {
'grant_type':'client_credentials',
'client_id':sfclientid,
'client_secret':sfclientsecret,
#'username':sfusername,
#'password':sfpassword+sfsecret
}
authURL = f"{sfinstanceurl}services/oauth2/token"
#authURL = "http://127.0.0.1:55555/services/oauth2/token"
lprint(f"Getting Auth token from {authURL}")
session = requests.Session()
authResp = session.post(authURL,\
data=payload,)
authRespData = jsonDecoder.decode(authResp.text)
# In[13]:
authRespDataPublic = authRespData.copy()
if 'access_token' in authRespDataPublic.keys():
authRespDataPublic['access_token'] = '*' * len(authRespDataPublic['access_token'])
lprint(authRespDataPublic)
# In[14]:
lprint("Creating Simple Salesforce Instance using sessionID...")
sf = Salesforce(instance_url=authRespData['instance_url'], session_id=authRespData['access_token'], version='58.0')
lprint("Session created!")
# In[15]:
metaData = {}
metaDataLock = threading.Lock()
for tbl in desiredTables:
fieldDescs = {}
lprint("Getting metadata for %s" % tbl)
tblDesc = getattr(sf, tbl).describe()
for field in tblDesc['fields']:
fieldDescs[field['name']] = {
'type':field['type'],
'length':field['length']
}
metaData[tbl] = fieldDescs
# In[16]:
daemonStatusLock = threading.Lock()
daemonStatus = {}
daemonCurTaskQueue = Queue()
# In[17]:
outputDataQueue = Queue()
extractDaemonStats = {}
def extractDaemon():
daemonName = 'extractDaemon'
while True:
with daemonStatusLock:
daemonStatus[daemonName] = f"{daemonName} waiting for job"
tbl = tableQueue.get()
daemonCurTaskQueue.put(daemonName)
lprint(f"Querying data for {tbl}")
startTime = datetime.now()
with daemonStatusLock:
daemonStatus[daemonName] = f"{daemonName} Querying data for {tbl}"
#with metaDataLock:
# feilds = ", ".join(metaData[tbl].keys())
feilds = ", ".join(jsonConfig['Tables'][tbl]['Columns'])
soql = "select %s from %s %s" % (feilds, tbl, soqlFilters[tbl])
lprint("Starting query: %s" % soql)
resp = sf.query_all(soql)
lprint(f"Adding {tbl} to output queue")
lprint("Finished %s" % tbl)
lprint("%s totalRecords %d" % (tbl, resp['totalSize']))
outputDataQueue.put( (tbl, resp) )
extractDaemonStats[tbl] = datetime.now() - startTime
tableQueue.task_done()
daemonCurTaskQueue.get()
daemonCurTaskQueue.task_done()
lprint("Creating extractDaemon Thread")
extractDaemonThread = threading.Thread(target=extractDaemon)
extractDaemonThread.daemon=True
extractDaemonThread.name = 'extractDaemon'
# In[18]:
dataFramesQueue = Queue()
transformDaemonStats = {}
transformDaemonStatsLock = threading.Lock()
transformDaemonThreads = []
def transformDaemon(num):
daemonName = f"transformDaemon[{num}]"
while True:
with daemonStatusLock:
daemonStatus[daemonName] = f"{daemonName} waiting for job"
(tbl, resp) = outputDataQueue.get()
daemonCurTaskQueue.put(daemonName)
lprint(f"Turning {tbl} into a dataframe")
startTime = datetime.now()
with daemonStatusLock:
daemonStatus[daemonName] = f"{daemonName} Turning {tbl} into a dataframe"
respDf = pd.DataFrame.from_dict(resp['records'])
if 'attributes' in respDf.columns:
lprint("Dropping attributes from %s" % tbl)
respDf.drop(columns=['attributes'], inplace=True)
lprint("%s shape %s" % (tbl, respDf.shape))
csvTblName = saveFileBaseName % tbl
lprint(f"Saving {tbl} to {csvTblName}")
with daemonStatusLock:
daemonStatus[daemonName] = f"{daemonName} Saving {tbl} to {csvTblName}"
respDf.to_csv(csvTblName, index=False)
lprint("Finished saving %s!" % tbl)
lprint(f"transforming columns for {tbl}...")
for col in respDf.columns:
with metaDataLock:
theType = metaData[tbl][col]['type']
with daemonStatusLock:
daemonStatus[daemonName] = f"{daemonName} processing {tbl}->{col}..."
if theType in ['date', 'datetime']:
lprint(f"Converting {tbl}->{col} to datetime...")
respDf[col] = pd.to_datetime(respDf[col], errors='coerce')
for col in respDf.columns:
if np.count_nonzero(respDf[col].map(lambda a: isinstance(a, dict ) or isinstance(a, list ))) > 0:
lprint("Ordered dict found in %s column %s converting..." % (tbl, col))
respDf[col] = respDf[col].map(lambda v: jcoder.encode(v) if not pd.isna(v) else None)
lprint("Updating type for %s column %s to JSON..." % (tbl, col))
with metaDataLock:
metaData[tbl][col]['type'] = 'JSON'
fieldLen = int(respDf[col].str.len().max())
lprint("Setting fieldlen to %d for %s" % (fieldLen, col))
with metaDataLock:
metaData[tbl][col]['length'] = int(respDf[col].str.len().max())
lprint(f"Adding response for {tbl} to dataFrame queue")
dataFramesQueue.put( (tbl, respDf) )
with transformDaemonStatsLock:
transformDaemonStats[tbl] = datetime.now() - startTime
outputDataQueue.task_done()
daemonCurTaskQueue.get()
daemonCurTaskQueue.task_done()
for i in range(transformThreadCount):
lprint(f"Creating dataFrameDaemon[{i}] thread")
threadObj = threading.Thread(target=transformDaemon,args=(i,))
threadObj.daemon=True
threadObj.name = f"transformDaemon[{i}]"
transformDaemonThreads.append(threadObj)
# In[19]:
jcoder = JSONEncoder()
# In[20]:
staticFields = {
'boolean':sa.Boolean,
'date':sa.DATE,
'datetime':sa.DATETIME,
'double': sa.FLOAT,
#'email',
#'id',
'int':sa.INT,
#'multipicklist',
#'picklist',
#'reference',
#'string',
'textarea':sa.TEXT,
#'JSON':sa.JSON
}
#this is a mess
def getSQLTypes(tbl, respDf):
with metaDataLock:
sqlTypes = {}
lprint("Getting SQLTypes for %s" % tbl)
curMeta = metaData[tbl]
for field in jsonConfig['Tables'][tbl]['Columns']:
if curMeta[field]['type'] in staticFields.keys():
sqlTypes[field] = staticFields[curMeta[field]['type']]()
else:
fieldLen = curMeta[field]['length']
if fieldLen <= 255:
sqlTypes[field] = sa.NVARCHAR(fieldLen)
#this is a fix they set some of the custom field max values to weird stuff
elif np.count_nonzero(~pd.isna(respDf[field])) > 0 \
and ( fieldLen := int(respDf[field].str.len().max())) <= 255:
sqlTypes[field] = sa.NVARCHAR(fieldLen)
else:
sqlTypes[field] = sa.TEXT()
return sqlTypes
# In[21]:
loadDaemonStats = {}
def loadDaemon():
daemonName = 'loadDaemon'
while True:
with daemonStatusLock:
daemonStatus[daemonName] = f"{daemonName} waiting for job"
(tbl, respDf) = dataFramesQueue.get()
daemonCurTaskQueue.put(daemonName)
startTime = datetime.now()
if respDf.shape[0] == 0:
lprint("Skipping %s no data!" % tbl)
loadDaemonStats[tbl] = "Skipped, no data!"
dataFramesQueue.task_done()
daemonCurTaskQueue.get()
daemonCurTaskQueue.task_done()
continue
with daemonStatusLock:
daemonStatus[daemonName] = f"{daemonName} getting SQL types for {tbl}"
sqlTypes = getSQLTypes(tbl, respDf)
sqlTblName = outputTableBaseName % tbl
lprint("Uploading table %s to etl.%s" % (tbl, sqlTblName))
with daemonStatusLock:
daemonStatus[daemonName] = f"{daemonName} uploading {tbl}"
with engine.begin() as conn:
respDf.to_sql(sqlTblName, conn, schema=sqlSchema, if_exists='replace', index=False, dtype=sqlTypes, chunksize=1)
lprint("Finished uploading %s!" % tbl)
loadDaemonStats[tbl] = datetime.now() - startTime
dataFramesQueue.task_done()
daemonCurTaskQueue.get()
daemonCurTaskQueue.task_done()
lprint("Creating loadDaemon thread")
loadDaemonThread = threading.Thread(target=loadDaemon)
loadDaemonThread.daemon=True
loadDaemonThread.name = "loadDaemon"
# In[22]:
tableQueue = Queue()
for tbl in desiredTables:
lprint(f"Queuing {tbl}")
tableQueue.put(tbl)
# In[23]:
lprint("Starting loadDaemon thread")
loadDaemonThread.start()
# In[24]:
lprint("Starting dataFrameDaemon threads")
for i,thread in enumerate(transformDaemonThreads):
lprint(f"Starting dataFrameDaemon[{i}]")
thread.start()
# In[25]:
lprint("Starting query Thread")
extractDaemonThread.start()
# In[26]:
lprint("All daemons started!")
# In[ ]:
comboSize = 1
while comboSize > 0:
tqSize = tableQueue.qsize()
odqSize = outputDataQueue.qsize()
dfqSize = dataFramesQueue.qsize()
runSize = daemonCurTaskQueue.qsize()
comboSize = tqSize + odqSize + dfqSize + runSize
with daemonStatusLock:
lprint("Daemon Status:\n" + ("\n".join(daemonStatus.values())))
lprint(f"Extract queue({tqSize})\tTransform queue({odqSize})\tLoad queue({dfqSize})\tRunning({runSize})\tTotal({comboSize})")
sleep(30)
lprint("All queues are empty but uploading is most likely still continueing")
# In[ ]:
tableQueue.join()
lprint("All table data extracted")
outputDataQueue.join()
lprint("All data transformed!")
dataFramesQueue.join()
lprint(f"All data loaded to {engine}")
# In[ ]:
daemonCurTaskQueue.join()
lprint("All running daemons have completed!")
# In[ ]:
for key in sorted(extractDaemonStats.keys()):
lprint(f"extractDaemon processed {key} in {extractDaemonStats[key]}")
# In[ ]:
for key in sorted(transformDaemonStats.keys()):
lprint(f"transformDaemon processed {key} in {transformDaemonStats[key]}")
# In[ ]:
for key in sorted(loadDaemonStats.keys()):
lprint(f"loadDaemon processed {key} in {loadDaemonStats[key]}")
# In[ ]:
statLists = [extractDaemonStats, transformDaemonStats, loadDaemonStats]
for key in sorted(extractDaemonStats.keys()):
if np.all([isinstance(statList[key], timedelta) for statList in statLists]):
comboTime = np.sum([statList[key] for statList in statLists])
lprint(f"{key} completed in {comboTime}")
else:
lprint(F"{key} incomplete {[str(l[key]) for l in statLists]}")
# In[ ]:
lprint("=============DONE!===================")
# In[ ]:
sleep(5)
# In[ ]:
#jupyter nbconvert .\TableETL-KippFoundation.ipynb --to python
# In[ ]: