-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathec2_gui.pyw
821 lines (701 loc) · 35.4 KB
/
ec2_gui.pyw
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
import sys
try:
import wx
except ImportError:
print 'Looks like you do not have wx installed.'
print 'You can install it here (you want the unicode version):'
print 'http://www.wxpython.org/download.php'
print 'Your python version: ' + str(sys.version_info[0:2])
sys.exit(1)
import wxPython.wx
import wx.grid as gridlib
import wx.lib.scrolledpanel as scrolled
import os
import ConfigParser
import logging
import copy
import ast
import datetime
import time
import subprocess
import random
try:
import boto
except ImportError:
print 'Looks like you do not have boto installed.'
print 'You can install it like this:'
print '-' * 20
print 'git clone https://github.com/boto/boto.git'
print 'cd boto'
print 'sudo python setup.py install'
print '-' * 20
sys.exit(1)
import boto.ec2
from boto.ec2.connection import EC2Connection
from boto.ec2.autoscale import AutoScaleConnection
from boto.ec2.autoscale import LaunchConfiguration
from boto.ec2.autoscale import Tag
from boto.ec2.autoscale import AutoScalingGroup
from boto.ec2.autoscale import ScalingPolicy
from boto.ec2.cloudwatch import CloudWatchConnection
from boto.ec2.cloudwatch import MetricAlarm
class ASG_Functionality():
def __init__(self, logLevel=logging.CRITICAL, logger=None):
""" This class contains the functionality needed to communicate with Amazon's Auto Scaling Group.
:param logLevel: Verbosity level of this command (DEBUG|INFO|WARNING|CRITICAL).
:type logLevel: logging.logLevel
:param logger: Optionally specificy a logger. Useful for multithreading.
:type logger: logging logger
"""
if logger is None:
#- Create the logger:
self.log = logging.getLogger(__name__)
self.log.handlers = []
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter('%(message)s'))
self.log.addHandler(ch)
self.log.setLevel(logLevel)
self.identityFile = None
else:
self.log = logger
#- OK, now connect to the region:
self.connectToRegion()
def connectToRegion(self):
#- Connect to us-east-1 region:
if 'AWS_ACCESS_KEY' in os.environ and 'AWS_SECRET_KEY' in os.environ:
self.conn = AutoScaleConnection(os.environ['AWS_ACCESS_KEY'], os.environ['AWS_SECRET_KEY'])
self.cwconn = CloudWatchConnection(os.environ['AWS_ACCESS_KEY'], os.environ['AWS_SECRET_KEY'])
else:
#- Maybe you can connect with the credentials in ~/.boto
self.conn = AutoScaleConnection()
self.cwconn = CloudWatchConnection()
def printAllASGs(self, logger=None):
if logger is None:
logger = self.log
all_asgs = self.safeFunc(self.conn.get_all_groups)
if len(all_asgs) == 0:
return 'No ASGs could be located!'
else:
retText = 'Total Number of ASGs: ' + str(len(all_asgs)) + '\n'
for asg in all_asgs:
retText = retText + '\n' + self.prettyPrintAsg(asg)
return retText
def prettyPrintAsg(self, asgObj, logger=None):
""" This function prints out vital information of an ASG object.
:param asgObj: boto ASG object.
:type asgObj: string
:param logger: Optionally specificy a logger. Useful for multithreading.
:type logger: logging logger
"""
if logger is None:
logger = self.log
retText = ''
#- General Information on ASG:
data = sorted([[i[0], str(i[1]).strip()] for i in vars(asgObj).items()])
for el in self.safeFunc(self.conn.get_all_activities, asgObj):
data.append(['Activity:', str(el.description)])
#- Print Launch Configuration Info:
data.append(['launch configurations:', ''])
for el in self.safeFunc(self.conn.get_all_launch_configurations, names=[str(asgObj.launch_config_name)]):
data.append(['\t----------Launch Description', ''])
data = data + sorted([['\t' + i[0], str(i[1]).strip()] for i in vars(el).items()])
#- Print Scaling Policies Info:
scalingPolicies = self.safeFunc(self.conn.get_all_policies, as_group=asgObj.name)
data.append(['scaling policies:', ''])
for policy in scalingPolicies:
data.append(['\t---------Scaling Policy Description', ''])
data = data + sorted([['\t' + i[0], str(i[1]).strip()] for i in vars(policy).items()])
#- Print Alarms:
data.append(['\talarms:', str(policy.alarms)])
for alarm in policy.alarms:
data.append(['\t\t----------Alarm Description', ''])
data = data + sorted([['\t\t' + i[0], str(i[1]).strip()] for i in vars(alarm).items()])
for cw_alarm in self.safeFunc(self.cwconn.describe_alarms, alarm_names=[alarm.name]):
data = data + sorted([['\t\t' + i[0], str(i[1]).strip()] for i in vars(cw_alarm).items()])
retText = retText + '\n--------------------------------\n'
retText = retText + '-------------- ASG -------------\n'
retText = retText + '--------------------------------\n'
retText = retText + self.prettyPrintColumns(data)
return retText
def prettyPrintColumns(self, data, padding=None):
""" This funciton returns a user friendly column output string.
:param data: A list of strings.
:type data: list of strings
:param padding: The number of spaces between columns Default is 2.
:type padding: int
:return: text
Example (output of _sectionPrint)::
data = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
print prettyPrintColumns(data)
a b c
aaaaaaaaaa b c
a bbbbbbbbbb c
"""
if len(data) == 0:
return ""
padding = 2 if padding is None else padding
#- Invert roles to columns:
dataPrime = zip(*data)
#- Calculate the max column width for each column:
column_widths = []
for i in range(0, len(data[0])):
column_widths.append(len(max(dataPrime[i], key=len)) + padding)
#- Modify the data directly with padding:
for i in range(0, len(data)):
for ii in range(0, len(column_widths) - 1):
data[i][ii] = data[i][ii].ljust(column_widths[ii])
retStr = ''
for row in data:
retStr = retStr + "".join(word for word in row) + '\n'
return retStr
def safeFunc(self, func, *args, **kwargs):
logger = self.log
if 'logger' in kwargs:
logger = kwargs['logger']
del kwargs['logger']
attempts = 60
retVal = None
done_waiting_string = 'Done Waiting. Raising Exception.'
while True:
sleeptime = random.random() * 3
try:
retVal = func(*args, **kwargs)
except Exception as ex:
if not hasattr(ex, 'error_code'):
raise
if ex.error_code == "AlreadyExists":
attempts = attempts - 1
logger.critical(ex.error_message + " " + str(sleeptime * 30) + " seconds), try again " + str(attempts) + " times...")
if attempts == 0:
logger.critical(done_waiting_string)
raise ex
time.sleep(sleeptime * 30)
elif ex.error_code == "Throttling":
attempts = attempts - 1
logger.critical(ex.error_message + " " + str(sleeptime * 30) + " seconds), try again " + str(attempts) + " times...")
if attempts == 0:
logger.critical(done_waiting_string)
raise ex
time.sleep(sleeptime)
elif ex.error_code == "ValidationError":
attempts = attempts - 1
logger.critical(ex.error_message + " " + str(sleeptime * 30) + " seconds), try again " + str(attempts) + " times...")
if attempts == 0:
logger.critical(done_waiting_string)
raise ex
time.sleep(sleeptime * 30)
else:
for i, j in vars(ex).items():
logger.critical(i + " === " + str(j))
raise
else:
break
return retVal
class EC2_Functionality():
def __init__(self, logLevel=logging.CRITICAL, logger=None):
""" Helper class to talk to EC2.
:param logLevel: Verbosity level of this command (DEBUG|INFO|WARNING|CRITICAL).
:type logLevel: logging.logLevel
:param logger: Optionally specificy a logger. Useful for multithreading.
:type logger: logging logger
"""
if logger is None:
#- Create the logger:
self.log = logging.getLogger(__name__)
self.log.handlers = []
ch = logging.StreamHandler()
ch.setFormatter(logging.Formatter('%(message)s'))
self.log.addHandler(ch)
self.log.setLevel(logLevel)
self.identityFile = None
else:
self.log = logger
#- OK, now connect to the region:
self.connectToRegion()
def connectToRegion(self):
#- Connect to us-east-1 region:
if 'AWS_ACCESS_KEY' in os.environ and 'AWS_SECRET_KEY' in os.environ:
self.conn = EC2Connection(os.environ['AWS_ACCESS_KEY'],
os.environ['AWS_SECRET_KEY'])
else:
#- Maybe you can connect with the credentials in ~/.boto or with IAM Role:
self.conn = EC2Connection()
self.log.critical('Connected to Region: ' + self.conn.region.name)
def createTags(self, resource_ids=[], dict_of_tags={}, logger=None):
""" This function creates tags on resource ID.
:param resource_ids: A list of AWS resource IDs.
:type resource_ids: list of strings
:param dict_of_tags: A dict of tags.
:type dict_of_tags: dict
:param logger: Optionally specificy a logger. Useful for multithreading.
:type logger: logging logger
"""
if logger is None:
logger = self.log
logger.critical('Creating Tags: ' + str(dict_of_tags) + 'on resource IDs: ' + str(resource_ids))
image = self.conn.create_tags(resource_ids, dict_of_tags)
def getInstanceById(self, instanceId, logger=None):
""" This function returns an instance object based on an instance AWS ID.
:param imageId: The AWS Instance ID.
:type imageId: string
:param logger: Optionally specificy a logger. Useful for multithreading.
:type logger: logging logger
:return: boto instance object
"""
if logger is None:
logger = self.log
logger.critical('Finding instance ' + instanceId + '... ')
reservations = self.conn.get_all_instances(instance_ids=[instanceId])
for reservation in reservations:
for instance in reservation.instances:
if instance.id == instanceId:
logger.critical('Returning instance ' + instanceId + '... ')
return instance
return None
def getAllInstances(self):
""" This function returns a list of all instance objects.
:return: list of boto instance objects
"""
return [i for r in self.conn.get_all_instances() for i in r.instances]
def terminateInstanceById(self, instanceId, logger=None):
""" This function terminates an instance by it's AWS ID.
:param instanceId: AWS Instance ID that you wish to terminate.
:type instanceId: string
:param logger: Optionally specificy a logger. Useful for multithreading.
:type logger: logging logger
"""
if logger is None:
logger = self.log
logger.critical('\nTerminating Instance: ' + instanceId)
instance = self.getInstanceById(instanceId)
if instance is None:
logger.critical('***Error: Instance not found: ' + instanceId)
else:
while instance.state != 'terminated':
instance.terminate()
instance.update()
if instance.state == 'shutting-down':
break
logger.critical('Waiting for terminated state. Currently: ' + instance.state)
time.sleep(10)
logger.critical('Instance ' + instanceId + ' is terminated or is terminating!')
class AsgInfoDialog(scrolled.ScrolledPanel):
def __init__(self, parent):
scrolled.ScrolledPanel.__init__(self, parent, -1)
vbox = wx.BoxSizer(wx.VERTICAL)
asgObj = ASG_Functionality(logger=None)
self.tText = asgObj.printAllASGs()
font = wx.Font(10, wx.FONTFAMILY_TELETYPE, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL)
desc = wx.StaticText(self, -1, self.tText)
desc.SetForegroundColour("Blue")
desc.SetFont(font)
#- Create the toolbar and all its widgets:
toolbar = parent.CreateToolBar()
x = toolbar.AddLabelTool(wx.ID_ANY, 'ASG', wx.Bitmap(os.path.join(os.path.dirname(__file__), os.path.join('data', 'copy.png'))))
toolbar.Realize()
parent.Bind(wx.EVT_TOOL, self.onCopyF, x)
vbox.Add(desc, 0, wx.ALIGN_LEFT|wx.ALL, 5)
self.SetSizer(vbox)
self.SetAutoLayout(1)
self.SetupScrolling()
def onCopyF(self, event):
print 'putting text to clipboard...'
self.dataObj = wx.TextDataObject()
self.dataObj.SetText(self.tText)
if wx.TheClipboard.Open():
wx.TheClipboard.SetData(self.dataObj)
wx.TheClipboard.Close()
else:
wx.MessageBox("Unable to open the clipboard", "Error")
class AdditionalInfoDialog(wx.Dialog):
def __init__ (self, parent, ID, title, instanceObj):
wx.Dialog.__init__(self, parent=parent,
pos=wx.DefaultPosition, size=(850,500),
style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
font = wx.Font(10, wx.DEFAULT, wx.NORMAL, wx.BOLD)
xposKey = 25
xposValue = 160
height = 20
yStartOfText = 20
heading = wx.StaticText(self, -1, 'Additional Info on Instance', (xposKey, 15))
heading.SetFont(font)
instance_attrs = ["id", "groups", "private_dns_name", "state", "previous_state",
"key_name", "instance_type", "launch_time", "image_id", "placement", "kernel", "ramdisk",
"architecture", "hypervisor", "virtualization_type", "product_codes", "ami_launch_index",
"monitored", "monitoring_state", "spot_instance_request_id", "subnet_id", "vpc_id",
"private_ip_address", "ip_address", "platform", "root_device_name", "root_device_type",
"block_device_mapping", "state_reason", "interfaces", "ebs_optimized", "instance_profile"]
wx.StaticLine(self, -1, (xposKey, 40), (300,1))
i = 1
bflip = False
for attr in instance_attrs:
rcolumn = 0
if bflip is False:
bflip = True
rcolumn = 380
i = i + 1
else:
bflip = False
t = wx.TextCtrl(parent=self, id=-1, size=(135,-1), pos=(xposKey + rcolumn, yStartOfText + i * height), style=wx.TE_READONLY|wx.BORDER_NONE)
t.SetValue(attr)
if attr == 'instance_profile':
val = getattr(instanceObj, attr)
if val is not None:
val = val['arn'][val['arn'].find('/')+1:]
elif attr == 'groups':
val = getattr(instanceObj, attr)
if val is not None:
strval = ''
for group in val:
print group.name + ':' + group.id
strval = strval + group.name + ','
if strval != '':
if strval[-1] == ',':
strval = strval[:-1]
val = strval
else:
val = str(getattr(instanceObj, attr))
t = wx.TextCtrl(parent=self, id=-1, size=(200,-1), pos=(xposValue + rcolumn, yStartOfText + i * height), style=wx.TE_READONLY|wx.BORDER_NONE)
t.SetValue(str(val))
i = i + 2
wx.Button(self, 1, 'OK', (140, yStartOfText + i * height), (60, 30))
self.Bind(wx.EVT_BUTTON, self.OnOk, id=1)
def OnOk(self, event):
self.Close()
class MyForm(wx.Frame):
def getMaxName(self, instance):
if 'Name' in instance.tags.keys():
return len(instance.tags['Name'])
else:
return 0
def getMaxTag(self, instance):
tags_minus_name = instance.tags.copy()
if 'Name' in instance.tags.keys():
del tags_minus_name['Name']
return len(str(tags_minus_name))
def createDictFromIni(self):
configfile = os.path.join(os.path.dirname(__file__), os.path.join('data', 'ec2_gui.ini'))
config = ConfigParser.RawConfigParser()
ret_sshFileDict = {}
ret_credentialsDict = {}
ret_usersDict = {}
if os.path.exists(configfile):
config.read(configfile)
sshFileSections = filter(lambda k: k.startswith('SSH_FILE-'), config.sections())
credentialSections = filter(lambda k: k.startswith('CREDENTIALS-'), config.sections())
userSections = filter(lambda k: k.startswith('USER-'), config.sections())
for section in sshFileSections:
ret_sshFileDict[section] = {}
ret_sshFileDict[section]['SSH_FILE'] = config.get(section, 'SSH_FILE')
ret_sshFileDict[section]['DISPLAY'] = config.get(section, 'DISPLAY')
for section in credentialSections:
ret_credentialsDict[section] = {}
ret_credentialsDict[section]['AWS_ACCESS_KEY'] = config.get(section, 'AWS_ACCESS_KEY')
ret_credentialsDict[section]['AWS_SECRET_KEY'] = config.get(section, 'AWS_SECRET_KEY')
ret_credentialsDict[section]['SSH_CMD'] = config.get(section, 'SSH_CMD')
for section in userSections:
ret_usersDict[section] = {}
ret_usersDict[section]['NAME'] = config.get(section, 'NAME')
ret_usersDict[section]['DISPLAY'] = config.get(section, 'DISPLAY')
else:
print 'location of pom: ' + configfile
dlg = wx.MessageDialog(None, 'Could not find ini file!' \
'See README.txt for more details.', "Error", wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
sys.exit(1)
return ret_sshFileDict, ret_credentialsDict, ret_usersDict
def __init__(self):
#- Read the a config:
self.ret_sshFileDict, self.ret_credentialsDict, self.ret_usersDict = self.createDictFromIni()
self.selected_row = 0
self.selected_col = 0
#- Get the instances:
self.reverseSort = True
credentials = [key for key in self.ret_credentialsDict.keys()]
self.setCredentialsBasedOnComboBoxSelection(credentials[0])
self.refreshEc2List()
#- Initialize the window:
wx.Frame.__init__(self, None, wx.ID_ANY, "EC2 Browser", size=(1100,300))
# Add a panel so it looks correct on all platforms
self.panel = wx.Panel(self, wx.ID_ANY)
num_of_columns = 7
self.grid = gridlib.Grid(self.panel)
self.grid.CreateGrid(len(self.all_instances), num_of_columns)
# Add the click events:
self.grid.Bind(gridlib.EVT_GRID_CELL_RIGHT_CLICK, self.handler_onRightClick)
self.grid.Bind(gridlib.EVT_GRID_LABEL_LEFT_DCLICK, self.handler_onRowDClick)
self.grid.Bind(gridlib.EVT_GRID_LABEL_LEFT_CLICK, self.handler_onRowClick)
self.grid.Bind(gridlib.EVT_GRID_CELL_CHANGE, self.handler_onCellChange)
#- Get the size of column based on largest text in column:
f = self.panel.GetFont()
dc = wx.WindowDC(self.panel)
dc.SetFont(f)
buff = 'WWW'
#- Set the Columns:
if len(self.all_instances) == 0:
max_name_len = 'W'*10
max_dns_name = 'W'*10
max_tags = 'W'*10
max_id = 'W'*10
max_private_dns_name = 'W'*10
max_state = 'W'*10
else:
i = max(self.all_instances, key=self.getMaxName)
if 'Name' in i.tags.keys():
max_name_len = i.tags['Name']
else:
max_name_len = buff
max_dns_name = max(self.all_instances, key=lambda x: len(x.dns_name)).dns_name
max_tags = str(max(self.all_instances, key=self.getMaxTag).tags)
max_id = max(self.all_instances, key=lambda x: len(x.id)).id
max_private_dns_name = max(self.all_instances, key=lambda x: len(x.private_dns_name)).private_dns_name
max_state = max(self.all_instances, key=lambda x: len(x.state)).state
self.columns = {}
self.columns["Name"] = {'col_id':0, 'ins_attr':'tags["Name"]','col_size':dc.GetTextExtent(max_name_len + buff)[0]}
self.columns["public-dns"] = {'col_id':1, 'ins_attr':'dns_name','col_size':dc.GetTextExtent(max_dns_name + buff)[0]}
self.columns["tags"] = {'col_id':2, 'ins_attr':'tags','col_size':dc.GetTextExtent(max_tags + buff)[0]}
self.columns["ID"] = {'col_id':3, 'ins_attr':'id','col_size':dc.GetTextExtent(max_id + buff)[0]}
self.columns["private-dns"] = {'col_id':4, 'ins_attr':'private_dns_name','col_size':dc.GetTextExtent(max_private_dns_name + buff)[0]}
self.columns["state"] = {'col_id':5, 'ins_attr':'state','col_size':dc.GetTextExtent(max_state + buff)[0]}
self.columns["launchTime"] = {'col_id':6, 'ins_attr':'launch_time','col_size':dc.GetTextExtent(max_state + buff)[0]}
#- Set the colors of the rows based on instance state:
self.state_colors = {}
self.state_colors['running'] = 'green'
self.state_colors['terminated'] = 'red'
self.state_colors['shutting-down'] = 'orange'
self.state_colors['pending'] = 'yellow'
self.state_colors['stopped'] = 'grey'
for col_name, val in self.columns.items():
self.grid.SetColLabelValue(val['col_id'], col_name)
self.grid.SetColSize(val['col_id'], val['col_size'])
self.refreshGrid()
#- Create the toolbar and all its widgets:
toolbar = self.CreateToolBar()
#- Pull down for credentials:
cb_credentials = wx.ComboBox(toolbar, value=credentials[0], pos=(50, 30), choices=credentials, style=wx.CB_READONLY)
cb_credentials.Bind(wx.EVT_COMBOBOX, self.handler_onComboBoxCredentialsSelect)
#- Pull down for user:
sshFiles = [v['DISPLAY'] for k,v in self.ret_sshFileDict.items()]
cb_sshFiles = wx.ComboBox(toolbar, value=sshFiles[0], pos=(50, 30), choices=sshFiles, style=wx.CB_READONLY)
self.setSshFileBasedOnComboBoxSelection(sshFiles[0])
cb_sshFiles.Bind(wx.EVT_COMBOBOX, self.handler_onComboBoxSSHFilesSelect)
#- Pull down for ssh pem/ppk files:
userSelection = [v['DISPLAY'] for k,v in self.ret_usersDict.items()]
cb_UserSelection = wx.ComboBox(toolbar, value=userSelection[0], pos=(50, 30), choices=userSelection, style=wx.CB_READONLY)
self.setUserFileBasedOnComboBoxSelection(userSelection[0])
cb_UserSelection.Bind(wx.EVT_COMBOBOX, self.handler_onComboBoxUserSelect)
#- Refresh button:
refreshButton = toolbar.AddLabelTool(wx.ID_ANY, 'Refresh', wx.Bitmap(os.path.join(os.path.dirname(__file__), os.path.join('data', 'refresh.png'))))
toolbar.AddSeparator()
self.Bind(wx.EVT_TOOL, self.refreshButton, refreshButton)
#- Text Search:
self.search = wx.SearchCtrl(toolbar, size=(150,-1))
self.search.Bind(wx.EVT_TEXT, self.handler_onTextEnteredInSearchField)
#- Now add all widgets to toolbar:
toolbar.AddControl(self.search)
toolbar.AddSeparator()
toolbar.AddControl(cb_credentials)
toolbar.AddSeparator()
toolbar.AddControl(cb_sshFiles)
toolbar.AddSeparator()
toolbar.AddControl(cb_UserSelection)
#- Create a button that displays ASG information:
toolbar.AddSeparator()
asgButton = toolbar.AddLabelTool(wx.ID_ANY, 'ASG', wx.Bitmap(os.path.join(os.path.dirname(__file__), os.path.join('data', 'ASG.png'))))
self.Bind(wx.EVT_TOOL, self.displayAsgButton, asgButton)
toolbar.Realize()
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(self.grid, 1, wx.EXPAND, num_of_columns)
self.panel.SetSizer(sizer)
#- Handle Right click menu stuff:
#- (note: if you change the text here, you'll have to update handler_onRightClick)
menu_titles = [ "Connect to Instance", "Terminate", "Aditional Info"]
self.menu_title_by_id = {}
for title in menu_titles:
self.menu_title_by_id[ wx.NewId() ] = title
self.search_text = ''
def handler_onComboBoxUserSelect(self, e):
self.setUserFileBasedOnComboBoxSelection(e.GetString())
def handler_onComboBoxSSHFilesSelect(self, e):
self.setSshFileBasedOnComboBoxSelection(e.GetString())
def setSshFileBasedOnComboBoxSelection(self, text):
self.sshFileSelected = text
def setUserFileBasedOnComboBoxSelection(self, text):
self.userSelected = text
def handler_onComboBoxCredentialsSelect(self, e):
self.setCredentialsBasedOnComboBoxSelection(e.GetString())
self.doRefreshButtonCommands()
def setCredentialsBasedOnComboBoxSelection(self, text):
self.credentialsSelected = text
os.environ['AWS_ACCESS_KEY'] = self.ret_credentialsDict[text]['AWS_ACCESS_KEY']
os.environ['AWS_SECRET_KEY'] = self.ret_credentialsDict[text]['AWS_SECRET_KEY']
def refreshEc2List(self):
print '------------refreshing ec2 list'
self.g_ec2 = EC2_Functionality()
self.all_instances = self.g_ec2.getAllInstances()
self.filtered_list = copy.deepcopy(self.all_instances)
self.makeAllVisible()
def refreshButton(self, event):
#- When you click on the refresh button, this code gets executed:
self.doRefreshButtonCommands()
def displayAsgButton(self, event):
frame = wx.Frame(None, wx.ID_ANY)
fa = AsgInfoDialog(frame)
frame.Show()
#frame = AsgInfoDialog(None, -1, 'Aliens')
#frame.Show(True)
#frame.Centre()
#dlg = AsgInfoDialog(parent=None, ID=0, title="Info", instanceObj=self.filtered_list[self.selected_row])
#dlg.ShowModal()
#dlg.Destroy()
#dlg = wxPython.lib.dialogs.wxScrolledMessageDialog(self, 'msg', 'title', size=(1200,300))
#dlg.ShowModal()
#dlg.Destroy()
def doRefreshButtonCommands(self):
self.refreshEc2List()
self.refreshGrid()
self.DoSearch(self.search_text)
def handler_onCellChange(self, evt):
value = self.grid.GetCellValue(evt.GetRow(), evt.GetCol())
print 'value: ', value
for k,v in self.columns.items():
if v['col_id'] == evt.GetCol():
print 'column modified: ' + k + '. instance ID: ' + str(self.filtered_list[evt.GetRow()].id)
#- We need to ignore the keys that start with AWS:
dict_of_tags = ast.literal_eval(value)
for key in dict_of_tags.keys():
if key.startswith('aws:'):
del dict_of_tags[key]
self.g_ec2.createTags(resource_ids=[str(self.filtered_list[evt.GetRow()].id)], dict_of_tags=dict_of_tags)
break
def handler_onTextEnteredInSearchField(self, evt):
self.search_text = self.search.GetValue()
self.DoSearch(self.search_text)
def makeAllVisible(self):
print '----------making all visible'
for i in self.all_instances:
i.visible = True
def DoSearch(self, text):
print 'Search text: ' + text
self.makeAllVisible()
ordered_search_strings = filter(None, text.strip().split(' '))
for ordered_search in ordered_search_strings:
for i in self.all_instances:
#- Hide the instances where this ordered_search does not appear:
if ordered_search.lower() not in i.dns_name.lower() and \
ordered_search.lower() not in i.private_dns_name.lower() and \
ordered_search.lower() not in i.state.lower() and \
not any( ordered_search.lower() in k for k in [el.lower() for el in i.tags.keys()] ) and \
not any( ordered_search.lower() in k for k in [el.lower() for el in i.tags.values()] ) and \
ordered_search.lower() not in [el.lower() for el in i.tags.values()] and \
ordered_search.lower() not in i.id.lower():
i.visible = False
self.refreshGrid()
def refreshGrid(self):
print '\n\n\n------------refresh grid'
self.grid.ClearGrid()
current, new = (self.grid.GetNumberRows(), len(self.all_instances))
if new < current:
#- Delete rows:
self.grid.DeleteRows(0, current-new, True)
if new > current:
#- append rows:
self.grid.AppendRows(new-current)
for i in range(len(self.all_instances)):
for col_name, val in self.columns.items():
self.grid.SetCellBackgroundColour(i, val['col_id'], 'white')
self.filtered_list = filter(lambda x: x.visible is True, self.all_instances)
for i in range(len(self.filtered_list)):
for col_name, val in self.columns.items():
col_val = ''
if col_name == 'Name':
if 'Name' in self.filtered_list[i].tags.keys():
col_val = self.filtered_list[i].tags['Name']
if hasattr(self.filtered_list[i], val['ins_attr']):
col_val = getattr(self.filtered_list[i], val['ins_attr'])
self.grid.SetCellValue(i, val['col_id'], str(col_val))
#- Set color based on state:
if self.filtered_list[i].state in self.state_colors:
self.grid.SetCellBackgroundColour(i, val['col_id'], self.state_colors[self.filtered_list[i].state])
def handler_onRowClick(self, event):
print 'column clicked!'
def handler_onRowDClick(self, event):
if self.reverseSort is False:
self.reverseSort = True
else:
self.reverseSort = False
col = event.GetCol()
if col == 0:
self.all_instances.sort(key=lambda x: '' if 'Name' not in x.tags else x.tags['Name'], reverse=self.reverseSort)
elif col == 1:
self.all_instances.sort(key=lambda x: x.dns_name, reverse=self.reverseSort)
elif col == 2:
self.all_instances.sort(key=lambda x: str(x.tags), reverse=self.reverseSort)
elif col == 3:
self.all_instances.sort(key=lambda x: x.id, reverse=self.reverseSort)
elif col == 4:
self.all_instances.sort(key=lambda x: x.private_dns_name, reverse=self.reverseSort)
elif col == 5:
self.all_instances.sort(key=lambda x: x.state, reverse=self.reverseSort)
self.refreshGrid()
def handler_onRightClick(self, event):
self.selected_row = event.GetRow()
self.grid.SetSelectionBackground(wx.NamedColour('blue'))
self.grid.SelectRow(self.selected_row, False) # True if the selection should be expanded
self.grid.Refresh()
### 2. Launcher creates wxMenu. ###
menu = wxPython.wx.wxMenu()
for (id,title) in self.menu_title_by_id.items():
### 3. Launcher packs menu with Append. ###
menu.Append( id, title )
### 4. Launcher registers menu handlers with EVT_MENU, on the menu. ###
wxPython.wx.EVT_MENU( menu, id, self.MenuSelectionCb )
### 5. Launcher displays menu with call to PopupMenu, invoked on the source component, passing event's GetPoint. ###
self.PopupMenu( menu )
menu.Destroy() # destroy to avoid mem leak
def MenuSelectionCb( self, event ):
operation = self.menu_title_by_id[ event.GetId() ]
if operation == 'Connect to Instance':
# Re-read the ini file:
self.ret_sshFileDict, self.ret_credentialsDict, self.ret_usersDict = self.createDictFromIni()
#- Based on the ssh pulldown, get the value:
ssh_file = None
for k,v in self.ret_sshFileDict.items():
if self.sshFileSelected == v['DISPLAY']:
ssh_file = v['SSH_FILE']
break
#- Based on the user pulldown, get the value:
name = None
for k,v in self.ret_usersDict.items():
if self.userSelected == v['DISPLAY']:
name = v['NAME']
break
#- Modify the cmd, based on the pulldowns:
cmd = self.ret_credentialsDict[self.credentialsSelected]['SSH_CMD']
cmd = cmd.replace('%DNS_NAME%', self.filtered_list[self.selected_row].dns_name)
cmd = cmd.replace('%SSH_FILE%', ssh_file)
cmd = cmd.replace('%NAME%', name)
print cmd
#DETACHED_PROCESS = 0x00000008
#subprocess.Popen(cmd,shell=False,stdin=None,stdout=None,stderr=None,close_fds=True,creationflags=DETACHED_PROCESS)
subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
if operation == 'Terminate':
# Terminate Instance
str_contents = 'Are you sure you want to delete this instance?'
dlg = wx.MessageDialog(None, str_contents, "Notice", wx.YES_NO | wx.ICON_QUESTION)
result = dlg.ShowModal() == wx.ID_YES
dlg.Destroy()
if result is True:
self.g_ec2.terminateInstanceById(instanceId=self.filtered_list[self.selected_row].id)
time.sleep(1)
self.doRefreshButtonCommands()
if operation == 'Aditional Info':
dlg = AdditionalInfoDialog(parent=None, ID=0, title="Info", instanceObj=self.filtered_list[self.selected_row])
dlg.ShowModal()
dlg.Destroy()
# Run the program
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MyForm().Show()
app.MainLoop()