-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathpycore.py
6705 lines (5209 loc) · 301 KB
/
pycore.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
import os, inspect, datetime, uuid, json, glob, random, logging, sys, copy, time
from sqlalchemy import Column, Integer, String, ForeignKey, Table, create_engine, MetaData, Date, DateTime, Float, Boolean, and_, or_, asc, desc
from sqlalchemy.orm import relationship, backref, scoped_session, sessionmaker, relation
from sqlalchemy.ext.declarative import declarative_base
from src.common.shellprinting import *
from src.logger.logger import Logger
class PyCore:
def __init__(self, core_manifest=str(os.getenv("ENV_CONFIGS_DIR", "/opt/work/configs") + "/jupyter.json")):
# the json config for this core:
self.m_core_file = core_manifest
self.m_db_json = {}
self.m_debug = False
# needs to be in the /opt/work/configs/jupyter.json => Core.Envs JSON Dict
self.m_env = str(os.getenv("ENV_DEPLOYMENT_TYPE", "Local"))
self.m_log = None # Eventually this will have syslog with: Logger(self.m_name, "/dev/log", logging.DEBUG)
self.m_core_json = {}
self.m_dbs = {} # dictionary where the keys are logical names for the underlying db session (applications)
self.m_db_apps_json = {}
self.m_db_app_system = None
self.m_rds = {} # dictionary where the keys are logical names for the underlying redis connections (applications)
self.m_rd_apps_json = {}
self.m_rd_app_system = None
self.m_slack_node_name = "jupyter"
self.m_slack_node = {
"BotName" : str(os.getenv("ENV_SLACK_BOTNAME", "bugbot")),
"ChannelName" : str(os.getenv("ENV_SLACK_CHANNEL", "debugging")),
"NotifyUser" : str(os.getenv("ENV_SLACK_NOTIFY_USER", "channel")),
"Token" : str(os.getenv("ENV_SLACK_TOKEN", "xoxb-51351043345-Lzwmto5IMVb8UK36MghZYMEi")),
"EnvName" : str(os.getenv("ENV_SLACK_ENVNAME", "dev-jupyter"))
}
self.m_slack_bot = str(self.m_slack_node["BotName"])
self.m_slack_enabled = os.getenv("ENV_SLACK_ENABLED", "1") == "1"
# load the core
self.load_json()
# Assign the name out of the json config
self.m_name = str(self.m_core_json["Core"]["Name"])
self.m_locale_dict = {}
self.m_locale_abb_dict = {}
self.load_db_apps()
self.load_redis_apps()
self.m_last_start_time = None
self.m_last_end_time = None
self.m_last_check_time = None
self.m_colors = {
"red" : "#E74C3C",
"feldspar" : "#D19275",
"orange" : "#FF7D40",
"pink" : "#FFCCCC",
"green" : "#2ECC71",
"blue" : "#3498db",
"black" : "#111111",
"copper" : "#EDC393",
"brown" : "#6B4226",
"lightgreen" : "#C0FF3E",
"darkgreen" : "#385E0F",
"maroon" : "#800000",
"gray" : "#8B8989",
"gold" : "#FFCC11",
"yellow" : "#FFE600",
"volumetop" : "#385E0F",
"volume" : "#ADFF2F",
"high" : "#CC1100",
"low" : "#164E71",
"open" : "#608DC0",
"close" : "#99CC32",
"white" : "#FFFFFF"
}
self.m_last_color_idx = -1
self.m_color_rotation = []
self.m_is_notebook = False
# end of __init__
def lg(self, msg, level=6):
# log it to syslog
if self.m_log:
# concat them
full_msg = self.m_name + ": " + msg
self.m_log.log(full_msg, level)
else:
if not self.m_is_notebook:
lg(str(self.m_name) + ": " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + " " + str(msg), level)
if self.m_debug:
lg(str(self.m_name) + ": " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")) + " " + str(msg), level)
return None
# end of lg
#####################################################################################################
#
# Initialize Resources
#
#####################################################################################################
def init_resources(self):
self.load_json()
self.load_db_apps()
self.load_redis_apps()
# end of init_resources
def load_json(self):
if len(self.m_core_json) == 0:
self.m_core_json = json.loads(open(self.m_core_file).read())
self.m_db_apps_json = json.loads(open(self.m_core_json["Core"]["Envs"][self.m_env]["Database"]).read())
self.m_rd_apps_json = json.loads(open(self.m_core_json["Core"]["Envs"][self.m_env]["Redis"]).read())
# end of load_json
def load_db_apps(self):
self.load_json()
if self.m_debug:
self.lg("Looking up DB Connectivity File", 6)
# end of if debug
# Load them if there are apps
if len(self.m_db_apps_json["Database Applications"]) > 0:
# Add the source base path
self.load_src_path("ENV_PYTHON_SRC_DIR", "/opt/work/src")
from connectors.database.database_application_system import DatabaseApplicationSystem
self.m_db_app_system = DatabaseApplicationSystem(None, False)
self.m_dbs = self.m_db_app_system.return_connectors(self.m_db_apps_json["Database Applications"])
self.m_db_app_system.connect_all()
# end of if there are Database apps to load
# end of load_db_apps
def load_redis_apps(self):
self.load_json()
if self.m_debug:
self.lg("Looking up RA Connectivity File", 6)
# end of if debug
# Load them if there are apps
if len(self.m_rd_apps_json["Redis Applications"]) > 0:
# Add the source base path
self.load_src_path("ENV_PYTHON_SRC_DIR", "/opt/work/src")
from connectors.redis.redis_application_system import RedisApplicationSystem
self.m_ra_app_system = RedisApplicationSystem(self.m_log, False)
self.m_rds = self.m_ra_app_system.return_connectors(self.m_rd_apps_json["Redis Applications"])
self.m_ra_app_system.connect_all()
# end of if there are Redis apps to load
# end of load_redis_apps
def load_thirdparty_dir(self, dir_name, debug=False):
load_dir = "/opt/work/src/thirdparty/" + str(dir_name)
if debug:
print load_dir
self.load_src_path("ENV_THIRD_PARTY_SOURCE_DIR", load_dir)
# end of load_thirdparty_dir
def load_src_path(self, env_key, default_path):
import sys
add_path = os.getenv(env_key, default_path)
found_path = False
for path in sys.path:
if path == add_path:
found_path = True
break
# end of iterating through path
if not found_path:
sys.path.insert(0, add_path)
# end of need to add path
# end of load_src_path
def enable_debug(self):
self.m_debug = True
# end of enable_debug
def disable_debug(self):
self.m_debug = False
# end of disable_debug
def is_notebook(self):
self.m_is_notebook = True
# end of is_notebook
#####################################################################################################
#
# AWS Methods
#
#####################################################################################################
def running_on_aws(self, debug=False):
return os.path.exists("/opt/aws/bin/ec2-metadata")
# end of running_on_aws
def aws_get_keys(self, debug=False):
record = {
"Key" : os.getenv("ENV_AWS_KEY"),
"Secret" : os.getenv("ENV_AWS_SECRET")
}
return record
# end of aws_get_keys
def aws_get_instance_from_metadata(self, debug=False):
results = self.build_def_hash("Display Error", "Failed to Get EC2 Instance from MetaData", {
"Name" : "",
"InstanceID" : "",
"InstanceType" : "",
"ImageID" : "",
"Running" : "",
"ImageName" : "",
"ExternalIP" : "",
"InternalIP" : ""
})
try:
import os, boto
if os.path.exists("/tmp/publicip"):
os.system("rm -f /tmp/publicip >> /dev/null")
cur_ip = ""
if self.running_on_aws():
os.system("/opt/aws/bin/ec2-metadata | grep public-ipv4 | awk '{print $NF}' > /tmp/publicip")
cur_ip = open("/tmp/publicip").read().strip().lstrip()
else:
cur_ip = "54.188.188.188"
if cur_ip == "":
self.lg("ERROR: Invalid IP(" + str(cur_ip) + ")", 0)
else:
self.lg("Looking for IP(" + str(cur_ip) + ")", 6)
aws_creds = self.aws_get_keys()
ec2 = boto.connect_ec2(aws_creds["Key"], aws_creds["Secret"])
filters = {"ip-address": cur_ip}
inst_list = ec2.get_only_instances(filters=filters)
if len(inst_list) > 0:
instance = inst_list[0]
if str(instance.ip_address) == str(cur_ip):
#self.lg("Res(" + str(reservation.id) + ") Instance(" + str(iidx) + ") ID(" + str(instance) + ")", 6)
tag_name = ""
if "Name" in instance.tags:
tag_name = str(instance.tags["Name"])
ami_results = ec2.get_all_images(image_ids=[str(instance.image_id)])
ami_name = ""
if len(ami_results) > 0:
if str(ami_results[0].name) != "":
ami_name= str(ami_results[0].name)
results["Record"] = {
"Name" : str(tag_name),
"InstanceID" : str(instance.id),
"InstanceType" : str(instance.instance_type),
"ImageID" : str(instance.image_id),
"Running" : str(instance.state),
"ImageName" : str(ami_name),
"ExternalIP" : str(instance.ip_address),
"InternalIP" : str(instance.private_ip_address)
}
if not self.running_on_aws():
results["Record"]["Name"] = "DSWorker-1"
# end if the ip matches
# end of get all instances
# end of if there's an ip or not
os.system("rm -f /tmp/publicip >> /dev/null")
results["Status"] = "SUCCESS"
results["Error"] = ""
except Exception,e:
err_msg = "Failed to Get Instance from MetaData with Ex(" + str(e) + ")"
self.lg("ERROR: " + str(err_msg), 0)
results = self.build_def_hash("Display Error", "Failed to Get Instance From MetaData", {
"Name" : "",
"InstanceID" : "",
"InstanceType" : "",
"ImageID" : "",
"Running" : "",
"ImageName" : "",
"ExternalIP" : "",
"InternalIP" : ""
})
results["Status"] = "FAILED"
results["Error"] = ""
# end of try/ex
return results
# end of aws_get_instance_from_metadata
def aws_get_instance_from_name(self, cur_name, debug=False):
results = self.build_def_hash("Display Error", "Failed to Get EC2 Instance by Name", {
"Name" : "",
"InstanceID" : "",
"InstanceType" : "",
"ImageID" : "",
"Running" : "",
"ImageName" : "",
"ExternalIP" : "",
"InternalIP" : ""
})
try:
import os, boto
if cur_name == "":
self.lg("ERROR: Invalid Name(" + str(cur_name) + ")", 0)
else:
self.lg("Looking for Name(" + str(cur_name) + ")", 6)
aws_creds = self.aws_get_keys()
ec2 = boto.connect_ec2(aws_creds["Key"], aws_creds["Secret"])
filters = {"tag:Name" : cur_name}
inst_list = ec2.get_only_instances(filters=filters)
if len(inst_list) > 0:
instance = inst_list[0]
if str(instance.ip_address) != "":
tag_name = ""
if "Name" in instance.tags:
tag_name = str(instance.tags["Name"])
if str(tag_name).lower().strip().lstrip() == str(cur_name).lower().strip().lstrip():
ami_results = ec2.get_all_images(image_ids=[str(instance.image_id)])
ami_name = ""
if len(ami_results) > 0:
if str(ami_results[0].name) != "":
ami_name= str(ami_results[0].name)
results["Record"] = {
"Name" : str(tag_name),
"InstanceID" : str(instance.id),
"InstanceType" : str(instance.instance_type),
"ImageID" : str(instance.image_id),
"Running" : str(instance.state),
"ImageName" : str(ami_name),
"ExternalIP" : str(instance.ip_address),
"InternalIP" : str(instance.private_ip_address)
}
# end if the ip matches
# end of get all instances
# end of if there's an ip or not
results["Status"] = "SUCCESS"
results["Error"] = ""
except Exception,e:
err_msg = "Failed to Get Instance from Name with Ex(" + str(e) + ")"
self.lg("ERROR: " + str(err_msg), 0)
results = self.build_def_hash("Display Error", "Failed to Get Instance From Name", {
"Name" : "",
"InstanceID" : "",
"InstanceType" : "",
"ImageID" : "",
"Running" : "",
"ImageName" : "",
"ExternalIP" : "",
"InternalIP" : ""
})
results["Status"] = "FAILED"
results["Error"] = ""
# end of try/ex
return results
# end of aws_get_instance_from_name
def aws_get_instances(self, debug=False):
results = self.build_def_hash("Display Error", "Failed to Get EC2 Instances", { "Instances" : [] })
try:
import os, boto
aws_creds = self.aws_get_keys()
ec2 = boto.connect_ec2(aws_creds["Key"], aws_creds["Secret"])
reservations = ec2.get_all_instances()
for ridx, reservation in enumerate(reservations):
for iidx, instance in enumerate(reservation.instances):
#self.lg("Res(" + str(reservation.id) + ") Instance(" + str(iidx) + ") ID(" + str(instance) + ")", 6)
tag_name = ""
if "Name" in instance.tags:
tag_name = str(instance.tags["Name"])
ami_results = ec2.get_all_images(image_ids=[str(instance.image_id)])
ami_name = ""
if len(ami_results) > 0:
if str(ami_results[0].name) != "":
ami_name= str(ami_results[0].name)
results["Record"]["Instances"].append({
"Name" : str(tag_name),
"InstanceID" : str(instance.id),
"InstanceType" : str(instance.instance_type),
"ImageID" : str(instance.image_id),
"Running" : str(instance.state),
"ImageName" : str(ami_name),
"ExternalIP" : str(instance.ip_address),
"InternalIP" : str(instance.private_ip_address)
})
# end of get all instances
# end of get all reservations
results["Status"] = "SUCCESS"
results["Error"] = ""
except Exception,e:
err_msg = "Failed to Get All Instances with Ex(" + str(e) + ")"
self.lg("ERROR: " + str(err_msg), 0)
results = self.build_def_hash("Display Error", "Failed to Get EC2 Instances", {})
results["Status"] = "FAILED"
results["Error"] = ""
# end of try/ex
return results
# end of aws_get_instances
#####################################################################################################
#
# General Util Methods
#
#####################################################################################################
def get_dbs(self):
return self.m_dbs
# end of get_dbs
def get_rds(self):
return self.m_rds
# end of get_rds
def db_convert_utc_date_to_str(self, db_cur_date):
return_str = ""
if db_cur_date != None:
convert_date = db_cur_date - datetime.timedelta(hours=4)
return_str = str(convert_date.strftime('%m/%d/%Y %H:%M:%S'))
return return_str
# end of db_convert_utc_date_to_str
def db_convert_date_to_str(self, db_cur_date, optional_format="%m/%d/%Y %H:%M:%S"):
return_str = ""
if db_cur_date != None:
return_str = str(db_cur_date.strftime(optional_format))
return return_str
# end of db_convert_date_to_str
def convert_utc_date_to_str(self, cur_date, optional_format="%m/%d/%Y %H:%M:%S"):
return_str = ""
if cur_date != None:
convert_date = cur_date - datetime.timedelta(hours=4)
return_str = str(convert_date.strftime('%m/%d/%Y %H:%M:%S'))
return return_str
# end of convert_utc_date_to_str
def convert_date_string_to_date(self, date_str, optional_format="%Y-%m-%dT%H:%M:%S.%fZ"):
date_to_return = None
try:
import datetime
date_to_return = datetime.datetime.strptime(str(date_str), optional_format)
except Exception,f:
self.lg("ERROR: Failed Converting Date(" + str(date_str) + ") with Format(" + str(optional_format) + ")", 0)
# end of tries to read this string as a valid date...
return date_to_return
# end of convert_date_string_to_date
def build_unique_key(self, length=-1):
return str(str(uuid.uuid4()).replace("-", "")[0:length])
# end of build_unique_key
def ppj(self, json_data):
return str(json.dumps(json_data, sort_keys=True, indent=4, separators=(',', ': ')))
# end of ppj
def convert_utc_date_string_to_est_datetime(self, utc_date_str, optional_format="%Y-%m-%dT%H:%M:%S.%fZ"):
utc_time = datetime.datetime.strptime(utc_date_str, optional_format)
utc_adjusted = utc_time.replace(tzinfo=self.m_utc_tz_zone)
offset_est_local_time = utc_adjusted.astimezone(self.m_est_tz_zone)
est_local_time = datetime.datetime(
year = offset_est_local_time.year,
month = offset_est_local_time.month,
day = offset_est_local_time.day,
hour = offset_est_local_time.hour,
minute = offset_est_local_time.minute,
second = offset_est_local_time.second)
return est_local_time
# end of convert_utc_date_string_to_est_datetime
def create_random_float(self, original, min_value, max_value):
new_random_float= float(original) + float(random.uniform(min_value, max_value))
return new_random_float
# end of create_random_float
def create_random_int(self, original, min_value, max_value):
new_random_int = random.uniform(min_value, max_value)
return original + int(int(original) * float(new_random_int))
# end of create_random_int
def get_random_number_in_range(self, min_int, max_int):
import random
return random.randint(min_int, max_int)
# end of get_random_number_in_range
def get_percent_done(self, progress, total):
return "%0.2f" % float(float(progress)/float(total)*100.00)
# end of get_percent_done
def to_float_str(self, cur_float):
return str("%0.2f" % float(cur_float))
# end of to_float_str
def to_upper(self, cur_str):
return str(cur_str).upper().strip().lstrip()
# end of to_upper
def width_percent_done(self, idx, total):
percent_str = "Percent(" + str(self.get_percent_done(idx, total)) + ")"
if len(percent_str) < 14:
percent_str += " "
return percent_str
# end of width_percent_done
def timer_start(self):
self.m_last_start_time = datetime.datetime.now()
# end of timer_start
def timer_end(self):
self.m_last_end_time = datetime.datetime.now()
# end of timer_end
def how_long(self):
if self.m_last_start_time == None:
self.lg("Forgot to start the timer with: self.timer_start()", 0)
return "-1"
# In case I forget to stop the timer just set it to whenever the how_long was invoked
elif self.m_last_end_time == None:
self.timer_end()
return self.to_float_str(float((self.m_last_end_time - self.m_last_start_time).total_seconds()))
# end of how_long
def log_msg_to_unique_file(self, msg, path_to_file="/tmp/errors_to_look_at_"):
log_file = str(path_to_file) + str(uuid.uuid4()).replace("-", "") + ".log"
with open(log_file, "w") as output_file:
output_file.write(str(msg))
return log_file
# end of log_msg_to_unique_file
def write_json_to_file(self, output_file, record_json):
try:
temp_output = "/tmp/tmpfile_" + datetime.datetime.now().strftime("%y-%m-%d-%H-%M-%S") + "_"
temp_file = self.log_msg_to_unique_file(self.ppj(record_json), temp_output)
os.system("mv " + str(temp_file) + " " + str(output_file))
if os.path.exists(output_file):
return output_file
else:
return "FAILED_TO_CREATE_FILE"
except Exception,k:
print "ERROR: Failed to write file with ppj with Ex(" + str(k) + ")"
return "FILE_DOES_NOT_EXIST"
# end of try/ex
return output_file
# end of write_json_to_file
def build_def_hash(self, start_status="FAILED", start_error="", record={}):
return { "Status" : str(start_status), "Error" : str(start_error), "Record" : record }
# end of build_def_hash
def handle_display_error(self, err_msg, def_rec={}, debug=False):
results = {}
results["Status"] = "Display Error"
results["Error"] = str(err_msg)
results["Record"] = def_rec
self.lg("ERROR: " + str(err_msg), 0)
if debug:
lg("ERROR: " + str(err_msg), 0)
return results
# end of handle_display_error
def handle_general_error(self, status, err_msg, def_rec={}, debug=False):
results = {}
results["Status"] = str(status)
results["Error"] = str(err_msg)
results["Record"] = def_rec
if debug:
self.lg("ERROR: " + str(err_msg), 0)
return results
# end of handle_general_error
def handle_exception(self, status, err_msg, ex, debug=False):
results = self.build_def_hash(status, err_msg, {
"Exception" : "Failed to Process"
})
try:
if self.m_slack_enabled:
self.handle_send_slack_internal_ex(ex, debug)
results = self.build_def_hash("SUCCESS", "", {
"Exception" : ""
})
else:
import traceback, sys
exc_type, exc_obj, exc_tb = sys.exc_info()
ex_error = self.get_exception_error_message(ex, exc_type, exc_obj, exc_tb, False, debug)
results = self.build_def_hash("SUCCESS", "", {
"Exception" : str(ex_error)
})
# end of branching if slack supported or not
except Exception, e:
err_msg = "Failed to post message to slack with Ex(" + str(e) + ")"
self.lg("ERROR: " + str(err_msg), 0)
results = self.build_def_hash("Display Error", str(err_msg), {
"Exception" : "Failed Processing with Exception"
})
results["Status"] = "FAILED"
# end of try/ex
return results
# end of handle_exception
def get_exception_error_message(self, ex, exc_type, exc_obj, exc_tb, slack_formatted=False, debug=False):
error_log_msg = "FAILED to process exception"
try:
path_to_file = str(exc_tb.tb_frame.f_code.co_filename)
last_line = int(exc_tb.tb_lineno)
gh_line_number = int(last_line) - 1
file_name = str(os.path.split(exc_tb.tb_frame.f_code.co_filename)[1])
path_to_file = str(exc_tb.tb_frame.f_code.co_filename)
ex_details_msg = str(ex)
if ex_details_msg != "":
error_log_msg = "Error on Line: \x1b[31m" + str(last_line) + "\x1b[0m Code: \n\t\x1b[31m" + str(ex_details_msg) + "\x1b[0m\n"
if slack_formatted:
self.lg("" + str(error_log_msg), 0)
error_log_msg = " Error on Line: *" + str(last_line) + "* Code: \n```" + str(ex_details_msg) + "``` \n"
else:
error_log_msg = "Error on Line Number: " + str(last_line)
except Exception,k:
error_log_msg = "Failed to process exception with(" + str(k) + ")"
self.lg("ERROR: " + str(error_log_msg), 0)
# end of trying to process the exception
return error_log_msg
# end of get_exception_error_message
#####################################################################################################
#
# Redis Application Methods
#
#####################################################################################################
def get_message_no_block(self, redis_app, input_key):
results = {}
results["Status"] = "FAILED"
results["Error"] = ""
results["Record"] = None
try:
results["Record"] = redis_app.get_message(False, input_key)
results["Status"] = "SUCCESS"
results["Error"] = ""
except ValueError, e:
err_msg = "RA - ValueError to Address(" + redis_app.get_address() + ") ValueEx(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Record"] = None
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
except Exception, e:
test_for_redis_connectivity = str(e)
if "Connection refused." in test_for_redis_connectivity:
err_msg = "RA - Connection REFUSED to Address(" + redis_app.get_address() + ") Key(" + input_key + ") ConEx(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Record"] = None
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
else:
err_msg = "RA - EX Address(" + redis_app.get_address() + ") Key(" + input_key + ") General Ex(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Record"] = None
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
# end of try/ex
return results
# end of get_message_no_block
def get_message_with_block(self, redis_app, input_key):
results = {}
results["Status"] = "FAILED"
results["Error"] = ""
results["Record"] = None
try:
results["Record"] = redis_app.get_message(True, input_key)
results["Status"] = "SUCCESS"
results["Error"] = ""
except ValueError, e:
err_msg = "RA - ValueError to Address(" + redis_app.get_address() + ") ValueEx(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Record"] = None
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
except Exception, e:
test_for_redis_connectivity = str(e)
if "Connection refused." in test_for_redis_connectivity:
err_msg = "RA - Connection REFUSED to Address(" + redis_app.get_address() + ") Key(" + input_key + ") ConEx(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Record"] = None
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
else:
err_msg = "RA - EX Address(" + redis_app.get_address() + ") Key(" + input_key + ") General Ex(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Record"] = None
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
# end of try/ex
return results
# end of get_message_with_block
def publish_message_to_key(self, message, dest_key, redis_app, debug=False):
results = {}
results["Status"] = "FAILED"
results["Error"] = ""
results["Record"] = {}
try:
if debug:
self.lg("Publish(" + str(dest_key) + ") RA(" + str(redis_app.get_address()) + ")", 6)
if redis_app.m_rw == None:
redis_app.connect()
redis_app.put_into_key(dest_key, message)
results["Record"] = {
"Address" : str(redis_app.get_address()),
"Key" : dest_key
}
results["Status"] = "SUCCESS"
results["Error"] = ""
if debug:
self.lg("Publish Done", 6)
except ValueError, e:
err_msg = "Connection to Address(" + str(redis_app.get_address()) + ") Results Key(" + str(dest_key) + ") Received a Non-Pickle Formatted Message Ex(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
results["Record"] = {}
except Exception, e:
test_for_redis_connectivity = str(e)
if "Connection refused." in test_for_redis_connectivity:
err_msg = "Connection REFUSED to Address(" + str(redis_app.get_address()) + ") Results Key(" + str(dest_key) + ") Received a Ex(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
results["Record"] = {}
else:
err_msg = "Publish Failed to Address(" + str(redis_app.get_address()) + ") Results Key(" + str(dest_key) + ") Received a Ex(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
results["Record"] = {}
# end of try/ex
if debug:
self.lg("Base Done Publish Result Key", 6)
return results
# end of publish_message_to_key
def add_records_to_cache_in_redis(self, json_record, dest_key, redis_app, debug=False):
results = {}
results["Status"] = "FAILED"
results["Error"] = ""
results["Record"] = {}
try:
if debug:
self.lg("Add Records to Cache(" + str(dest_key) + ") RA(" + str(redis_app.get_address()) + ")", 6)
if redis_app.m_rw == None:
redis_app.connect()
redis_app.put_into_key(dest_key, json_record)
results["Record"] = {
"Address" : str(redis_app.get_address()),
"Key" : dest_key
}
results["Status"] = "SUCCESS"
results["Error"] = ""
if debug:
self.lg("Add Records to Cache Done", 6)
except ValueError, e:
err_msg = "Connection to Address(" + str(redis_app.get_address()) + ") Results Key(" + str(dest_key) + ") Received a Non-Pickle Formatted Message Ex(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
results["Record"] = {}
except Exception, k:
test_for_redis_connectivity = str(k)
if "Connection refused." in test_for_redis_connectivity:
err_msg = "Add Records - Connection REFUSED to Address(" + str(redis_app.get_address()) + ") Results Key(" + str(dest_key) + ") Received a Ex(" + str(k) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
results["Record"] = {}
else:
err_msg = "Add Records - Cache Failed to Address(" + str(redis_app.get_address()) + ") Results Key(" + str(dest_key) + ") Received a Ex(" + str(k) +")"
self.lg("ERROR: " + str(err_msg), 0)
cache_results = self.handle_exception("FAILED", err_msg, k)
# end of try/ex
if debug:
self.lg("Add to Cache Done", 6)
return results
# end of add_records_to_cache_in_redis
def purge_and_cache_records_in_redis(self, redis_app, dest_key, message, debug=False):
results = {}
results["Status"] = "FAILED"
results["Error"] = ""
results["Record"] = {}
try:
if debug:
self.lg("Purge and Cache(" + str(dest_key) + ") RA(" + str(redis_app.get_address()) + ")", 6)
if redis_app.m_rw == None:
redis_app.connect()
found_msg = True
while found_msg != None:
found_msg = redis_app.m_rw.get(False, 0.01, dest_key)
# end of purging this cache
redis_app.put_into_key(dest_key, message)
results["Record"] = {
"Address" : str(redis_app.get_address()),
"Key" : dest_key
}
results["Status"] = "SUCCESS"
results["Error"] = ""
if debug:
self.lg("Purge and Cache Done", 6)
except ValueError, e:
err_msg = "Connection to Address(" + str(redis_app.get_address()) + ") Results Key(" + str(dest_key) + ") Received a Non-Pickle Formatted Message Ex(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)
results["Status"] = "FAILED"
results["Error"] = str(err_msg)
results["Record"] = {}
except Exception, e:
test_for_redis_connectivity = str(e)
if "Connection refused." in test_for_redis_connectivity:
err_msg = "Connection REFUSED to Address(" + str(redis_app.get_address()) + ") Results Key(" + str(dest_key) + ") Received a Ex(" + str(e) +")"
self.lg("ERROR: " + str(err_msg), 0)