forked from NixOS/nixops-aws
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ec2.py
2112 lines (1841 loc) · 83.4 KB
/
ec2.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
# -*- coding: utf-8 -*-
import re
import time
import math
import calendar
import boto.ec2
import boto.ec2.blockdevicemapping
import boto.ec2.networkinterface
from nixops.backends import MachineDefinition, MachineState
from nixops.nix_expr import Function, Call, RawValue
from nixopsaws.resources.ebs_volume import EBSVolumeState
from nixopsaws.resources.elastic_ip import ElasticIPState
import nixopsaws.resources.ec2_common
import nixopsaws.resources
from nixops.util import (
device_name_to_boto_expected,
device_name_stored_to_real,
device_name_user_entered_to_stored,
)
import nixopsaws.ec2_utils
import nixops.known_hosts
import datetime
import boto3
class EC2InstanceDisappeared(Exception):
pass
# name conventions:
# device - device name that user enters: sd, xvd or nvme
# device_stored - device name stored in db: sd or nvme
# device_real - device name attached to machine: xvd or nvme, sd can't be attached
# device_that_boto_expects - only sd device names can be passed to boto, but amazon will attach them as xvd or nvme based on machine type
class EC2Definition(MachineDefinition):
"""Definition of an EC2 machine."""
@classmethod
def get_type(cls):
return "ec2"
def __init__(self, xml, config):
MachineDefinition.__init__(self, xml, config)
self.access_key_id = config["ec2"]["accessKeyId"]
self.region = config["ec2"]["region"]
self.zone = config["ec2"]["zone"]
self.tenancy = config["ec2"]["tenancy"]
self.ami = config["ec2"]["ami"]
if self.ami == "":
raise Exception("no AMI defined for EC2 machine ‘{0}’".format(self.name))
self.instance_type = config["ec2"]["instanceType"]
self.key_pair = config["ec2"]["keyPair"]
self.private_key = config["ec2"]["privateKey"]
self.security_groups = config["ec2"]["securityGroups"]
self.placement_group = config["ec2"]["placementGroup"]
self.instance_profile = config["ec2"]["instanceProfile"]
self.tags = config["ec2"]["tags"]
self.root_disk_size = config["ec2"]["ebsInitialRootDiskSize"]
self.spot_instance_price = config["ec2"]["spotInstancePrice"]
self.spot_instance_timeout = config["ec2"]["spotInstanceTimeout"]
self.spot_instance_request_type = config["ec2"]["spotInstanceRequestType"]
self.spot_instance_interruption_behavior = config["ec2"][
"spotInstanceInterruptionBehavior"
]
self.ebs_optimized = config["ec2"]["ebsOptimized"]
self.subnet_id = config["ec2"]["subnetId"]
self.associate_public_ip_address = config["ec2"]["associatePublicIpAddress"]
self.use_private_ip_address = config["ec2"]["usePrivateIpAddress"]
self.source_dest_check = config["ec2"]["sourceDestCheck"]
self.security_group_ids = config["ec2"]["securityGroupIds"]
# convert sd to xvd because they are equal from aws perspective
self.block_device_mapping = {
device_name_user_entered_to_stored(k): v
for k, v in config["ec2"]["blockDeviceMapping"].items()
}
self.elastic_ipv4 = config["ec2"]["elasticIPv4"]
self.dns_hostname = config["route53"]["hostName"].lower()
self.dns_ttl = config["route53"]["ttl"]
self.route53_access_key_id = config["route53"]["accessKeyId"]
self.route53_use_public_dns_name = config["route53"]["usePublicDNSName"]
self.route53_private = config["route53"]["private"]
def show_type(self):
return "{0} [{1}]".format(self.get_type(), self.region or self.zone or "???")
def host_key_type(self):
return (
"ed25519"
if nixops.util.parse_nixos_version(self.config["nixosRelease"])
>= ["15", "09"]
else "dsa"
)
class EC2State(MachineState, nixopsaws.resources.ec2_common.EC2CommonState):
"""State of an EC2 machine."""
@classmethod
def get_type(cls):
return "ec2"
state = nixops.util.attr_property("state", MachineState.MISSING, int) # override
# We need to store this in machine state so wait_for_ip knows what to wait for
# Really it seems like this whole class should be parameterized by its definition.
# (or the state shouldn't be doing the polling)
public_ipv4 = nixops.util.attr_property("publicIpv4", None)
private_ipv4 = nixops.util.attr_property("privateIpv4", None)
public_dns_name = nixops.util.attr_property("publicDnsName", None)
use_private_ip_address = nixops.util.attr_property(
"ec2.usePrivateIpAddress", False, type=bool
)
source_dest_check = nixops.util.attr_property(
"ec2.sourceDestCheck", True, type=bool
)
associate_public_ip_address = nixops.util.attr_property(
"ec2.associatePublicIpAddress", False, type=bool
)
elastic_ipv4 = nixops.util.attr_property("ec2.elasticIpv4", None)
access_key_id = nixops.util.attr_property("ec2.accessKeyId", None)
region = nixops.util.attr_property("ec2.region", None)
zone = nixops.util.attr_property("ec2.zone", None)
tenancy = nixops.util.attr_property("ec2.tenancy", None)
ami = nixops.util.attr_property("ec2.ami", None)
instance_type = nixops.util.attr_property("ec2.instanceType", None)
ebs_optimized = nixops.util.attr_property("ec2.ebsOptimized", None, bool)
key_pair = nixops.util.attr_property("ec2.keyPair", None)
public_host_key = nixops.util.attr_property("ec2.publicHostKey", None)
private_host_key = nixops.util.attr_property("ec2.privateHostKey", None)
private_key_file = nixops.util.attr_property("ec2.privateKeyFile", None)
instance_profile = nixops.util.attr_property("ec2.instanceProfile", None)
security_groups = nixops.util.attr_property("ec2.securityGroups", None, "json")
placement_group = nixops.util.attr_property("ec2.placementGroup", None, "json")
block_device_mapping = nixops.util.attr_property(
"ec2.blockDeviceMapping", {}, "json"
)
root_device_type = nixops.util.attr_property("ec2.rootDeviceType", None)
backups = nixops.util.attr_property("ec2.backups", {}, "json")
dns_hostname = nixops.util.attr_property("route53.hostName", None)
dns_ttl = nixops.util.attr_property("route53.ttl", None, int)
route53_access_key_id = nixops.util.attr_property("route53.accessKeyId", None)
client_token = nixops.util.attr_property("ec2.clientToken", None)
spot_instance_request_id = nixops.util.attr_property(
"ec2.spotInstanceRequestId", None
)
spot_instance_price = nixops.util.attr_property("ec2.spotInstancePrice", None)
subnet_id = nixops.util.attr_property("ec2.subnetId", None)
first_boot = nixops.util.attr_property("ec2.firstBoot", True, type=bool)
virtualization_type = nixops.util.attr_property("ec2.virtualizationType", None)
def __init__(self, depl, name, id):
MachineState.__init__(self, depl, name, id)
self._conn = None
self._conn_vpc = None
self._conn_route53 = None
self._conn_boto3 = None
self._cached_instance = None
def _reset_state(self):
"""Discard all state pertaining to an instance."""
with self.depl._db:
self.state = MachineState.MISSING
self.associate_public_ip_address = None
self.use_private_ip_address = None
self.source_dest_check = None
self.vm_id = None
self.public_ipv4 = None
self.private_ipv4 = None
self.public_dns_name = None
self.elastic_ipv4 = None
self.region = None
self.zone = None
self.tenancy = None
self.ami = None
self.instance_type = None
self.ebs_optimized = None
self.key_pair = None
self.public_host_key = None
self.private_host_key = None
self.instance_profile = None
self.security_groups = None
self.placement_group = None
self.tags = {}
self.block_device_mapping = {}
self.root_device_type = None
self.backups = {}
self.dns_hostname = None
self.dns_ttl = None
self.subnet_id = None
self.client_token = None
self.spot_instance_request_id = None
self.spot_instance_price = None
def get_ssh_name(self):
retVal = None
if self.use_private_ip_address:
if not self.private_ipv4:
raise Exception(
"EC2 machine '{0}' does not have a private IPv4 address (yet)".format(
self.name
)
)
retVal = self.private_ipv4
else:
if not self.public_ipv4:
raise Exception(
"EC2 machine ‘{0}’ does not have a public IPv4 address (yet)".format(
self.name
)
)
retVal = self.public_ipv4
return retVal
def get_ssh_private_key_file(self):
if self.private_key_file:
return self.private_key_file
if self._ssh_private_key_file:
return self._ssh_private_key_file
for r in self.depl.active_resources.values():
if (
isinstance(r, nixopsaws.resources.ec2_keypair.EC2KeyPairState)
and r.state == nixopsaws.resources.ec2_keypair.EC2KeyPairState.UP
and r.keypair_name == self.key_pair
):
return self.write_ssh_private_key(r.private_key)
return None
def get_ssh_flags(self, *args, **kwargs):
file = self.get_ssh_private_key_file()
super_flags = super(EC2State, self).get_ssh_flags(*args, **kwargs)
return super_flags + (["-i", file] if file else [])
def get_physical_spec(self):
block_device_mapping = {}
for device_stored, v in self.block_device_mapping.items():
device_real = device_name_stored_to_real(device_stored)
if (
v.get("encrypt", False)
and v.get("encryptionType", "luks") == "luks"
and v.get("passphrase", "") == ""
and v.get("generatedKey", "") != ""
):
block_device_mapping[device_real] = {
"passphrase": Call(
RawValue("pkgs.lib.mkOverride 10"), v["generatedKey"]
),
}
return {
"imports": [
RawValue("<nixpkgs/nixos/modules/virtualisation/amazon-image.nix>")
],
("deployment", "ec2", "blockDeviceMapping"): block_device_mapping,
("deployment", "ec2", "instanceId"): self.vm_id,
("ec2", "hvm"): self.virtualization_type == "hvm"
or self.virtualization_type is None,
}
def get_physical_backup_spec(self, backupid):
val = {}
if backupid in self.backups:
for device_stored, snap in self.backups[backupid].items():
device_real = device_name_stored_to_real(device_stored)
is_root_device = device_real.startswith(
"/dev/xvda"
) or device_real.startswith("/dev/nvme0")
if not is_root_device:
val[device_real] = {
"disk": Call(RawValue("pkgs.lib.mkOverride 10"), snap)
}
val = {("deployment", "ec2", "blockDeviceMapping"): val}
else:
val = RawValue("{{}} /* No backup found for id '{0}' */".format(backupid))
return Function("{ config, pkgs, ... }", val)
def get_keys(self):
keys = MachineState.get_keys(self)
# Ugly: we have to add the generated keys because they're not
# there in the first evaluation (though they are present in
# the final nix-build). Had to hardcode the default here to
# make the old way of defining keys work.
for device_stored, v in self.block_device_mapping.items():
if (
v.get("encrypt", False)
and v.get("passphrase", "") == ""
and v.get("generatedKey", "") != ""
and v.get("encryptionType", "luks") == "luks"
):
device_real = device_name_stored_to_real(device_stored)
key_name = "luks-" + device_real.replace("/dev/", "")
keys[key_name] = {
"text": v["generatedKey"],
"keyFile": "/run/keys/" + key_name,
"destDir": "/run/keys",
"group": "root",
"permissions": "0600",
"user": "root",
}
return keys
def show_type(self):
s = super(EC2State, self).show_type()
if self.zone or self.region:
s = "{0} [{1}; {2}]".format(s, self.zone or self.region, self.instance_type)
return s
@property
def resource_id(self):
return self.vm_id
def address_to(self, m):
if isinstance(m, EC2State): # FIXME: only if we're in the same region
return m.private_ipv4
return MachineState.address_to(self, m)
def connect(self):
if self._conn:
return self._conn
self._conn = nixopsaws.ec2_utils.connect(self.region, self.access_key_id)
return self._conn
def connect_boto3(self):
if self._conn_boto3:
return self._conn_boto3
self._conn_boto3 = nixopsaws.ec2_utils.connect_ec2_boto3(
self.region, self.access_key_id
)
return self._conn_boto3
def connect_vpc(self):
if self._conn_vpc:
return self._conn_vpc
self._conn_vpc = nixopsaws.ec2_utils.connect_vpc(
self.region, self.access_key_id
)
return self._conn_vpc
def connect_route53(self):
if self._conn_route53:
return
# Get the secret access key from the environment or from ~/.ec2-keys.
(access_key_id, secret_access_key) = nixopsaws.ec2_utils.fetch_aws_secret_key(
self.route53_access_key_id
)
self._conn_route53 = boto.connect_route53(access_key_id, secret_access_key)
def _get_spot_instance_request_by_id(self, request_id, allow_missing=False):
"""Get spot instance request object by id."""
self.connect()
try:
result = self._conn.get_all_spot_instance_requests([request_id])
except boto.exception.EC2ResponseError as e:
if (
allow_missing
and e.error_code == "InvalidSpotInstanceRequestID.NotFound"
):
result = []
else:
raise
if len(result) == 0:
if allow_missing:
return None
raise EC2InstanceDisappeared(
"Spot instance request ‘{0}’ disappeared!".format(request_id)
)
return result[0]
def _get_instance(self, instance_id=None, allow_missing=False, update=False):
"""Get instance object for this machine, with caching"""
if not instance_id:
instance_id = self.vm_id
assert instance_id
if not self._cached_instance:
self.connect()
try:
instances = self._conn.get_only_instances([instance_id])
except boto.exception.EC2ResponseError as e:
if allow_missing and e.error_code == "InvalidInstanceID.NotFound":
instances = []
else:
raise
if len(instances) == 0:
if allow_missing:
return None
raise EC2InstanceDisappeared(
"EC2 instance ‘{0}’ disappeared!".format(instance_id)
)
self._cached_instance = instances[0]
elif update:
self._cached_instance.update()
if self._cached_instance.launch_time:
self.start_time = calendar.timegm(
time.strptime(
self._cached_instance.launch_time, "%Y-%m-%dT%H:%M:%S.000Z"
)
)
return self._cached_instance
def _get_snapshot_by_id(self, snapshot_id):
"""Get snapshot object by instance id."""
self.connect()
snapshots = self._conn.get_all_snapshots([snapshot_id])
if len(snapshots) != 1:
raise Exception("unable to find snapshot ‘{0}’".format(snapshot_id))
return snapshots[0]
def _wait_for_ip(self):
self.log_start("waiting for IP address... ".format(self.name))
def _instance_ip_ready(ins):
ready = True
if self.associate_public_ip_address and not ins.ip_address:
ready = False
if self.use_private_ip_address and not ins.private_ip_address:
ready = False
return ready
while True:
instance = self._get_instance(update=True)
self.log_continue("[{0}] ".format(instance.state))
if instance.state not in {
"pending",
"running",
"scheduling",
"launching",
"stopped",
}:
raise Exception(
"EC2 instance ‘{0}’ failed to start (state is ‘{1}’)".format(
self.vm_id, instance.state
)
)
if instance.state != "running":
time.sleep(3)
continue
if _instance_ip_ready(instance):
break
time.sleep(3)
self.log_end(
"{0} / {1}".format(instance.ip_address, instance.private_ip_address)
)
with self.depl._db:
self.private_ipv4 = instance.private_ip_address
self.public_ipv4 = instance.ip_address
self.public_dns_name = instance.public_dns_name
self.ssh_pinged = False
nixops.known_hosts.update(
self.public_ipv4, self._ip_for_ssh_key(), self.public_host_key
)
def _ip_for_ssh_key(self):
if self.use_private_ip_address:
return self.private_ipv4
else:
return self.public_ipv4
def _booted_from_ebs(self):
return self.root_device_type == "ebs"
def update_block_device_mapping(self, k, v):
x = self.block_device_mapping
if v == None:
x.pop(k, None)
else:
x[k] = v
self.block_device_mapping = x
def get_backups(self):
if not self.region:
return {}
self.connect()
backups = {}
current_volumes = set(
[v["volumeId"] for v in self.block_device_mapping.values()]
)
for b_id, b in self.backups.items():
b = {device_name_stored_to_real(device): snap for device, snap in b.items()}
backups[b_id] = {}
backup_status = "complete"
info = []
for device_stored, v in self.block_device_mapping.items():
device_real = device_name_stored_to_real(device_stored)
snapshot_id = b.get(device_real, None)
if snapshot_id is not None:
try:
snapshot = self._get_snapshot_by_id(snapshot_id)
snapshot_status = snapshot.update()
info.append(
"progress[{0},{1},{2}] = {3}".format(
self.name, device_real, snapshot_id, snapshot_status
)
)
if snapshot_status != "100%":
backup_status = "running"
except boto.exception.EC2ResponseError as e:
if e.error_code != "InvalidSnapshot.NotFound":
raise
info.append(
"{0} - {1} - {2} - Snapshot has disappeared".format(
self.name, device_real, snapshot_id
)
)
backup_status = "unavailable"
backups[b_id]["status"] = backup_status
backups[b_id]["info"] = info
return backups
def remove_backup(self, backup_id, keep_physical=False):
self.log("removing backup {0}".format(backup_id))
self.connect()
_backups = self.backups
if not backup_id in _backups.keys():
self.warn("backup {0} not found, skipping".format(backup_id))
else:
if not keep_physical:
for dev, snapshot_id in _backups[backup_id].items():
snapshot = None
try:
snapshot = self._get_snapshot_by_id(snapshot_id)
except:
self.warn(
"snapshot {0} not found, skipping".format(snapshot_id)
)
if not snapshot is None:
self.log("removing snapshot {0}".format(snapshot_id))
self._retry(lambda: snapshot.delete())
_backups.pop(backup_id)
self.backups = _backups
def backup(self, defn, backup_id, devices=[]):
self.connect()
self.log("backing up machine ‘{0}’ using id ‘{1}’".format(self.name, backup_id))
backup = {}
_backups = self.backups
for device_stored, v in self.block_device_mapping.items():
device_real = device_name_stored_to_real(device_stored)
if devices == [] or device_real in devices:
snapshot = self._retry(
lambda: self._conn.create_snapshot(volume_id=v["volumeId"])
)
self.log(
"+ created snapshot of volume ‘{0}’: ‘{1}’".format(
v["volumeId"], snapshot.id
)
)
snapshot_tags = {}
snapshot_tags.update(defn.tags)
snapshot_tags.update(self.get_common_tags())
snapshot_tags["Name"] = "{0} - {3} [{1} - {2}]".format(
self.depl.name, self.name, device_stored, backup_id
)
self._retry(
lambda: self._conn.create_tags([snapshot.id], snapshot_tags)
)
backup[device_stored] = snapshot.id
_backups[backup_id] = backup
self.backups = _backups
# devices - array of dictionaries, keys - /dev/nvme or /dev/xvd device name, values - device options
def restore(self, defn, backup_id, devices=[]):
self.stop()
self.log("restoring machine ‘{0}’ to backup ‘{1}’".format(self.name, backup_id))
for d in devices:
self.log(" - {0}".format(d))
for device_stored, v in self.sorted_block_device_mapping():
device_real = device_name_stored_to_real(device_stored)
if devices == [] or device_real in devices:
# detach disks
volume = nixopsaws.ec2_utils.get_volume_by_id(
self.connect(), v["volumeId"]
)
if volume and volume.update() == "in-use":
self.log("detaching volume from ‘{0}’".format(self.name))
volume.detach()
# attach backup disks
snapshot_id = self.backups[backup_id][device_stored]
self.log("creating volume from snapshot ‘{0}’".format(snapshot_id))
self.wait_for_snapshot_to_become_completed(snapshot_id)
new_volume = self._conn.create_volume(
size=0, snapshot=snapshot_id, zone=self.zone
)
# Check if original volume is available, aka detached from the machine.
if volume:
nixopsaws.ec2_utils.wait_for_volume_available(
self._conn, volume.id, self.logger
)
# Check if new volume is available.
nixopsaws.ec2_utils.wait_for_volume_available(
self._conn, new_volume.id, self.logger
)
self.log(
"attaching volume ‘{0}’ to ‘{1}’ as {2}".format(
new_volume.id, self.name, device_real
)
)
device_that_boto_expects = device_name_to_boto_expected(
device_real
) # boto expects only sd names
new_volume.attach(self.vm_id, device_that_boto_expects)
new_v = self.block_device_mapping[device_stored]
if (
v.get("partOfImage", False)
or v.get("charonDeleteOnTermination", False)
or v.get("deleteOnTermination", False)
):
new_v["charonDeleteOnTermination"] = True
self._delete_volume(v["volumeId"], True)
new_v["volumeId"] = new_volume.id
self.update_block_device_mapping(device_stored, new_v)
def wait_for_snapshot_to_become_completed(self, snapshot_id):
def check_completed():
res = self._get_snapshot_by_id(snapshot_id).status
self.log_continue("[{0}] ".format(res))
return res == "completed"
self.log_start(
"waiting for snapshot ‘{0}’ to have status ‘completed’... ".format(
snapshot_id
)
)
nixops.util.check_wait(check_completed)
self.log_end("")
def create_after(self, resources, defn):
# EC2 instances can require key pairs, IAM roles, security
# groups, EBS volumes and elastic IPs. FIXME: only depend on
# the specific key pair / role needed for this instance.
return {
r
for r in resources
if isinstance(r, nixopsaws.resources.ec2_keypair.EC2KeyPairState)
or isinstance(r, nixopsaws.resources.iam_role.IAMRoleState)
or isinstance(
r, nixopsaws.resources.ec2_security_group.EC2SecurityGroupState
)
or isinstance(
r, nixopsaws.resources.ec2_placement_group.EC2PlacementGroupState
)
or isinstance(r, nixopsaws.resources.ebs_volume.EBSVolumeState)
or isinstance(r, nixopsaws.resources.elastic_ip.ElasticIPState)
or isinstance(r, nixopsaws.resources.vpc_subnet.VPCSubnetState)
or isinstance(r, nixopsaws.resources.vpc_route.VPCRouteState)
or isinstance(
r, nixopsaws.resources.elastic_file_system.ElasticFileSystemState
)
or isinstance(
r,
nixopsaws.resources.elastic_file_system_mount_target.ElasticFileSystemMountTargetState,
)
}
def attach_volume(self, device_stored, volume_id):
device_real = device_name_stored_to_real(device_stored)
volume = nixopsaws.ec2_utils.get_volume_by_id(self.connect(), volume_id)
if not volume:
raise Exception(
"volume {0} doesn't exist, run check to update the state of the volume".format(
volume_id
)
)
if (
volume.status == "in-use"
and self.vm_id != volume.attach_data.instance_id
and self.depl.logger.confirm(
"volume ‘{0}’ is in use by instance ‘{1}’, "
"are you sure you want to attach this volume?".format(
volume_id, volume.attach_data.instance_id
)
)
):
self.log_start(
"detaching volume ‘{0}’ from instance ‘{1}’... ".format(
volume_id, volume.attach_data.instance_id
)
)
volume.detach()
def check_available():
res = volume.update()
self.log_continue("[{0}] ".format(res))
return res == "available"
nixops.util.check_wait(check_available)
self.log_end("")
if volume.update() != "available":
self.log(
"force detaching volume ‘{0}’ from instance ‘{1}’...".format(
volume_id, volume.attach_data.instance_id
)
)
volume.detach(True)
nixops.util.check_wait(check_available)
self.log_start(
"attaching volume ‘{0}’ as ‘{1}’... ".format(volume_id, device_real)
)
if self.vm_id != volume.attach_data.instance_id:
# Attach it.
device_that_boto_expects = device_name_to_boto_expected(device_stored)
self._conn.attach_volume(volume_id, self.vm_id, device_that_boto_expects)
def check_attached():
volume.update()
res = volume.attach_data.status
self.log_continue("[{0}] ".format(res or "not-attached"))
return res == "attached"
# If volume is not in attached state, wait for it before going on.
if volume.attach_data.status != "attached":
nixops.util.check_wait(check_attached)
# Wait until the device is visible in the instance.
def check_device():
res = self.run_command("test -e {0}".format(device_real), check=False)
return res == 0
if not nixops.util.check_wait(
check_device, initial=1, max_tries=10, exception=False
):
# If stopping times out, then do an unclean shutdown.
self.log_end("(timed out)")
self.log("can't find device ‘{0}’...".format(device_real))
self.log("available devices:")
self.run_command("lsblk")
raise Exception("operation timed out")
else:
self.log_end("")
def _assign_elastic_ip(self, elastic_ipv4, check):
instance = self._get_instance()
# Assign or release an elastic IP address, if given.
if (
(self.elastic_ipv4 or "") != elastic_ipv4
or (instance.ip_address != elastic_ipv4)
or check
):
if elastic_ipv4 != "":
# wait until machine is in running state
self.log_start(
"waiting for machine to be in running state... ".format(self.name)
)
while True:
self.log_continue("[{0}] ".format(instance.state))
if instance.state == "running":
break
if instance.state not in {"running", "pending"}:
raise Exception(
"EC2 instance ‘{0}’ failed to reach running state (state is ‘{1}’)".format(
self.vm_id, instance.state
)
)
time.sleep(3)
instance = self._get_instance(update=True)
self.log_end("")
addresses = self._conn.get_all_addresses(addresses=[elastic_ipv4])
if (
addresses[0].instance_id != ""
and addresses[0].instance_id is not None
and addresses[0].instance_id != self.vm_id
and not self.depl.logger.confirm(
"are you sure you want to associate IP address ‘{0}’, which is currently in use by instance ‘{1}’?".format(
elastic_ipv4, addresses[0].instance_id
)
)
):
raise Exception(
"elastic IP ‘{0}’ already in use...".format(elastic_ipv4)
)
else:
self.log("associating IP address ‘{0}’...".format(elastic_ipv4))
addresses[0].associate(self.vm_id)
self.log_start(
"waiting for address to be associated with this machine... "
)
instance = self._get_instance(update=True)
while True:
self.log_continue("[{0}] ".format(instance.ip_address))
if instance.ip_address == elastic_ipv4:
break
time.sleep(3)
instance = self._get_instance(update=True)
self.log_end("")
nixops.known_hosts.update(
self.public_ipv4, elastic_ipv4, self.public_host_key
)
with self.depl._db:
self.elastic_ipv4 = elastic_ipv4
self.public_ipv4 = elastic_ipv4
self.ssh_pinged = False
elif self.elastic_ipv4 != None:
addresses = self._conn.get_all_addresses(addresses=[self.elastic_ipv4])
if len(addresses) == 1 and addresses[0].instance_id == self.vm_id:
self.log(
"disassociating IP address ‘{0}’...".format(self.elastic_ipv4)
)
self._conn.disassociate_address(public_ip=self.elastic_ipv4)
else:
self.log(
"address ‘{0}’ was not associated with instance ‘{1}’".format(
self.elastic_ipv4, self.vm_id
)
)
with self.depl._db:
self.elastic_ipv4 = None
self.public_ipv4 = None
self.ssh_pinged = False
def security_groups_to_ids(self, subnetId, groups):
sg_names = filter(lambda g: not g.startswith("sg-"), groups)
if sg_names != [] and subnetId != "":
self.connect_vpc()
vpc_id = self._conn_vpc.get_all_subnets([subnetId])[0].vpc_id
groups = [
nixopsaws.ec2_utils.name_to_security_group(self._conn, g, vpc_id)
for g in groups
]
return groups
def _wait_for_spot_request_fulfillment(self, request_id):
self.log_start(
"waiting for spot instance request ‘{0}’ to be fulfilled... ".format(
self.spot_instance_request_id
)
)
while True:
request = self._get_spot_instance_request_by_id(
self.spot_instance_request_id
)
self.log_continue("[{0}] ".format(request.status.code))
if request.status.code == "fulfilled":
break
if request.status.code in {
"schedule-expired",
"canceled-before-fulfillment",
"bad-parameters",
"system-error",
}:
self.spot_instance_request_id = None
self.log_end("")
raise Exception(
"spot instance request failed with result ‘{0}’".format(
request.status.code
)
)
time.sleep(3)
self.log_end("")
instance = self._retry(
lambda: self._get_instance(instance_id=request.instance_id)
)
return instance
def create_instance(self, defn, zone, user_data, ebs_optimized, args):
IamInstanceProfile = {}
if defn.instance_profile.startswith("arn:"):
IamInstanceProfile["Arn"] = defn.instance_profile
else:
IamInstanceProfile["Name"] = defn.instance_profile
if defn.subnet_id != "":
if defn.security_groups != [] and defn.security_groups != ["default"]:
raise Exception(
"‘deployment.ec2.securityGroups’ is incompatible with ‘deployment.ec2.subnetId’"
)
args["NetworkInterfaces"] = [
dict(
AssociatePublicIpAddress=defn.associate_public_ip_address,
SubnetId=defn.subnet_id,
DeviceIndex=0,
Groups=self.security_groups_to_ids(
defn.subnet_id, defn.security_group_ids
),
)
]
else:
args["SecurityGroups"] = defn.security_groups
if defn.spot_instance_price:
args["InstanceMarketOptions"] = dict(
MarketType="spot",
SpotOptions=dict(
MaxPrice=str(defn.spot_instance_price / 100.0),
SpotInstanceType=defn.spot_instance_request_type,
InstanceInterruptionBehavior=defn.spot_instance_interruption_behavior,
),
)
if defn.spot_instance_timeout:
args["InstanceMarketOptions"]["SpotOptions"]["ValidUntil"] = (
datetime.datetime.utcnow()
+ datetime.timedelta(0, defn.spot_instance_timeout)
).isoformat()
placement = dict(AvailabilityZone=zone or "")
if defn.tenancy:
placement["Tenancy"] = defn.tenancy
args["InstanceType"] = defn.instance_type
args["ImageId"] = defn.ami
args["IamInstanceProfile"] = IamInstanceProfile
args["KeyName"] = defn.key_pair
args["Placement"] = placement
args["UserData"] = user_data
args["EbsOptimized"] = ebs_optimized
args["MaxCount"] = 1 # We always want to deploy one instance.
args["MinCount"] = 1
# Use a client token to ensure that instance creation is
# idempotent; i.e., if we get interrupted before recording
# the instance ID, we'll get the same instance ID on the
# next run.
if not self.client_token:
with self.depl._db:
self.client_token = nixops.util.generate_random_string(
length=48
) # = 64 ASCII chars
self.state = self.STARTING
args["ClientToken"] = self.client_token
reservation = self._retry(lambda: self._conn_boto3.run_instances(**args))
if not defn.spot_instance_price:
# On demand instance, no need to any more checks, return it.
return self._get_instance(reservation["Instances"][0]["InstanceId"])
with self.depl._db:
self.spot_instance_price = defn.spot_instance_price
self.spot_instance_request_id = reservation["Instances"][0][
"SpotInstanceRequestId"
]
tags = {"Name": "{0} [{1}]".format(self.depl.description, self.name)}
tags.update(defn.tags)
tags.update(self.get_common_tags())
self._retry(
lambda: self._conn.create_tags([self.spot_instance_request_id], tags)
)
return self._wait_for_spot_request_fulfillment(self.spot_instance_request_id)
def _cancel_spot_request(self):
if self.spot_instance_request_id is None:
return
self.log_start(