-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path44.js
More file actions
2735 lines (2186 loc) · 103 KB
/
Copy path44.js
File metadata and controls
2735 lines (2186 loc) · 103 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
/**
* The js-aws version of the AWS EC2 API.
*
* Conforms to the run-anywhere calling convention.
*
* runInstance() -- Launch an instance.
*/
var sg = require('sgsg');
var _ = sg._;
var aws = require('aws-sdk');
var jsaws = require('../jsaws');
var superagent = require('superagent');
var ra = require('run-anywhere');
var helpers = require('../helpers');
var path = require('path');
var util = require('util');
var awsJsonLib = require('aws-json');
var awsServiceLib = require('../service/service');
// run-anywhere-ified modules
var raVpc = ra.require('./vpc', __dirname);
var raIam = ra.require('../iam/iam', __dirname);
var raRoute53 = ra.require('../route-53/route-53', __dirname);
var raRoute53_2 = ra.require('../../lib2/route53/route53', __dirname);
var raEc2; /* Gets build from the libEc2 object at the end of this file */
// Sub-object functions
var getConfig = jsaws.getConfig;
var get2X2 = jsaws.get2X2;
var get2X2_2 = jsaws.get2X2_2;
var argvGet = sg.argvGet;
var argvExtract = sg.argvExtract;
var firstKey = sg.firstKey;
var deref = sg.deref;
var setOn = sg.setOn;
var setOnn = sg.setOnn;
var setOnna = sg.setOnna;
var die = sg.die;
var numKeys = sg.numKeys;
var isInCidrBlock = helpers.isInCidrBlock;
var addTag = awsJsonLib.addTag;
var toAwsTags = awsJsonLib.toAwsTags;
var awsService = awsServiceLib.awsService;
var extractServiceArgs = awsServiceLib.extractServiceArgs;
//var log = helpers.log;
var format = util.format;
var libEc2 = {};
// ===================================================================================================
//
// Functionality
//
// ===================================================================================================
/**
* Launch an AWS instance.
*
* @param {Object} argv - Run-anywhere style argv object.
* @param {Object} context - Run-anywhere style context object.
* @param {Function} context - Run-anywhere style callback.
*
* ra invoke lib/ec2/ec2.js runInstance --db=10.11.21.220 --util=10.11.21.4 --namespace=serverassist3 --color=black --build-number=16 --key=serverassist_demo --instance-type=t2.large --image-id=ami- --ip=10.11.21.119
*
* WordPress:
* --db=10.11.21.220 --util=10.11.21.4 --namespace=serverassist3 --color=black --key=serverassist_demo --instance-type=c4.xlarge --image-id=ami-46ec9451 --ip=10.11.21.119
*
* Required:
* argv.ip
* argv.instance_type
* argv.key
*
* argv.num_tries : Try this many times to launch with the IP. If we get InvalidIPAddress.InUse, try with the next IP address.
* argv.force_ip : The opposite of num_tries. Use only this IP.
* argv.namespace
* argv.tier
* argv.service
* argv.serviceType
* argv.owner_id
* argv.environment
* argv.test
* argv.username
* argv.no_wait
* argv.region
* argv.image_id
* argv.min_count
* argv.max_count
* argv.monitoring
* argv.shutdown_behavior
* argv.api_termination
* argv.placement
* argv.zone
* argv.dry_run
* argv.account
* argv.instance_profile
* argv.user_data
*/
libEc2.runInstance = function(argv, context, callback, options_) {
// Did the caller pass in information for a different account?
var roleSessionName = argvGet(argv, 'role_session_name,session') || 'main';
var acct = argvGet(argv, 'account,acct');
var role = argvGet(argv, 'role');
var region = argvGet(argv, 'region');
var log = sg.mkLogger(argv);
var options = options_ || {};
var getUserdata = options.getUserdata || getUserdata0;
// All the stuff we will figure out in the sg.__run() callbacks
var ip, stack, instanceName, m;
// How many times will we try go find a non-used IP address?
var numTriesLeft = argvGet(argv, 'num-tries,tries') || 10;
// Do we have a forced IP address?
if ((ip = argvGet(argv, 'force-ip'))) {
numTriesLeft = 0;
}
// Make sure we have a private IP address
if (!ip && !(ip = argvGet(argv, 'ip'))) { return die('No internal IP address', callback, 'runInstance'); }
// Get user options
var buildoutEnvVars = {};
var octets = ip.split('.');
var namespace = argvGet(argv, 'namespace') || process.env.NAMESPACE || 'jsaws';
var namespaceEx = argvGet(argv, 'namespace-ex,ns-ex,ns2');
var tier = argvGet(argv, 'tier') || getConfig('tierForIp', ip) || 'app';
var service = argvGet(argv, 'service') || getConfig('serviceForIp', ip) || 'app';
var serviceType = argvGet(argv, 'serviceType') || getConfig('serviceTypeForIp', ip) || 'app';
var dbIp = argvGet(argv, 'db-ip,db') || process.env.SERVERASSIST_DB_IP || '10.10.21.229';
var utilIp = argvGet(argv, 'util-ip,util') || process.env.SERVERASSIST_UTIL_IP || '10.10.21.4';
var username = argvGet(argv, 'username') || 'scotty';
var origUsername = argvGet(argv, 'orig-username') || 'ubuntu';
var driveSize = +(argvGet(argv, 'drive,xvdf') || '0');
var firstBuildup = argvGet(argv, 'first-buildup,first');
var buildNumber = argvGet(argv, 'build-num,build-number');
var color = argvGet(argv, 'color');
var launchAcctName;
var awsEc2;
if (!namespaceEx && (m = namespace.match(/^(.*)([0-9]+)$/))) {
namespaceEx = namespace;
namespace = m[1];
}
if (!namespaceEx) {
namespaceEx = namespace;
}
var upNamespace = namespace.toUpperCase().replace(/[0-9]+$/g, ''); /* strip trailing numbers */
var serviceNum = 0;
// Get the default launch configuration (and use the passed-in argv)
var launchConfig_ = defLaunchConfig(argv);
// ----- Build up the configuration
var launchConfig = sg.deepCopy(launchConfig_);
// The things that are found
var vpc, subnet, securityGroups, ownerId, reservations;
// See if the args provide some of them
ownerId = argvGet(argv, 'owner-id,owner') || ownerId;
log('Launching instance');
return sg.__run([function(next) {
console.error(sg.inspect({
ip : ip,
service : service,
namespace : namespace,
tier : tier,
serviceType : serviceType,
build : buildNumber,
color : color,
db : dbIp,
util : utilIp
}));
// Warn the user of various things, and let them stop the build
var warned = false, time = 2000;
if (!dbIp) { warned = true; giantWarning("You should provde a DB IP address. Using "+dbIp+"."); }
if (!utilIp) { warned = true; giantWarning("You should provde a Util IP address. Using "+utilIp+"."); }
if (warned) { time = 20000; }
/* otherwise -- stall so the user can read the messages */
setTimeout(next, time);
}, function(next) {
// ----- Get the VPC, given the IP address, and the stack, and compute the instance name.
return raVpc.vpcsForIp(_.extend({ip:ip}, argv), context, function(err, vpcs) {
if (err) { return die(err, callback, 'runInstance.vpcsForIp'); }
if (numKeys(vpcs) !== 1) { return die('Found '+numKeys(vpcs)+' vpcs, needs to be only one.'+JSON.stringify(argv), callback, 'runInstance.vpcsForIp'); }
vpc = deref(vpcs, firstKey(vpcs));
stack = getConfig('stackForVpc', vpc);
instanceName = [namespace, stack, octets[1], service].join('-');
log(instanceName);
return next();
});
}], function() {
return sg.__runll([function(next) {
// ----- Get subnet for this IP
return raVpc.getSubnets(argv, context, function(err, subnets_) {
if (err) { return die(err, callback, 'runInstance.getSubnets'); }
var subnets = _.filter(subnets_, function(subnet, id) {
return isInCidrBlock(ip, subnet.CidrBlock) && (subnet.VpcId === vpc.VpcId);
});
if (numKeys(subnets) !== 1) { return die('Found '+numKeys(subnets)+' subnets, needs to be only one. For: '+ip, callback, 'runInstance.getSubnets'); }
subnet = subnets[0];
launchAcctName = subnet.accountName || launchAcctName;
if (!awsEc2 && launchAcctName) {
awsEc2 = awsService('EC2', {acctName: launchAcctName});
}
log('using subnet', subnet.SubnetId);
return next();
});
}, function(next) {
// ----- How does this new instance fit in with the already-existing instances?
return raEc2.getInstances(function(err, instances) {
// TODO: Handle code: 'RequestLimitExceeded' (See bottom of this file) -- Needs to be an until
if (err) { return die(err, callback, 'runInstance.getInstances'); }
var nic, id;
// Find the ownerId
for (id in instances) {
if (!(nic = deref(instances[id], 'NetworkInterfaces'))) { continue; }
if (!(nic = nic[firstKey(nic)])) { continue; }
if ((ownerId = deref(nic, 'OwnerId'))) {
break;
}
}
log('owner', ownerId);
// Find the names of the instances - so we can find the right service number
var names = _.chain(instances).filter(function(instance) {
return instance.VpcId === vpc.VpcId;
}).map(function(instance) {
return deref(instance, 'Tags.Name');
}).compact().value();
log('name(s)', names);
// Try to find the next service number
return sg.until(function(again, last, count) {
var name = instanceName + sg.pad(serviceNum, 2);
if (count >= 99) {
instanceName = name;
return last();
}
if (names.indexOf(name) === -1) {
instanceName = name;
return last();
}
// Try again with the next number
serviceNum += 1;
return again();
}, function() {
log('service number', serviceNum);
return next();
});
});
}, function(next) {
// ----- Get the SGs for this VPC -- at least the ones that know where to apply themselves
return raVpc.getSecurityGroups(argv, context, function(err, securityGroups_) {
if (err) { return die(err, callback, 'runInstance.getSubnets'); }
securityGroups = _.filter(securityGroups_, function(securityGroup, id) {
var applyToServices = [];
if (securityGroup.VpcId !== vpc.VpcId) { return false; }
if (service === 'admin') {
if (taggedAs(securityGroup, 'sg', namespace) == 'admin') { return true; }
}
applyToServices = applyToServices.concat((taggedAs(securityGroup, 'applyToServices', namespace) || '').split(','));
applyToServices = applyToServices.concat((taggedAs(securityGroup, 'applyToServices', 'serverassist') || '').split(','));
applyToServices = _.compact(applyToServices).join(',');
if (!applyToServices) { return false; }
if (sg.inList(applyToServices, 'all')) { return true; }
return sg.inList(applyToServices, service);
});
log('security Groups', _.pluck(securityGroups, 'GroupId'));
return next();
});
}], function() {
setOn(argv, 'acctName', launchAcctName);
return sg.__run([function(next) {
if (!namespace || !service) { return next(); }
// TODO: fix the hack. Do not force '3' on the end of the namespace
var iamNs = namespaceEx;
return raIam.getInstanceProfileForRole(argv, [iamNs, service, 'instance-role'].join('-'), context, function(err, arn) {
if (err) {
if (err.code !== 'NoSuchEntity') { return die(err, callback, 'runInstance.getInstanceProfile1'+iamNs+'/'+service); }
// TODO: fix the 'remove x' hack
var iamNsNoX = iamNs.replace(/x$/ig, '');
return raIam.getInstanceProfileForRole(argv, [iamNsNoX, service, 'instance-role'].join('-'), context, function(err, arn) {
if (err) {
if (err.code !== 'NoSuchEntity') { return die(err, callback, 'runInstance.getInstanceProfile1'+iamNsNoX+'/'+service); }
// No such instance profile -- use the generic one
return raIam.getInstanceProfileForRole(argv, [iamNs, '', 'instance-role'].join('-'), context, function(err, arn) {
if (err) { return die(err, callback, 'runInstance.getInstanceProfile2'+iamNs+'/'+service); }
setOn(launchConfig, 'IamInstanceProfile.Arn', arn);
return next();
});
}
setOn(launchConfig, 'IamInstanceProfile.Arn', arn);
return next();
});
}
setOn(launchConfig, 'IamInstanceProfile.Arn', arn);
return next();
});
}, function(next) {
// TODO: Should use sg.until()
return once();
function once() {
// ----- Warnings -----
if (!ownerId) {
console.warn('Warning: could not find the owner id.');
}
// ----- Network Interface -----
var nic = {
DeleteOnTermination : true,
Groups : [],
DeviceIndex : 0
};
setOn(nic, 'AssociatePublicIpAddress', deref(subnet, 'MapPublicIpOnLaunch'));
setOn(nic, 'SubnetId', deref(subnet, 'SubnetId'));
setOn(nic, 'PrivateIpAddress', ip);
nic.Groups = _.pluck(securityGroups, 'GroupId');
launchConfig.NetworkInterfaces = [nic];
// ----- Placement -----
setOn(launchConfig, 'Placement.Tenancy', deref(launchConfig, 'Placement.Tenancy') || 'default');
setOn(launchConfig, 'Placement.AvailabilityZone', deref(subnet, 'AvailabilityZone') || 'us-east-1a');
// ----- Shutdown -----
if (sg.startsWith(argvGet(argv, 'environment,env'), 'prod')) {
setOn(launchConfig, 'InstanceInitiatedShutdownBehavior', 'stop');
setOn(launchConfig, 'DisableApiTermination', true);
} else if (argv.test) {
setOn(launchConfig, 'InstanceInitiatedShutdownBehavior', 'terminate');
}
// ----- Block Devices -----
launchConfig.BlockDeviceMappings = [];
if (firstBuildup) {
// No additional drives
launchConfig.BlockDeviceMappings.push(blockDevice('sda1', 32));
if (driveSize && driveSize > 0) {
launchConfig.BlockDeviceMappings.push(blockDevice('sdf', driveSize));
}
} else if (service === 'db') {
launchConfig.BlockDeviceMappings.push(blockDevice('sda1', 32));
launchConfig.BlockDeviceMappings.push(blockDevice('sdf', 500));
launchConfig.BlockDeviceMappings.push(blockDevice('sdg', 25));
launchConfig.BlockDeviceMappings.push(blockDevice('sdh', 10));
} else {
launchConfig.BlockDeviceMappings.push(blockDevice('sda1', 32));
if (driveSize && driveSize > 0) {
launchConfig.BlockDeviceMappings.push(blockDevice('sdf', driveSize));
}
}
// ----- Critical Startup Environment Variables -----
buildoutEnvVars.NAMESPACE = namespace;
buildoutEnvVars[upNamespace+"_SERVICE"] = buildoutEnvVars.SERVERASSIST_SERVICE = service;
buildoutEnvVars[upNamespace+"_STACK"] = buildoutEnvVars.SERVERASSIST_STACK = stack;
buildoutEnvVars[upNamespace+"_TIER"] = tier;
if (color) { buildoutEnvVars[upNamespace+"_COLOR"] = color; }
if (buildNumber) { buildoutEnvVars[upNamespace+"_BUILD"] = buildNumber; }
if (dbIp) { buildoutEnvVars[upNamespace+"_DB_HOSTNAME"] = dbIp; }
if (utilIp) { buildoutEnvVars[upNamespace+"_UTIL_HOSTNAME"] = utilIp; }
if (dbIp) { buildoutEnvVars[upNamespace+"_DB_IP"] = dbIp; }
if (utilIp) { buildoutEnvVars[upNamespace+"_UTIL_IP"] = utilIp; }
buildoutEnvVars.SERVERASSIST_DB_HOSTNAME = buildoutEnvVars[upNamespace+"_DB_HOSTNAME"];
launchConfig.UserData = getUserdata(username, upNamespace, buildoutEnvVars, origUsername);
// ----- Other -----
launchConfig.InstanceType = launchConfig.InstanceType || 't2.large';
launchConfig.KeyName = launchConfig.KeyName || namespace+'_demo';
// Launch
log('done collecting info... trying to launch', launchConfig.InstanceType, ip);
// The AWS EC2 service
if (!awsEc2) {
awsEc2 = awsService('EC2', roleSessionName, acct, role, region);
}
return awsEc2.runInstances(launchConfig, function(err, reservations_) {
//console.error("RunInstance:", err, sg.inspect(launchConfig));
if (err) {
// if the IP address is already in use, this is not an error
if (err.code === 'InvalidIPAddress.InUse' && numTriesLeft > 0) {
if (argvGet(argv, 'prev-ip')) {
ip = helpers.prevIp(ip);
} else {
ip = helpers.nextIp(ip);
}
numTriesLeft -= 1;
return once();
}
// Log if this is a dry-run
if (err.code === 'DryRunOperation') {
log('dry-run', err, launchConfig);
return callback();
}
// OK, this is an error
console.error("Error - here is the launch config", launchConfig);
return die(err, callback, 'runInstance.runInstances');
}
reservations = reservations_;
log('launchConfig', launchConfig);
log('reservations', reservations);
log('userScript', Buffer.from(launchConfig.UserData, 'base64').toString());
return next();
});
}
}, function(next) {
// ----- Tag Instances -----
var tagRiptype;
var tagBuildNumber = buildNumber;
var diParams = { ImageIds : [launchConfig.ImageId] };
return raEc2.getImages(diParams, context, function(err, images) {
// If the AMI has a build number, use it.
if (!err && images) {
_.each(images, function(image) {
var buildNum = taggedAs(image, 'build', namespace, namespaceEx);
if (buildNum) {
tagBuildNumber = +buildNum;
}
var ripType = taggedAs(image, 'riptype', namespace, namespaceEx);
if (ripType) {
tagRiptype = ripType;
}
});
}
var Tags = [{Key:'Name', Value:instanceName}];
if (namespace) {
Tags.push({Key:'namespace', Value:namespace});
if (service) { Tags.push({Key:[ 'service'].join(':'), Value:service}); }
if (color) { Tags.push({Key:[ 'color'].join(':'), Value:color}); }
if (stack) { Tags.push({Key:[ 'stack'].join(':'), Value:stack}); }
if (tagBuildNumber) { Tags.push({Key:[ 'build'].join(':'), Value:''+tagBuildNumber}); }
// Special tags for RIPs
if (tagRiptype) { Tags.push({Key:[ 'riptype'].join(':'), Value:''+tagRiptype}); }
}
return raEc2.tagInstances({ids: _.pluck(reservations.Instances, 'InstanceId'), Tags: Tags}, context, function(err, result) {
return next();
});
});
}], function() {
// Return now, if the caller does not want to wait for the instance to be running
if (argvGet(argv, 'no-wait,nowait')) {
return callback(null, reservations, launchConfig);
}
/* otherwise -- wait for it to be running */
var waitArgv = {
instanceId : _.pluck(reservations.Instances, 'InstanceId'),
state : 'running'
};
return raEc2.waitForInstanceState(_.extend(waitArgv, argv), context, function(err, instances) {
return callback(null, instances, launchConfig);
});
});
});
});
};
/**
* Launch an instance from an AMI.
*
* At this point, this function just sets the userdata to something basic.
*/
libEc2.runInstanceFromAmi = function(argv, context, callback) {
var creds = extractServiceArgs(argv);
var namespace = argvGet(argv, 'namespace,ns') || process.env.NAMESPACE;
var namespace = namespace.replace(/[0-9]+$/, '');
return libEc2.runInstance(_.extend({}, argv, creds), context, function(err, instances, launchConfig) {
if (err) { return die(err, callback, 'runInstanceFromAmi.runInstance'); }
if (!instances) { return die('No instances started', callback, 'runInstanceFromAmi.runInstance'); }
// Was that a web-instance, which might need to be pointed-to by a sub-domain name?
var instance = instances[firstKey(instances)];
var privateIp = instance.PrivateIpAddress;
var instStats = instanceStats(privateIp);
if (instance && instance.Tags && instance.Tags[namespace]) {
var service = taggedAs(instance, 'service', namespace) || instStats.service;
if (service !== 'web') { return callback(null, instances, launchConfig); }
var params = _.extend({
instance_id : instance.InstanceId,
fqdn : instStats.fqdn
}, creds);
return raEc2.assignFqdnToInstance(params, context, function(err, result) {
//if (err) { console.error(sg.inspect(params)); return die(err, callback, 'runInstanceFromAmi.assignFqdnToInstances'); }
if (err) { console.error(sg.inspect(params)); }
return callback(err, instances, launchConfig);
});
}
/* otherwise */
return callback(null, instances, launchConfig);
}, {getUserdata : getUserdataForAmi});
};
/**
* Tag an EC2 resource
*
* See also the pickTags function
*/
libEc2.tagImages = libEc2.tagImage = libEc2.tagInstances = libEc2.tagInstance = libEc2.tagResource = function(argv, context, callback) {
argv = jsaws.prep(argv);
var awsEc2 = jsaws.getEc2(argv);
var Tags = sg.toArray(argv.Tags);
// argv might have normal JS style tags in the 'tags' attribute
_.each(argvGet(argv, 'tags,tag'), function(value, key) {
if (!_.isString(key) || !_.isString(value)) { return; }
Tags.push({Key:key, Value:value});
});
// also count all 'tag-xyz=value' params
_.each(_.keys(argv), function(param) {
if (!_.isString(param) || !_.isString(argv[param])) { return; }
if (param === 'tag' || param === 'tags') { return; }
if (sg.startsWith(param, 'tag')) {
Tags.push({Key: param.substr(3).replace(/^[^a-zA-Z0-9]+/, '').replace(/[^a-zA-Z0-9]/g, ':'), Value: argv[param]});
}
});
var resources = sg.toArray(argvGet(argv, 'resources,resource,ids,id'));
var createTagsParams = {Resources : resources, Tags : Tags};
// Tagging might fail, if so, try again
var ctResult;
return sg.until(function(again, last, count) {
if (count > 5) { return last(); }
return awsEc2.createTags(createTagsParams, function(err, result) {
if (err) {
console.error('createTags err', err, 'for', createTagsParams, 'trying again...');
return again(250 * (count + 1));
}
ctResult = result;
return last();
});
}, function() {
return callback(null, ctResult);
});
};
/**
* Pick the tags out of the object.
*/
var pickTags = libEc2.pickTags = function(x) {
var result = {};
_.each(x, function(value, key) {
if (_.isString(key) && _.isString(value) && /^tag/i.exec(key)) {
result[key] = value;
}
});
if (x.Tags) {
result.Tags = _.toArray(x.Tags);
}
return result;
};
/**
* Wait for the instances to be in the requested state.
*/
libEc2.waitForInstanceState = function(argv, context, callback) {
var timeout = (argvGet(argv, 'timeout') || 90) * 1000; // 90 seconds
// Wait until we get success from getInstances, and we are in the right state.
return sg.until(function(again, last, count, elapsed) {
if (count > 200 || elapsed > timeout) { return callback('Waited too long for image state.'); }
return raEc2.isInstanceState(argv, context, function(err, isRunning, instances) {
if (err || !isRunning || !instances) { return again(500); }
// We also need the IP address
if (!(instances[sg.firstKey(instances)] || {}).PrivateIpAddress) { return again(500); }
return last(null, instances);
});
}, function(err, instances) {
return callback(err, instances);
});
};
/**
* Is the instance(s) in the given state?
*/
libEc2.isInstanceState = function(argv, context, callback) {
var log = sg.mkLogger(argv);
var instanceId = argvGet(argv, 'instance-id,id');
var instanceIds = argvGet(argv, 'instance-ids,ids') || instanceId;
var state = argvGet(argv, 'state') || 'running';
if (!_.isArray(instanceIds)) { instanceIds = [instanceIds]; }
log('waiting for', instanceIds);
var diParams = _.extend({ InstanceIds : instanceIds }, _.pick(argv, 'session', 'acct', 'account', 'role', 'region', 'acctName'));
// Get instance state from AWS
return raEc2.getInstances(diParams, context, function(err, instances) {
if (err) { return callback(err, false); }
var all = _.all(instances, function(instance) { return deref(instance, 'State.Name') === state; });
return callback(null, all, instances);
});
};
/**
* The JS-ification of the EC2 createImage API.
*/
libEc2.createAmi = function(argv, context, callback) {
var name = argvGet(argv, 'name');
var ciParams = {
NoReboot : false,
InstanceId : argvGet(argv, 'instance-id'),
Name : name,
Description : argvGet(argv, 'description')
};
var nameParts = name.split('-');
var namespace = nameParts[0];
var stack = nameParts[1];
var buildNumber = sg.smartValue(nameParts[2]);
var service = nameParts[3];
return sg.until(function(again, done, count, elapsed) {
// 9999 is the end of the road
if (buildNumber >= 9999) { return die(err, callback, 'createAmi.createImage'); }
ciParams.Name = name = [namespace, stack, buildNumber, service].join('-');
// Call the raw, but ra-ified createImage function
return raEc2.createImage(ciParams, context, function(err, results) {
if(err) {
// If we already have an image with that Name...
if (err.code === 'InvalidAMIName.Duplicate') {
// ...bump the build number and try again
buildNumber += 1;
console.error(ciParams.Name+' is already taken, trying '+buildNumber);
return again();
}
/* otherwise -- its an error */
return die(err, callback, 'createAmi.createImage');
}
return raEc2.waitForImageState(_.extend({imageId:results.ImageId}, argv), context, function(err, images) {
var tags = pickTags(argv);
tags.tags = tags.tags || {};
tags.tags.Name = name;
if (namespace) {
tags.tags.namespace = namespace;
if (buildNumber) { tags.tags.build = ''+buildNumber; }
if (stack) { tags.tags.stack = stack; }
if (service) { tags.tags.service = service; }
}
/* otherwise -- tag it */
var tiParams = _.extend({id: results.ImageId}, tags);
return raEc2.tagImage(tiParams, context, function(err, tagResults) {
return callback(err, images);
});
});
});
}, function() {
});
};
/**
* Wait for the AMI created image to be in the desired state.
*/
libEc2.waitForImageState = function(argv, context, callback) {
var imageId = argvGet(argv, 'image-id,id');
var state = argvGet(argv, 'state') || 'available';
var timeout = (argvGet(argv, 'timeout') || 60) * 1000 * 60; // 60 minutes
var noWait = argvGet(argv, 'no-wait');
var noWaitInstance = argvGet(argv, 'no-wait-instance');
var instanceId = argvGet(argv, 'instance-id');
var diParams = {
ImageIds : _.isArray(imageId) ? imageId : [imageId]
};
if (!instanceId) {
noWaitInstance = true;
}
if (noWait && noWaitInstance) {
return callback(null);
}
var results, images, instances, isRunning;
return sg.until(function(again, last, count, elapsed) {
if (elapsed > timeout) { return callback('Waited too long for image state.'); }
return sg.__runll([function(next) {
images = null;
return raEc2.getImages(diParams, context, function(err, images_) {
if (!err) { images = images_; }
return next();
});
}, function(next) {
instances = null;
isRunning = false;
return raEc2.isInstanceState(argv, context, function(err, isRunning_, instances_) {
if (!err) {
instances = instances_;
isRunning = isRunning_;
}
return next();
});
}], function() {
var imageOk = true, instanceOk = true, currState;
// TODO: Handle 'failed' state of image
if (!noWait) {
imageOk = images && _.all(images, function(image) { currState = image.State; return image.State === state; });
}
if (!noWaitInstance) {
instanceOk = instances && isRunning;
}
//console.error('Waiting for image; ', currState, isRunning);
if (!instanceOk || !imageOk) {
return again(5000);
}
return last(null, images);
});
}, function(err, images) {
return callback(err, images);
});
};
/**
* Make the given instance answer for the FQDN.
*
* We find, and then associate the appropriate elastic IP to the instance.
*/
libEc2.assignFqdnToInstance = function(argv, context, callback) {
var instanceId = argvExtract(argv, 'instance-id,id');
var fqdn = argvExtract(argv, 'fqdn');
if (!instanceId) { return callback(sg.toError("Need --instance-id")); }
if (!fqdn) { return callback(sg.toError("Need --fqdn")); }
// Allow caller to tell us multiple accts to search
var extraAccts = argvExtract(argv, 'extra-accts,accts') || []; if (!_.isArray(extraAccts)) { extraAccts = (''+extraAccts).split(','); }
var extraRoles = argvExtract(argv, 'extra-roles,roles') || []; if (!_.isArray(extraRoles)) { extraRoles = (''+extraRoles).split(','); }
var extraSessions = argvExtract(argv, 'extra-sessions,sessions') || []; if (!_.isArray(extraSessions)) { extraSessions = (''+extraSessions).split(','); }
// Ensure that we have an equal number of extra accts, roles, sessions
_.each(extraAccts, function(acct, index) {
extraRoles[index] = extraRoles[index] || extraRoles[0];
extraSessions[index] = extraSessions[index] || extraSessions[0];
});
//
var domainName = [], subDomain;
var parts = fqdn.split('.');
domainName.unshift(parts.pop());
domainName.unshift(parts.pop());
domainName = domainName.join('.');
subDomain = parts.join('.');
var addresses, resourceRecordSets = [];
return sg.__runll([function(next) {
return raEc2.getAddresses(argv, context, function(err, addresses_) {
if (err) { return die(err, callback, 'libEc2.assignFqdnToInstance.getAddresses'); }
addresses = addresses_;
return next();
});
}, function(next) {
// Get rrs from the main account (the one that the change is going to be in)
var params = _.extend({domain : domainName+'.', zero:true}, argv);
return raRoute53.listResourceRecordSets(params, context, function(err, recordSets) {
if (err) { return die(err, callback, 'libEc2.assignFqdnToInstance.listResourceRecordSets'); }
resourceRecordSets = resourceRecordSets.concat(recordSets.ResourceRecordSets);
return next();
});
}, function(next) {
// Get rrs from the extra accounts
sg.__eachll(extraAccts, function(acct, nextAcct, index) {
var params = {
domain : domainName+'.',
zero : true,
acct : acct,
role : extraRoles[index],
session : extraSessions[index]
};
params = _.extend(params, argv);
return raRoute53.listResourceRecordSets(params, context, function(err, recordSets) {
if (err) { return die(err, callback, 'libEc2.assignFqdnToInstance.listResourceRecordSets-extra'); }
resourceRecordSets = resourceRecordSets.concat(recordSets.ResourceRecordSets);
return nextAcct();
});
}, function() {
return next();
});
}], function() {
var ip, address;
_.each(resourceRecordSets, function(recordSet) {
if (recordSet.Name === fqdn+'.' && recordSet.Type === 'A') {
if (recordSet.ResourceRecords && recordSet.ResourceRecords.length > 0) {
ip = recordSet.ResourceRecords[0].Value;
}
}
});
if (ip) {
_.each(addresses, function(address_) {
if (address_.PublicIp === ip) {
// address is our EIP
address = address_;
}
});
if (address) {
var aaParams = _.extend({ AllocationId : address.AllocationId, InstanceId : instanceId}, argv);
return raEc2.associateAddress(aaParams, context, function(err, result) {
if (err) { return die(err, callback, 'libEc2.assignFqdnToInstance.associateAddress'); }
return callback(err, result);
});
}
/* otherwise -- found IP, not address */
console.error("Found IP, not Address: "+ip+" maybe you want to add ***** --session=prod --acct=244406501905 --role=mobilewebassist *****");
_.each(addresses, function(address) {
console.error('address:', sg.inspect(address));
});
return callback(sg.toError("Found IP, not Address: "+ip+" maybe you want to add ***** --session=prod --acct=244406501905 --role=mobilewebassist *****"));
}
/* otherwise -- did not find IP address */
return callback(sg.toError("Did not find IP"+" maybe you want to add ***** --session=prod --acct=244406501905 --role=mobilewebassist *****"));
});
};
/**
*
*/
libEc2.clusterIps = function(argv, context, callback) {
var result = {};
var namespace = argvExtract(argv, 'namespace,ns') || 'serverassist';
var namespaceEx = argvExtract(argv, 'namespace_ex,ns_ex') || namespace+'3';
var resultDebug = [];
var data = {};
return sg.__runll([function(next) {
return raVpc.getVpcs(argv, context, function(err, vpcs) {
if (err) { return die(err, callback, 'libEc2.clusterIps.getVpcs'); }
data.vpcs = vpcs;
return next();
});
}, function(next) {
return raEc2.getInstances({}, context, function(err, instances) {
if (err) { return die(err, callback, 'libEc2.clusterIps.getInstances'); }
data.instances = instances;
return next();
});
}], function() {
var ourVpcs = sg.reduce(data.vpcs, {}, function(m, vpc, name) {
if (sg.startsWith(deref(vpc, 'Tags.aws.cloudformation.stackName'), namespaceEx)) {
return sg.kv(m, name, vpc);
}
return m;
});
var ourInstances = {};
_.each(data.instances, function(instance, instanceId) {
if (!instance.VpcId) {
return resultDebug.push({noVpcInstance: instance});
}
if (!instance.PrivateIpAddress) {
return resultDebug.push({noPrivateIp : instance});
}
if (deref(instance, 'State.Name') !== "running") {
return resultDebug.push({notRunning : instance});
}
if (deref(instance, 'Tags.participation') === "building") {