-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy patherrors.js
More file actions
535 lines (467 loc) · 17.7 KB
/
Copy patherrors.js
File metadata and controls
535 lines (467 loc) · 17.7 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
/*
* 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 2020 Joyent, Inc.
* Copyright 2024 MNX Cloud, Inc.
*/
/*
* Error classes that CloudAPI may produce are defined or re-exported from here.
*
* *
* Warning: The use of this error module is far from univeral in CloudAPI,
* mainly because this file came later in its dev. CloudAPI code often all
* just passes through errors from SDC API clients. As a result, read this
* CloudAPI error plan as aspirational.
* *
*
*
* # Goals
*
* 1. Respond with meaningful error responses that don't expose internal and
* implementation details.
* 2. Log relevant error details for debugging and analysis.
* 3. Have a reasonably elegant API for raising errors in the sdc-cloudapi code.
*
* One of the main sources of error information is the error responses from
* internal SDC APIs (VMAPI, CNAPI, etc.). Goal #1 basically means whitelisting
* details from internal errors.
*
*
* # Guidelines for sdc-cloudapi errors
*
* - Never return a raw internal SDC API error. Always wrap them with one of
* the `errors.${api}ErrorWrap` methods:
* callback(errors.vmapiErrorWrap(
* err, 'problem creating machine'));
* or using one of the error classes in this module, e.g.:
* res.send(new errors.CloudApiError('error deleting tag'));
*
* - If using the generic `CloudApiError` class, pass in any cause `err`:
* callback(new errors.CloudApiError(err,
* 'this message is exposed to the user'));
* The `err` is then logged internally (a Good Thing), but details aren't
* exposed to the user of cloudapi.
*
* - If there is a useful category of errors, then create a custom error class
* for it. See `ACustomError` and `IAmATeapotError` templates below. A custom
* class has three effects:
*
* (a) its restCode is logged as `err.code`
*
* (b) its restCode (e.g. "ResourceNotFound") is shown in the client-side
* error message, at least by the `triton` client, e.g.:
*
* $ triton inst tag delete vm0 bar
* triton inst: error (ResourceNotFound): tag 'bar' not found
* ^^^^^^^^^^^^^^^^
*
* (c) it is easy to grep for that class of errors in sdc-cloudapi code.
*
*
* # Error Hierarchy
*
* verror.VError
* restify.HttpError
* restify.RestError
*
* # The subset of core restify errors that are used.
* restify.ResourceNotFoundError
* ...
*
* # Error used by the `${api}ErrorWrap` methods
* ExposedSDCError This exposes body.errors, restCode, and
* statusCode from the given cause error.
*
* # Custom error classes for this package
* _CloudApiBaseError
* CloudApiError generic catch all; exposes cause.statusCode
* ...
*
*
* # Background
*
* See:
* <https://github.com/TritonDataCenter/eng/blob/master/docs/index.md#error-handling>
* for Joyent Eng Guidelines on REST API error response bodies.
*
* A Bunyan-logged error looks like this:
*
* ...
* "err": {
* "message": "problem creating mach...",
* "name": "WError",
* "stack": "SDCClientError: problem creating mach..."
* "code": "ValidationFailed",
* "errors": [
* {
* "field": "alias",
* "code": "Duplicate",
* "message": "Already exists for this owner_uuid"
* }
* ]
* },
* ...
*/
var util = require('util'),
format = util.format;
var assert = require('assert-plus');
var restify = require('restify');
// ---- error classes
/**
* Base class for custom error classes. It provides a nice call signature
* with variable args (a la `util.format`) and an optional leading "cause"
* Error argument. (This is *similar* to `verror.VError`, but uses the more
* lenient `util.format` behaviour rather than the strict sprintf which blows
* up on a leading string with accidental format codes.) Calling forms:
*
* new MyError('my message', ...);
* new MyError(cause, 'my message', ...);
* new MyError('my message with %d formats', arg1, arg2, ...);
*
* This class also asserts that subclass prototype has the following fields:
* - restCode: A string used for the restCode.
* - statusCode: An HTTP integer statusCode.
*
* This class shouldn't be exported, because all usages should be of one of the
* subclasses.
*/
function _FriendlySigRestError(_opts) {
var ctor = this.constructor;
assert.string(ctor.prototype.restCode, ctor.name + '.prototype.restCode');
assert.number(ctor.prototype.statusCode,
ctor.name + '.prototype.statusCode');
/*
* In versions of node since (I think) 0.10, `Error.toString()` does
* not use `this.constructor.name`. Therefore to get that error subclass
* name in printed errors and error.stack, we need to set `prototype.name`.
*/
if (!ctor.prototype.hasOwnProperty('name')) {
ctor.prototype.name = ctor.name;
}
var restErrorOpts = {
restCode: ctor.prototype.restCode,
statusCode: ctor.prototype.statusCode
};
var msgArgs;
if (arguments[0] instanceof Error) {
// `new <Error>(<err>, ...)`
restErrorOpts.cause = arguments[0];
msgArgs = Array.prototype.slice.call(arguments, 1);
} else if (arguments.length === 0) {
msgArgs = [];
} else if (typeof (arguments[0]) === 'string') {
// `new <Error>(<string>, ...)`
msgArgs = Array.prototype.slice.call(arguments);
} else {
// `new <Error>(<not a string>, ...)`
// Almost certainly an error, show `inspect(<not a string>)`.
msgArgs = Array.prototype.slice.call(arguments);
msgArgs[0] = util.inspect(msgArgs[0]);
}
if (msgArgs.length > 0 && msgArgs[0] === undefined) {
msgArgs.shift();
}
restErrorOpts.message = format.apply(null, msgArgs);
restify.RestError.call(this, restErrorOpts);
}
util.inherits(_FriendlySigRestError, restify.RestError);
/**
* The generic catch-all error to use if there isn't a specific error class.
*
* If a cause error is given, then this error will steal (i.e. expose) its
* `statusCode`. Other details (restCode, message, body) are *not* exposed.
*/
function CloudApiError() {
_FriendlySigRestError.apply(this, arguments);
// Steal the statusCode from the cause error, if any.
var cause = this.cause();
if (cause && cause.statusCode) {
this.statusCode = cause.statusCode;
}
}
util.inherits(CloudApiError, _FriendlySigRestError);
CloudApiError.prototype.restCode = 'CloudApiError';
CloudApiError.prototype.statusCode = 500;
CloudApiError.prototype.description = 'Encountered an internal error.';
/*
* Custom error class templates:
*
* Here is a `ACustomError` class. It defines a statusCode and restCode, but
* otherwise passes through the cause and message given at the call site:
*
* function ACustomError() {
* _FriendlySigRestError.apply(this, arguments);
* }
* util.inherits(ACustomError, _FriendlySigRestError);
* ACustomError.prototype.restCode = 'ACustom';
* ACustomError.prototype.statusCode = 409;
* ACustomError.prototype.description = 'This custom thing broke.';
*
* Here is a `IAmATeapotError` class that hardwires an error message, but
* still takes a cause:
*
* function IAmATeapotError(cause) {
* assert.optionalObject(cause, 'cause');
* restify.RestError.call(this, {
* cause: cause,
* message: 'I am a teapot',
* statusCode: this.constructor.prototype.statusCode,
* restCode: this.constructor.prototype.restCode
* });
* }
* util.inherits(IAmATeapotError, restify.RestError);
* IAmATeapotError.prototype.restCode = 'IAmATeapotError';
* IAmATeapotError.prototype.statusCode = 418;
* IAmATeapotError.prototype.description = 'Earl grey. Hot.';
*
* Note: The ceremony over adding fields to the constructor prototype isn't
* technically required right now, but does allow for generation of the
* cloudapi docs' errors table -- as is being done in IMGAPI right now:
* https://github.com/TritonDataCenter/sdc-imgapi/blob/master/lib/errors.js#L558-L605
*/
function CannotDestroyMachineError() {
_FriendlySigRestError.apply(this, arguments);
}
util.inherits(CannotDestroyMachineError, _FriendlySigRestError);
CannotDestroyMachineError.prototype.restCode = 'CannotDestroyMachineError';
CannotDestroyMachineError.prototype.statusCode = 409;
CannotDestroyMachineError.prototype.description = 'Machine cannot be destroyed';
// ---- wrappers for API responses
/**
* An error used to expose the error from a node-sdc-clients API request.
*
* This *prefers* they are following:
* https://github.com/TritonDataCenter/eng/blob/master/docs/index.md#error-handling
* but we have enough exceptions, even in APIs like IMGAPI that try hard
* to be defensive.
*/
function ExposedSDCError(cause, message) {
assert.object(cause, 'cause');
assert.string(message, 'message');
assert.string(cause.restCode, 'cause.restCode');
assert.optionalObject(cause.body, 'cause.body');
var body = cause.body || {};
assert.optionalString(body.message, 'cause.body.message');
var fullMsg = format('%s: %s', message,
body.message || cause.message || cause.toString());
restify.RestError.call(this, {
cause: cause,
message: fullMsg,
restCode: cause.restCode,
statusCode: cause.statusCode
});
if (body.errors) {
this.body.errors = body.errors;
}
}
util.inherits(ExposedSDCError, restify.RestError);
/**
* Selectively expose some NAPI error details via a whitelist on restCode.
* Other NAPI error codes are wrapped such that the error is *logged*, but
* only the `statusCode` is exposed.
*
* Usage:
* next(new errors.napiErrorWrap(err, 'error creating NIC'));
*/
function napiErrorWrap(cause, message) {
assert.object(cause, 'cause');
assert.string(message, 'message');
if (!cause) {
return cause;
} else if (!cause.restCode) {
return new CloudApiError(cause, message);
}
switch (cause.restCode) {
case 'ResourceNotFound':
return new ExposedSDCError(cause, message);
/* By default don't expose internal error message details. */
default:
return new CloudApiError(cause, message);
}
}
/**
* Selectively expose some VMAPI error details via a whitelist on restCode.
* Other VMAPI error codes are wrapped such that the error is *logged*, but
* only the `statusCode` is exposed.
*
* Usage:
* next(new errors.vmapiErrorWrap(err, 'error deleting tag'));
*/
function vmapiErrorWrap(cause, message) {
assert.object(cause, 'cause');
assert.string(message, 'message');
if (!cause) {
return cause;
} else if (!cause.restCode) {
return new CloudApiError(cause, message);
}
switch (cause.restCode) {
case 'ValidationFailed':
return new ExposedSDCError(cause, message);
case 'VolumesNotReachable':
return new VolumesNotReachableError(cause);
/* By default don't expose internal error message details. */
default:
return new CloudApiError(cause, message);
}
}
function VolumesNotReachableError(cause) {
assert.object(cause, 'cause');
var message = 'Volumes not reachable from machine';
message += ': ' + cause.body.errors.map(function renderErr(err) {
return err.message;
}).join(', ');
restify.RestError.call(this, {
cause: cause,
message: message,
statusCode: this.constructor.prototype.statusCode,
restCode: this.constructor.prototype.restCode
});
}
util.inherits(VolumesNotReachableError, restify.RestError);
VolumesNotReachableError.prototype.name = 'VolumesNotReachableError';
VolumesNotReachableError.restCode = 'VolumesNotReachableError';
VolumesNotReachableError.statusCode = 409;
VolumesNotReachableError.description = 'Volumes not reachable from machine';
/**
* Selectively expose some VOLAPI error details via a whitelist on restCode.
* Other VOLAPI error codes are wrapped such that the error is *logged*, but
* only the `statusCode` is exposed.
*
* Usage:
* next(new errors.volapiErrorWrap(err, 'error deleting tag'));
*/
function volapiErrorWrap(cause, message) {
assert.object(cause, 'cause');
assert.string(message, 'message');
switch (cause.restCode) {
case 'InvalidNetworks':
case 'ValidationError':
case 'VolumeAlreadyExists':
case 'VolumeInUse':
case 'VolumeNotFound':
case 'VolumeSizeNotAvailable':
return new ExposedSDCError(cause, message);
/* By default don't expose internal error message details. */
default:
return new CloudApiError(cause, message);
}
}
function DefaultFabricNetworkNotConfiguredError(cause) {
assert.optionalObject(cause, 'cause');
var errMsg = 'default_network is not configured for account';
_FriendlySigRestError.call(this, cause, errMsg);
}
util.inherits(DefaultFabricNetworkNotConfiguredError, _FriendlySigRestError);
DefaultFabricNetworkNotConfiguredError.prototype.restCode =
'DefaultFabricNetworkNotConfiguredError';
DefaultFabricNetworkNotConfiguredError.prototype.statusCode = 409;
function MachineHasNoVNCError(brand) {
assert.string(brand, 'brand');
var errMsg = format('Instance type %s does not support VNC connections',
brand);
_FriendlySigRestError.call(this, null, errMsg);
}
util.inherits(MachineHasNoVNCError, _FriendlySigRestError);
MachineHasNoVNCError.prototype.restCode = 'MachineHasNoVNCError';
MachineHasNoVNCError.prototype.statusCode = 400;
MachineHasNoVNCError.prototype.description = 'Instance does not support VNC';
function MachineHasNoConsoleError(brand) {
assert.string(brand, 'brand');
var errMsg = format('Instance type %s does not support console connections',
brand);
_FriendlySigRestError.call(this, null, errMsg);
}
util.inherits(MachineHasNoConsoleError, _FriendlySigRestError);
MachineHasNoConsoleError.prototype.restCode = 'MachineHasNoConsoleError';
MachineHasNoConsoleError.prototype.statusCode = 400;
MachineHasNoConsoleError.prototype.description = 'Instance does not support console';
function MachineStoppedError() {
_FriendlySigRestError.call(this, null,
'Cannot connect to a stopped machine');
}
util.inherits(MachineStoppedError, _FriendlySigRestError);
MachineStoppedError.prototype.restCode = 'MachineStoppedError';
MachineStoppedError.prototype.statusCode = 400;
MachineStoppedError.prototype.description = 'Instance is stopped';
function UpgradeRequiredError(msg) {
assert.string(msg, 'msg');
_FriendlySigRestError.call(this, null, msg);
}
util.inherits(UpgradeRequiredError, _FriendlySigRestError);
UpgradeRequiredError.prototype.restCode = 'UpgradeRequiredError';
UpgradeRequiredError.prototype.statusCode = 400;
UpgradeRequiredError.prototype.description =
'Endpoint is a websocket and must be upgraded';
function isDataVersionError(err) {
assert.object(err, 'err');
return err.name === 'DataVersionError';
}
function isInternalMetadataSearchError(err) {
assert.object(err, 'err');
return err.name === 'InternalServerError' &&
err.message.indexOf('internal_metadata') !== -1;
}
/*
* This will return translated duplicate IP errors if found, otherwise no
* action will be taken.
*
* This function is helpful when we are in the CreateMachine or AddNic path,
* and the user has passed in a network object that specifies an IP address.
*/
function translateDuplicateIpErrors(error) {
assert.object(error, 'error');
var body = error.body;
assert.object(body, 'body');
assert.arrayOfObject(body.errors, 'errors array');
/*
* Since ZAPI-816, vmapi will pre-provision NICs one at a time. If an IP is
* already in use the napi error will be piped through back to cloudapi.
*/
body.errors = body.errors.map(function translateUsedByErrors(e) {
if (e.field === 'ip' && e.code === 'UsedBy') {
/*
* Until NAPI-438 lands, we lack the necessary information to
* report back what IPs are currently in use. For now we translate
* the error to drop the zone UUID to ensure that we do not leak
* any info on shared private networks i.e. another account may
* have provisioned the zone.
*/
return {
field: 'ip',
code: 'UsedBy',
message: 'IP in use'
};
}
return e;
});
return error;
}
// ---- exports
module.exports = {
// Re-exported restify errors. Add more as needed.
ResourceNotFoundError: restify.ResourceNotFoundError,
InvalidArgumentError: restify.InvalidArgumentError,
// Custom error classes.
CloudApiError: CloudApiError,
CannotDestroyMachineError: CannotDestroyMachineError,
DefaultFabricNetworkNotConfiguredError:
DefaultFabricNetworkNotConfiguredError,
VolumesNotReachableError: VolumesNotReachableError,
MachineHasNoVNCError: MachineHasNoVNCError,
MachineHasNoConsoleError: MachineHasNoConsoleError,
MachineStoppedError: MachineStoppedError,
UpgradeRequiredError: UpgradeRequiredError,
// Internal SDC API wrappers
vmapiErrorWrap: vmapiErrorWrap,
napiErrorWrap: napiErrorWrap,
volapiErrorWrap: volapiErrorWrap,
// Utility functions
isDataVersionError: isDataVersionError,
isInternalMetadataSearchError: isInternalMetadataSearchError,
translateDuplicateIpErrors: translateDuplicateIpErrors
};
// vim: set softtabstop=4 shiftwidth=4: