forked from googleapis/google-cloud-node
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvm.js
More file actions
997 lines (914 loc) · 27.9 KB
/
vm.js
File metadata and controls
997 lines (914 loc) · 27.9 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
/*!
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*!
* @module compute/vm
*/
'use strict';
var common = require('@google-cloud/common');
var createErrorClass = require('create-error-class');
var extend = require('extend');
var format = require('string-format-obj');
var is = require('is');
var util = require('util');
/**
* @type {module:compute/disk}
* @private
*/
var Disk = require('./disk.js');
/**
* Custom error type for errors related to detaching a disk.
*
* @private
*
* @param {string} message - Custom error message.
* @return {Error}
*/
var DetachDiskError = createErrorClass('DetachDiskError');
/**
* Custom error type for when `waitFor()` does not return a status in a timely
* fashion.
*
* @private
*
* @param {string} message - Custom error message.
* @return {Error}
*/
var WaitForTimeoutError = createErrorClass('WaitForTimeoutError');
/**
* The statuses that a VM can be in.
*
* @private
*/
var VALID_STATUSES = [
'PROVISIONING',
'STAGING',
'RUNNING',
'STOPPING',
'SUSPENDING',
'SUSPENDED',
'TERMINATED'
];
/**
* Interval for polling during waitFor.
*
* @private
*/
var WAIT_FOR_POLLING_INTERVAL_MS = 2000;
/*! Developer Documentation
*
* @param {module:zone} zone - Zone object this instance belongs to.
* @param {string} name - Name of the instance.
*/
/**
* An Instance object allows you to interact with a Google Compute Engine
* instance.
*
* @resource [Instances and Networks]{@link https://cloud.google.com/compute/docs/instances-and-network}
* @resource [Instance Resource]{@link https://cloud.google.com/compute/docs/reference/v1/instances}
*
* @constructor
* @alias module:compute/vm
*
* @example
* var zone = gce.zone('zone-name');
*
* var vm = zone.vm('vm-name');
*/
function VM(zone, name) {
this.name = name.replace(/.*\/([^/]+)$/, '$1'); // Just the instance name.
this.zone = zone;
this.hasActiveWaiters = false;
this.waiters = [];
this.url = format('{base}/{project}/zones/{zone}/instances/{name}', {
base: 'https://www.googleapis.com/compute/v1/projects',
project: zone.compute.projectId,
zone: zone.name,
name: this.name
});
var methods = {
/**
* Create a virtual machine.
*
* @param {object} config - See {module:compute/zone#createVM}.
*
* @example
* var config = {
* // ...
* };
*
* vm.create(config, function(err, vm, operation, apiResponse) {
* // `vm` is a VM object.
*
* // `operation` is an Operation object that can be used to check the
* // status of the request.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.create(config).then(function(data) {
* var vm = data[0];
* var operation = data[1];
* var apiResponse = data[2];
* });
*/
create: true,
/**
* Check if the vm exists.
*
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this
* request.
* @param {boolean} callback.exists - Whether the vm exists or not.
*
* @example
* vm.exists(function(err, exists) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.exists().then(function(data) {
* var exists = data[0];
* });
*/
exists: true,
/**
* Get a virtual machine if it exists.
*
* You may optionally use this to "get or create" an object by providing an
* object with `autoCreate` set to `true`. Any extra configuration that is
* normally required for the `create` method must be contained within this
* object as well.
*
* @param {options=} options - Configuration object.
* @param {boolean} options.autoCreate - Automatically create the object if
* it does not exist. Default: `false`
*
* @example
* vm.get(function(err, vm, apiResponse) {
* // `vm` is a VM object.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.get().then(function(data) {
* var vm = data[0];
* var apiResponse = data[1];
* });
*/
get: true,
/**
* Get the instance's metadata.
*
* @resource [Instance Resource]{@link https://cloud.google.com/compute/docs/reference/v1/instances}
* @resource [Instance: get API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/get}
*
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this
* request.
* @param {object} callback.metadata - The instance's metadata.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* vm.getMetadata(function(err, metadata, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.getMetadata().then(function(data) {
* var metadata = data[0];
* var apiResponse = data[1];
* });
*/
getMetadata: true
};
common.ServiceObject.call(this, {
parent: zone,
baseUrl: '/instances',
id: this.name,
createMethod: zone.createVM.bind(zone),
methods: methods
});
}
util.inherits(VM, common.ServiceObject);
/**
* Attach a disk to the instance.
*
* @resource [Disks Overview]{@link https://cloud.google.com/compute/docs/disks}
* @resource [Disk Resource]{@link https://cloud.google.com/compute/docs/reference/v1/disks}
* @resource [Instance: attachDisk API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/attachDisk}
*
* @throws {Error} if a {module:compute/disk} is not provided.
*
* @param {module:compute/disk} disk - The disk to attach.
* @param {object=} options - See the
* [Instances: attachDisk](https://cloud.google.com/compute/docs/reference/v1/instances/attachDisk)
* request body.
* @param {boolean} options.readOnly - Attach the disk in read-only mode. (Alias
* for `options.mode = READ_ONLY`)
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:compute/operation} callback.operation - An operation object
* that can be used to check the status of the request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* var disk = zone.disk('my-disk');
*
* function callback(err, operation, apiResponse) {
* // `operation` is an Operation object that can be used to check the status
* // of the request.
* }
*
* vm.attachDisk(disk, callback);
*
* //-
* // Provide an options object to customize the request.
* //-
* var options = {
* autoDelete: true,
* readOnly: true
* };
*
* vm.attachDisk(disk, options, callback);
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.attachDisk(disk, options).then(function(data) {
* var operation = data[0];
* var apiResponse = data[1];
* });
*/
VM.prototype.attachDisk = function(disk, options, callback) {
if (!(disk instanceof Disk)) {
throw new Error('A Disk object must be provided.');
}
if (is.fn(options)) {
callback = options;
options = {};
}
var body = extend({
// Default the deviceName to the name of the disk, like the Console does.
deviceName: disk.name
}, options, {
source: disk.formattedName
});
if (body.readOnly) {
body.mode = 'READ_ONLY';
delete body.readOnly;
}
this.request({
method: 'POST',
uri: '/attachDisk',
json: body
}, callback);
};
/**
* Delete the instance.
*
* @resource [Instance: delete API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/delete}
*
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:compute/operation} callback.operation - An operation object
* that can be used to check the status of the request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* vm.delete(function(err, operation, apiResponse) {
* // `operation` is an Operation object that can be used to check the status
* // of the request.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.delete().then(function(data) {
* var operation = data[0];
* var apiResponse = data[1];
* });
*/
VM.prototype.delete = function(callback) {
this.request({
method: 'DELETE',
uri: ''
}, callback || common.util.noop);
};
/**
* Detach a disk from the instance.
*
* @resource [Instance: detachDisk API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/detachDisk}
*
* @param {module:compute/disk|string} deviceName - The device name of the disk
* to detach. If a Disk object is provided, we try to find the device name
* automatically by searching through the attached disks on the instance.
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:compute/operation} callback.operation - An operation object
* that can be used to check the status of the request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* var disk = zone.disk('my-disk');
*
* vm.detachDisk(disk, function(err, operation, apiResponse) {
* // `operation` is an Operation object that can be used to check the status
* // of the request.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.detachDisk(disk).then(function(data) {
* var operation = data[0];
* var apiResponse = data[1];
* });
*/
VM.prototype.detachDisk = function(disk, callback) {
var self = this;
if (!(disk instanceof Disk)) {
throw new Error('A Disk object must be provided.');
}
this.getMetadata(function(err, metadata) {
if (err) {
callback(new DetachDiskError(err.message));
return;
}
var diskName = common.util.replaceProjectIdToken(
disk.formattedName,
self.zone.compute.authClient.projectId
);
var deviceName;
var baseUrl = 'https://www.googleapis.com/compute/v1/';
var disks = metadata.disks || [];
// Try to find the deviceName by matching the source of the attached disks
// to the name of the disk provided by the user.
for (var i = 0; !deviceName && i < disks.length; i++) {
var attachedDisk = disks[i];
var source = attachedDisk.source.replace(baseUrl, '');
if (source === diskName) {
deviceName = attachedDisk.deviceName;
}
}
if (!deviceName) {
callback(new DetachDiskError('Device name for this disk was not found.'));
return;
}
self.request({
method: 'POST',
uri: '/detachDisk',
qs: {
deviceName: deviceName
}
}, callback || common.util.noop);
});
};
/**
* Returns the serial port output for the instance.
*
* @resource [Instances: getSerialPortOutput API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/getSerialPortOutput}
*
* @param {number=} port - The port from which the output is retrieved (1-4).
* Default: `1`.
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object} callback.output - The output from the port.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* vm.getSerialPortOutput(function(err, output, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.getSerialPortOutput().then(function(data) {
* var output = data[0];
* var apiResponse = data[1];
* });
*/
VM.prototype.getSerialPortOutput = function(port, callback) {
if (is.fn(port)) {
callback = port;
port = 1;
}
var reqOpts = {
uri: '/serialPort',
qs: {
port: port
}
};
var request = common.ServiceObject.prototype.request;
request.call(this, reqOpts, function(err, resp) {
if (err) {
callback(err, null, resp);
return;
}
callback(null, resp.contents, resp);
});
};
/**
* Get the instance's tags and their fingerprint.
*
* This method wraps {module:compute/vm#getMetadata}, returning only the `tags`
* property.
*
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object[]} callback.tags - Tag objects from this VM.
* @param {string} callback.fingerprint - The current tag fingerprint.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* vm.getTags(function(err, tags, fingerprint, apiResponse) {});
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.getTags().then(function(data) {
* var tags = data[0];
* var fingerprint = data[1];
* var apiResponse = data[2];
* });
*/
VM.prototype.getTags = function(callback) {
this.getMetadata(function(err, metadata, apiResponse) {
if (err) {
callback(err, null, null, apiResponse);
return;
}
callback(null, metadata.tags.items, metadata.tags.fingerprint, apiResponse);
});
};
/**
* Reset the instance.
*
* @resource [Instances: reset API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/reset}
*
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:compute/operation} callback.operation - An operation object
* that can be used to check the status of the request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* vm.reset(function(err, operation, apiResponse) {
* // `operation` is an Operation object that can be used to check the status
* // of the request.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.reset().then(function(data) {
* var operation = data[0];
* var apiResponse = data[1];
* });
*/
VM.prototype.reset = function(callback) {
this.request({
method: 'POST',
uri: '/reset'
}, callback || common.util.noop);
};
/**
* Set the machine type for this instance, **stopping and restarting the VM as
* necessary**.
*
* For a list of the standard, high-memory, and high-CPU machines you may choose
* from, see
* [Predefined machine types]{@link https://cloud.google.com/compute/docs/machine-types#predefined_machine_types}.
*
* In order to change the machine type, the VM must not be running. This method
* will automatically stop the VM if it is running before changing the machine
* type. After it is sucessfully changed, the VM will be started.
*
* @resource [Instances: setMachineType API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/setMachineType}
* @resource [Predefined machine types]{@link https://cloud.google.com/compute/docs/machine-types#predefined_machine_types}
*
* @param {string} machineType - Full or partial machine type. See a list of
* predefined machine types
* [here](https://cloud.google.com/compute/docs/machine-types#predefined_machine_types).
* @param {object=} options - Configuration object.
* @param {boolean} options.start - Start the VM after successfully updating the
* machine type. Default: `false`.
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* vm.resize('n1-standard-1', function(err, apiResponse) {
* if (!err) {
* // The VM is running and its machine type was changed successfully.
* }
* });
*
* //-
* // By default, calling `resize` will start your server after updating its
* // machine type. If you want to leave it stopped, set `options.start` to
* // `false`.
* //-
* var options = {
* start: false
* };
*
* vm.resize('ns-standard-1', options, function(err, apiResponse) {
* if (!err) {
* // The VM is stopped and its machine type was changed successfully.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.resize('ns-standard-1', options).then(function(data) {
* var apiResponse = data[0];
* });
*/
VM.prototype.resize = function(machineType, options, callback) {
var self = this;
var compute = this.zone.parent;
if (is.fn(options)) {
callback = options;
options = {};
}
options = options || {};
var isPartialMachineType = machineType.indexOf('/') === -1;
if (isPartialMachineType) {
machineType = format('zones/{zoneName}/machineTypes/{machineType}', {
zoneName: this.zone.name,
machineType: machineType
});
}
this.request({
method: 'POST',
uri: '/setMachineType',
json: {
machineType: machineType
}
}, compute.execAfterOperation_(function(err, apiResponse) {
if (err) {
if (err.message === 'Instance is starting or running.') {
// The instance must be stopped before its machine type can be set.
self.stop(compute.execAfterOperation_(function(err, apiResponse) {
if (err) {
callback(err, apiResponse);
return;
}
// Try again now that the instance is stopped.
self.resize(machineType, callback);
}));
} else {
callback(err, apiResponse);
}
return;
}
// The machine type was changed successfully.
if (options.start === false) {
callback(null, apiResponse);
} else {
self.start(compute.execAfterOperation_(callback));
}
}));
};
/**
* Set the metadata for this instance.
*
* @resource [Instances: setMetadata API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/setMetadata}
*
* @param {object} metadata - New metadata.
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:compute/operation} callback.operation - An operation object
* that can be used to check the status of the request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* var metadata = {
* 'startup-script': '...'
* };
*
* vm.setMetadata(metadata, function(err, operation, apiResponse) {
* // `operation` is an Operation object that can be used to check the status
* // of the request.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.setMetadata(metadata).then(function(data) {
* var operation = data[0];
* var apiResponse = data[1];
* });
*/
VM.prototype.setMetadata = function(metadata, callback) {
var self = this;
callback = callback || common.util.noop;
this.getMetadata(function(err, currentMetadata, apiResponse) {
if (err) {
callback(err, null, apiResponse);
return;
}
var newMetadata = {
fingerprint: currentMetadata.metadata.fingerprint,
items: []
};
for (var prop in metadata) {
if (metadata.hasOwnProperty(prop)) {
newMetadata.items.push({
key: prop,
value: metadata[prop]
});
}
}
self.request({
method: 'POST',
uri: '/setMetadata',
json: newMetadata
}, callback);
});
};
/**
* Set the instance's tags.
*
* @resource [Instances: setTags API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/setTags}
*
* @param {string[]} tags - The new tags for the instance.
* @param {string} fingerprint - The current tags fingerprint. An up-to-date
* fingerprint must be provided.
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:compute/operation} callback.operation - An operation object
* that can be used to check the status of the request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* vm.getTags(function(err, tags, fingerprint) {
* tags.push('new-tag');
*
* vm.setTags(tags, fingerprint, function(err, operation, apiResponse) {
* // `operation` is an Operation object that can be used to check the
* // status of the request.
* });
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.getTags().then(function(data) {
* var tags = data[0];
* var fingerprint = data[1];
*
* tags.push('new-tag');
*
* return vm.setTags(tags, fingerprint);
* }).then(function(data) {
* var operation = data[0];
* var apiResponse = data[1];
* });
*/
VM.prototype.setTags = function(tags, fingerprint, callback) {
var body = {
items: tags,
fingerprint: fingerprint
};
this.request({
method: 'POST',
uri: '/setTags',
json: body
}, callback || common.util.noop);
};
/**
* Start the instance.
*
* @resource [Instances: start API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/start}
*
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:compute/operation} callback.operation - An operation object
* that can be used to check the status of the request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* vm.start(function(err, operation, apiResponse) {
* // `operation` is an Operation object that can be used to check the status
* // of the request.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.start().then(function(data) {
* var operation = data[0];
* var apiResponse = data[1];
* });
*/
VM.prototype.start = function(callback) {
this.request({
method: 'POST',
uri: '/start'
}, callback || common.util.noop);
};
/**
* Stop the instance.
*
* @resource [Instances: stop API Documentation]{@link https://cloud.google.com/compute/docs/reference/v1/instances/stop}
*
* @param {function=} callback - The callback function.
* @param {?error} callback.err - An error returned while making this request.
* @param {module:compute/operation} callback.operation - An operation object
* that can be used to check the status of the request.
* @param {object} callback.apiResponse - The full API response.
*
* @example
* vm.stop(function(err, operation, apiResponse) {
* // `operation` is an Operation object that can be used to check the status
* // of the request.
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.stop().then(function(data) {
* var operation = data[0];
* var apiResponse = data[1];
* });
*/
VM.prototype.stop = function(callback) {
this.request({
method: 'POST',
uri: '/stop'
}, callback || common.util.noop);
};
/**
* This function will callback when the VM is in the specified state.
*
* Will time out after the specified time (default: 300 seconds).
*
* @param {string} status - The status to wait for. This can be:
* - "PROVISIONING"
* - "STAGING"
* - "RUNNING"
* - "STOPPING"
* - "SUSPENDING"
* - "SUSPENDED"
* - "TERMINATED"
* @param {object=} options - Configuration object.
* @param {number} options.timeout - The number of seconds to wait until timing
* out, between `0` and `600`. Default: `300`
* @param {function} callback - The callback function.
* @param {?error} callback.err - An error returned while waiting for the
* status.
* @param {object} callback.metadata - The instance's metadata.
*
* @example
* vm.waitFor('RUNNING', function(err, metadata) {
* if (!err) {
* // The VM is running.
* }
* });
*
* //-
* // By default, `waitFor` will timeout after 300 seconds while waiting for the
* // desired state to occur. This can be changed to any number between 0 and
* // 600. If the timeout is set to 0, it will poll once for status and then
* // timeout if the desired state is not reached.
* //-
* var options = {
* timeout: 600
* };
*
* vm.waitFor('TERMINATED', options, function(err, metadata) {
* if (!err) {
* // The VM is terminated.
* }
* });
*
* //-
* // If the callback is omitted, we'll return a Promise.
* //-
* vm.waitFor('RUNNING', options).then(function(data) {
* var metadata = data[0];
* });
*/
VM.prototype.waitFor = function(status, options, callback) {
if (is.fn(options)) {
callback = options;
options = {};
}
options = options || {};
status = status.toUpperCase();
// The timeout should default to five minutes, be less than or equal to 10
// minutes, and be greater than or equal to 0 seconds.
var timeout = 300;
if (is.number(options.timeout)) {
timeout = Math.min(Math.max(options.timeout, 0), 600);
}
if (VALID_STATUSES.indexOf(status) === -1) {
throw new Error('Status passed to waitFor is invalid.');
}
this.waiters.push({
status: status,
timeout: timeout,
startTime: new Date() / 1000,
callback: callback
});
if (!this.hasActiveWaiters) {
this.hasActiveWaiters = true;
this.startPolling_();
}
};
/**
* Poll `getMetadata` to check the VM's status. This runs a loop to ping
* the API on an interval.
*
* Note: This method is automatically called when a `waitFor()` call
* is made.
*
* @private
*/
VM.prototype.startPolling_ = function() {
var self = this;
if (!this.hasActiveWaiters) {
return;
}
this.getMetadata(function(err, metadata) {
var now = new Date() / 1000;
var waitersToRemove = self.waiters.filter(function(waiter) {
if (err) {
waiter.callback(err);
return true;
}
if (metadata.status === waiter.status) {
waiter.callback(null, metadata);
return true;
}
if (now - waiter.startTime >= waiter.timeout) {
var waitForTimeoutError = new WaitForTimeoutError([
'waitFor timed out waiting for VM ' + self.name,
'to be in status: ' + waiter.status
].join(' '));
waiter.callback(waitForTimeoutError);
return true;
}
});
waitersToRemove.forEach(function(waiter) {
self.waiters.splice(self.waiters.indexOf(waiter), 1);
});
self.hasActiveWaiters = self.waiters.length > 0;
if (self.hasActiveWaiters) {
setTimeout(self.startPolling_.bind(self), WAIT_FOR_POLLING_INTERVAL_MS);
}
});
};
/**
* Make a new request object from the provided arguments and wrap the callback
* to intercept non-successful responses.
*
* Most operations on a VM are long-running. This method handles building an
* operation and returning it to the user's provided callback. In methods that
* don't require an operation, we simply don't do anything with the `Operation`
* object.
*
* @private
*
* @param {string} method - Action.
* @param {string} path - Request path.
* @param {*} query - Request query object.
* @param {*} body - Request body contents.
* @param {function} callback - The callback function.
*/
VM.prototype.request = function(reqOpts, callback) {
var zone = this.zone;
var request = common.ServiceObject.prototype.request;
request.call(this, reqOpts, function(err, resp) {
if (err) {
callback(err, null, resp);
return;
}
var operation = zone.operation(resp.name);
operation.metadata = resp;
callback(null, operation, resp);
});
};
/*! Developer Documentation
*
* All async methods (except for streams) will return a Promise in the event
* that a callback is omitted.
*/
common.util.promisifyAll(VM);
module.exports = VM;