-
Notifications
You must be signed in to change notification settings - Fork 304
Expand file tree
/
Copy pathcluster.py
More file actions
2276 lines (2117 loc) · 92.5 KB
/
Copy pathcluster.py
File metadata and controls
2276 lines (2117 loc) · 92.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
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
# Copyright 2009-2014 Justin Riley
#
# This file is part of StarCluster.
#
# StarCluster is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# StarCluster is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with StarCluster. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import time
import string
import pprint
import warnings
import datetime
import iptools
from starcluster import utils
from starcluster import static
from starcluster import sshutils
from starcluster import managers
from starcluster import userdata
from starcluster import deathrow
from starcluster import exception
from starcluster import threadpool
from starcluster import validators
from starcluster import progressbar
from starcluster import clustersetup
from starcluster.node import Node
from starcluster.plugins import sge
from starcluster.utils import print_timing
from starcluster.templates import user_msgs
from starcluster.logger import log
class ClusterManager(managers.Manager):
"""
Manager class for Cluster objects
"""
def __repr__(self):
return "<ClusterManager: %s>" % self.ec2.region.name
def get_cluster(self, cluster_name, group=None, load_receipt=True,
load_plugins=True, load_volumes=True, require_keys=True):
"""
Returns a Cluster object representing an active cluster
"""
try:
clname = self._get_cluster_name(cluster_name)
cltag = self.get_tag_from_sg(clname)
if not group:
group = self.ec2.get_security_group(clname)
cl = Cluster(ec2_conn=self.ec2, cluster_tag=cltag,
cluster_group=group)
if load_receipt:
cl.load_receipt(load_plugins=load_plugins,
load_volumes=load_volumes)
try:
cl.keyname = cl.keyname or cl.master_node.key_name
key_location = self.cfg.get_key(cl.keyname).get('key_location')
cl.key_location = key_location
if require_keys:
cl.validator.validate_keypair()
except (exception.KeyNotFound, exception.MasterDoesNotExist):
if require_keys:
raise
cl.key_location = ''
return cl
except exception.SecurityGroupDoesNotExist:
raise exception.ClusterDoesNotExist(cluster_name)
def get_clusters(self, load_receipt=True, load_plugins=True):
"""
Returns a list of all active clusters
"""
cluster_groups = self.get_cluster_security_groups()
clusters = [self.get_cluster(g.name, group=g,
load_receipt=load_receipt,
load_plugins=load_plugins)
for g in cluster_groups]
return clusters
def get_default_cluster_template(self):
"""
Returns name of the default cluster template defined in the config
"""
return self.cfg.get_default_cluster_template()
def get_cluster_template(self, template_name, tag_name=None):
"""
Returns a new Cluster object using the settings from the cluster
template template_name
If tag_name is passed, the Cluster object's cluster_tag setting will
be set to tag_name
"""
cl = self.cfg.get_cluster_template(template_name, tag_name=tag_name,
ec2_conn=self.ec2)
return cl
def get_cluster_or_none(self, cluster_name, **kwargs):
"""
Same as get_cluster but returns None instead of throwing an exception
if the cluster does not exist
"""
try:
return self.get_cluster(cluster_name, **kwargs)
except exception.ClusterDoesNotExist:
pass
def cluster_exists(self, tag_name):
"""
Returns True if cluster exists
"""
return self.get_cluster_or_none(tag_name) is not None
def ssh_to_master(self, cluster_name, user='root', command=None,
forward_x11=False, forward_agent=False,
pseudo_tty=False):
"""
ssh to master node of cluster_name
user keyword specifies an alternate user to login as
"""
cluster = self.get_cluster(cluster_name, load_receipt=False,
require_keys=True)
return cluster.ssh_to_master(user=user, command=command,
forward_x11=forward_x11,
forward_agent=forward_agent,
pseudo_tty=pseudo_tty)
def ssh_to_cluster_node(self, cluster_name, node_id, user='root',
command=None, forward_x11=False,
forward_agent=False, pseudo_tty=False):
"""
ssh to a node in cluster_name that has either an id,
dns name, or alias matching node_id
user keyword specifies an alternate user to login as
"""
cluster = self.get_cluster(cluster_name, load_receipt=False,
require_keys=False)
node = cluster.get_node(node_id)
key_location = self.cfg.get_key(node.key_name).get('key_location')
cluster.key_location = key_location
cluster.keyname = node.key_name
cluster.validator.validate_keypair()
return node.shell(user=user, forward_x11=forward_x11,
forward_agent=forward_agent,
pseudo_tty=pseudo_tty, command=command)
def _get_cluster_name(self, cluster_name):
"""
Returns human readable cluster name/tag prefixed with '@sc-'
"""
if not cluster_name.startswith(static.SECURITY_GROUP_PREFIX):
cluster_name = static.SECURITY_GROUP_TEMPLATE % cluster_name
return cluster_name
def add_node(self, cluster_name, alias=None, no_create=False,
image_id=None, instance_type=None, zone=None,
placement_group=None, spot_bid=None):
cl = self.get_cluster(cluster_name)
return cl.add_node(alias=alias, image_id=image_id,
instance_type=instance_type, zone=zone,
placement_group=placement_group, spot_bid=spot_bid,
no_create=no_create)
def add_nodes(self, cluster_name, num_nodes, aliases=None, no_create=False,
image_id=None, instance_type=None, zone=None,
placement_group=None, spot_bid=None):
"""
Add one or more nodes to cluster
"""
cl = self.get_cluster(cluster_name)
return cl.add_nodes(num_nodes, aliases=aliases, image_id=image_id,
instance_type=instance_type, zone=zone,
placement_group=placement_group, spot_bid=spot_bid,
no_create=no_create)
def remove_node(self, cluster_name, alias=None, terminate=True,
force=False):
"""
Remove a single node from a cluster
"""
cl = self.get_cluster(cluster_name)
n = cl.get_node(alias) if alias else None
return cl.remove_node(node=n, terminate=terminate, force=force)
def remove_nodes(self, cluster_name, num_nodes=None, aliases=None,
terminate=True, force=False):
"""
Remove one or more nodes from cluster
"""
cl = self.get_cluster(cluster_name)
nodes = cl.get_nodes(aliases) if aliases else None
return cl.remove_nodes(nodes=nodes, num_nodes=num_nodes,
terminate=terminate, force=force)
def restart_cluster(self, cluster_name, reboot_only=False):
"""
Reboots and reconfigures cluster_name
"""
cl = self.get_cluster(cluster_name)
cl.restart_cluster(reboot_only=reboot_only)
def stop_cluster(self, cluster_name, terminate_unstoppable=False,
force=False):
"""
Stop an EBS-backed cluster
"""
cl = self.get_cluster(cluster_name, load_receipt=not force,
require_keys=not force)
cl.stop_cluster(terminate_unstoppable, force=force)
def terminate_cluster(self, cluster_name, force=False):
"""
Terminates cluster_name
"""
cl = self.get_cluster(cluster_name, load_receipt=not force,
require_keys=not force)
cl.terminate_cluster(force=force)
def get_cluster_security_group(self, group_name):
"""
Return cluster security group by appending '@sc-' to group_name and
querying EC2.
"""
gname = self._get_cluster_name(group_name)
return self.ec2.get_security_group(gname)
def get_cluster_group_or_none(self, group_name):
try:
return self.get_cluster_security_group(group_name)
except exception.SecurityGroupDoesNotExist:
pass
def get_cluster_security_groups(self):
"""
Return all security groups on EC2 that start with '@sc-'
"""
glob = static.SECURITY_GROUP_TEMPLATE % '*'
sgs = self.ec2.get_security_groups(filters={'group-name': glob})
return sgs
def get_tag_from_sg(self, sg):
"""
Returns the cluster tag name from a security group name that starts
with static.SECURITY_GROUP_PREFIX
Example:
sg = '@sc-mycluster'
print get_tag_from_sg(sg)
mycluster
"""
regex = re.compile('^' + static.SECURITY_GROUP_TEMPLATE % '(.*)')
match = regex.match(sg)
tag = None
if match:
tag = match.groups()[0]
if not tag:
raise ValueError("Invalid cluster group name: %s" % sg)
return tag
def list_clusters(self, cluster_groups=None, show_ssh_status=False):
"""
Prints a summary for each active cluster on EC2
"""
if not cluster_groups:
cluster_groups = self.get_cluster_security_groups()
if not cluster_groups:
log.info("No clusters found...")
else:
try:
cluster_groups = [self.get_cluster_security_group(g) for g
in cluster_groups]
except exception.SecurityGroupDoesNotExist:
raise exception.ClusterDoesNotExist(g)
for scg in cluster_groups:
tag = self.get_tag_from_sg(scg.name)
try:
cl = self.get_cluster(tag, group=scg, load_plugins=False,
load_volumes=False, require_keys=False)
except exception.IncompatibleCluster as e:
sep = '*' * 60
log.error('\n'.join([sep, e.msg, sep]),
extra=dict(__textwrap__=True))
print
continue
header = '%s (security group: %s)' % (tag, scg.name)
print '-' * len(header)
print header
print '-' * len(header)
nodes = cl.nodes
try:
n = nodes[0]
except IndexError:
n = None
state = getattr(n, 'state', None)
ltime = 'N/A'
uptime = 'N/A'
if state in ['pending', 'running']:
ltime = getattr(n, 'local_launch_time', 'N/A')
uptime = getattr(n, 'uptime', 'N/A')
print 'Launch time: %s' % ltime
print 'Uptime: %s' % uptime
if scg.vpc_id:
print 'VPC: %s' % scg.vpc_id
print 'Subnet: %s' % getattr(n, 'subnet_id', 'N/A')
print 'Zone: %s' % getattr(n, 'placement', 'N/A')
print 'Keypair: %s' % getattr(n, 'key_name', 'N/A')
ebs_vols = []
for node in nodes:
devices = node.attached_vols
if not devices:
continue
node_id = node.alias or node.id
for dev in devices:
d = devices.get(dev)
vol_id = d.volume_id
status = d.status
ebs_vols.append((vol_id, node_id, dev, status))
if ebs_vols:
print 'EBS volumes:'
for vid, nid, dev, status in ebs_vols:
print(' %s on %s:%s (status: %s)' %
(vid, nid, dev, status))
else:
print 'EBS volumes: N/A'
spot_reqs = cl.spot_requests
if spot_reqs:
active = len([s for s in spot_reqs if s.state == 'active'])
opn = len([s for s in spot_reqs if s.state == 'open'])
msg = ''
if active != 0:
msg += '%d active' % active
if opn != 0:
if msg:
msg += ', '
msg += '%d open' % opn
print 'Spot requests: %s' % msg
if nodes:
print 'Cluster nodes:'
for node in nodes:
nodeline = " %7s %s %s %s" % (node.alias, node.state,
node.id, node.addr or '')
if node.spot_id:
nodeline += ' (spot %s)' % node.spot_id
if show_ssh_status:
ssh_status = {True: 'Up', False: 'Down'}
nodeline += ' (SSH: %s)' % ssh_status[node.is_up()]
print nodeline
print 'Total nodes: %d' % len(nodes)
else:
print 'Cluster nodes: N/A'
print
def run_plugin(self, plugin_name, cluster_tag):
"""
Run a plugin defined in the config.
plugin_name must match the plugin's section name in the config
cluster_tag specifies the cluster to run the plugin on
"""
cl = self.get_cluster(cluster_tag, load_plugins=False)
if not cl.is_cluster_up():
raise exception.ClusterNotRunning(cluster_tag)
plugs = [self.cfg.get_plugin(plugin_name)]
plug = deathrow._load_plugins(plugs)[0]
cl.run_plugin(plug, name=plugin_name)
class Cluster(object):
def __init__(self,
ec2_conn=None,
spot_bid=None,
cluster_tag=None,
cluster_description=None,
cluster_size=None,
cluster_user=None,
cluster_shell=None,
dns_prefix=None,
master_image_id=None,
master_instance_type=None,
node_image_id=None,
node_instance_type=None,
node_instance_types=[],
availability_zone=None,
keyname=None,
key_location=None,
volumes=[],
plugins=[],
permissions=[],
userdata_scripts=[],
refresh_interval=30,
disable_queue=False,
num_threads=20,
disable_threads=False,
cluster_group=None,
force_spot_master=False,
disable_cloudinit=False,
subnet_id=None,
public_ips=None,
**kwargs):
# update class vars with given vars
_vars = locals().copy()
del _vars['cluster_group']
del _vars['ec2_conn']
self.__dict__.update(_vars)
# more configuration
now = time.strftime("%Y%m%d%H%M")
if self.cluster_tag is None:
self.cluster_tag = "cluster%s" % now
if cluster_description is None:
self.cluster_description = "Cluster created at %s" % now
self.ec2 = ec2_conn
self.cluster_size = cluster_size or 0
self.volumes = self.load_volumes(volumes)
self.plugins = self.load_plugins(plugins)
self.userdata_scripts = userdata_scripts or []
self.dns_prefix = dns_prefix and cluster_tag
self._cluster_group = None
self._placement_group = None
self._subnet = None
self._zone = None
self._master = None
self._nodes = []
self._pool = None
self._progress_bar = None
self.__default_plugin = None
self.__sge_plugin = None
def __repr__(self):
return '<Cluster: %s (%s-node)>' % (self.cluster_tag,
self.cluster_size)
@property
def zone(self):
if not self._zone:
self._zone = self._get_cluster_zone()
return self._zone
def _get_cluster_zone(self):
"""
Returns the cluster's zone. If volumes are specified, this method
determines the common zone between those volumes. If a zone is
explicitly specified in the config and does not match the common zone
of the volumes, an exception is raised. If all volumes are not in the
same zone an exception is raised. If no volumes are specified, returns
the user-specified zone if it exists. Returns None if no volumes and no
zone is specified.
"""
zone = None
if self.availability_zone:
zone = self.ec2.get_zone(self.availability_zone)
common_zone = None
for volume in self.volumes:
volid = self.volumes.get(volume).get('volume_id')
vol = self.ec2.get_volume(volid)
if not common_zone:
common_zone = vol.zone
elif vol.zone != common_zone:
vols = [self.volumes.get(v).get('volume_id')
for v in self.volumes]
raise exception.VolumesZoneError(vols)
if common_zone and zone and zone.name != common_zone:
raise exception.InvalidZone(zone.name, common_zone)
if not zone and common_zone:
zone = self.ec2.get_zone(common_zone)
if not zone:
try:
zone = self.ec2.get_zone(self.master_node.placement)
except exception.MasterDoesNotExist:
pass
return zone
@property
def _plugins(self):
return [p.__plugin_metadata__ for p in self.plugins]
def load_plugins(self, plugins):
if plugins and isinstance(plugins[0], dict):
warnings.warn("In a future release the plugins kwarg for Cluster "
"will require a list of plugin objects and not a "
"list of dicts", DeprecationWarning)
plugins = deathrow._load_plugins(plugins)
return plugins
@property
def _default_plugin(self):
if not self.__default_plugin:
self.__default_plugin = clustersetup.DefaultClusterSetup(
disable_threads=self.disable_threads,
num_threads=self.num_threads)
return self.__default_plugin
@property
def _sge_plugin(self):
if not self.__sge_plugin:
self.__sge_plugin = sge.SGEPlugin(
disable_threads=self.disable_threads,
num_threads=self.num_threads)
return self.__sge_plugin
def load_volumes(self, vols):
"""
Iterate through vols and set device/partition settings automatically if
not specified.
This method assigns the first volume to /dev/sdz, second to /dev/sdy,
etc. for all volumes that do not include a device/partition setting
"""
devices = ['/dev/sd%s' % s for s in string.lowercase]
devmap = {}
for volname in vols:
vol = vols.get(volname)
dev = vol.get('device')
if dev in devices:
# rm user-defined devices from the list of auto-assigned
# devices
devices.remove(dev)
volid = vol.get('volume_id')
if dev and volid not in devmap:
devmap[volid] = dev
volumes = utils.AttributeDict()
for volname in vols:
vol = vols.get(volname)
vol_id = vol.get('volume_id')
device = vol.get('device')
if not device:
if vol_id in devmap:
device = devmap.get(vol_id)
else:
device = devices.pop()
devmap[vol_id] = device
if not utils.is_valid_device(device):
raise exception.InvalidDevice(device)
v = volumes[volname] = utils.AttributeDict()
v.update(vol)
v['device'] = device
part = vol.get('partition')
if part:
partition = device + str(part)
if not utils.is_valid_partition(partition):
raise exception.InvalidPartition(part)
v['partition'] = partition
return volumes
def update(self, kwargs):
for key in kwargs.keys():
if hasattr(self, key):
self.__dict__[key] = kwargs[key]
def get(self, name):
return self.__dict__.get(name)
def __str__(self):
cfg = self.__getstate__()
return pprint.pformat(cfg)
def load_receipt(self, load_plugins=True, load_volumes=True):
"""
Load the original settings used to launch this cluster into this
Cluster object. Settings are loaded from cluster group tags and the
master node's user data.
"""
try:
tags = self.cluster_group.tags
version = tags.get(static.VERSION_TAG, '')
if utils.program_version_greater(version, static.VERSION):
d = dict(cluster=self.cluster_tag, old_version=static.VERSION,
new_version=version)
msg = user_msgs.version_mismatch % d
sep = '*' * 60
log.warn('\n'.join([sep, msg, sep]), extra={'__textwrap__': 1})
self.update(self._get_settings_from_tags())
if not (load_plugins or load_volumes):
return True
try:
master = self.master_node
except exception.MasterDoesNotExist:
unfulfilled_spots = [sr for sr in self.spot_requests if not
sr.instance_id]
if unfulfilled_spots:
self.wait_for_active_spots()
master = self.master_node
else:
raise
if load_plugins:
self.plugins = self.load_plugins(master.get_plugins())
if load_volumes:
self.volumes = master.get_volumes()
except exception.PluginError:
log.error("An error occurred while loading plugins: ",
exc_info=True)
raise
except exception.MasterDoesNotExist:
raise
except Exception:
log.debug('load receipt exception: ', exc_info=True)
raise exception.IncompatibleCluster(self.cluster_group)
return True
def __getstate__(self):
cfg = {}
exclude = ['key_location', 'plugins']
include = ['_zone', '_plugins']
for key in self.__dict__.keys():
private = key.startswith('_')
if (not private or key in include) and key not in exclude:
val = getattr(self, key)
if type(val) in [str, unicode, bool, int, float, list, dict]:
cfg[key] = val
elif isinstance(val, utils.AttributeDict):
cfg[key] = dict(val)
return cfg
@property
def _security_group(self):
return static.SECURITY_GROUP_TEMPLATE % self.cluster_tag
@property
def subnet(self):
if not self._subnet and self.subnet_id:
self._subnet = self.ec2.get_subnet(self.subnet_id)
return self._subnet
@property
def cluster_group(self):
if self._cluster_group:
return self._cluster_group
sg = self.ec2.get_group_or_none(self._security_group)
if not sg:
desc = 'StarCluster-%s' % static.VERSION.replace('.', '_')
if self.subnet:
desc += ' (VPC)'
vpc_id = getattr(self.subnet, 'vpc_id', None)
sg = self.ec2.create_group(self._security_group,
description=desc,
auth_ssh=True,
auth_group_traffic=True,
vpc_id=vpc_id)
self._add_tags_to_sg(sg)
self._add_permissions_to_sg(sg)
self._cluster_group = sg
return sg
def _add_permissions_to_sg(self, sg):
ssh_port = static.DEFAULT_SSH_PORT
for p in self.permissions:
perm = self.permissions.get(p)
ip_protocol = perm.get('ip_protocol', 'tcp')
from_port = perm.get('from_port')
to_port = perm.get('to_port')
cidr_ip = perm.get('cidr_ip', static.WORLD_CIDRIP)
if not self.ec2.has_permission(sg, ip_protocol, from_port,
to_port, cidr_ip):
log.info("Opening %s port range %s-%s for CIDR %s" %
(ip_protocol, from_port, to_port, cidr_ip))
sg.authorize(ip_protocol, from_port, to_port, cidr_ip)
else:
log.info("Already open: %s port range %s-%s for CIDR %s" %
(ip_protocol, from_port, to_port, cidr_ip))
includes_ssh = from_port <= ssh_port <= to_port
open_to_world = cidr_ip == static.WORLD_CIDRIP
if ip_protocol == 'tcp' and includes_ssh and not open_to_world:
sg.revoke(ip_protocol, ssh_port, ssh_port,
static.WORLD_CIDRIP)
def _add_chunked_tags(self, sg, chunks, base_tag_name):
for i, chunk in enumerate(chunks):
tag = "%s-%s" % (base_tag_name, i) if i != 0 else base_tag_name
if tag not in sg.tags:
sg.add_tag(tag, chunk)
def _add_tags_to_sg(self, sg):
if static.VERSION_TAG not in sg.tags:
sg.add_tag(static.VERSION_TAG, str(static.VERSION))
core_settings = dict(cluster_size=self.cluster_size,
master_image_id=self.master_image_id,
master_instance_type=self.master_instance_type,
node_image_id=self.node_image_id,
node_instance_type=self.node_instance_type,
availability_zone=self.availability_zone,
dns_prefix=self.dns_prefix,
subnet_id=self.subnet_id,
public_ips=self.public_ips,
disable_queue=self.disable_queue,
disable_cloudinit=self.disable_cloudinit)
user_settings = dict(cluster_user=self.cluster_user,
cluster_shell=self.cluster_shell,
keyname=self.keyname, spot_bid=self.spot_bid)
core = utils.dump_compress_encode(core_settings, use_json=True,
chunk_size=static.MAX_TAG_LEN)
self._add_chunked_tags(sg, core, static.CORE_TAG)
user = utils.dump_compress_encode(user_settings, use_json=True,
chunk_size=static.MAX_TAG_LEN)
self._add_chunked_tags(sg, user, static.USER_TAG)
def _load_chunked_tags(self, sg, base_tag_name):
tags = [i for i in sg.tags if i.startswith(base_tag_name)]
tags.sort()
chunks = [sg.tags[i] for i in tags if i.startswith(base_tag_name)]
return utils.decode_uncompress_load(chunks, use_json=True)
def _get_settings_from_tags(self, sg=None):
sg = sg or self.cluster_group
cluster = {}
if static.CORE_TAG in sg.tags:
cluster.update(self._load_chunked_tags(sg, static.CORE_TAG))
if static.USER_TAG in sg.tags:
cluster.update(self._load_chunked_tags(sg, static.USER_TAG))
return cluster
@property
def placement_group(self):
if self._placement_group is None:
pg = self.ec2.get_or_create_placement_group(self._security_group)
self._placement_group = pg
return self._placement_group
@property
def master_node(self):
if not self._master:
for node in self.nodes:
if node.is_master():
self._master = node
if not self._master:
raise exception.MasterDoesNotExist()
self._master.key_location = self.key_location
return self._master
@property
def nodes(self):
states = ['pending', 'running', 'stopping', 'stopped']
filters = {'instance-state-name': states,
'instance.group-name': self._security_group}
nodes = self.ec2.get_all_instances(filters=filters)
# remove any cached nodes not in the current node list from EC2
current_ids = [n.id for n in nodes]
remove_nodes = [n for n in self._nodes if n.id not in current_ids]
for node in remove_nodes:
self._nodes.remove(node)
# update node cache with latest instance data from EC2
existing_nodes = dict([(n.id, n) for n in self._nodes])
log.debug('existing nodes: %s' % existing_nodes)
for node in nodes:
if node.id in existing_nodes:
log.debug('updating existing node %s in self._nodes' % node.id)
enode = existing_nodes.get(node.id)
enode.key_location = self.key_location
enode.instance = node
else:
log.debug('adding node %s to self._nodes list' % node.id)
n = Node(node, self.key_location)
if n.is_master():
self._master = n
self._nodes.insert(0, n)
else:
self._nodes.append(n)
self._nodes.sort(key=lambda n: n.alias)
log.debug('returning self._nodes = %s' % self._nodes)
return self._nodes
def get_nodes_or_raise(self):
nodes = self.nodes
if not nodes:
filters = {'instance.group-name': self._security_group}
terminated_nodes = self.ec2.get_all_instances(filters=filters)
raise exception.NoClusterNodesFound(terminated_nodes)
return nodes
def get_node(self, identifier, nodes=None):
"""
Returns a node if the identifier specified matches any unique instance
attribute (e.g. instance id, alias, spot id, dns name, private ip,
public ip, etc.)
"""
nodes = nodes or self.nodes
for node in self.nodes:
if node.alias == identifier:
return node
if node.id == identifier:
return node
if node.spot_id == identifier:
return node
if node.dns_name == identifier:
return node
if node.ip_address == identifier:
return node
if node.private_ip_address == identifier:
return node
if node.public_dns_name == identifier:
return node
if node.private_dns_name == identifier:
return node
raise exception.InstanceDoesNotExist(identifier, label='node')
def get_nodes(self, identifiers, nodes=None):
"""
Same as get_node but takes a list of identifiers and returns a list of
nodes.
"""
nodes = nodes or self.nodes
node_list = []
for i in identifiers:
n = self.get_node(i, nodes=nodes)
if n in node_list:
continue
else:
node_list.append(n)
return node_list
def get_node_by_dns_name(self, dns_name, nodes=None):
warnings.warn("Please update your code to use Cluster.get_node()",
DeprecationWarning)
return self.get_node(dns_name, nodes=nodes)
def get_node_by_id(self, instance_id, nodes=None):
warnings.warn("Please update your code to use Cluster.get_node()",
DeprecationWarning)
return self.get_node(instance_id, nodes=nodes)
def get_node_by_alias(self, alias, nodes=None):
warnings.warn("Please update your code to use Cluster.get_node()",
DeprecationWarning)
return self.get_node(alias, nodes=nodes)
def _nodes_in_states(self, states):
return filter(lambda x: x.state in states, self.nodes)
def _make_alias(self, id=None, master=False):
if master:
if self.dns_prefix:
return "%s-master" % self.dns_prefix
else:
return "master"
elif id is not None:
if self.dns_prefix:
alias = '%s-node%.3d' % (self.dns_prefix, id)
else:
alias = 'node%.3d' % id
else:
raise AttributeError("_make_alias(...) must receive either"
" master=True or a node id number")
return alias
@property
def running_nodes(self):
return self._nodes_in_states(['running'])
@property
def stopped_nodes(self):
return self._nodes_in_states(['stopping', 'stopped'])
@property
def spot_requests(self):
group_id = self.cluster_group.id
states = ['active', 'open']
filters = {'state': states}
vpc_id = self.cluster_group.vpc_id
if vpc_id and self.subnet_id:
# According to the EC2 API docs this *should* be
# launch.network-interface.group-id but it doesn't work
filters['network-interface.group-id'] = group_id
else:
filters['launch.group-id'] = group_id
return self.ec2.get_all_spot_requests(filters=filters)
def get_spot_requests_or_raise(self):
spots = self.spot_requests
if not spots:
raise exception.NoClusterSpotRequests
return spots
def create_node(self, alias, image_id=None, instance_type=None, zone=None,
placement_group=None, spot_bid=None, force_flat=False):
return self.create_nodes([alias], image_id=image_id,
instance_type=instance_type, zone=zone,
placement_group=placement_group,
spot_bid=spot_bid, force_flat=force_flat)[0]
def _get_cluster_userdata(self, aliases):
alias_file = utils.string_to_file('\n'.join(['#ignored'] + aliases),
static.UD_ALIASES_FNAME)
plugins = utils.dump_compress_encode(self._plugins)
plugins_file = utils.string_to_file('\n'.join(['#ignored', plugins]),
static.UD_PLUGINS_FNAME)
volumes = utils.dump_compress_encode(self.volumes)
volumes_file = utils.string_to_file('\n'.join(['#ignored', volumes]),
static.UD_VOLUMES_FNAME)
udfiles = [alias_file, plugins_file, volumes_file]
user_scripts = self.userdata_scripts or []
udfiles += [open(f) for f in user_scripts]
use_cloudinit = not self.disable_cloudinit
udata = userdata.bundle_userdata_files(udfiles,
use_cloudinit=use_cloudinit)
log.debug('Userdata size in KB: %.2f' % utils.size_in_kb(udata))
return udata
def create_nodes(self, aliases, image_id=None, instance_type=None,
zone=None, placement_group=None, spot_bid=None,
force_flat=False):
"""
Convenience method for requesting instances with this cluster's
settings. All settings (kwargs) except force_flat default to cluster
settings if not provided. Passing force_flat=True ignores spot_bid
completely forcing a flat-rate instance to be requested.
"""
spot_bid = spot_bid or self.spot_bid
if force_flat:
spot_bid = None
cluster_sg = self.cluster_group.name
instance_type = instance_type or self.node_instance_type
if placement_group or instance_type in static.PLACEMENT_GROUP_TYPES:
region = self.ec2.region.name
if region not in static.PLACEMENT_GROUP_REGIONS:
cluster_regions = ', '.join(static.PLACEMENT_GROUP_REGIONS)
log.warn("Placement groups are only supported in the "
"following regions:\n%s" % cluster_regions)
log.warn("Instances will not be launched in a placement group")
placement_group = None
elif not placement_group:
placement_group = self.placement_group.name
image_id = image_id or self.node_image_id
count = len(aliases) if not spot_bid else 1
user_data = self._get_cluster_userdata(aliases)
kwargs = dict(price=spot_bid, instance_type=instance_type,
min_count=count, max_count=count, count=count,
key_name=self.keyname,
availability_zone_group=cluster_sg,
launch_group=cluster_sg,
placement=zone or getattr(self.zone, 'name', None),
user_data=user_data,
placement_group=placement_group)
if self.subnet_id:
netif = self.ec2.get_network_spec(
device_index=0, associate_public_ip_address=self.public_ips,
subnet_id=self.subnet_id, groups=[self.cluster_group.id])
kwargs.update(
network_interfaces=self.ec2.get_network_collection(netif))
else:
kwargs.update(security_groups=[cluster_sg])
resvs = []
if spot_bid:
security_group_id = self.cluster_group.id
for alias in aliases:
if not self.subnet_id:
kwargs['security_group_ids'] = [security_group_id]
kwargs['user_data'] = self._get_cluster_userdata([alias])
resvs.extend(self.ec2.request_instances(image_id, **kwargs))
else:
resvs.append(self.ec2.request_instances(image_id, **kwargs))
for resv in resvs:
log.info(str(resv), extra=dict(__raw__=True))
return resvs
def _get_next_node_num(self):
nodes = self._nodes_in_states(['pending', 'running'])
nodes = filter(lambda x: not x.is_master(), nodes)
highest = 0
for n in nodes:
match = re.search('node(\d{3})', n.alias)
try:
_possible_highest = match.group(1)
except AttributeError:
continue
highest = max(int(_possible_highest), highest)
next = int(highest) + 1
log.debug("Highest node number is %d. choosing %d." % (highest, next))
return next
def add_node(self, alias=None, no_create=False, image_id=None,
instance_type=None, zone=None, placement_group=None,
spot_bid=None):
"""
Add a single node to this cluster
"""
aliases = [alias] if alias else None
return self.add_nodes(1, aliases=aliases, image_id=image_id,
instance_type=instance_type, zone=zone,
placement_group=placement_group,
spot_bid=spot_bid, no_create=no_create)
def add_nodes(self, num_nodes, aliases=None, image_id=None,
instance_type=None, zone=None, placement_group=None,
spot_bid=None, no_create=False):