/
machines.js
2047 lines (1721 loc) · 58.4 KB
/
machines.js
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
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/*
* Copyright (c) 2017, Joyent, Inc.
*/
/*
* Virtual Machines or customer "instances".
*/
var assert = require('assert-plus');
var util = require('util');
var restify = require('restify');
var libuuid = require('libuuid');
var semver = require('semver');
var clone = require('clone');
var vasync = require('vasync');
var errors = require('./errors');
var images = require('./datasets');
var resources = require('./resources');
var membership = require('./membership'),
preloadGroups = membership.preloadGroups;
var triton_affinity = require('./triton-affinity');
// --- Globals
var InvalidArgumentError = restify.InvalidArgumentError;
var MissingParameterError = restify.MissingParameterError;
var ResourceNotFoundError = restify.ResourceNotFoundError;
var InternalError = restify.InternalError;
var RestError = restify.RestError;
var MD_RE = /^metadata\.\w/;
var TAG_RE = /^tag\..+/;
var BEFORE_NETWORK_VERSION_RE = /^~?7\.0(\.\d+)?$/;
var EXTERNAL_NIC_TAG = 'external';
var INTERNAL_NIC_TAG = 'internal';
// networks used if pkg doesn't have any
var DEFAULT_NETWORKS = [EXTERNAL_NIC_TAG, INTERNAL_NIC_TAG];
var PKG_USED_PARAMS = ['uuid', 'max_physical_memory', 'name', 'version',
'networks', 'active', 'default', 'owner_uuids', 'fss', 'os'];
var sprintf = util.format;
// --- Helpers
function KeyRequiredError() {
var message = 'At least one SSH key is required to provision';
RestError.call(this, {
statusCode: 409,
restCode: 'KeyRequired',
message: message,
constructorOpt: KeyRequiredError
});
this.name = 'KeyRequiredError';
}
util.inherits(KeyRequiredError, RestError);
function translateState(state) {
switch (state) {
case 'configured':
case 'incomplete':
case 'unavailable':
case 'provisioning':
state = 'provisioning';
break;
// Cause ready happens now during reboot only:
case 'ready':
state = 'ready';
break;
case 'running':
state = 'running';
break;
case 'halting':
case 'stopping':
case 'shutting_down':
state = 'stopping';
break;
case 'off':
case 'down':
case 'installed':
case 'stopped':
state = 'stopped';
break;
case 'unreachable':
state = 'offline';
break;
case 'destroyed':
state = 'deleted';
break;
case 'failed':
state = 'failed';
break;
default:
state = 'unknown';
break;
}
return state;
}
function translate(machine, req) {
assert.ok(machine);
var credentials = req.params.credentials;
var version = req.getVersion();
var msg = {
id: machine.uuid,
name: machine.alias,
type: machine.brand === 'kvm' ? 'virtualmachine' : 'smartmachine',
brand: machine.brand,
state: translateState(machine.state),
image: machine.image_uuid,
ips: [],
memory: Number(machine.ram),
disk: (Number(machine.quota) * 1024) || 0,
metadata: machine.customer_metadata || {},
tags: machine.tags,
credentials: credentials,
created: machine.create_timestamp || (new Date()).toISOString(),
updated: machine.last_modified || (new Date()).toISOString()
};
if (machine.docker) {
msg.docker = true;
}
if (!BEFORE_NETWORK_VERSION_RE.test(version)) {
msg.networks = [];
}
if (msg.type === 'virtualmachine' && machine.disks[0]) {
msg.image = machine.disks[0].image_uuid;
}
if (msg.type === 'virtualmachine' && machine.disks[1] &&
machine.disks[1].size) {
msg.disk = Number(machine.disks[1].size);
}
if (machine.nics && machine.nics.length) {
machine.nics.forEach(function (nic) {
msg.ips.push(nic.ip);
if (!BEFORE_NETWORK_VERSION_RE.test(version)) {
msg.networks.push(nic.network_uuid);
}
});
var primaryNic = machine.nics.filter(function (nic) {
return nic.primary;
})[0];
// For backwards-compat. Some old VMs don't have a primary
// attribute set on their nics, but have an 'external' nic tag.
if (!primaryNic) {
primaryNic = machine.nics.filter(function (nic) {
return nic.nic_tag === EXTERNAL_NIC_TAG;
}).pop();
}
// if we found nothing yet, just pick any NIC
primaryNic = primaryNic || machine.nics[0];
msg.primaryIp = primaryNic ? primaryNic.ip : '';
}
if (credentials && machine.internal_metadata &&
typeof (machine.internal_metadata) === 'object') {
msg.metadata.credentials = {};
Object.keys(machine.internal_metadata).forEach(function (k) {
if (/_pw$/.test(k)) {
msg.metadata.credentials[k.replace(/_pw$/, '')] =
machine.internal_metadata[k];
}
});
// Do not keep around when empty:
if (msg.metadata.credentials &&
typeof (msg.metadata.credentials) === 'object' &&
Object.keys(msg.metadata.credentials).length === 0) {
delete msg.metadata.credentials;
}
}
if (typeof (machine.firewall_enabled) !== 'undefined') {
msg.firewall_enabled = machine.firewall_enabled;
}
if (typeof (machine.server_uuid) !== 'undefined') {
msg.compute_node = machine.server_uuid;
}
if (machine.billing_id && req.packages) {
var packages = req.packages.filter(function (d) {
return (d.uuid === machine.billing_id);
});
msg.package = packages[0] ? packages[0].name : '';
} else {
msg.package = '';
}
if (machine.dns_names !== undefined) {
msg.dns_names = machine.dns_names;
}
return msg;
}
// Note the throws in this function are ok, as restify is contractually
// obligated to catch them and do res.send for us
function getListOptions(req) {
assert.ok(req);
var opts = {};
switch (req.params.state) {
case 'provisioning':
opts.state = 'active';
break;
case 'stopping':
opts.state = 'active';
break;
case 'active':
opts.state = 'active';
break;
case 'stopped':
opts.state = 'stopped';
break;
case 'running':
opts.state = 'running';
break;
case 'unknown':
opts.state = 'unknown';
break;
case 'destroyed':
opts.state = 'destroyed';
break;
case undefined:
break;
default:
throw new InvalidArgumentError('%s is not a valid state',
req.params.state);
}
switch (req.params.type) {
case 'smartmachine':
opts.predicate = '{ "ne": [ "brand", "kvm" ] }';
break;
case 'virtualmachine':
opts.predicate = '{ "eq": [ "brand", "kvm" ] }';
break;
case undefined:
break;
default:
throw new InvalidArgumentError('%s is not a valid type',
req.params.type);
}
if (req.params.brand) {
opts.brand = req.params.brand;
}
if (req.params.image) {
opts.image_uuid = req.params.image;
}
var docker = req.params.docker;
if (typeof (docker) === 'boolean') {
opts.docker = docker;
}
if (typeof (docker) === 'string') {
if (docker === 'true') {
opts.docker = true;
} else if (docker === 'false') {
opts.docker = false;
} else {
throw new InvalidArgumentError('%s is not a valid boolean', docker);
}
}
// Not implemented right now into VMAPI
opts.limit = req.params.limit || 1000;
if (req.params.memory) {
opts.ram = req.params.memory;
}
if (req.params.name) {
opts.alias = req.params.name;
}
// Not implemented right now into VMAPI
opts.offset = req.params.offset || 0;
// Copy in any and all tags.
Object.keys(req.params).forEach(function (k) {
if (TAG_RE.test(k)) {
opts[k] = req.params[k];
}
});
// By default, VMAPI will return everything unless it's told to not
// retrieve destroyed machines.
if (!req.params.tombstone && !opts.state) {
opts.state = 'active';
}
return opts;
}
/*
* Convert the various arguments passed in over HTTP on POST to options which
* vmapi.createVm() understands.
*/
function getCreateOptions(req) {
assert.ok(req);
assert.ok(req.params);
assert.ok(req.pkg);
assert.ok(req.dataset);
var params = req.params;
var pkg = req.pkg;
var img = req.dataset;
var brand = img.requirements && img.requirements.brand;
if (!brand) {
brand = img.brand || (img.type === 'zvol' ? 'kvm' : 'joyent');
}
var opts = {
'package': pkg.uuid,
ram: pkg.max_physical_memory,
brand: brand,
billing_id: pkg.uuid
};
if (pkg.os) {
opts.os = pkg.os;
}
if (pkg.fss) {
opts.cpu_shares = Math.ceil(pkg.fss);
}
if (brand === 'kvm') {
opts.disks = [
{ image_uuid: img.uuid },
{ size: parseInt(pkg.quota, 10) }
];
// PUBAPI-652: Fixed 10GiB quota for root dataset of all the KVM
// machines. User data isn't stored in a zone's root dataset, but a
// separate one.
opts.quota = 10;
} else {
opts.image_uuid = img.uuid;
opts.image_os = img.os;
opts.image_name = img.name;
if (Number(pkg.quota)) {
opts.quota = Number(pkg.quota) / 1024;
}
}
var networkUuids = [];
// Starting in version 7.3, CloudAPI supports what we call interface-
// centric provisioning. Traditionally, CloudAPI accepted provisioning
// here in the form of:
//
// [ uuid_0, uuid_1, ... ]
//
// CloudAPI then translates that format into a form that VMAPI is
// familiar with. Which is something that looks like:
//
// [ { uuid: uuid_0, primary: true }, { uuid: uuid_1 }, ... ]
//
// Unlike vmapi, it never supported the form that allows the user to
// specify an IP or which device was primary. Instead, we have a new
// form which allows us to request IPs, and will easily evolve into an
// IPv6-compatible form:
//
// [
// {
// ipv4_uuid: uuid_0, ipv4_count: <number>,
// ipv4_ips: [ ip0, ip1, ... ],
// ipv6_uuid: uuid_1, ipv6_count: <number>,
// ipv6_ips: [ ip0, ip1, ... ],
// primary: true
// }, ...
// ]
//
// The idea here is that each object is an interface. Interfaces can be
// IPv4 and IPv6 uuids. That said, we don't quite support everything
// here yet. We only support a count of 1, or a single IP in the array.
// We don't support both of those at this time, though we'll go through
// and support it later on; the same is true for IPv6. The goal is just
// to future-proof ourselves at the various layers of the stack.
//
// Conveniently though, VMAPI supports both forms of this interface.
// Therefore, if we are in a newer version and we see something that
// looks like an Object, we'll treat it like this new form, but if we
// just have arrays of strings, then there's nothing for us to worry
// worry about, and there's nothing we have to do.
//
// If we encounter an API version that's less than 7.3, we end up assuming
// that it's basically our uuid format, and then move on.
if (Array.isArray(params.networks)) {
var ver = req.getVersion();
var objectsAllowed =
semver.satisfies('7.3.0', ver) || semver.ltr('7.3.0', ver);
var ifaceObjects = 0;
var ifaceStrings = 0;
var alreadyAdded = {};
networkUuids = params.networks.filter(function (netObj, idx) {
var netType = typeof (netObj);
var netUuid = netObj;
if (objectsAllowed) {
switch (netType) {
case 'string':
ifaceObjects++;
break;
case 'object':
ifaceObjects++;
netUuid = netObj.ipv4_uuid;
if (typeof (netUuid) !== 'string') {
throw new InvalidArgumentError(sprintf(
'property "networks[%d].ipv4_uuid": ' +
'string expected', idx));
}
break;
default:
// the 'property "foo" ...' format intended to match
// the json-schema error format:
throw new InvalidArgumentError(sprintf(
'property "networks[%d]": array of strings or ' +
'objects expected', idx));
}
} else {
if (netType !== 'string') {
// Match the existing 7.2 behaviour:
throw new InvalidArgumentError('Invalid Networks');
}
}
if (alreadyAdded[netUuid]) {
return false;
}
alreadyAdded[netUuid] = true;
return true;
});
if (ifaceObjects.length > 0 && ifaceStrings.length > 0) {
throw new InvalidArgumentError(
'property "networks": cannot mix objects and strings');
}
} else {
var pkgNetworks = pkg.networks;
if (typeof (pkgNetworks) === 'string') {
try {
pkgNetworks = JSON.parse(pkgNetworks);
} catch (e) {
pkgNetworks = null;
}
}
if (pkgNetworks) {
networkUuids = pkgNetworks;
} else {
// Determine whether to add external and/or internal nics. The
// user can change which of these are provided, and if they do
// not, default to external.
var defaultNetworks = params.default_networks || DEFAULT_NETWORKS;
if (req.external_nets.length &&
defaultNetworks.indexOf(EXTERNAL_NIC_TAG) !== -1) {
networkUuids.push(req.external_nets[0]);
}
if (req.internal_nets.length &&
defaultNetworks.indexOf(INTERNAL_NIC_TAG) !== -1) {
var internalNet = getInternalNetwork(req);
if (internalNet) {
networkUuids.push(internalNet);
}
}
}
}
checkNetworks(req, networkUuids);
opts.networks = networkUuids;
if (typeof (networkUuids[0]) === 'object') {
// We only support ipv4_uuid and ipv4_count for now, so only allow
// them, just to be safe:
opts.networks = opts.networks.map(function (n) {
return {
ipv4_count: n.ipv4_count || 1,
ipv4_uuid: n.ipv4_uuid
};
});
} else {
// Always use the new format for networks ("ipv4_uuid" vs. "uuid"):
opts.networks = networkUuids.map(function (netUuid) {
return { ipv4_uuid: netUuid };
});
}
// if we have any external networks, make the first one the primary
if (req.external_nets.length) {
for (var i = 0; i !== opts.networks.length; i++) {
var net = opts.networks[i];
if (req.external_nets.indexOf(net.ipv4_uuid) !== -1) {
net.primary = true;
break;
}
}
}
if (typeof (params.firewall_enabled) !== 'undefined') {
opts.firewall_enabled = params.firewall_enabled;
}
var metadata = {};
var shortId;
var tags = {};
opts.uuid = libuuid.create();
shortId = opts.uuid.split(/-/)[0];
if (params.name) {
opts.alias = params.name.replace(/{{shortId}}/g, shortId);
} else {
opts.alias = shortId;
}
// Copy in all the tags and metadata
Object.keys(params).forEach(function (k) {
if (TAG_RE.test(k)) {
tags[k.replace(/^tag\./, '')] = params[k];
} else if (MD_RE.test(k) && !/_pw$/.test(k)) {
metadata[k.replace(/^metadata\./, '')] = params[k];
}
});
if (Object.keys(tags).length) {
opts.tags = JSON.stringify(tags);
}
// Windows administrator password:
if (params.password) {
metadata.administrator_pw = params.password;
}
if (params.administrator_pw) {
metadata.administrator_pw = params.administrator_pw;
}
// root_authorized_keys right place:
if (req.root_authorized_keys) {
metadata.root_authorized_keys = req.root_authorized_keys;
}
var credentials = metadata.credentials;
delete metadata.credentials;
if (typeof (credentials) === 'string') {
try {
credentials = JSON.parse(credentials);
} catch (e) {
credentials = null;
}
}
if (credentials) {
// Check users, and ensure we're taking passwords either when they are
// specified as '<user>_pw' or simply with the respective user names:
Object.keys(credentials).forEach(function (k) {
if (!/_pw$/.test(k)) {
credentials[k + '_pw'] = credentials[k];
delete credentials[k];
}
});
// Pass a string to VMAPI, not an object, or validation will fail
opts.internal_metadata = JSON.stringify(credentials);
}
if (Object.keys(metadata).length) {
opts.customer_metadata = JSON.stringify(metadata);
}
if (img.disk_driver) {
opts.disk_driver = img.disk_driver;
}
if (img.nic_driver) {
opts.nic_driver = img.nic_driver;
}
// Intentionally not documented, at least until we are checking on
// vmapi that owner is allowed to specify a given server:
// PUBAPI-724: Only allow in test mode
if (params.server_uuid && req.config.test) {
opts.server_uuid = params.server_uuid;
}
// Another alternative to provide server_uuid, (which I mostly use
// locally to run node-smartdc tests w/o having to hardcode server_uuid
// into sdc-createmachine):
if (process.env.SERVER_UUID) {
opts.server_uuid = process.env.SERVER_UUID;
}
if (params.locality) {
opts.locality = params.locality;
}
// 'affinity' is the new replacement for 'locality' (now deprecated).
if (params.affinity) {
if (params.locality) {
throw new InvalidArgumentError(
'cannot specify both "locality" (deprecated) and "affinity"');
}
opts.affinity = params.affinity;
}
Object.keys(pkg).forEach(function (p) {
if (typeof (opts[p]) === 'undefined' &&
(PKG_USED_PARAMS.indexOf(p) === -1)) {
opts[p] = pkg[p];
}
});
return opts;
}
/*
* Return a network object for an internal network, if one is available.
* Whether the internal network can optionally be a fabric or not is determined
* by the package name prefix.
*/
function getInternalNetwork(req) {
assert.ok(req);
var cfg = req.config;
var pkg = req.pkg;
var allNets = req.networks;
var internalNetUuids = req.internal_nets;
assert.ok(cfg);
assert.ok(pkg);
assert.ok(allNets);
assert.ok(internalNetUuids);
if (pkgAllowsFabric(cfg, pkg)) {
return internalNetUuids[0];
}
return internalNetUuids.filter(function (netUuid) {
var net = getNetwork(allNets, netUuid);
assert.ok(net);
return !net.fabric;
})[0];
}
/*
* If cloudapi's config lists an array of package name prefixes that can be used
* with fabrics, and the package used in the current request doesn't have one of
* those prefixes, check that none of the networks is a fabric.
*
* 'networks' arg is an array of UUIDs and hashes
*/
function checkNetworks(req, networks) {
assert.ok(req);
var cfg = req.config;
var pkg = req.pkg;
var allNets = req.networks;
assert.ok(cfg);
assert.ok(pkg);
assert.ok(allNets);
if (pkgAllowsFabric(cfg, pkg)) {
return;
}
for (var i = 0; i !== networks.length; i++) {
var network = networks[i];
var netUuid = network.ipv4_uuid || network;
var net = getNetwork(allNets, netUuid);
if (!net) {
// if we didn't find a network, it's likely because the user doesn't
// have permission for that network. We skip this since there are
// checks elsewhere to ensure such requests are rejected
continue;
}
if (net.fabric) {
var msg = 'Fabric network cannot be used with this package. Only ' +
'packages with names starting with the following can be ' +
'used with a fabric network: ' +
cfg.fabric_package_prefixes.join(', ');
var err = new InvalidArgumentError(msg);
err.body.code = err.restCode = 'InvalidFabricPackage';
throw err;
}
}
}
function getNetwork(networks, netUuid) {
for (var i = 0; i < networks.length; i++) {
var net = networks[i];
if (net.uuid === netUuid) {
return net;
}
}
return null;
}
/*
* Check if the current package has a name that matches an allowed prefix. This
* only applies if cloudapi's config specifies a non-empty array for
* fabric_package_prefixes.
*/
function pkgAllowsFabric(cfg, pkg) {
var fabricPkgs = cfg.fabric_package_prefixes;
if (!fabricPkgs || fabricPkgs.length === 0) {
return true;
}
var canHaveFabric = false;
fabricPkgs.forEach(function (prefix) {
canHaveFabric = canHaveFabric || pkg.name.indexOf(prefix) === 0;
});
return canHaveFabric;
}
function updateCallback(req, res, next) {
var log = req.log;
return function callback(err) {
if (err) {
return next(err);
}
var m = req.params.machine;
log.debug('%s (%s/%s): ok', req.action, req.account.login, m);
res.send(202);
return next(false);
};
}
function xorIfPresent(a, b) {
if (!a && !b) {
return true;
}
return (!a != !b);
}
function loadMachine(req, res, next) {
var pathname = req.getUrl().pathname;
if (pathname === '/--ping' || !(/\/machines/.test(pathname))) {
return next();
}
assert.ok(req.sdc);
var customer = req.account.uuid;
var name = req.params.machine;
// set by resources.js, if a PUT with role tags is being done
if (req.params.resource_name === 'machines' && req.params.resource_id) {
name = name || req.params.resource_id;
}
if (!name) {
return next();
}
var machine;
return vasync.pipeline({
funcs: [
function _getVm(_, cb) {
req.sdc.vmapi.getVm({
uuid: name,
owner_uuid: customer,
fields: '*'
}, {
log: req.log,
headers: {
'x-request-id': req.getId()
}
}, function (err, m) {
if (err) {
return cb(err);
}
machine = m;
return cb(null, m);
});
},
function _getImg(_, cb) {
if (req.datasets) {
return cb(null, req.datasets);
}
req.params.image = (machine.image_uuid) ? machine.image_uuid :
(machine.brand === 'kvm' && machine.disks[0].image_uuid) ?
machine.disks[0].image_uuid : null;
if (req.params.image === null) {
return cb(new ResourceNotFoundError('Cannot find ' +
'machine image'));
}
return images.loadImage(req, function (err, img) {
if (err) {
if (err.statusCode && err.statusCode === 404) {
// IMGAPI-328: Users can destroy custom images
req.datasets = [];
return cb(null, req.datasets);
}
return cb(err);
}
req.dataset = img;
req.log.debug({image: req.dataset},
'selected image loaded');
req.datasets = [img];
return cb(null, req.datasets);
});
},
function _getPkg(_, cb) {
if (req.packages) {
return cb(null, req.packages);
}
var pkgUuid = machine.billing_id;
if (!pkgUuid) {
req.log.warn('Ignoring missing billing_id');
return cb();
}
return req.sdc.papi.get(pkgUuid, {}, function (err, pkg) {
if (err) {
if (err.name === 'ResourceNotFoundError') {
req.log.warn('Ignoring missing package in papi:',
pkgUuid);
return cb();
}
return cb(err);
}
req.packages = [pkg];
req.log.debug({'package': req.pkg},
'selected package loaded');
return cb(null, req.packages);
});
},
function _getNetwork(_, cb) {
loadNetworkUuids(req, machine, function (err, m) {
if (err) {
return cb(err);
}
machine = m;
return cb();
});
},
function _getCNSNames(_, cb) {
if (!req.sdc.cns || req.account.triton_cns_enabled !== 'true') {
cb();
return;
}
var opts = {};
opts.headers = { 'x-request-id': req.getId() };
req.sdc.cns.getVM(name, opts, function (err, obj) {
if (err && err.statusCode === 404) {
machine.dns_names = [];
return cb();
} else if (err) {
req.log.error(err,
'failed to look up VM %s in CNS REST API', name);
var rerr = new InternalError('Unable to contact the ' +
'Triton CNS API');
return cb(rerr);
}
machine.dns_names = obj.names;
return cb();
});
}
]
}, function (err, results) {
if (err) {
return next(err);
}
req.machine = translate(machine, req);
if (machine.role_tags && machine.role_tags.length) {
req.machine_role_tags = machine.role_tags;
}
return next();
});
}
// PUBAPI-943 - some VMs which should have a network_uuid listed in each nic
// do not. When this happens for v7.1+ nics, we fetch the network_uuid directly
// from napi for every nic in the machine.
function loadNetworkUuids(req, machine, cb) {
var version = req.getVersion();
if (!machine.nics || machine.nics.length === 0 ||
machine.state === 'destroyed' ||
BEFORE_NETWORK_VERSION_RE.test(version)) {
return cb(null, machine);
}
var options = { headers: { 'x-request-id': req.getId() } };
var napi = req.sdc.napi;
function getNic(vmapiNic, next) {
if (vmapiNic.network_uuid) {
return next();
}
return napi.getNic(vmapiNic.mac, options, function (err, napiNic) {
if (err) {
if (err.name === 'ResourceNotFoundError') {
req.log.warn('Ignoring missing nic in napi:', vmapiNic.mac);
return next();
}
return next(err);
}
vmapiNic.network_uuid = napiNic.network_uuid;
return next();
});
}
return vasync.forEachPipeline({
inputs: machine.nics,
func: getNic
}, function (err) {
return cb(err, machine);
});