-
Notifications
You must be signed in to change notification settings - Fork 1
/
jery.py
2051 lines (1729 loc) · 92.4 KB
/
jery.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/local/bin/python3
#-*- coding: iso-8859-1 -*-
#############################################################
## © Copyright 2017 Hewlett Packard Enterprise Development LP
## Author: Yann Allandit
## Contact: dwh2@hp.com
## Creation Date: 10th of March 2014
#############################################################
import Tkinter
from Tkinter import *
import cx_Oracle
import threading
import time
import tkMessageBox
import ConfigParser
import psycopg2
######################## CONNECTION ##########################
def connectToOracle(ip, port, SID, user, passwd, threaded=False):
dsn = cx_Oracle.makedsn(host = ip, port = port, service_name = SID)
con = cx_Oracle.connect(user, passwd, dsn, threaded=threaded)
return con
def connectToEDB(ip, dbname, user, passwd):
# print "ip " + ip
# print "dbname " + dbname
# print "user " + user
# print "passwd " + passwd
con = psycopg2.connect(host=ip, user=user, password=passwd, dbname=dbname)
return con
########################### GUI ##############################
class CreateTestSchemaWindow(Tkinter.Toplevel):
def __init__(CrSchemaWindow, SID, user, passwd, ip, port):
Tkinter.Toplevel.__init__(CrSchemaWindow)
""" Test schema Creation class
Is a loop insert of the scott.emp table into a new schema table.
Include 5 procedures inot the top level window apps:
- Create schema: test is the new table exists, create it, create the statistics table (used for
estimating how long are the jobs. Used also for the graph). Create also the sequence for the stat table
- Drop test schema (can create a new one smaller or bigger)
- Creation info: the schema creation can be time consuming, thus a loop will tell which step is currently executed.
- Stop procedure and close window
- Handling for the "x" press of the Toplevel window. Allow a clean close of the window.
"""
"""Global variable checking wether a toplevel window is open or not"""
global OpenToplevel
OpenToplevel += 1
""" Toplevel window implementation"""
CrSchemaWindow.wm_title(" Test schema creation ")
CrSchemaWindow.protocol("WM_DELETE_WINDOW", CrSchemaWindow.handler)
CrSchemaWindow.SID = SID
CrSchemaWindow.user = user
CrSchemaWindow.passwd = passwd
CrSchemaWindow.ip = ip
CrSchemaWindow.port = port
CrSchemaWindow.LabelTableRatio = Tkinter.Label(CrSchemaWindow, text="Select the scaling ratio ")
CrSchemaWindow.LabelTableRatio.grid(column=0, row=0)
CrSchemaWindow.RatioVar = IntVar()
Ratio1 = Tkinter.Radiobutton(CrSchemaWindow, text='1: Disk space needed 11MB', variable=CrSchemaWindow.RatioVar, value=1)
Ratio2 = Tkinter.Radiobutton(CrSchemaWindow, text='2: Disk space needed 22MB', variable=CrSchemaWindow.RatioVar, value=2)
Ratio3 = Tkinter.Radiobutton(CrSchemaWindow, text='3: Disk space needed 43MB', variable=CrSchemaWindow.RatioVar, value=3)
Ratio4 = Tkinter.Radiobutton(CrSchemaWindow, text='4: Disk space needed 88MB', variable=CrSchemaWindow.RatioVar, value=4)
Ratio5 = Tkinter.Radiobutton(CrSchemaWindow, text='5: Disk space needed 176MB', variable=CrSchemaWindow.RatioVar, value=5)
Ratio6 = Tkinter.Radiobutton(CrSchemaWindow, text='6: Disk space needed 344MB', variable=CrSchemaWindow.RatioVar, value=6)
Ratio7 = Tkinter.Radiobutton(CrSchemaWindow, text='7: Disk space needed 680MB', variable=CrSchemaWindow.RatioVar, value=7)
Ratio8 = Tkinter.Radiobutton(CrSchemaWindow, text='8: Disk space needed 1.4GB', variable=CrSchemaWindow.RatioVar, value=8)
Ratio9 = Tkinter.Radiobutton(CrSchemaWindow, text='9: Disk space needed 2.7GB', variable=CrSchemaWindow.RatioVar, value=9)
Ratio10 = Tkinter.Radiobutton(CrSchemaWindow, text='10: Disk space needed 5.5GB', variable=CrSchemaWindow.RatioVar, value=10)
Ratio1.grid(row=1, column=0, sticky='W')
Ratio2.grid(row=2, column=0, sticky='W')
Ratio3.grid(row=3, column=0, sticky='W')
Ratio4.grid(row=4, column=0, sticky='W')
Ratio5.grid(row=5, column=0, sticky='W')
Ratio6.grid(row=6, column=0, sticky='W')
Ratio7.grid(row=7, column=0, sticky='W')
Ratio8.grid(row=8, column=0, sticky='W')
Ratio9.grid(row=9, column=0, sticky='W')
Ratio10.grid(row=10, column=0, sticky='W')
Ratio1.select()
buttonQuit = Tkinter.Button(CrSchemaWindow,text=u"Close window", command=CrSchemaWindow.CloseCrSchemaWindow, width=39)
buttonQuit.grid (column=0, row=14, sticky=S)
buttonCreate = Tkinter.Button(CrSchemaWindow,text=u"Create the data now", command=lambda:
CrSchemaWindow.CreateSchema(CrSchemaWindow.SID,CrSchemaWindow.user,CrSchemaWindow.passwd,CrSchemaWindow.ip,CrSchemaWindow.port,int(CrSchemaWindow.RatioVar.get())) \
, width=39)
buttonCreate.grid (column=0, row=12, sticky=S)
buttonDrop = Tkinter.Button(CrSchemaWindow,text=u"Drop the test data now", command=lambda:
CrSchemaWindow.DropSchema(CrSchemaWindow.SID,CrSchemaWindow.user,CrSchemaWindow.passwd,CrSchemaWindow.ip,CrSchemaWindow.port), width=39)
buttonDrop.grid (column=0, row=13, sticky=S)
CrSchemaWindow.VocableVariable = Tkinter.StringVar()
Vocable = Tkinter.Label(CrSchemaWindow,textvariable=CrSchemaWindow.VocableVariable, anchor="w", fg="white", bg="blue")
Vocable.grid(column=0, row=11, columnspan=2, sticky='EW')
CrSchemaWindow.VocableVariable.set(u"Hello !")
CrSchemaWindow.grid_columnconfigure(0,weight=1)
CrSchemaWindow.resizable(True,False)
CrSchemaWindow.update()
CrSchemaWindow.geometry(CrSchemaWindow.geometry())
def CreateSchema(CrSchemaWindow, SID, user, passwd, ip, port, RatioVar):
""" Test if the connection parameters are valid.
- If the connection is valid print the db_name into the vocable label.
Otherwise print an error message.
"""
error_con = 0
CrSchemaWindow.LoopRatioVar = RatioVar + 14
CrSchemaWindow.i = 1
if mode == 0:
try:
con = connectToOracle(str(ip), str(port), str(SID), "system", str(passwd))
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 1017:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Invalid username or password")
error_con = 1
elif error.code == 12154:
CrSchemaWindow.VocableVariable.set(str(SID) + ": TNS couldn't resolve the SID")
error_con = 1
elif error.code == 12543:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Destination host not available")
error_con = 1
else:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Unable to connect")
error_con = 1
if error_con != 1:
cur = con.cursor()
f = open('./queries/scott_ora.sql')
full_sql = f.read()
sql_commands = full_sql.split(';')
for sql_command in sql_commands:
try:
cur.execute(sql_command)
except cx_Oracle.DatabaseError as e:
error, = e.args
try:
cur.execute('create table scott.emp2 as select * from scott.emp')
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 3113:
cur.execute('drop table scott.emp2')
cur.execute('create table scott.emp2 as select * from scott.emp')
elif error.code == 955:
cur.execute('drop table scott.emp2')
cur.execute('create table scott.emp2 as select * from scott.emp')
else:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Failed to create schema")
cur.close()
return
try:
cur.execute('create table scott.dwhstat (seq int not null primary key, elapsed int, insdate date)')
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 955:
cur.execute('truncate table scott.dwhstat')
try:
cur.execute('CREATE SEQUENCE scott.seq START WITH 1 INCREMENT BY 1 NOCACHE')
except cx_Oracle.DatabaseError as e:
CrSchemaWindow.VocableVariable.set("Schema already exists!")
cur.close()
CrSchemaWindow.CreateSchemaProgress(SID, user, passwd, ip, port)
con.close()
elif mode == 1:
try:
con = connectToEDB(str(ip), str(SID), str(user), str(passwd))
except (psycopg2.DatabaseError, psycopg2.OperationalError) as e:
error, = e.args
error = error.replace('FATAL: ', '')
error = error.replace('\n', '')
CrSchemaWindow.VocableVariable.set(str(SID) + ": " + error)
error_con = 1
if error_con != 1:
cur = con.cursor()
f = open('./queries/scott_edb.sql')
full_sql = f.read()
sql_commands = full_sql.split(';')
try:
cur.execute("drop table dept cascade")
cur.execute("drop table emp cascade")
cur.execute("drop table bonus cascade")
cur.execute("drop table salgrade cascade")
except (psycopg2.DatabaseError, psycopg2.ProgrammingError) as e:
error = e.pgcode
print e
con.rollback()
if error != '42P01':
print e
con.commit()
for sql_command in sql_commands:
try:
if sql_command != "":
cur.execute(sql_command)
except (psycopg2.DatabaseError, psycopg2.ProgrammingError) as e:
con.rollback()
error, = e.args
print error
con.commit()
try:
cur.execute('create table emp2 as select * from emp')
except psycopg2.DatabaseError as e:
error = e.pgcode
con.rollback()
if error == '42P07':
cur.execute('drop table emp2')
cur.execute('create table emp2 as select * from emp')
else:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Failed to create schema")
cur.close()
return
con.commit()
try:
cur.execute('create table dwhstat (seq int not null primary key, elapsed int, insdate date)')
except psycopg2.DatabaseError as e:
error = e.pgcode
con.rollback()
if error == '42P07':
cur.execute('truncate table dwhstat')
con.commit()
try:
cur.execute('CREATE SEQUENCE seq START WITH 1 INCREMENT BY 1')
except psycopg2.DatabaseError as e:
CrSchemaWindow.VocableVariable.set("Schema already exists!")
con.commit()
cur.close()
CrSchemaWindow.CreateSchemaProgress(SID, user, passwd, ip, port)
con.close()
def DropSchema(CrSchemaWindow, SID, user, passwd, ip, port):
""" Test if the connection parameters are valid.
- If the connection is valid print the db_name into the vocable label.
Otherwise print an error message.
"""
if mode == 0:
error_con = 0
try:
con = connectToOracle(str(ip), str(port), str(SID), "system", str(passwd))
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 1017:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Invalid username or password")
error_con = 1
elif error.code == 12154:
CrSchemaWindow.VocableVariable.set(str(SID) + ": TNS couldn't resolve the SID")
error_con = 1
elif error.code == 12543:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Destination host not available")
error_con = 1
else:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Unable to connect")
error_con = 1
if error_con != 1:
cur = con.cursor()
try:
cur.execute('drop table scott.emp2')
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 942:
CrSchemaWindow.VocableVariable.set('Test schema does not exist')
else:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Failed to drop the test schema")
error_con = 2
try:
cur.execute('drop table scott.dwhstat')
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 942:
CrSchemaWindow.VocableVariable.set('Test schema does not exist')
error_con = 2
else:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Failed to drop the test schema")
error_con = 2
try:
cur.execute('drop SEQUENCE scott.seq')
except cx_Oracle.DatabaseError:
error_con = 3
cur.close()
con.close()
if error_con == 0:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Test schema dropped!")
elif mode == 1:
error_con = 0
try:
con = connectToEDB(str(ip), str(SID), str(user), str(passwd))
except (psycopg2.DatabaseError, psycopg2.OperationalError) as e:
error, = e.args
error = error.replace('FATAL: ', '')
error = error.replace('\n', '')
CrSchemaWindow.VocableVariable.set(str(SID) + ": " + error)
error_con = 1
if error_con != 1:
cur = con.cursor()
try:
cur.execute('drop table emp2')
except psycopg2.DatabaseError as e:
error = e.pgcode
con.rollback()
if error == '42P01':
CrSchemaWindow.VocableVariable.set('Test schema does not exist')
error_con = 2
else:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Failed to drop the test schema")
error_con = 2
con.commit()
try:
cur.execute('drop table dwhstat')
except psycopg2.DatabaseError as e:
error = e.pgcode
con.rollback()
if error == '3F000':
CrSchemaWindow.VocableVariable.set('Test schema does not exist')
error_con = 2
else:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Failed to drop the test schema")
error_con = 2
try:
cur.execute('drop SEQUENCE seq')
except (psycopg2.DatabaseError, psycopg2.ProgrammingError):
error_con = 3
cur.close()
con.close()
if error_con == 0:
CrSchemaWindow.VocableVariable.set(str(SID) + ": Test schema dropped!")
def CreateSchemaProgress(CrSchemaWindow, SID, user, passwd, ip, port):
""" Used as progress bar.
for each and every recursive insert done, a message is printed into the vocable blue bar
"""
if mode == 0:
con = connectToOracle(str(ip), str(port), str(SID), "system", str(passwd))
cur2 = con.cursor()
cur2.execute('insert into scott.emp2 select * from scott.emp2')
con.commit()
CrSchemaWindow.i += 1
CrSchemaWindow.VocableVariable.set("Test schema processing step {0} out of {1}".format(str(CrSchemaWindow.i),
str(CrSchemaWindow.LoopRatioVar - 1)))
if CrSchemaWindow.i < CrSchemaWindow.LoopRatioVar:
CrSchemaWindow.after(500, lambda:
CrSchemaWindow.CreateSchemaProgress(SID, user, passwd, ip, port))
else:
con.close()
CrSchemaWindow.VocableVariable.set("Updating statistics, please wait...")
CrSchemaWindow.Statistics(SID, user, passwd, ip, port)
elif mode == 1:
con = connectToEDB(str(ip), str(SID), str(user), str(passwd))
cur2 = con.cursor()
cur2.execute('insert into emp2 select * from emp2')
con.commit()
CrSchemaWindow.i += 1
CrSchemaWindow.VocableVariable.set(
"Test schema processing step {0} out of {1}".format(str(CrSchemaWindow.i),
str(CrSchemaWindow.LoopRatioVar - 1)))
if CrSchemaWindow.i < CrSchemaWindow.LoopRatioVar:
CrSchemaWindow.after(500, lambda:
CrSchemaWindow.CreateSchemaProgress(SID, user, passwd, ip, port))
else:
con.close()
CrSchemaWindow.VocableVariable.set("Updating statistics, please wait...")
CrSchemaWindow.Statistics(SID, user, passwd, ip, port)
def Statistics(CrSchemaWindow, SID, user, passwd, ip, port):
""" Used generating staistics in SCOTT schema.
"""
if mode == 0:
con = connectToOracle(str(ip), str(port), str(SID), "system", str(passwd))
cur3 = con.cursor()
cur3.execute("""
begin
dbms_stats.gather_schema_stats(:name, estimate_percent => 100, method_opt => :method, options => :options, cascade => true,degree => 4);
end;""",
name = 'SCOTT',
method = 'for all columns size auto',
options = 'gather stale')
con.close()
CrSchemaWindow.VocableVariable.set("Test schema created with ratio: {0}".format(str(CrSchemaWindow.RatioVar.get())))
# ToDo: fix statistics generation
elif mode == 1:
CrSchemaWindow.VocableVariable.set("Test schema created with ratio: {0}".format(str(CrSchemaWindow.RatioVar.get())))
def CloseCrSchemaWindow(CrSchemaWindow):
"""Close the window and decrement the number of toplevel window counter
"""
global OpenToplevel
OpenToplevel -= 1
CrSchemaWindow.destroy()
def handler(CrSchemaWindow):
""" Close properly the Toplevel window if the user click the "x" button
"""
CrSchemaWindow.CloseCrSchemaWindow()
class CreateAProposWindow(Tkinter.Toplevel):
def __init__(AProposWindow):
Tkinter.Toplevel.__init__(AProposWindow)
"""
Classe A Propos
Deliver information about this program.
"""
AProposWindow.wm_title(" A Propos... ")
version = ConfigSectionMap("Info")['version']
build = ConfigSectionMap("Info")['build']
contact = ConfigSectionMap("Info")['contact']
AProposWindow.LabelVersion = Tkinter.Label(AProposWindow, text="Version: " + version)
AProposWindow.LabelDate = Tkinter.Label(AProposWindow, text="Build: " + build)
AProposWindow.LabelContact = Tkinter.Label(AProposWindow, text="Contact: " + contact)
AProposWindow.LabelVersion.grid(column=0, row=1)
AProposWindow.LabelDate.grid(column=0, row=2)
AProposWindow.LabelContact.grid(column=0, row=3)
buttonQuit = Tkinter.Button(AProposWindow,text=u"Close window", command=AProposWindow.destroy, width=20)
buttonQuit.grid(column=0, row=15, sticky=S)
AProposWindow.grid_columnconfigure(0,weight=1)
AProposWindow.resizable(True,False)
AProposWindow.update()
AProposWindow.geometry(AProposWindow.geometry())
class GraphWindow(Tkinter.Toplevel):
def __init__(GraphWindow, user, passwd, SID, ip, port):
Tkinter.Toplevel.__init__(GraphWindow, height=600, width=450)
""" This window shows graphically the evolution of the job execution time.
3 procedures in this class:
- run
- stop
- handling for the "x" button press. Need to properly close the Toplevel window
"""
GraphWindow.wm_title(" -- Queries execution time -- ")
GraphWindow.geometry ("450x600")
GraphWindow.user = user
GraphWindow.passwd = passwd
GraphWindow.SID = SID
GraphWindow.ip = ip
GraphWindow.port = port
GraphWindow.LoopGraphVar = 0
GraphWindow.resizable(False,False)
GraphWindow.protocol("WM_DELETE_WINDOW", GraphWindow.handler)
GraphWindow.update()
buttonQuit = Tkinter.Button(GraphWindow,text=u"Close window", command=GraphWindow.StopGraph, width=20)
buttonQuit.pack (side=BOTTOM)
"""
Global variable checking the status of the toplevel windows opening a thread
"""
global OpenToplevel
OpenToplevel += 1
GraphThread = threading.Thread(target=GraphWindow.RunGraph, args=())
GraphThread.start()
def RunGraph(GraphWindow):
"""
Graph runs in a loop until quit is hited
Print a bar in a chart for the last 200 completed jobs
Refresh done every 2 seconds by a complete redesign of the graph.
"""
while GraphWindow.LoopGraphVar == 0:
error_con = 0
c_width = 450
c_height = 600
c = Tkinter.Canvas(GraphWindow, width=c_width, height=c_height, bg='white')
y_stretch = 15
y_gap = 20
x_stretch = 10
x_width = 20
x_gap = 20
pos = 1
if mode == 0:
"""Test the connection before printing the graph"""
try:
con = connectToOracle(GraphWindow.ip, GraphWindow.port, GraphWindow.SID, GraphWindow.user, GraphWindow.passwd)
except cx_Oracle.DatabaseError:
error_con = 1
return error_con
"""if the connection is established, read the latest events of the stat table -dwhstat- and print the graph"""
if error_con != 1:
curRampUp = con.cursor()
curRampUp.execute('select count(*) from dwhstat')
for result in curRampUp:
curValue = con.cursor()
if int(result[0]) > 0:
curValue.execute('select elapsed from (select seq, elapsed from dwhstat) where seq>(select max(seq) - 20 from dwhstat) order by seq')
for y in curValue:
x0 = pos * 20 +10
y0 = c_height - (int(y[0]) * y_stretch + y_gap)
x1 = pos * 20 +25
y1 = c_height - y_gap
c.create_rectangle(x0, y0, x1, y1, fill="red")
c.create_text(x0 + 2, y0, anchor=Tkinter.SW, text=str(int(y[0])))
pos += 1
curValue.close()
c.pack()
refresh = int(ConfigSectionMap("Settings")['refresh'])
time.sleep(refresh)
c.destroy()
if mode == 1:
"""Test the connection before printing the graph"""
try:
con = connectToEDB(GraphWindow.ip, GraphWindow.SID, GraphWindow.user, GraphWindow.passwd)
except psycopg2.DatabaseError:
error_con = 1
return error_con
"""if the connection is established, read the latest events of the stat table -dwhstat- and print the graph"""
if error_con != 1:
curRampUp = con.cursor()
curRampUp.execute('select count(*) from dwhstat')
for result in curRampUp:
curValue = con.cursor()
if int(result[0]) > 0:
curValue.execute(
'select elapsed from (select seq, elapsed from dwhstat) AS derivedTable where seq>(select max(seq) - 20 from dwhstat) order by seq')
for y in curValue:
x0 = pos * 20 + 10
y0 = c_height - (int(y[0]) * y_stretch + y_gap)
x1 = pos * 20 + 25
y1 = c_height - y_gap
c.create_rectangle(x0, y0, x1, y1, fill="red")
c.create_text(x0 + 2, y0, anchor=Tkinter.SW, text=str(int(y[0])))
pos += 1
curValue.close()
c.pack()
refresh = int(ConfigSectionMap("Settings")['refresh'])
time.sleep(refresh)
c.destroy()
def StopGraph(GraphWindow):
"""Close the window and decrement the number of toplevel window counter
"""
global OpenToplevel
OpenToplevel -= 1
GraphWindow.LoopGraphVar = 1
GraphWindow.after(2000, GraphWindow.destroy)
def handler(GraphWindow):
""" Close properly the Toplevel window if the user click the "x" button
"""
GraphWindow.StopGraph()
class ExtendedStatisticsWindow(Tkinter.Toplevel):
def __init__(statWindow, SID, passwd, ip, port):
Tkinter.Toplevel.__init__(statWindow)
"""
This procedure collects statistics from the system tables of the Oracle database
It prints for up to 4 nodes:
- the node name
- ORACLE_SID
- the number of users connected to the instance
- the average CPU usage for the last 15 seconds
- the average number of SQL orders/sec for the last 15 seconds
- the average IOMB/sec for the last 15 seconds
- the average number of block reads/ sec for the last 15 seconds.
Variable naming is static
"""
statWindow.wm_title(" Extended Statistics")
statWindow.SID = SID
statWindow.passwd = passwd
statWindow.ip = ip
statWindow.port = port
statWindow.LoopWindowVar = 0
statWindow.protocol("WM_DELETE_WINDOW", statWindow.handler)
""" Global variable checking the status of the toplevel windows opening a thread """
global OpenToplevel
OpenToplevel += 1
""" Label and Entry definition """
statWindow.LabelNodeName = Tkinter.Label(statWindow, text="Node name")
statWindow.LabelNodeName.grid(column=0, row=0)
statWindow.LabelInstanceName = Tkinter.Label(statWindow, text="Instance")
statWindow.LabelInstanceName.grid(column=1, row=0)
statWindow.LabelNbUsers = Tkinter.Label(statWindow, text="Nb. Users")
statWindow.LabelNbUsers.grid(column=2, row=0)
statWindow.LabelBusyTime = Tkinter.Label(statWindow, text="% Busy Time")
statWindow.LabelBusyTime.grid(column=3, row=0)
statWindow.LabelSQLSec = Tkinter.Label(statWindow, text="SQL orders/Sec.")
statWindow.LabelSQLSec.grid(column=4, row=0)
statWindow.LabelIOMSec = Tkinter.Label(statWindow, text="IO MB/Sec.")
statWindow.LabelIOMSec.grid(column=5, row=0)
statWindow.LabelBlockRead = Tkinter.Label(statWindow, text="Blocks read/Sec.")
statWindow.LabelBlockRead.grid(column=6, row=0)
statWindow.EntryNodeName1var = Tkinter.StringVar()
statWindow.EntryNodeName1 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryNodeName1var,\
width=12)
statWindow.EntryNodeName1.grid(column=0, row=1, sticky='EW')
statWindow.EntryInstanceName1var = Tkinter.StringVar()
statWindow.EntryInstanceName1 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryInstanceName1var,\
width=12)
statWindow.EntryInstanceName1.grid(column=1, row=1, sticky='EW')
statWindow.EntryNbUsers1var = Tkinter.StringVar()
statWindow.EntryNbUsers1 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryNbUsers1var,\
width=12)
statWindow.EntryNbUsers1.grid(column=2, row=1, sticky='EW')
statWindow.EntryBusyTime1var = Tkinter.StringVar()
statWindow.EntryBusyTime1 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryBusyTime1var,\
width=12)
statWindow.EntryBusyTime1.grid(column=3, row=1, sticky='EW')
statWindow.EntrySQLSec1var = Tkinter.StringVar()
statWindow.EntrySQLSec1 = Tkinter.Entry(statWindow, textvariable=statWindow.EntrySQLSec1var,\
width=12)
statWindow.EntrySQLSec1.grid(column=4, row=1, sticky='EW')
statWindow.EntryIOMSec1var = Tkinter.StringVar()
statWindow.EntryIOMSec1 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryIOMSec1var,\
width=12)
statWindow.EntryIOMSec1.grid(column=5, row=1, sticky='EW')
statWindow.EntryBlockRead1var = Tkinter.StringVar()
statWindow.EntryBlockRead1 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryBlockRead1var,\
width=12)
statWindow.EntryBlockRead1.grid(column=6, row=1, sticky='EW')
statWindow.EntryNodeName2var = Tkinter.StringVar()
statWindow.EntryNodeName2 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryNodeName2var,\
width=12)
statWindow.EntryNodeName2.grid(column=0, row=2, sticky='EW')
statWindow.EntryInstanceName2var = Tkinter.StringVar()
statWindow.EntryInstanceName2 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryInstanceName2var,\
width=12)
statWindow.EntryInstanceName2.grid(column=1, row=2, sticky='EW')
statWindow.EntryNbUsers2var = Tkinter.StringVar()
statWindow.EntryNbUsers2 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryNbUsers2var,\
width=12)
statWindow.EntryNbUsers2.grid(column=2, row=2, sticky='EW')
statWindow.EntryBusyTime2var = Tkinter.StringVar()
statWindow.EntryBusyTime2 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryBusyTime2var,\
width=12)
statWindow.EntryBusyTime2.grid(column=3, row=2, sticky='EW')
statWindow.EntrySQLSec2var = Tkinter.StringVar()
statWindow.EntrySQLSec2 = Tkinter.Entry(statWindow, textvariable=statWindow.EntrySQLSec2var,\
width=12)
statWindow.EntrySQLSec2.grid(column=4, row=2, sticky='EW')
statWindow.EntryIOMSec2var = Tkinter.StringVar()
statWindow.EntryIOMSec2 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryIOMSec2var,\
width=12)
statWindow.EntryIOMSec2.grid(column=5, row=2, sticky='EW')
statWindow.EntryBlockRead2var = Tkinter.StringVar()
statWindow.EntryBlockRead2 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryBlockRead2var,\
width=12)
statWindow.EntryBlockRead2.grid(column=6, row=2, sticky='EW')
statWindow.EntryNodeName3var = Tkinter.StringVar()
statWindow.EntryNodeName3 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryNodeName3var,\
width=12)
statWindow.EntryNodeName3.grid(column=0, row=3, sticky='EW')
statWindow.EntryInstanceName3var = Tkinter.StringVar()
statWindow.EntryInstanceName3 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryInstanceName3var,\
width=12)
statWindow.EntryInstanceName3.grid(column=1, row=3, sticky='EW')
statWindow.EntryNbUsers3var = Tkinter.StringVar()
statWindow.EntryNbUsers3 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryNbUsers3var,\
width=12)
statWindow.EntryNbUsers3.grid(column=2, row=3, sticky='EW')
statWindow.EntryBusyTime3var = Tkinter.StringVar()
statWindow.EntryBusyTime3 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryBusyTime3var,\
width=12)
statWindow.EntryBusyTime3.grid(column=3, row=3, sticky='EW')
statWindow.EntrySQLSec3var = Tkinter.StringVar()
statWindow.EntrySQLSec3 = Tkinter.Entry(statWindow, textvariable=statWindow.EntrySQLSec3var,\
width=12)
statWindow.EntrySQLSec3.grid(column=4, row=3, sticky='EW')
statWindow.EntryIOMSec3var = Tkinter.StringVar()
statWindow.EntryIOMSec3 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryIOMSec3var,\
width=12)
statWindow.EntryIOMSec3.grid(column=5, row=3, sticky='EW')
statWindow.EntryBlockRead3var = Tkinter.StringVar()
statWindow.EntryBlockRead3 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryBlockRead3var,\
width=12)
statWindow.EntryBlockRead3.grid (column=6, row=3, sticky='EW')
statWindow.EntryNodeName4var = Tkinter.StringVar()
statWindow.EntryNodeName4 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryNodeName4var,\
width=12)
statWindow.EntryNodeName4.grid(column=0, row=4, sticky='EW')
statWindow.EntryInstanceName4var = Tkinter.StringVar()
statWindow.EntryInstanceName4 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryInstanceName4var,\
width=12)
statWindow.EntryInstanceName4.grid(column=1, row=4, sticky='EW')
statWindow.EntryNbUsers4var = Tkinter.StringVar()
statWindow.EntryNbUsers4 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryNbUsers4var,\
width=12)
statWindow.EntryNbUsers4.grid(column=2, row=4, sticky='EW')
statWindow.EntryBusyTime4var = Tkinter.StringVar()
statWindow.EntryBusyTime4 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryBusyTime4var,\
width=12)
statWindow.EntryBusyTime4.grid(column=3, row=4, sticky='EW')
statWindow.EntrySQLSec4var = Tkinter.StringVar()
statWindow.EntrySQLSec4 = Tkinter.Entry(statWindow, textvariable=statWindow.EntrySQLSec4var,\
width=12)
statWindow.EntrySQLSec4.grid(column=4, row=4, sticky='EW')
statWindow.EntryIOMSec4var = Tkinter.StringVar()
statWindow.EntryIOMSec4 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryIOMSec4var,\
width=12)
statWindow.EntryIOMSec4.grid(column=5, row=4, sticky='EW')
statWindow.EntryBlockRead4var = Tkinter.StringVar()
statWindow.EntryBlockRead4 = Tkinter.Entry(statWindow, textvariable=statWindow.EntryBlockRead4var,\
width=12)
statWindow.EntryBlockRead4.grid(column=6, row=4, sticky='EW')
""" Button definition """
buttonQuit = Tkinter.Button(statWindow,text=u"Quit Statistics", command=statWindow.StopStatWindow, width=12)
buttonQuit.grid (column=5, row=13, sticky=S)
""" Vocable blue bar Entry definition """
statWindow.VocableVariable = Tkinter.StringVar()
Vocable = Tkinter.Label(statWindow,textvariable=statWindow.VocableVariable, anchor="w", fg="white", bg="blue")
Vocable.grid(column=0, row=13, columnspan=4, sticky='EW')
statWindow.VocableVariable.set(u"Hello !")
""" Start data collecting thread """
StatThread = threading.Thread(target=statWindow.CollectStat, args=(statWindow.SID, statWindow.passwd, statWindow.ip, statWindow.port))
StatThread.start()
statWindow.grid_columnconfigure(0,weight=1)
statWindow.resizable(True,False)
statWindow.update()
statWindow.geometry(statWindow.geometry())
def CollectStat(statWindow, SID, passwd, ip, port):
""" Test if the connection parameters are valid.
- If the connection is valid print the db_name into the vocable label.
Otherwise print an error message.
"""
#dsn_tns = cx_Oracle.makedsn('15.136.28.39', 1526, SID)
#dsn_tns = ('scott/tiger@' + str(self.Entry3.get()))
#version_DB['text'] = str(self.Entry3.get())
while statWindow.LoopWindowVar == 0:
error_con = 0
try:
con = connectToOracle(str(ip), str(port), str(SID), "system", str(passwd))
except cx_Oracle.DatabaseError as e:
error, = e.args
if error.code == 1017:
statWindow.VocableVariable.set(str(SID) + ": Invalid username or password")
error_con = 1
elif error.code == 12154:
statWindow.VocableVariable.set(str(SID) + ": TNS couldn't resolve the SID")
error_con = 1
elif error.code == 12543:
statWindow.VocableVariable.set(str(SID) + ": Destination host not available")
error_con = 1
else:
statWindow.VocableVariable.set(str(SID) + ": Unable to connect")
error_con = 1
if error_con != 1:
cur = con.cursor()
compteur = 0
cur.execute('select t.inst_id, t.value, q.value, c.value, io.value, count(u.username), substr (i.host_name,1,8), substr (i.instance_name,1,8) from gv$sysmetric t, gv$sysmetric q, gv$sysmetric c, gv$sysmetric io, gv$session u, gv$instance i where t.metric_id=2121 and q.metric_id=2004 and c.metric_id=2057 and io.metric_id=2145 and t.group_id=3 and q.group_id=3 and c.group_id=3 and t.inst_id=q.inst_id and t.inst_id=c.inst_id and t.inst_id=i.inst_id and io.inst_id=i.inst_id and t.inst_id=u.inst_id and u.username like \'SCOTT\' group by t.inst_id, t.value, q.value, c.value, io.value, i.host_name, i.instance_name order by t.inst_id')
for result in cur:
compteur += 1
if compteur == 1:
statWindow.EntryNodeName1var.set(str(result[6]))
statWindow.EntryInstanceName1var.set(str(result[7]))
statWindow.EntryNbUsers1var.set(str(int(result[5])))
statWindow.EntryBusyTime1var.set(str("{0:.2f}".format(float(result[3]))))
statWindow.EntrySQLSec1var.set(str("{0:.1f}".format(float(result[1]))))
statWindow.EntryIOMSec1var.set(str("{0:.1f}".format(float(result[4]))))
statWindow.EntryBlockRead1var.set(str(int(result[2])))
elif compteur == 2:
statWindow.EntryNodeName2var.set(str(result[6]))
statWindow.EntryInstanceName2var.set(str(result[7]))
statWindow.EntryNbUsers2var.set(str(int(result[5])))
statWindow.EntryBusyTime2var.set(str("{0:.2f}".format(float(result[3]))))
statWindow.EntrySQLSec2var.set(str("{0:.1f}".format(float(result[1]))))
statWindow.EntryIOMSec2var.set(str("{0:.1f}".format(float(result[4]))))
statWindow.EntryBlockRead2var.set(str(int(result[2])))
elif compteur == 3:
statWindow.EntryNodeName3var.set(str(result[6]))
statWindow.EntryInstanceName3var.set(str(result[7]))
statWindow.EntryNbUsers3var.set(str(int(result[5])))
statWindow.EntryBusyTime3var.set(str("{0:.2f}".format(float(result[3]))))
statWindow.EntrySQLSec3var.set(str("{0:.1f}".format(float(result[1]))))
statWindow.EntryIOMSec3var.set(str("{0:.1f}".format(float(result[4]))))
statWindow.EntryBlockRead3var.set(str(int(result[2])))
elif compteur == 4:
statWindow.EntryNodeName4var.set(str(result[6]))
statWindow.EntryInstanceName4var.set(str(result[7]))
statWindow.EntryNbUsers4var.set(str(int(result[5])))
statWindow.EntryBusyTime4var.set(str("{0:.2f}".format(float(result[3]))))
statWindow.EntrySQLSec4var.set(str("{0:.1f}".format(float(result[1]))))
statWindow.EntryIOMSec4var.set(str("{0:.1f}".format(float(result[4]))))
statWindow.EntryBlockRead4var.set(str(int(result[2])))
statWindow.VocableVariable.set("You are connected to {0}".format(str(SID)))
cur.close()
con.close()
time.sleep(2)
def StopStatWindow(statWindow):
""" Close the window and decrement the number of toplevel window counter
"""
global OpenToplevel
OpenToplevel -= 1
statWindow.LoopWindowVar = 1
statWindow.after(2000, statWindow.destroy)
def handler(statWindow):
""" Close properly the Toplevel window if the user click the "x" button
"""
statWindow.StopStatWindow()
################################################################
########################## HELPER ############################
class LoadThread(threading.Thread):
def __init__(self, OraUser, OraPwd, OraConnect, OraIp, OraPort, LengthTest):
"""
Initialisation of the execution thread.
Parameters received:
- Schema to be used
- Password of the schema
- Connect string of the instance
- Test length. If 0 is received, the test will run one week (604800 seconds).
Otherwise, the parameter is converted in seconds.
"""
threading.Thread.__init__(self)
self.OraUser = OraUser
self.OraPwd = OraPwd
self.OraConnect = OraConnect
self.OraIp = OraIp
self.OraPort = OraPort
self.LengthTest = LengthTest
if self.LengthTest == 0:
self.LengthTest = 604800
else:
self.LengthTest = self.LengthTest * 60
self.runLoad = 0
def run(self):
"""
The thread executes the same query in loop as long as:
- it cans be connected to the database
- the test period is not over (time.time() < (StartTimeTest + self.LengthTest)
- the flag self.runLoad == 0. This one is switched to 1 when:
- the test period is over
- the user click on the stop test button
"""
global GlobalStop
error_con = 0
StartTimeTest = time.time()
"""Test the connection. If valid, enter in a loop until the "stop load" button is hit
or the test period is over
app.ExecTime() call the statistics method
"""
if mode == 0:
try:
con = connectToOracle(self.OraIp, self.OraPort, self.OraConnect, self.OraUser, self.OraPwd, threaded=True)
except cx_Oracle.DatabaseError:
error_con = 1
return error_con
if error_con != 1:
while self.runLoad == 0:
cur = con.cursor()
cur2 = con.cursor()
startTimeQuery = time.time()
try:
cur.execute('select e1.ename, min(e2.deptno), max(e2.deptno), avg(to_number(to_char(e2.sal))), \
avg(e2.comm), max(to_number(to_char(e2.comm))) from emp2 e2, emp e1 where e1.ename=e2.ename group by e1.ename')
except cx_Oracle.OperationalError:
error_con = 1
print cx_Oracle.OperationalError
return error_con
elapsedTimeQuery = int(time.time() - startTimeQuery)
cur2.execute('insert into dwhstat values (seq.NEXTVAL, :id, sysdate)',{"id":elapsedTimeQuery})
con.commit()
cur.close()
cur2.close()
app.ExecTime()
if time.time() > (StartTimeTest + self.LengthTest):
app.OnButtonStopLoadClick()
#self.GlobalStop = 1
GlobalStop = 1
con.close()
elif mode == 1:
try:
con = connectToEDB(self.OraIp, self.OraConnect, self.OraUser, self.OraPwd)
except psycopg2.DatabaseError:
error_con = 1
print psycopg2.DatabaseError
return error_con